diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..a99050d --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# Support the @imqueue framework +custom: + - "https://imqueue.com/" diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml index 4fdcb29..67a1722 100644 --- a/.github/workflows/cla.yml +++ b/.github/workflows/cla.yml @@ -27,7 +27,12 @@ jobs: with: path-to-signatures: 'signatures/version1/cla.json' path-to-document: 'https://github.com/imqueue/.github/blob/master/CONTRIBUTION-TERMS.md' - branch: 'master' + # NOT master, and not any branch that gains a ruleset later. The + # bot writes this file with a direct commit, which cannot satisfy the + # status check the default branch requires — every signature failed + # to record, so no outside contribution could be merged. The branch + # holds the signature file and nothing else. + branch: 'cla-signatures' allowlist: 'dependabot[bot],*[bot]' custom-notsigned-prcomment: >- Thank you for your contribution to **@imqueue**. Before this pull diff --git a/.github/workflows/no-ai-attribution.yml b/.github/workflows/no-ai-attribution.yml new file mode 100644 index 0000000..8001eb2 --- /dev/null +++ b/.github/workflows/no-ai-attribution.yml @@ -0,0 +1,22 @@ +# Fails this push or PR if a commit carries AI attribution, or if a +# vendor-locked agent config file (CLAUDE.md and friends) is committed. +# +# The rules live in imqueue/.github/.github/workflows/no-ai-attribution.yml. +# They exist because GitHub renders a `Co-Authored-By: Claude ...` trailer as a +# second author on the commit page — 148 such commits were rewritten out of this +# org's history, and this check is what stops them coming back. +# +# The half that actually blocks is local: a commit-msg and pre-push hook running +# the same rules. This is the backstop for --no-verify, a machine without the +# hooks, and the GitHub web editor. + +name: No AI attribution + +on: + pull_request: + types: [opened, reopened, synchronize] + push: + +jobs: + attribution: + uses: imqueue/.github/.github/workflows/no-ai-attribution.yml@master diff --git a/.github/workflows/pr-quality.yml b/.github/workflows/pr-quality.yml new file mode 100644 index 0000000..06a99a9 --- /dev/null +++ b/.github/workflows/pr-quality.yml @@ -0,0 +1,18 @@ +# Fails this PR if it has no usable description or its title says nothing. +# +# The rules live in imqueue/.github/.github/workflows/pr-quality.yml. They exist because +# generated release notes are built from PR titles and bodies — see release.yml, which +# creates the GitHub Release page on tag push and cannot invent detail nobody wrote down. +# +# `edited` is in the trigger list on purpose: fixing the description must clear the +# failure without pushing a commit. + +name: PR quality + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + description: + uses: imqueue/.github/.github/workflows/pr-quality.yml@master diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..cc94613 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,44 @@ +# Creates the GitHub Release page for a version tag. +# +# The notes are composed by the shared workflow in +# imqueue/.github/.github/workflows/release.yml: a CHANGELOG.md section for the exact +# version when one exists, otherwise GitHub's PR-derived notes, always followed by a +# standard About + links block. +# +# This fires on `git push --follow-tags` after `npm version`, so it needs no change to +# the existing release habit. workflow_dispatch is for backfilling a tag that already +# exists, and defaults to a dry run so the notes can be read before anything is created. + +name: Release + +on: + push: + tags: ['v*'] + workflow_dispatch: + inputs: + tag: + description: 'Existing tag to compose notes for, e.g. v1.2.3' + required: true + type: string + dry-run: + description: 'Only print the notes; do not create or update the release' + required: false + type: boolean + default: true + +jobs: + release: + uses: imqueue/.github/.github/workflows/release.yml@master + # A called workflow can hold no more permission than its caller grants, so this is + # required even though the shared workflow declares it too. + permissions: + contents: write + with: + package: '@imqueue/cli' + tag: ${{ inputs.tag || '' }} + dry-run: ${{ inputs.dry-run || false }} + blurb: >- + `@imqueue/cli` (`imq`) scaffolds @imqueue services and orchestrates them: create a service + and its CI/registry wiring in one command, generate typed clients (`imq client generate + `), run a local fleet, and coordinate fleet-wide version bumps (`imq service + update-version --bump`). diff --git a/.gitignore b/.gitignore index a6eac35..b9f6982 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,5 @@ stats.json benchmark-result/* *.tgz + +GQL-PROPOSAL.md diff --git a/AGENTS.md b/AGENTS.md index 58c4fad..4a7169e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,8 +99,8 @@ Getting this wrong yields `TS2307/TS2882` and a non-zero build that aborts `deriveStructured()` reads either; writes emit both. A 3.x config must keep working (github+travis+dockerhub) and a downgrade must still read what we wrote. -- **Templates**: templates repo `master` is frozen; the CLI pins - `templatesRef = v4` (config-overridable). A template is **v2** iff it has an +- **Templates**: the CLI reads the templates repo at `templatesRef` + (default `master`, config-overridable). A template is **v2** iff it has an `imq-template.json` manifest, else v1. Don't assume v2. - **Option precedence everywhere**: flag → `.imqrc.json` (service root) → global config → prompt (TTY only) → default. Resolution lives in @@ -117,6 +117,7 @@ Getting this wrong yields `TS2307/TS2882` and a non-zero build that aborts `IMQ_CLI_HOME`, `IMQ_NO_UPDATE_CHECK`, `IMQ_TEMPLATES_REPO`, `IMQ_GITHUB_API_URL`, `IMQ_GITLAB_API_URL`, `IMQ_BITBUCKET_API_URL`, `IMQ_CIRCLECI_API_URL`, `IMQ_TRAVIS_API_URL`, `IMQ_GIT_REMOTE_BASE`, +`IMQ_SSH_DIR` (ssh dir scanned for git-protocol auto-detection), `IMQ_CLI_MISSING_COMMANDS` (test seam for `commandExists`). Any new network endpoint MUST get an `IMQ_*_API_URL` override so it is testable and enterprise-ready. Default the templates repo to public **HTTPS** (no SSH @@ -162,6 +163,23 @@ Note two *different* service-detection strategies, by design: the current default template (no `require()`/`chai`). - `service create`'s commit step sets a **repo-local** git identity from the author/email, so it works without a global git identity. +- `service create` push transport is chosen by `vcs.protocol` + (`--git-protocol` flag → `.imqrc` → global → `https` default), resolved in + `create-plan.ts` (`resolveGitProtocol`) and applied in `create-pipeline.ts` + step 6. **`https` (default): push authenticated with the VCS access token** + (the one that created the repo), injected per-push via + `git -c http.extraHeader=Authorization: Basic …` — never persisted to + `.git/config` (the remote URL stays token-free). This avoids the classic + "Repository not found" SSH failure when the user's key/active account lacks + access to a private org repo. Per-host basic-auth username is + `VcsHostProvider.httpAuthUser` (`x-access-token`/`oauth2`/`x-token-auth`). + **`ssh`: push over the host ssh url using the user's keys, no token + injection.** `git.initAndPush` injects the header only for `https://` remotes. + `IMQ_GIT_REMOTE_BASE` still overrides the target entirely (no token injection + there) and takes precedence over `vcs.protocol`. `imq config init` + auto-detects the default protocol via `lib/ssh.ts` `detectGitProtocol()` + (SSH when `~/.ssh` has keys, else HTTPS; `IMQ_SSH_DIR` overrides the dir), + reports it, and lets the user change it. - `update-version` must not filter by export name containing "Service" — walk the prototype chain. - Some sandboxes/containers have **no runtime network**; the docker harness is @@ -180,9 +198,9 @@ Note two *different* service-detection strategies, by design: ## Current state -Active work is on the **`v4`** branch (target release `4.0.0`), not yet merged -to `master`. During the 4.0 cycle, branch from and PR against `v4` (note: -CONTRIBUTING.md still says `master`, which applies once 4.0 has shipped). -Templates repo `v4` branch holds the v2 default template + `catalog.json`; its -`master` stays frozen until CLI 4.0 ships. Full suite green (`npm test`), lint -+ format clean, docker harness "ALL CHECKS PASSED". +The `v4` work (release `4.0.0`) has been merged to **`master`**; `master` is now +the active branch — branch from and PR against it (`v4` is retained as the +pre-merge snapshot, no longer updated). Templates repo `master` holds the v2 +default template + `catalog.json`, and the CLI reads `master` by default. Full +suite green (`npm test`), lint + format clean, docker harness +"ALL CHECKS PASSED". diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 97a824c..8d7d1f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,10 +23,6 @@ terms.** In short: ## How to contribute -> During an active release cycle the development branch may differ from -> `master` (the 4.0 work happens on `v4`). Check the "Current state" section of -> [AGENTS.md](./AGENTS.md) and branch from / PR against whatever it names. - 1. **Open an issue first** for anything non-trivial, so we can agree on the approach before you invest time. 2. **Fork** the repository and create a topic branch from `master` diff --git a/README.md b/README.md index 8fd1de4..41cc010 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # I Message Queue CLI (@imqueue/cli) -[![Build](https://github.com/imqueue/cli/actions/workflows/build.yml/badge.svg)](https://github.com/imqueue/cli/actions/workflows/build.yml) -[![codebeat badge](https://codebeat.co/badges/0824c9af-d6fa-47ac-bc44-eb51d7b37eba)](https://codebeat.co/projects/github-com-imqueue-cli-master) +[![Build Status](https://img.shields.io/github/actions/workflow/status/imqueue/cli/build.yml)](https://github.com/imqueue/cli/actions/workflows/build.yml) +[![npm version](https://img.shields.io/npm/v/@imqueue/cli)](https://www.npmjs.com/package/@imqueue/cli) [![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://github.com/imqueue/cli/blob/master/LICENSE) ## Why? @@ -10,8 +10,14 @@ Frees you from writing boilerplate when making @imqueue services. ## Documentation -This README is a quick reference. The full user manual lives in the -[project wiki](https://github.com/imqueue/cli/wiki): +This README is a quick reference. The full user manual is published at +[imqueue.org/cli](https://imqueue.org/cli/) (and mirrored in the +[project wiki](https://github.com/imqueue/cli/wiki)). Commercial licensing & +support: [imqueue.com](https://imqueue.com/). Using an AI assistant? Point it at +[imqueue.org/llms.txt](https://imqueue.org/llms.txt) or see [AGENTS.md](./AGENTS.md). +Current version, licence and Node floor for every package: +[imqueue.org/status.json](https://imqueue.org/status.json). +Wiki chapters: - [Installation](https://github.com/imqueue/cli/wiki/Installation) - [Configuration](https://github.com/imqueue/cli/wiki/Configuration) — layers, schema, secrets, env vars @@ -119,6 +125,8 @@ Options: -L, --node-docker-tag Node docker tag to use as base docker image -N, --docker-namespace Registry namespace / repository / ACR name -T, --github-token VCS auth token + --git-protocol Git transport for the initial push: https (default) or + ssh [choices: "https","ssh"] -p, --private Repository will be private [boolean] --dry-run Print the resolved plan and exit [boolean] -y, --yes Skip the confirmation prompt [boolean] @@ -132,6 +140,17 @@ reference, packages) without making any changes — handy for scripting and CI. The chosen providers and packages are written to a committed `.imqrc.json` in the generated service, so later commands and re-creations reuse them. +**Git transport for the initial push.** By default (`vcs.protocol: https`) the +initial commit is pushed over HTTPS authenticated with the same access token +that created the repository — the token is used only for that push and is never +written into the repository's `.git/config`. This makes a push to a private +organization repo succeed even when your SSH key (or a different "active" +git/gh account) has no access to it. Pass `--git-protocol ssh` (or set +`vcs.protocol ssh`) to push over SSH with your own keys instead. `imq config +init` auto-detects a sensible default from whether you have SSH keys in +`~/.ssh`. See +[Configuration → Git transport](https://github.com/imqueue/cli/wiki/Configuration#git-transport-for-the-initial-push-https-vs-ssh). + #### Package Catalog `imq service create --packages ` adds secondary @imqueue libraries and @@ -141,7 +160,7 @@ new addons can be published without a CLI release. Groups marked *exclusive* allow a single choice: - **tracing** (exclusive): `dd-trace`, `opentelemetry` -- **orm** (exclusive): `sequelize`, `prisma` +- **orm** (exclusive): `sequelize`, `pg-prisma` - **features**: `pg-cache`, `pg-pubsub`, `tag-cache`, `job`, `net`, `http-protect`, `graphql-dependency`, `type-graphql-dependency` @@ -204,7 +223,9 @@ command: imq config init ~~~ -which will guide you through configuration process. +which will guide you through configuration process. When you enable a VCS host +it auto-detects the git transport (SSH if you have keys in `~/.ssh`, otherwise +HTTPS), tells you what it picked, and lets you change it. There are also useful commands to retrieve and set specific configuration values, stored in a configuration file: @@ -224,12 +245,12 @@ will print a single requested option value. imq config set [option_name] [new_value] ~~~ will set requested option to a given new value. Nested options can be -addressed with a dot-path, e.g. `imq config set ci.provider circleci` or -`imq config set vcs.namespace my-org`. The config keeps the structured v4 -keys (`vcs`, `ci`, `registry`, `packages`, `templatesRef`) and their legacy -equivalents in sync, so upgrading or downgrading the CLI keeps working. A -config written by an older CLI is read transparently (github + travis + -dockerhub). +addressed with a dot-path, e.g. `imq config set ci.provider circleci`, +`imq config set vcs.namespace my-org` or `imq config set vcs.protocol ssh`. +The config keeps the structured v4 keys (`vcs`, `ci`, `registry`, `packages`, +`templatesRef`) and their legacy equivalents in sync, so upgrading or +downgrading the CLI keeps working. A config written by an older CLI is read +transparently (github + travis + dockerhub). ~~~bash imq config check diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..fd062fe --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# Security Policy + +## Reporting a vulnerability + +If you believe you have found a security vulnerability in **@imqueue/cli** (or any +`@imqueue/*` package), please report it **privately** — do not open a public issue, +pull request, or discussion for it. + +Two private channels: + +- **GitHub** — use *Security → Report a vulnerability* on this repository to open a + private advisory (preferred; it keeps the report and the fix coordinated in one + place). +- **Email** — with the details below. + +Please include: + +- the affected package and version(s); +- a description of the issue and its impact; +- steps to reproduce, or a proof of concept, where possible. + +## What to expect + +- We aim to acknowledge a report within a few business days. +- We'll confirm the issue, keep you updated on progress, and coordinate a fix and a + disclosure timeline with you. +- Once a fix is released we'll credit the reporter in the advisory unless you prefer + to remain anonymous. + +## Supported versions + +Security fixes land on the latest published release line of each `@imqueue/*` +package on npm. Please make sure you can reproduce an issue against the current +release before reporting. + +## Scope + +The `@imqueue` framework is open source under GPL-3.0. This policy covers the code +in the `@imqueue/*` packages. Vulnerabilities in third-party dependencies should be +reported to those projects, though we're glad to help coordinate an upgrade. diff --git a/context7.json b/context7.json new file mode 100644 index 0000000..fd0cd37 --- /dev/null +++ b/context7.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://context7.com/schema/context7.json", + "projectTitle": "@imqueue/cli", + "description": "Command line interface for @imqueue — scaffold Redis-RPC microservices, generate typed clients, and manage a local service fleet.", + "branch": "master", + "excludeFolders": ["src", "lib", "bin", "test", "tests", "dist", "coverage", "node_modules", "scripts", ".github"], + "excludeFiles": ["CHANGELOG.md", "LICENSE", "CLAUDE.md", "CONTRIBUTING.md", "CONTRIBUTION-TERMS.md", "SECURITY.md", "wiki/_Sidebar.md", "wiki/README.md"], + "rules": [ + "@imqueue/cli is the `imq` command for the @imqueue framework: it scaffolds Redis-RPC services from templates, generates typed clients, and runs a local fleet. Install globally with `npm i -g @imqueue/cli`.", + "The command surface is `imq service`, `imq client`, `imq config`, `imq ctl`, `imq log`, `imq up` and `imq completions`. Run bare `imq` for the summary.", + "From 4.x the standalone `imqctl`, `imqlog` and `imqup` tools are subcommands — `imq ctl`, `imq log`, `imq up` — with unchanged options. Do not suggest the old binaries.", + "Scaffold with `imq service create `, e.g. `imq service create billing ./billing`.", + "`imq client generate [path]` needs the service RUNNING and Redis reachable, because it introspects the live interface. Against a stopped service it waits, then fails.", + "The name `imq client generate` takes is the service's QUEUE name, which IMQService defaults to its own class name (`this.name = name || this.constructor.name`); the CLI passes it straight to IMQClient.create().", + "So it is `imq client generate BillingService ./src/clients`, not `billing`. The lower-case project or directory name is what `imq ctl -s` takes — the two are different names and mixing them up times the generator out.", + "Generation writes `/.ts`, whose only export is a namespace named after the service with a lower-case first letter, holding a class whose trailing `Service` is replaced by `Client`.", + "`-o, --overwrite` replaces an existing client without prompting; `-w, --timeout` is seconds to wait for the service (default 30, and `0` waits forever).", + "Development flow: `imq ctl start -s billing -c` to bring it up and wait for readiness, then `imq client generate BillingService ./src/clients`, then `imq ctl stop -s billing`.", + "`imq service update-version [branch]` releases across one or many services: git checkout, pull, `npm version`, `git push --follow-tags`, stopping that service at the first failing step.", + "update-version detects services by LOADING the built module and walking the prototype chain for IMQService, so the class need not be named `*Service`. `imq up` and `imq ctl` detect by scanning source instead.", + "Use `imq service update-version` for a release against built, committed services, and `imq up` for dependency maintenance (`ncu -u` plus reinstall). update-version takes `-b/[branch]`, default master; `imq up` uses the current branch.", + "Every option resolves by a strict precedence: flag, then the per-service `.imqrc.json`, then global config, then an interactive prompt, then the default. So CI and scripted runs never hang waiting for input.", + "`imq config init | get | set | check` manages settings. The CLI home is `~/.imq/`, and IMQ_CLI_HOME relocates it — which is how you give each project an isolated CLI environment.", + "`imq service create --packages ` adds addon packages; `--no-packages` means explicitly none; `imq config set packages opentelemetry,pg-cache` sets a default for every new service.", + "List every addon id with `imq service packages`, or `imq service packages --json` for a machine-readable form.", + "Two addon groups are EXCLUSIVE and accept at most one member: tracing/APM (`opentelemetry`, `dd-trace`) and ORM/database (`pg-prisma`, `sequelize`). Selecting two members of one group is rejected with an error.", + "At most one, not exactly one: selecting no ORM is a normal answer and the right one for a service that talks to no database.", + "Catalog ids are not npm names, and two no longer match: `dd-trace` installs @imqueue/datadog and `sequelize` installs @imqueue/pg-sequelize. The ids stayed put through the renames so existing configs keep working.", + "The non-exclusive feature group is pg-cache, pg-pubsub, tag-cache, job, net, http-protect, graphql-dependency, type-graphql-dependency, validation, core and gcp.", + "The `core` addon adds @imqueue/core as a direct dependency. It already arrives transitively through @imqueue/rpc, so take it only when the service imports from it directly.", + "The `gcp` addon is the Google Cloud Trace exporter: it needs `opentelemetry` selected as well, and exports once GOOGLE_APPLICATION_CREDENTIALS is set.", + "Defaults are `pg-prisma` for the ORM and `opentelemetry` for tracing — unless the surrounding fleet already agrees on something else, in which case matching the fleet wins.", + "`imq service create` treats sibling directories whose package.json depends on @imqueue/rpc as the fleet, and preselects the ORM and tracing members they agree on. A strict majority wins; a tie preselects nothing.", + "The fleet scan is cached in `~/.imq/var/fleet.json`, keyed by directory and invalidated when the set of sibling directories changes. Choosing against the analysis is recorded as an override for that directory.", + "For each selected addon the scaffolder merges its dependencies, injects code at the `%ADDON_PRELOAD` and `%ADDON_CONFIG` template tokens, may add files, and prints the environment variables that addon needs.", + "A traced service's reported name comes from SERVICE_NAME via `src/config.ts` on v2 templates (zod-validated, defaulting to the scaffolded name), or from an inlined IMQ_SERVICE_NAME on v1. `dd-trace` takes neither — use DD_SERVICE.", + "Do not confuse those with the `%SERVICE_NAME` template token, which is substituted once at scaffold time and is not read at runtime.", + "Templates and the addon catalog live in a separate repo, pointed at by IMQ_TEMPLATES_REPO and `templatesRef`, so new addons can appear without a CLI release.", + "Every network endpoint has an environment-variable override, which is what makes GitHub Enterprise, self-managed GitLab and Bitbucket-compatible endpoints work.", + "On every interactive run `imq` checks npm for a newer release and offers to self-update. Set IMQ_NO_UPDATE_CHECK=1 to skip that check in scripts and CI.", + "`imq completions` installs or removes shell completions for bash and zsh.", + "Requires Node.js 22.12+. The package is ESM-only. Shell snippets assume a POSIX shell, so Windows users should use WSL or Git Bash.", + "@imqueue/cli is GPL-3.0-only. Commercial licensing for closed-source products: https://imqueue.com/license/.", + "The full CLI manual is at https://imqueue.org/cli/; a machine-readable docs index at https://imqueue.org/llms.txt; a hosted MCP server for agents at https://mcp.imqueue.org/mcp." + ], + "url": "https://context7.com/imqueue/cli", + "public_key": "pk_fjNtG1ue4XLAYwKYgyOMq" +} diff --git a/lib/catalog.json b/lib/catalog.json index 6e9113b..f645e3b 100644 --- a/lib/catalog.json +++ b/lib/catalog.json @@ -1,46 +1,103 @@ { "version": 1, "groups": { - "tracing": { "title": "Tracing / APM", "exclusive": true }, - "orm": { "title": "ORM / database", "exclusive": true }, + "tracing": { + "title": "Tracing / APM", + "exclusive": true, + "pick": "Only if the service is traced — none is normal." + }, + "orm": { + "title": "ORM / database", + "exclusive": true, + "pick": "Only if the service uses a database — none is normal." + }, "features": { "title": "Service features", "exclusive": false } }, "packages": { "opentelemetry": { "group": "tracing", "title": "OpenTelemetry instrumentation", - "deps": { "@imqueue/opentelemetry-instrumentation-imqueue": "*" }, - "snippets": { "preload": "import '@imqueue/opentelemetry-instrumentation-imqueue';" }, + "pick": "Recommended: vendor-neutral, so the backend can change without touching service code.", + "deps": { + "@imqueue/opentelemetry": "*", + "@opentelemetry/api": "*", + "@opentelemetry/instrumentation": "*", + "@opentelemetry/resources": "*", + "@opentelemetry/sdk-trace-node": "*", + "@opentelemetry/semantic-conventions": "*" + }, + "snippets": { "preload": "import './telemetry.js';" }, "env": ["OTEL_EXPORTER_OTLP_ENDPOINT"], "instructions": [ - "OpenTelemetry: set OTEL_EXPORTER_OTLP_ENDPOINT to your collector endpoint." + "OpenTelemetry: tracing is initialized in src/telemetry.ts (imported first at start-up).", + "OpenTelemetry: add the 'gcp' package to export traces to Google Cloud Trace." + ] + }, + "gcp": { + "group": "features", + "title": "Google Cloud Trace exporter (for OpenTelemetry)", + "deps": { "@google-cloud/opentelemetry-cloud-trace-exporter": "*" }, + "env": ["GOOGLE_APPLICATION_CREDENTIALS"], + "instructions": [ + "GCP trace export: requires the opentelemetry package; traces export to Google Cloud Trace when GOOGLE_APPLICATION_CREDENTIALS is set." ] }, "dd-trace": { "group": "tracing", - "title": "Datadog APM (dd-trace)", - "deps": { "@imqueue/dd-trace": "*" }, - "snippets": { "preload": "import '@imqueue/dd-trace';" }, + "title": "Datadog APM", + "hint": "already on Datadog", + "pick": "For a fleet already standing on Datadog\u2019s own agent; otherwise take opentelemetry.", + "deps": { "@imqueue/datadog": "*" }, + "snippets": { "preload": "import './tracer.js';" }, "env": ["DD_AGENT_HOST", "DD_TRACE_ENABLED"], "instructions": [ + "Datadog: tracing is initialized in src/tracer.ts (imported first at start-up).", "Datadog: ensure a Datadog agent is reachable via DD_AGENT_HOST." ] }, "sequelize": { "group": "orm", - "title": "Sequelize ORM", - "deps": { "@imqueue/sequelize": "*", "sequelize": "*" }, + "title": "Sequelize ORM + @imqueue/pg-sequelize toolkit", + "hint": "match a Sequelize fleet", + "pick": "For a service joining a fleet already built on Sequelize, where matching the existing stack is worth more than the default. Migrating the fleet to pg-prisma is worth proposing, as separate work.", + "deps": { "@imqueue/pg-sequelize": "*", "sequelize": "*" }, "instructions": [ "Sequelize: configure your database connection in config.ts." ] }, - "prisma": { + "pg-prisma": { "group": "orm", - "title": "Prisma ORM", - "deps": { "@prisma/client": "*" }, - "devDeps": { "prisma": "*" }, + "title": "Prisma ORM + @imqueue/pg-prisma toolkit", + "pick": "Recommended. Take this unless the fleet the service joins is already built on Sequelize.", + "deps": { + "@imqueue/pg-prisma": "*", + "@imqueue/validation": "*", + "@prisma/client": "*", + "@prisma/adapter-pg": "*", + "pg": "*", + "zod": "*" + }, + "devDeps": { "prisma": "*", "@types/pg": "*" }, + "env": ["DATABASE_URL"], + "instructions": [ + "pg-prisma: set DATABASE_URL, then run `npx prisma migrate dev` to create the database.", + "pg-prisma: edit prisma/schema.prisma and run `npx prisma generate` to (re)generate models." + ] + }, + "validation": { + "group": "features", + "title": "Input validation (@imqueue/validation)", + "deps": { "@imqueue/validation": "*", "zod": "*" }, + "instructions": [ + "validation: annotate argument classes with @validatable/@validate and methods with @validated." + ] + }, + "core": { + "group": "features", + "title": "@imqueue/core (direct dependency)", + "deps": { "@imqueue/core": "*" }, "instructions": [ - "Prisma: run `npx prisma init` and define your schema." + "core: @imqueue/core is otherwise pulled in transitively by @imqueue/rpc; add it directly only if you import from it." ] }, "pg-cache": { diff --git a/lib/config-schema.ts b/lib/config-schema.ts index 862e34e..47110c5 100644 --- a/lib/config-schema.ts +++ b/lib/config-schema.ts @@ -23,12 +23,18 @@ */ import type { IMQCLIConfig } from './config.js'; -export const DEFAULT_TEMPLATES_REF = 'v4'; +export const DEFAULT_TEMPLATES_REF = 'master'; export interface VcsConfig { provider?: string; namespace?: string; private?: boolean; + /** + * Git transport used for the commit/push at create time: `https` (default, + * authenticated with the access token) or `ssh` (uses the user's ssh + * keys/agent, no token injection). + */ + protocol?: 'ssh' | 'https'; auth?: { token?: string }; } diff --git a/lib/index.ts b/lib/index.ts index 7121d8b..5d3f509 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -38,4 +38,5 @@ export * from './travis.js'; export * from './template.js'; export * from './github.js'; export * from './node.js'; +export * from './ssh.js'; export * from './autoupdate.js'; diff --git a/lib/ssh.ts b/lib/ssh.ts new file mode 100644 index 0000000..23e1999 --- /dev/null +++ b/lib/ssh.ts @@ -0,0 +1,87 @@ +/*! + * @imqueue/cli library: ssh + * + * I'm Queue Software Project + * Copyright (C) 2026 imqueue.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you want to use this code in a closed source (commercial) project, you can + * purchase a proprietary commercial license. Please contact us at + * to get commercial licensing options. + */ +import { readdirSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +/** + * Default private key basenames created by `ssh-keygen` across algorithms. + * A `.pub` public key is also treated as evidence that keys are set up. + */ +const SSH_PRIVATE_KEY_NAMES = new Set([ + 'id_rsa', + 'id_dsa', + 'id_ecdsa', + 'id_ecdsa_sk', + 'id_ed25519', + 'id_ed25519_sk', + 'identity', +]); + +/** + * Returns the SSH directory examined for keys: the `IMQ_SSH_DIR` override + * (testing / non-standard homes) or `~/.ssh`. + * + * @return {string} + */ +export function sshDir(): string { + return process.env.IMQ_SSH_DIR || join(homedir(), '.ssh'); +} + +/** + * Detects whether the current machine user has any SSH keys set up, by looking + * for a conventional private key (id_rsa, id_ed25519, …) or any public + * (`*.pub`) key in the user's `.ssh` directory. Purely filesystem-based: it + * makes no network calls and spawns no processes, so it is fast and safe to + * call during interactive setup. + * + * @param {string} [dir] - ssh directory to inspect (defaults to `sshDir()`) + * @return {boolean} + */ +export function hasSshKeys(dir: string = sshDir()): boolean { + let entries: string[]; + + try { + entries = readdirSync(dir); + } catch { + // no ~/.ssh (or unreadable) -> no keys + return false; + } + + return entries.some( + entry => SSH_PRIVATE_KEY_NAMES.has(entry) || entry.endsWith('.pub'), + ); +} + +/** + * Chooses the git transport to default to for pushing new services: `ssh` when + * the user has SSH keys on this machine, otherwise `https`. This mirrors what + * the user is most likely already able to authenticate with. + * + * @param {string} [dir] - ssh directory to inspect (defaults to `sshDir()`) + * @return {'ssh' | 'https'} + */ +export function detectGitProtocol(dir?: string): 'ssh' | 'https' { + return hasSshKeys(dir) ? 'ssh' : 'https'; +} diff --git a/package-lock.json b/package-lock.json index a86806c..093ceb0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "@imqueue/cli", - "version": "4.0.0", + "version": "5.2.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@imqueue/cli", - "version": "4.0.0", + "version": "5.2.10", "license": "GPL-3.0-only", "dependencies": { - "@imqueue/rpc": "^3.2.1", + "@imqueue/rpc": "^3.9.5", "inquirer": "^8.2.6", "inquirer-autocomplete-prompt": "^1.4.0", "libsodium-wrappers": "^0.8.4", @@ -32,32 +32,41 @@ }, "engines": { "node": ">=22.12.0" + }, + "funding": { + "url": "https://imqueue.com/" } }, "node_modules/@imqueue/core": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/@imqueue/core/-/core-3.2.1.tgz", - "integrity": "sha512-iMRsXsHg9wS/vNKVw/2hVHdPfvzE6R8e5aAnE0n5bJyo7LP7MOgPGgb7rDpSbqVZwZoc7vJGeaW8MuBbDTJakQ==", + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/@imqueue/core/-/core-3.5.4.tgz", + "integrity": "sha512-fKtfe++2/Evp4gqq3a+2zbu7bO8RZNjjWLIXJTv2Q6P2KfKMQYx7UVnX0m1TurIYUospWybELynY7HyDrSRPyg==", "license": "GPL-3.0-only", "dependencies": { "ioredis": "^5.11.1" }, "engines": { "node": ">=22.12.0" + }, + "funding": { + "url": "https://imqueue.com/" } }, "node_modules/@imqueue/rpc": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/@imqueue/rpc/-/rpc-3.2.1.tgz", - "integrity": "sha512-K88g+ehGLym2ltTRvs+OJp9L2LqVKokbciS3vARuAN95KvzzEDNuFqmwiXGH06HBEwZgUHF32PKL5B3fSfheBA==", + "version": "3.9.5", + "resolved": "https://registry.npmjs.org/@imqueue/rpc/-/rpc-3.9.5.tgz", + "integrity": "sha512-k8Rr/pOvxf/Go1BuGCm6QrLhILi5dPdOG94emQ/Ozs8tpaRng8Uzm5FOM3FALW/4NIp9kztZd54dQq+3EOxWPw==", "license": "GPL-3.0-only", "dependencies": { - "@imqueue/core": "^3.2.1", + "@imqueue/core": "^3.5.4", "acorn": "^8.17.0", "typescript": "^7.0.2" }, "engines": { "node": ">=22.12.0" + }, + "funding": { + "url": "https://imqueue.com/" } }, "node_modules/@inquirer/external-editor": { diff --git a/package.json b/package.json index 5de487b..232605d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@imqueue/cli", - "version": "4.0.0", + "version": "5.2.10", "description": "Command line interface for @imqueue - scaffold Redis-RPC microservices, generate typed clients, and manage a local service fleet", "keywords": [ "command-line-tool", @@ -19,6 +19,7 @@ ], "scripts": { "prepare": "npm run build", + "postpublish": "gh api -X POST repos/imqueue/imqueue.com/dispatches -f event_type=cli-released >/dev/null 2>&1 && echo '→ notified imqueue.com to refresh the CLI User Guide' || echo 'note: could not notify imqueue.com (is gh installed & authed?) — trigger manually: gh api -X POST repos/imqueue/imqueue.com/dispatches -f event_type=cli-released'", "build": "npm run clean-compiled && tsc", "postbuild": "chmod +x index.js", "lint": "oxlint", @@ -41,11 +42,12 @@ "bugs": { "url": "https://github.com/imqueue/cli/issues" }, - "homepage": "https://imqueue.com/", + "homepage": "https://imqueue.org/", + "funding": "https://imqueue.com/", "author": "imqueue.com (https://imqueue.com)", "license": "GPL-3.0-only", "dependencies": { - "@imqueue/rpc": "^3.2.1", + "@imqueue/rpc": "^3.9.5", "inquirer": "^8.2.6", "inquirer-autocomplete-prompt": "^1.4.0", "libsodium-wrappers": "^0.8.4", diff --git a/src/catalog/fleet.ts b/src/catalog/fleet.ts new file mode 100644 index 0000000..dd5ff6f --- /dev/null +++ b/src/catalog/fleet.ts @@ -0,0 +1,721 @@ +/*! + * @imqueue/cli catalog: fleet analysis + * + * I'm Queue Software Project + * Copyright (C) 2026 imqueue.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you want to use this code in a closed source (commercial) project, you can + * purchase a proprietary commercial license. Please contact us at + * to get commercial licensing options. + */ +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + statSync, + writeFileSync, +} from 'fs'; +import { join } from 'path'; +import { VAR_HOME, resolve } from '../../lib/index.js'; + +/** + * How one member of a group can be recognised in an existing service. + * + * Any of the three is enough. They exist because the four groups leave three + * different kinds of trace: an addon shows up as a dependency, a CI provider as + * the config file it reads, and a VCS host only in the git remote. + */ +interface ProbeMember { + /** Catalog id, provider id — whatever the prompt for this group selects. */ + id: string; + /** + * A dependency in the service's package.json, or several. + * + * A list is how a renamed package stays detectable: every name the package + * has shipped under counts as evidence. Without that, the rename of an addon + * would make every service that has not migrated yet invisible to the probe, + * and the group would report nothing detected — no error, just a + * recommendation that steers a fleet off its own stack. + */ + dep?: string | string[]; + /** A path inside the service, file or directory. */ + files?: string[]; + /** A substring of a remote URL in the service's .git/config. */ + remote?: string; +} + +/** + * A one-of-many choice the fleet can answer instead of the user. + * + * Add a probe and the corresponding prompt starts proposing; nothing else needs + * to change. A choice that leaves no trace in an existing service cannot be + * probed this way and belongs absent rather than half-supported. + */ +interface GroupProbe { + /** Group id: a catalog group for `catalog` probes, else a name for the note. */ + group: string; + /** Human name for the group, for the note. */ + label: string; + /** + * `catalog` members are catalog package ids and reach the packages prompt + * through {@link fleetDefaults}; `setting` members are provider ids chosen by + * their own prompt and must NOT be handed to the catalog, which would reject + * them as unknown packages. + */ + kind: 'catalog' | 'setting'; + members: ProbeMember[]; + /** + * The member to propose when the fleet uses several, where the project + * recommends one. It also decides whether a fleet on something else is told + * that moving is worth considering. + * + * Without it a split fleet falls back to its own majority, which is the + * honest answer where the project has no preference: one git host or CI + * provider is not better than another, so those two probes leave it unset. + */ + recommended?: string; + /** + * What to recommend when the fleet says nothing at all. + * + * The recommendation is DYNAMIC: a fleet that already runs on something is + * its own recommendation, because matching it is what a new service joining + * it should do. This is the edge case underneath — an empty fleet, or one + * that uses nothing from this group — where the project's own preference is + * the only thing left to go on. + * + * Configured settings do not appear in that chain because they never reach a + * prompt: a `vcs.provider` or a `packages` list in the config is used + * outright, so there is nothing left to recommend. + */ + baseline: string; +} + +const PROBES: GroupProbe[] = [ + { + group: 'orm', + label: 'ORM', + kind: 'catalog', + members: [ + { + id: 'sequelize', + dep: ['@imqueue/pg-sequelize', '@imqueue/sequelize'], + }, + { id: 'pg-prisma', dep: '@imqueue/pg-prisma' }, + ], + recommended: 'pg-prisma', + baseline: 'pg-prisma', + }, + { + group: 'tracing', + label: 'tracing', + kind: 'catalog', + members: [ + { + id: 'opentelemetry', + dep: [ + '@imqueue/opentelemetry', + '@imqueue/opentelemetry-instrumentation-imqueue', + ], + }, + { + id: 'dd-trace', + dep: ['@imqueue/datadog', '@imqueue/dd-trace'], + }, + ], + recommended: 'opentelemetry', + baseline: 'opentelemetry', + }, + { + group: 'vcs', + label: 'VCS host', + kind: 'setting', + members: [ + { id: 'github', remote: 'github.com' }, + // Host rather than domain: GitLab and Bitbucket are both commonly + // self-hosted, and `gitlab.example.com` is still GitLab. A host that + // names none of them — GitHub Enterprise on a custom domain, say — + // leaves no evidence, which is reported as no evidence. + { id: 'gitlab', remote: 'gitlab' }, + { id: 'bitbucket', remote: 'bitbucket' }, + ], + baseline: 'github', + }, + { + group: 'ci', + label: 'CI provider', + kind: 'setting', + members: [ + { id: 'github-actions', files: ['.github/workflows'] }, + { id: 'circleci', files: ['.circleci/config.yml'] }, + { id: 'travis', files: ['.travis.yml', '.travis.yaml'] }, + ], + baseline: 'github-actions', + }, +]; + +/** What the fleet says about one exclusive group. */ +export interface GroupAnalysis { + /** Member id to propose, or `null` when the fleet says nothing useful. */ + propose: string | null; + /** Services using each member, by member id. */ + counts: Record; + /** + * `scan` when the directories were read, `cache` when a previous scan + * answered, `override` when the user's own contradicting choice did. + */ + source: 'scan' | 'cache' | 'override'; +} + +/** What a fleet scan found. */ +export interface FleetAnalysis { + /** Services found in the fleet. */ + services: number; + /** One entry per probed group, keyed by catalog group id. */ + groups: Record; +} + +interface FleetRecord { + /** Services using each member, keyed by group id then member id. */ + groups: Record>; + services: number; + /** Immediate subdirectory names at scan time — the staleness fingerprint. */ + dirs: string[]; + /** Member id the user picked against the scan, by group id. */ + overrides?: Record; + at: number; +} + +interface FleetCache { + version: number; + fleets: Record; +} + +// 2: per-group counts and overrides, where 1 held only the ORM. An older cache +// is discarded rather than migrated — it costs one scan to rebuild. +const CACHE_VERSION = 2; +// A fleet member is an @imqueue service, and every one of them depends on rpc. +// This is deliberately NOT lib/discoverServices(), which reads every .ts file +// under each candidate's src/ looking for a service class: these questions are +// answered by dependencies, and this runs before a prompt, so it has to be +// cheap. One package.json per subdirectory, no source parsing. +const RPC = '@imqueue/rpc'; + +/** + * Path of the analysis cache. Under VAR_HOME, so IMQ_CLI_HOME relocates it + * along with everything else the CLI writes — which is what lets tests use a + * sandbox rather than the developer's real cache. + * + * @return {string} + */ +export function fleetCachePath(): string { + return resolve(VAR_HOME, 'fleet.json'); +} + +/** + * Reads the cache, treating any damage as an empty cache. + * + * @return {FleetCache} + */ +function readCache(): FleetCache { + try { + const raw = JSON.parse(readFileSync(fleetCachePath(), 'utf8')); + + if (raw && raw.version === CACHE_VERSION && raw.fleets) { + return raw as FleetCache; + } + } catch { + /* missing, unreadable or from an older shape - start over */ + } + + return { version: CACHE_VERSION, fleets: {} }; +} + +/** + * Writes the cache, ignoring failure. + * + * @remarks + * A cache that cannot be written is a slower next run, not a broken one, so a + * read-only or full disk must not take `imq service create` down with it. + * + * @param {FleetCache} cache + */ +function writeCache(cache: FleetCache): void { + try { + mkdirSync(resolve(VAR_HOME), { recursive: true }); + writeFileSync(fleetCachePath(), JSON.stringify(cache, null, 2) + '\n'); + } catch { + /* the analysis just runs again next time */ + } +} + +/** + * Immediate subdirectory names of a path, sorted. + * + * @param {string} root + * @return {string[]} + */ +function subDirs(root: string): string[] { + if (!existsSync(root)) { + return []; + } + + const dirs: string[] = []; + + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (entry.name.startsWith('.') || entry.name === 'node_modules') { + continue; + } + + let isDir = entry.isDirectory(); + + if (entry.isSymbolicLink()) { + try { + isDir = statSync(join(root, entry.name)).isDirectory(); + } catch { + isDir = false; + } + } + + if (isDir) { + dirs.push(entry.name); + } + } + + return dirs.sort(); +} + +/** + * Every dependency name a package.json declares, runtime and dev. + * + * @param {string} dir + * @return {Set} + */ +function dependenciesOf(dir: string): Set { + try { + const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); + + return new Set([ + ...Object.keys(pkg.dependencies || {}), + ...Object.keys(pkg.devDependencies || {}), + ]); + } catch { + return new Set(); + } +} + +/** + * The remote URLs a service's git config names. + * + * @remarks + * Read straight out of `.git/config` rather than by shelling out to git: this + * runs once per service before a prompt, and a process per service is exactly + * the cost the cache exists to avoid. + * + * @param {string} dir + * @return {string} + */ +function gitRemotes(dir: string): string { + try { + return readFileSync(join(dir, '.git', 'config'), 'utf8'); + } catch { + return ''; + } +} + +/** + * Whether one service shows evidence of a member. + * + * @param {string} dir - the service directory + * @param {Set} deps - its declared dependencies + * @param {string} remotes - its .git/config contents + * @param {ProbeMember} member + * @return {boolean} + */ +function usesMember( + dir: string, + deps: Set, + remotes: string, + member: ProbeMember, +): boolean { + if (member.dep) { + const names = Array.isArray(member.dep) ? member.dep : [member.dep]; + + if (names.some(name => deps.has(name))) { + return true; + } + } + + if (member.files?.some(file => existsSync(join(dir, file)))) { + return true; + } + + return !!member.remote && remotes.includes(member.remote); +} + +/** + * Counts, for every probed group, how many services use each of its members. + * + * @param {string} root - directory holding the service directories + * @return {FleetRecord} + */ +function scan(root: string): FleetRecord { + const dirs = subDirs(root); + const groups: Record> = {}; + let services = 0; + + for (const probe of PROBES) { + groups[probe.group] = Object.fromEntries( + probe.members.map(m => [m.id, 0]), + ); + } + + for (const dir of dirs) { + const path = join(root, dir); + const deps = dependenciesOf(path); + + if (!deps.has(RPC)) { + continue; + } + + services++; + + // Read once per service, not once per member: three of the four probes + // want it and re-reading would make the scan four times the IO. + const remotes = gitRemotes(path); + + for (const probe of PROBES) { + for (const member of probe.members) { + if (usesMember(path, deps, remotes, member)) { + groups[probe.group][member.id]++; + } + } + } + } + + return { groups, services, dirs, at: Date.now() }; +} + +/** + * Decides what to propose for one group from its counts. + * + * @param {GroupProbe} probe + * @param {Record} counts + * @return {string | null} + */ +function proposeFor( + probe: GroupProbe, + counts: Record, +): string | null { + const used = probe.members.filter(m => (counts[m.id] || 0) > 0); + + if (!used.length) { + // Nothing in the fleet uses this group, and picking for the user here + // would add a capability nobody asked for. `(none)` stays. + return null; + } + + if (used.length === 1) { + return used[0].id; + } + + if (probe.recommended) { + return probe.recommended; + } + + // No recommendation to fall back on, so follow the fleet: the member most + // of it uses. A dead heat proposes nothing rather than breaking the tie on + // catalog order, which would look like advice and be arbitrary. + const [first, second] = [...used].sort( + (a, b) => (counts[b.id] || 0) - (counts[a.id] || 0), + ); + + return counts[first.id] === counts[second.id] ? null : first.id; +} + +/** + * Compares two directory listings. + * + * @param {string[]} a + * @param {string[]} b + * @return {boolean} + */ +function sameDirs(a: string[], b: string[]): boolean { + return a.length === b.length && a.every((name, i) => name === b[i]); +} + +/** + * Builds the public analysis from a record. + * + * @param {FleetRecord} record + * @param {boolean} fromCache + * @return {FleetAnalysis} + */ +function toAnalysis(record: FleetRecord, fromCache: boolean): FleetAnalysis { + const groups: Record = {}; + + for (const probe of PROBES) { + const counts = record.groups[probe.group] || {}; + const override = record.overrides?.[probe.group]; + + groups[probe.group] = { + propose: override || proposeFor(probe, counts), + counts, + source: override ? 'override' : fromCache ? 'cache' : 'scan', + }; + } + + return { services: record.services, groups }; +} + +/** + * Works out what a fleet is built on, for every group the prompt can propose in. + * + * @remarks + * Answers from the cache when it can. The cache is keyed by path and carries the + * subdirectory names it was built from, so a fleet that has gained or lost a + * directory is rescanned — one `readdir` to know, rather than a package.json per + * service. A user's own contradicting choice, recorded by + * {@link recordFleetChoices}, outranks both: they said it deliberately, and it + * survives later rescans until a scan agrees with it. + * + * @param {string} root - directory holding the service directories + * @return {FleetAnalysis} + */ +export function analyseFleet(root: string): FleetAnalysis { + const abs = resolve(root); + const cache = readCache(); + const cached = cache.fleets[abs]; + + if (cached && sameDirs(cached.dirs, subDirs(abs))) { + return toAnalysis(cached, true); + } + + const fresh = scan(abs); + + // An override is intent, not measurement, so it outlives a rescan — but + // once the fleet itself says what the user said, it has nothing left to + // override and would only mask a later change. + for (const [group, choice] of Object.entries(cached?.overrides || {})) { + const probe = PROBES.find(p => p.group === group); + + if (probe && proposeFor(probe, fresh.groups[group] || {}) !== choice) { + fresh.overrides = { ...fresh.overrides, [group]: choice }; + } + } + + cache.fleets[abs] = fresh; + writeCache(cache); + + return toAnalysis(fresh, false); +} + +/** + * The CATALOG ids to preselect. + * + * @remarks + * Catalog groups only. A provider id like `github` would be rejected by + * `validateSelection` as an unknown package, and rightly — it is not one. + * + * @param {FleetAnalysis} analysis + * @return {string[]} + */ +export function fleetDefaults(analysis: FleetAnalysis): string[] { + return PROBES.filter(probe => probe.kind === 'catalog') + .map(probe => analysis.groups[probe.group]?.propose) + .filter((id): id is string => !!id); +} + +/** + * What to mark as recommended for one group. + * + * @remarks + * The fleet first: a fleet already running on something IS the recommendation, + * because a new service joining it should match it. Only when the fleet says + * nothing does the project's own preference apply — pg-prisma, opentelemetry, + * github, github-actions. + * + * This is a LABEL, not the pre-selection. For the optional groups the cursor + * still opens on `(none)` when the fleet is silent: a service that needs no + * database is not a service that chose wrongly. + * + * @param {FleetAnalysis | null} analysis + * @param {string} group + * @return {string | null} + */ +export function recommendedFor( + analysis: FleetAnalysis | null, + group: string, +): string | null { + const probe = PROBES.find(p => p.group === group); + + if (!probe) { + return null; + } + + return fleetProposal(analysis, group) || probe.baseline; +} + +/** + * What the fleet proposes for one group, or `null` when it says nothing. + * + * @remarks + * For the choices with their own prompt — the VCS host and the CI provider — + * where the caller supplies its own default to fall back on. + * + * @param {FleetAnalysis | null} analysis + * @param {string} group + * @return {string | null} + */ +export function fleetProposal( + analysis: FleetAnalysis | null, + group: string, +): string | null { + return analysis?.groups[group]?.propose || null; +} + +/** + * One line per group explaining what was proposed and why, for the prompt. + * + * @remarks + * Keyed by catalog group id, and a group the fleet says nothing about gets no + * entry — silence is the right output when there is nothing to report. + * + * @param {FleetAnalysis} analysis + * @return {Record} + */ +export function fleetNotes(analysis: FleetAnalysis): Record { + const notes: Record = {}; + + for (const probe of PROBES) { + const group = analysis.groups[probe.group]; + + if (!group?.propose) { + const used = probe.members.filter( + m => (group?.counts[m.id] || 0) > 0, + ); + + // A dead heat is worth saying out loud: the fleet is genuinely + // divided, and the user is the one to settle it. + if (used.length > 1) { + notes[probe.group] = + `This fleet is split evenly between ` + + `${used.map(m => m.id).join(' and ')} — your call.`; + } + + continue; + } + + const from = + group.source === 'override' + ? 'your earlier choice here' + : `${analysis.services} service${ + analysis.services === 1 ? '' : 's' + } in this fleet`; + const split = probe.members.filter(m => (group.counts[m.id] || 0) > 0); + let note: string; + + if (group.source !== 'override' && split.length > 1) { + const detail = split + .map(m => `${group.counts[m.id]} on ${m.id}`) + .join(', '); + + note = probe.recommended + ? `This fleet uses more than one ${probe.label} (${detail}); ` + + `preselected the recommended one.` + : `This fleet uses more than one ${probe.label} (${detail}); ` + + `preselected the one most of it uses.`; + } else { + note = `Preselected ${group.propose} to match ${from}.`; + } + + // Where the project recommends something else, say so — proposing what + // the fleet uses is not the same as endorsing it forever. + if (probe.recommended && group.propose !== probe.recommended) { + note += + ` Moving the fleet to ${probe.recommended} is worth ` + + 'considering — as its own piece of work, not as part of this.'; + } + + notes[probe.group] = note; + } + + return notes; +} + +/** + * The note for one group, ready to append to a prompt message, or `''`. + * + * @param {FleetAnalysis | null} analysis + * @param {string} group + * @return {string} + */ +export function fleetNote( + analysis: FleetAnalysis | null, + group: string, +): string { + return analysis ? fleetNotes(analysis)[group] || '' : ''; +} + +/** + * Records selections that contradict the scan, so the next run proposes what the + * user actually wants. + * + * @remarks + * Only a contradiction is written. Agreeing with the scan is not an instruction, + * and storing it would make an override out of a shrug. Selecting nothing from a + * group is not a contradiction either: it says the service does not need that + * capability, not that the fleet is built differently. + * + * @param {string} root - directory holding the service directories + * @param {string[]} selection - the resolved catalog ids + */ +export function recordFleetChoices(root: string, selection: string[]): void { + const abs = resolve(root); + const cache = readCache(); + const record = cache.fleets[abs]; + + if (!record) { + return; + } + + let changed = false; + + for (const probe of PROBES) { + const chosen = probe.members.find(m => selection.includes(m.id))?.id; + + if (!chosen) { + continue; + } + + const effective = + record.overrides?.[probe.group] || + proposeFor(probe, record.groups[probe.group] || {}); + + if (effective === chosen) { + continue; + } + + record.overrides = { ...record.overrides, [probe.group]: chosen }; + changed = true; + } + + if (changed) { + record.at = Date.now(); + cache.fleets[abs] = record; + writeCache(cache); + } +} diff --git a/src/catalog/resolve.ts b/src/catalog/resolve.ts index 8846b9d..b5bb203 100644 --- a/src/catalog/resolve.ts +++ b/src/catalog/resolve.ts @@ -23,6 +23,13 @@ */ import inquirer, { type QuestionCollection } from 'inquirer'; import type { Catalog } from './types.js'; +import { + analyseFleet, + fleetDefaults, + fleetNotes, + recommendedFor, + recordFleetChoices, +} from './fleet.js'; /** * Lists the catalog package ids that belong to a group, in catalog order. @@ -121,11 +128,18 @@ export function parsePackagesFlag(flag: any): string[] | null { * * @param {Catalog} catalog * @param {string[]} defaults - ids to pre-select + * @param {Record} [notes] - extra line per group id, shown above + * its list; used to say why something + * is preselected + * @param {Record} [recommended] - member id per group id to mark + * as recommended * @return {Promise} */ export async function promptPackages( catalog: Catalog, defaults: string[], + notes: Record = {}, + recommended: Record = {}, ): Promise { const chosen: string[] = []; @@ -138,15 +152,36 @@ export async function promptPackages( } if (group.exclusive) { + // The group's own guidance goes above the list, and each choice + // carries its short hint. Without them the prompt showed bare + // titles, so everything `imq service packages` explains about + // choosing was missing at the one moment the choice is made. const answer = await inquirer.prompt<{ sel: string }>([ { type: 'list', name: 'sel', - message: `Select ${group.title}:`, + message: + `Select ${group.title}:` + + (group.pick ? `\n ${group.pick}` : '') + + (notes[groupId] ? `\n ${notes[groupId]}` : ''), choices: [ { name: '(none)', value: '' }, + // "(recommended)" is appended here rather than stored + // in the catalog because WHICH member is recommended + // depends on the fleet: in a Sequelize fleet, sequelize + // is the recommendation. Only the fallback is fixed. + // One suffix, never both: a title plus a hint plus the + // marker runs past 80 columns, and a wrapped row breaks + // an arrow-key list. Being recommended IS the case this + // option suits, so it supersedes the hint. ...ids.map(id => ({ - name: catalog.packages[id].title || id, + name: + (catalog.packages[id].title || id) + + (recommended[groupId] === id + ? ' (recommended)' + : catalog.packages[id].hint + ? ` — ${catalog.packages[id].hint}` + : ''), value: id, })), ], @@ -183,11 +218,21 @@ export async function promptPackages( * flag (--packages/--no-packages) -> per-service -> global -> prompt -> none, * then validates it against the catalog. * + * When a fleet root is given, every exclusive group the fleet can answer for is + * preselected from what its services already use — the ORM and the tracing + * backend today. A group nothing in the fleet uses preselects nothing. + * + * That applies to the PROMPT only. A non-interactive run with no flag and no + * configured packages still selects nothing: a proposal a user can decline is + * one thing, and quietly adding a database dependency to an automated run is + * another. + * * @param {any} flag - raw --packages flag value * @param {string[] | undefined} service - per-service packages * @param {string[] | undefined} global - global-config packages * @param {Catalog} catalog * @param {boolean} interactive + * @param {string} [fleetRoot] - directory holding the sibling services * @return {Promise} */ export async function resolvePackages( @@ -196,8 +241,13 @@ export async function resolvePackages( global: string[] | undefined, catalog: Catalog, interactive: boolean, + fleetRoot?: string, ): Promise { let selection = parsePackagesFlag(flag); + // Only a choice made HERE — by flag or at the prompt — is worth remembering + // against this path. Configured packages are already a standing decision, + // and turning one into a per-fleet override would spread it silently. + let deliberate = selection !== null; if (selection === null && Array.isArray(service)) { selection = service; @@ -207,9 +257,41 @@ export async function resolvePackages( selection = global; } + // Run whenever a fleet root is known, not only before a prompt: a run that + // takes its ORM from --packages still needs the record to exist for + // recordOrmChoice() to write an override against. A cache hit costs one + // readdir. + const analysis = fleetRoot ? analyseFleet(fleetRoot) : null; + if (selection === null) { - selection = interactive ? await promptPackages(catalog, []) : []; + if (interactive) { + const advice: Record = {}; + + for (const group of Object.keys(catalog.groups)) { + const pick = recommendedFor(analysis, group); + + if (pick) { + advice[group] = pick; + } + } + + selection = await promptPackages( + catalog, + analysis ? fleetDefaults(analysis) : [], + analysis ? fleetNotes(analysis) : {}, + advice, + ); + deliberate = true; + } else { + selection = []; + } + } + + const validated = validateSelection(selection, catalog); + + if (fleetRoot && deliberate) { + recordFleetChoices(fleetRoot, validated); } - return validateSelection(selection, catalog); + return validated; } diff --git a/src/catalog/types.ts b/src/catalog/types.ts index 876054d..1ec5974 100644 --- a/src/catalog/types.ts +++ b/src/catalog/types.ts @@ -29,17 +29,63 @@ export interface CatalogGroup { title: string; exclusive: boolean; + /** + * When the group applies at all, for the groups where picking nothing is a + * normal answer rather than an omission. + * + * `exclusive` already means "at most one", and the prompt offers `(none)` + * as its default — but a list of options with per-option guidance and no + * word about skipping reads as a question you have to answer. A service + * with no database wants no ORM; a service nobody traces wants no tracing. + * Saying so is what stops a caller — an AI agent especially — picking one + * because one appeared to be required. + */ + pick?: string; } /** * A single installable addon. Effects are all optional so an entry can be a * pure dependency, a code-injecting addon, or anything in between. + * + * What belongs here is an INTEGRATED option: something the scaffolder wires into + * the service. A bare dependency that a user could add with `npm i` and get the + * same result does not need an entry, and having one makes a recommended list + * read like a menu of equals — a bare `prisma` addon sat next to `pg-prisma` + * for exactly that reason and was removed. Bespoke setups are what the + * custom-templates mechanism is for; the catalog carries the recommended path. */ export interface CatalogEntry { /** group id this entry belongs to */ group: string; /** human title (defaults to the entry id when absent) */ title?: string; + /** + * When to pick this one over the others in its group. + * + * Exists for exclusive groups, where the title alone leaves a caller — an + * AI agent especially — to guess between two entries that both sound + * right. `imq service create` is by definition a NEW service, so a group + * with a default should say so here rather than leave it implied. + * + * One sentence, imperative, and about the CHOICE rather than about setup: + * anything to do after installing belongs in `instructions`. + */ + pick?: string; + /** + * A few words of the same guidance, for the selection prompt. + * + * `pick` is a sentence or two and belongs in `imq service packages`, where + * there is room to read. A prompt renders one line per choice and wraps + * badly past the terminal width, which garbles an arrow-key list — so the + * prompt gets this instead. Keep it under about 30 characters and phrase it + * as the case it suits, e.g. "recommended" or "match a Sequelize fleet". + * + * Beware of a discriminator that does not discriminate: "new services" was + * useless here, because `imq service create` only ever creates a new + * service. What varies between two callers is the stack the fleet already + * runs on, so that is what the guidance has to name. + */ + hint?: string; /** runtime dependencies to merge into the service package.json */ deps?: Record; /** dev dependencies to merge into the service package.json */ diff --git a/src/config/init.ts b/src/config/init.ts index 41a8421..39cbe37 100644 --- a/src/config/init.ts +++ b/src/config/init.ts @@ -36,6 +36,9 @@ import { loadTemplates, loadTemplate, licensingOptions, + detectGitProtocol, + hasSshKeys, + sshDir, } from '../../lib/index.js'; import { ciProviders, @@ -526,9 +529,50 @@ export async function vcsHostOptions(config: IMQCLIConfig): Promise { if (config.useGit) { config.vcs = { ...config.vcs, provider: answer.provider }; + await gitProtocolOptions(config); } } +/** + * Chooses the git transport for pushing new services. The default is + * auto-detected from whether the machine user has SSH keys (SSH when present, + * HTTPS otherwise); the detection is reported and the user can override it. + * + * @param {IMQCLIConfig} config + */ +export async function gitProtocolOptions(config: IMQCLIConfig): Promise { + const detected = detectGitProtocol(); + const reason = hasSshKeys() + ? `SSH keys were found in ${sshDir()}` + : `no SSH keys were found in ${sshDir()}`; + + console.log( + styleText( + 'gray', + `Detected git transport for pushes: ` + + `${styleText('cyan', detected)} (${reason}).`, + ), + ); + + const answer = await inquirer.prompt<{ protocol: 'ssh' | 'https' }>([ + { + type: 'list', + name: 'protocol', + message: 'Git transport for pushing new services:', + choices: [ + { + name: 'HTTPS (authenticated with your access token)', + value: 'https', + }, + { name: 'SSH (uses your ssh keys)', value: 'ssh' }, + ], + default: detected, + }, + ]); + + config.vcs = { ...config.vcs, protocol: answer.protocol }; +} + export async function ciOptions(config: IMQCLIConfig): Promise { registerBuiltinProviders(); diff --git a/src/config/set.ts b/src/config/set.ts index 13a291f..e78b72e 100644 --- a/src/config/set.ts +++ b/src/config/set.ts @@ -82,6 +82,16 @@ function validateProvider(option: string, value: unknown): void { `Valid: ${spec.registry.ids().join(', ')}.`, ); } + + // enum-valued structured key: git transport for the create-time push + if ( + option === 'vcs.protocol' && + typeof value === 'string' && + value !== 'https' && + value !== 'ssh' + ) { + throw new Error(`Invalid git protocol "${value}". Valid: https, ssh.`); + } } /** diff --git a/src/providers/ci/github-actions.ts b/src/providers/ci/github-actions.ts index a3abcec..35721fe 100644 --- a/src/providers/ci/github-actions.ts +++ b/src/providers/ci/github-actions.ts @@ -30,35 +30,98 @@ import type { import { Github } from '../../../lib/index.js'; import { registryOf, registryShellTokens } from './common.js'; -const TEST_JOB = `name: Build +// Composite action shared by all jobs: pins Node and installs deps once so +// every job resolves dependencies identically (mirrors the @imqueue service +// convention of a `./.github/actions/setup` step). +const SETUP_ACTION = `name: Setup +description: Install Node and project dependencies. + +runs: + using: composite + steps: + - uses: actions/setup-node@v5 + with: + node-version: %GHA_NODE_PRIMARY + cache: npm + + - name: Install dependencies + shell: bash + run: npm ci --prefer-offline --no-audit --no-fund +`; + +const TEST_JOB = `name: CI on: push: branches: ['**'] tags: ['**'] pull_request: +permissions: + contents: read + +concurrency: + group: ci-\${{ github.ref }} + cancel-in-progress: true + jobs: + lint: + name: Lint & format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup + - run: npm run lint + - run: npm run format:check + + typecheck: + name: Typecheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup + - run: npm run typecheck + test: + name: Unit tests runs-on: ubuntu-latest - strategy: - matrix: - node-version: %GHA_NODE_MATRIX steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup + - run: npm run test:unit + + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup + - run: npm run build:bundle + - name: Upload build output + uses: actions/upload-artifact@v4 with: - node-version: \${{ matrix.node-version }} - - run: npm ci - - run: npm test + name: build + path: build + retention-days: 1 + if-no-files-found: error `; const DOCKER_JOB = ` docker: - needs: test + name: Build & push image + needs: [lint, typecheck, test, build] if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + + # reuse the exact deploy bundle produced (and verified) by the build job; + # the Dockerfile COPYs build/ in rather than compiling inside the image + - name: Download build output + uses: actions/download-artifact@v4 + with: + name: build + path: build + - name: Build and push image env: %GHA_SECRETS_ENV @@ -81,11 +144,18 @@ export const githubActions: CiProvider = { files(ctx: CreateContext): FileFragment[] { const content = ctx.dockerize ? TEST_JOB + DOCKER_JOB : TEST_JOB; - return [{ relPath: '.github/workflows/build.yml', content }]; + return [ + { relPath: '.github/workflows/ci.yml', content }, + { + relPath: '.github/actions/setup/action.yml', + content: SETUP_ACTION, + }, + ]; }, tokens(ctx: CreateContext): Record { const tokens: Record = { + GHA_NODE_PRIMARY: ctx.nodeTags[0] || 'lts/*', GHA_NODE_MATRIX: `[${ctx.nodeTags.map(t => `'${t}'`).join(', ')}]`, IMAGE_REF: '', REGISTRY_LOGIN: '', diff --git a/src/providers/scm/git.ts b/src/providers/scm/git.ts index e088551..bc13106 100644 --- a/src/providers/scm/git.ts +++ b/src/providers/scm/git.ts @@ -22,7 +22,7 @@ * to get commercial licensing options. */ import { execFileSync } from 'child_process'; -import type { CreateContext, ScmProvider } from '../types.js'; +import type { CreateContext, ScmAuth, ScmProvider } from '../types.js'; import { commandExists } from '../../../lib/index.js'; /** @@ -33,7 +33,11 @@ export const git: ScmProvider = { id: 'git', title: 'Git', - async initAndPush(ctx: CreateContext, remoteUrl: string): Promise { + async initAndPush( + ctx: CreateContext, + remoteUrl: string, + auth?: ScmAuth, + ): Promise { if (!commandExists('git')) { throw new Error('Git command expected, but is not installed!'); } @@ -41,6 +45,30 @@ export const git: ScmProvider = { // no shell: urls/branches cannot be injected const run = (...args: string[]) => execFileSync('git', args, { cwd: ctx.path, stdio: 'inherit' }); + + // When an access token is supplied for an HTTPS remote, authenticate + // the push with it instead of relying on the user's ssh keys or git + // credential helper. This is the same token that just created the + // repository, so it is guaranteed to have write access - which the + // user's ssh identity (or a different active account) may not. + // + // The credential is passed via a per-invocation `-c http.extraHeader` + // so it is NEVER written into the repository's .git/config (the remote + // url stays clean and token-free). It applies only to https requests. + const authArgs = + auth && /^https:\/\//i.test(remoteUrl) + ? [ + '-c', + `http.extraHeader=Authorization: Basic ${Buffer.from( + `${auth.user}:${auth.token}`, + ).toString('base64')}`, + ] + : []; + const push = (...args: string[]) => + execFileSync('git', [...authArgs, 'push', ...args], { + cwd: ctx.path, + stdio: 'inherit', + }); const tag = `v${ctx.version}`; console.log('Committing changes...'); @@ -63,7 +91,7 @@ export const git: ScmProvider = { .trim() || 'main'; run('remote', 'add', 'origin', remoteUrl); - run('push', 'origin', branch); + push('origin', branch); console.log('Setting up version tag...'); @@ -74,12 +102,12 @@ export const git: ScmProvider = { } try { - run('push', 'origin', `:refs/tags/${tag}`); + push('origin', `:refs/tags/${tag}`); } catch { /* no remote tag to drop */ } run('tag', '-fa', tag, '-m', `Tagging version ${tag}`); - run('push', 'origin', branch, '--tags'); + push('origin', branch, '--tags'); }, }; diff --git a/src/providers/types.ts b/src/providers/types.ts index ec067c3..b3f9c39 100644 --- a/src/providers/types.ts +++ b/src/providers/types.ts @@ -114,13 +114,34 @@ export interface VcsHostProvider extends Provider { /** optional rollback of a repository this run created */ deleteRepository?(ctx: CreateContext): Promise; authSpec: AuthSpec; + /** + * Basic-auth username to pair with the access token when pushing over + * HTTPS (the token goes in the password field). Host-specific: + * `x-access-token` (GitHub), `oauth2` (GitLab), `x-token-auth` + * (Bitbucket). Absent means the host has no token-over-HTTPS push scheme. + */ + httpAuthUser?: string; +} + +/** + * Credentials for an HTTPS git push: the basic-auth username plus the access + * token used as the password. Injected ephemerally per push so the token is + * never persisted into the repository's git config. + */ +export interface ScmAuth { + user: string; + token: string; } /** * Source control tool operating on the local working copy (git only, for now). */ export interface ScmProvider extends Provider { - initAndPush(ctx: CreateContext, remoteUrl: string): Promise; + initAndPush( + ctx: CreateContext, + remoteUrl: string, + auth?: ScmAuth, + ): Promise; } /** diff --git a/src/providers/vcs/bitbucket.ts b/src/providers/vcs/bitbucket.ts index 9793b25..eed377f 100644 --- a/src/providers/vcs/bitbucket.ts +++ b/src/providers/vcs/bitbucket.ts @@ -74,6 +74,10 @@ export const bitbucket: VcsHostProvider = { authSpec: { path: 'vcs.auth.token', describe: 'Bitbucket access token' }, + // Bitbucket HTTPS basic-auth for workspace/repo access tokens: username + // `x-token-auth`, the token as the password + httpAuthUser: 'x-token-auth', + remoteUrl( namespace: string, name: string, diff --git a/src/providers/vcs/github.ts b/src/providers/vcs/github.ts index 0a63bde..8ad3d47 100644 --- a/src/providers/vcs/github.ts +++ b/src/providers/vcs/github.ts @@ -37,6 +37,10 @@ export const github: VcsHostProvider = { describe: 'GitHub auth token', }, + // GitHub HTTPS basic-auth: any username with the token as the password; + // `x-access-token` is the documented convention (matches actions/checkout) + httpAuthUser: 'x-access-token', + remoteUrl( namespace: string, name: string, diff --git a/src/providers/vcs/gitlab.ts b/src/providers/vcs/gitlab.ts index 74230de..6d3b36d 100644 --- a/src/providers/vcs/gitlab.ts +++ b/src/providers/vcs/gitlab.ts @@ -72,6 +72,10 @@ export const gitlab: VcsHostProvider = { authSpec: { path: 'vcs.auth.token', describe: 'GitLab access token' }, + // GitLab HTTPS basic-auth: username `oauth2`, personal/project access + // token as the password + httpAuthUser: 'oauth2', + remoteUrl( namespace: string, name: string, diff --git a/src/service/create-pipeline.ts b/src/service/create-pipeline.ts index ae4517a..5aaead7 100644 --- a/src/service/create-pipeline.ts +++ b/src/service/create-pipeline.ts @@ -23,7 +23,7 @@ */ import { styleText } from 'node:util'; import { execFileSync } from 'child_process'; -import { rmSync } from 'fs'; +import { readFileSync, rmSync } from 'fs'; import { join } from 'path'; import { DEFAULT_TEMPLATES_REF, @@ -53,6 +53,7 @@ import { createServiceFile, createServiceTestFile, ensureTemplate, + generateAddons, isEsmService, loadTemplateManifest, overlayFragments, @@ -86,7 +87,8 @@ export function printPlanSummary(plan: CreatePlan): void { 'vcs', plan.useVcs ? `${plan.config.vcs.provider} (${plan.config.vcs.namespace}, ` + - `${plan.config.vcs.private ? 'private' : 'public'})` + `${plan.config.vcs.private ? 'private' : 'public'}, ` + + `${plan.config.vcs.protocol === 'ssh' ? 'ssh' : 'https'})` : styleText('gray', 'disabled'), ); line('ci', plan.config.ci.provider || styleText('gray', 'none')); @@ -242,16 +244,95 @@ export async function applyCi( } /** - * Installs the service dependencies exactly as declared by the template's - * package.json. + * Every package.json dependency section npm can persist to, paired with the + * `npm install --save-*` flag that targets it. A custom template may declare + * any subset of these, so all are handled uniformly rather than just prod/dev. + * + * (`bundleDependencies` is intentionally absent: it is a bare array of names + * already listed in `dependencies`, carries no version to resolve, and has no + * standalone `--save-*` install target - `--save-bundle` only augments another + * save.) + */ +const DEP_SECTIONS: ReadonlyArray<{ + field: string; + flag: string; + label: string; +}> = [ + { field: 'dependencies', flag: '--save-prod', label: 'dependencies' }, + { field: 'devDependencies', flag: '--save-dev', label: 'dev dependencies' }, + { + field: 'optionalDependencies', + flag: '--save-optional', + label: 'optional dependencies', + }, + { + field: 'peerDependencies', + flag: '--save-peer', + label: 'peer dependencies', + }, +]; + +/** + * Installs the service dependencies declared by the template's package.json + * (plus any merged from the addon catalog). + * + * The template and catalog declare every dependency with a `"*"` placeholder + * version - resolving those into real, pinned versions is precisely what this + * step is for. A plain `npm install` would honor the `"*"` and leave it written + * back verbatim, so we install by name with the matching `--save-*` flag + * (exactly as `npm i --save ...` does), which resolves each package to its + * current release and rewrites package.json with a concrete caret range. A + * concrete range that a template author pinned deliberately is preserved as-is. + * + * Each npm dependency section (`dependencies`, `devDependencies`, + * `optionalDependencies`, `peerDependencies`) is installed with its own + * `--save-*` flag, so a custom template using any of them is fully supported. */ function installPackages(plan: CreatePlan): void { if (!commandExists('npm')) { throw new Error('npm command is not installed!'); } - console.log('Installing dependencies...'); - execFileSync('npm', ['install'], { cwd: plan.path, stdio: 'inherit' }); + const pkg = JSON.parse( + readFileSync(join(plan.path, 'package.json'), 'utf8'), + ); + // "*" / "x" / "latest" (and an empty value) mean "resolve the current + // version" -> install by bare name so npm pins it; a real range is kept. + const toSpecs = (deps: unknown): string[] => + deps && typeof deps === 'object' + ? Object.entries(deps as Record).map( + ([name, range]) => + !range || + range === '*' || + range === 'x' || + range === 'latest' + ? name + : `${name}@${range}`, + ) + : []; + + const npm = (args: string[]): void => { + execFileSync('npm', args, { cwd: plan.path, stdio: 'inherit' }); + }; + + let installedAny = false; + + for (const { field, flag, label } of DEP_SECTIONS) { + const specs = toSpecs(pkg[field]); + + if (specs.length) { + console.log(`Installing ${label}...`); + npm(['install', flag, ...specs]); + installedAny = true; + } + } + + // no declared dependencies at all (unusual) - still materialize + // node_modules and a lockfile so the service is runnable. + if (!installedAny) { + console.log('Installing dependencies...'); + npm(['install']); + } } /** @@ -274,6 +355,7 @@ export function writeServiceConfig(plan: CreatePlan): void { provider: vcs.provider, namespace: vcs.namespace, private: vcs.private, + protocol: vcs.protocol, }) : undefined, ci: ci.provider ? { provider: ci.provider } : undefined, @@ -331,6 +413,18 @@ export async function runCreate( // merge addon dependencies into the (now compiled) package.json mergeDependencies(plan.path, addons.deps, addons.devDeps); + // generate addon files that need real (conditional) code rather than inline + // catalog snippets: OpenTelemetry setup and the full pg-prisma persistence + // layer (schema, config, request-context, extended client), plus the + // native-decorator tsconfig / package.json wiring they require + generateAddons( + plan.path, + plan.license.header, + plan.config.packages, + isV2, + plan.name, + ); + // v1 templates lack %ADDON token points, so code snippets can't inject if (addons.hasSnippets && !isV2) { console.log( @@ -407,14 +501,33 @@ export async function runCreate( if (state.repoCreated) { const vcs = vcsHosts.get(plan.config.vcs.provider as string); const scm = scmTools.get('git'); - // IMQ_GIT_REMOTE_BASE overrides the push target (custom/self-hosted - // git or integration testing); otherwise use the host's ssh url + // Transport selection: + // - IMQ_GIT_REMOTE_BASE overrides the target entirely (custom/ + // self-hosted git or integration testing); pushed as given. + // - `https` (default): push over HTTPS authenticated with the access + // token we already hold. Chosen as the default because that token + // just created the repo, so it is guaranteed to have write access - + // whereas the user's ssh identity (or a different active git/gh + // account) frequently does not, which surfaced as a misleading + // "Repository not found" on push. + // - `ssh`: push over the host's ssh url using the user's ssh + // keys/agent; the token is NOT injected. const remoteBase = process.env.IMQ_GIT_REMOTE_BASE; + const protocol = plan.config.vcs.protocol === 'ssh' ? 'ssh' : 'https'; + const token = plan.config.vcs.auth?.token; const remoteUrl = remoteBase ? `${remoteBase.replace(/\/+$/, '')}/${plan.name}.git` - : vcs.remoteUrl(plan.config.vcs.namespace as string, plan.name); - - await scm.initAndPush(plan, remoteUrl); + : vcs.remoteUrl( + plan.config.vcs.namespace as string, + plan.name, + protocol, + ); + const auth = + !remoteBase && protocol === 'https' && vcs.httpAuthUser && token + ? { user: vcs.httpAuthUser, token } + : undefined; + + await scm.initAndPush(plan, remoteUrl, auth); } // 7. REPORT diff --git a/src/service/create-plan.ts b/src/service/create-plan.ts index 24b12e2..13295bb 100644 --- a/src/service/create-plan.ts +++ b/src/service/create-plan.ts @@ -22,6 +22,7 @@ * to get commercial licensing options. */ import * as os from 'os'; +import { dirname } from 'path'; import * as semver from 'semver'; import inquirer, { type QuestionCollection } from 'inquirer'; import { @@ -41,6 +42,14 @@ import type { CreateContext } from '../providers/types.js'; import { type ResolvedLicense, resolveLicense } from './create-scaffold.js'; import { loadCatalog } from '../catalog/load.js'; import { resolvePackages } from '../catalog/resolve.js'; +import { + type FleetAnalysis, + analyseFleet, + fleetNote, + fleetProposal, + recommendedFor, + recordFleetChoices, +} from '../catalog/fleet.js'; import { ciProviders, containerRegistries, @@ -201,6 +210,33 @@ async function resolveNodeTags( return toTravisTags(tags); } +/** + * Resolves the git transport for the create-time commit/push: an explicit + * `--git-protocol` flag wins, then a configured `vcs.protocol`, then the + * `https` default. Validates the value so a bad config fails clearly rather + * than silently falling back. + * + * @param {any} argv + * @param {StructuredConfig} structured + * @return {'ssh' | 'https'} + */ +function resolveGitProtocol( + argv: any, + structured: StructuredConfig, +): 'ssh' | 'https' { + const raw = String(argv.gitProtocol || structured.vcs.protocol || 'https') + .trim() + .toLowerCase(); + + if (raw !== 'ssh' && raw !== 'https') { + throw new TypeError( + `Invalid git protocol "${raw}". Use "https" (default) or "ssh".`, + ); + } + + return raw; +} + /** * Resolves the VCS section (namespace/token/private) when git integration is * enabled, prompting only interactively; throws with a clear message when a @@ -210,28 +246,44 @@ async function resolveVcsProvider( argv: any, structured: StructuredConfig, interactive: boolean, + fleet: FleetAnalysis | null = null, ): Promise { registerBuiltinProviders(); let id = (argv.vcs || '').trim() || structured.vcs.provider || ''; if (!id) { + // The fleet's own git remotes answer this better than a constant does: + // a service joining services hosted on GitLab is going on GitLab. + const proposed = fleetProposal(fleet, 'vcs'); + const note = fleetNote(fleet, 'vcs'); + // What the fleet runs on, or the project's own preference when the fleet + // is silent — never a fixed label, since a fleet on GitLab recommends + // GitLab. + const advised = recommendedFor(fleet, 'vcs'); + if (interactive) { const answer = await inquirer.prompt<{ vcs: string }>([ { type: 'list', name: 'vcs', - message: 'Select VCS host:', - choices: vcsHosts - .list() - .map(p => ({ name: p.title, value: p.id })), - default: DEFAULT_VCS, + message: 'Select VCS host:' + (note ? `\n ${note}` : ''), + choices: vcsHosts.list().map(p => ({ + name: + p.title + + (advised === p.id ? ' (recommended)' : ''), + value: p.id, + })), + default: proposed || DEFAULT_VCS, }, ] as QuestionCollection); id = answer.vcs; } else { - id = DEFAULT_VCS; + // Unlike a package, a VCS host is not an added capability: one is + // picked either way, so following the fleet beats following a + // constant even without a prompt. + id = proposed || DEFAULT_VCS; } } @@ -356,6 +408,7 @@ async function resolveCi( structured: StructuredConfig, vcsProvider: string, interactive: boolean, + fleet: FleetAnalysis | null = null, ): Promise { registerBuiltinProviders(); @@ -377,15 +430,33 @@ async function resolveCi( .list() .filter(p => compatible(p.id)) .map(p => ({ name: p.title, value: p.id })); + // Proposed from the CI config files the fleet's services carry — but + // only if it survives the VCS compatibility filter, which is the harder + // constraint: Travis with a cloud registry is rejected outright further + // down, so proposing an incompatible provider would just move the error. + const proposed = fleetProposal(fleet, 'ci'); + const fromFleet = + proposed && choices.some(c => c.value === proposed) + ? proposed + : null; + const note = fromFleet ? fleetNote(fleet, 'ci') : ''; + const advisedCi = recommendedFor(fleet, 'ci'); if (interactive && choices.length) { const answer = await inquirer.prompt<{ ci: string }>([ { type: 'list', name: 'ci', - message: 'Select CI provider:', - choices, + message: + 'Select CI provider:' + (note ? `\n ${note}` : ''), + choices: choices.map(c => ({ + ...c, + name: + c.name + + (advisedCi === c.value ? ' (recommended)' : ''), + })), default: + fromFleet || choices.find(c => c.value === DEFAULT_CI)?.value || choices[0]?.value, }, @@ -393,10 +464,12 @@ async function resolveCi( ci = answer.ci; } else { - ci = compatible(DEFAULT_CI) - ? DEFAULT_CI - : ciProviders.list().find(p => compatible(p.id))?.id || - DEFAULT_CI; + ci = + fromFleet || + (compatible(DEFAULT_CI) + ? DEFAULT_CI + : ciProviders.list().find(p => compatible(p.id))?.id || + DEFAULT_CI); } } @@ -749,7 +822,30 @@ export async function buildCreatePlan( interactive, ); - const vcsConfig = { provider: '', namespace: '', private: true }; + // The fleet is the new service's SIBLINGS: --path names the service's own + // directory, so its parent is where the others live. That is the assumption + // `imq up` makes about a fleet, and one scan answers every proposal in this + // run — the ORM and tracing groups in the packages prompt, the VCS host and + // the CI provider in their own. + const fleetRoot = dirname(resolve(argv.path)); + const fleet = analyseFleet(fleetRoot); + // Worth remembering against this path only when the user said it HERE: by + // flag, or by answering the prompt. A configured value is already a standing + // decision, and copying it into a per-fleet override would spread it + // silently. + const vcsFromFlag = !!(argv.vcs || '').trim(); + const vcsDeliberate = + vcsFromFlag || (interactive && !structured.vcs.provider); + const ciFromFlag = !!(argv.ci || '').trim(); + const ciDeliberate = + ciFromFlag || (interactive && useVcs && !structured.ci.provider); + + const vcsConfig = { + provider: '', + namespace: '', + private: true, + protocol: 'https' as 'ssh' | 'https', + }; let token = ''; if (useVcs) { @@ -757,6 +853,7 @@ export async function buildCreatePlan( argv, structured, interactive, + fleet, ); // A namespace/token stored in config belong to the host they were @@ -786,19 +883,23 @@ export async function buildCreatePlan( vcsConfig.provider = providerId; vcsConfig.namespace = vcs.namespace; vcsConfig.private = vcs.private; + vcsConfig.protocol = resolveGitProtocol(argv, structured); token = vcs.token; } - // dockerization depends on a pushed repo; disable when git is off - const registry = useVcs - ? await resolveRegistry( - argv, - structured, - serviceUseDocker, - globalUseDocker, - interactive, - ) - : EMPTY_REGISTRY; + // dockerization is opt-in via -D / config (resolveRegistry returns an empty + // registry unless requested), and no longer requires git: the Dockerfile + // and local docker:* scripts are useful without a remote, and the CI docker + // job stays dormant (it is tag-gated) until a repository exists. Actual + // registry-secret provisioning remains git-gated in the pipeline, since it + // needs a created repository to attach the secrets to. + const registry = await resolveRegistry( + argv, + structured, + serviceUseDocker, + globalUseDocker, + interactive, + ); const dockerize = registry.want; // don't prompt for a CI provider when git integration is off - a CI has no @@ -808,8 +909,17 @@ export async function buildCreatePlan( structured, vcsConfig.provider, interactive && useVcs, + fleet, ); + // A choice against what the fleet shows is remembered for this path, so the + // next run in the same fleet proposes what the user actually wants. Only the + // groups they decided here are passed. + recordFleetChoices(fleetRoot, [ + ...(vcsDeliberate ? [vcsConfig.provider] : []), + ...(ciDeliberate ? [ciProvider] : []), + ]); + // travis only knows how to push to Docker Hub (it hardcodes the dockerhub // login/env); fail fast rather than generate a broken .travis.yml for a // cloud registry @@ -832,6 +942,7 @@ export async function buildCreatePlan( Array.isArray(global.packages) ? global.packages : undefined, loadCatalog(), interactive, + fleetRoot, ); const license = resolveLicense( await resolveLicenseId(argv, global, service, interactive), @@ -846,6 +957,7 @@ export async function buildCreatePlan( provider: vcsConfig.provider || undefined, namespace: vcsConfig.namespace || undefined, private: vcsConfig.private, + protocol: vcsConfig.provider ? vcsConfig.protocol : undefined, auth: { token: token || undefined }, }, ci: { provider: ciProvider, auth: structured.ci.auth }, diff --git a/src/service/create-scaffold.ts b/src/service/create-scaffold.ts index e900e6b..f39d313 100644 --- a/src/service/create-scaffold.ts +++ b/src/service/create-scaffold.ts @@ -23,6 +23,7 @@ */ import * as fs from 'fs'; import * as p from 'path'; +import { styleText } from 'node:util'; import { CUSTOM_TPL_HOME, findLicense, @@ -448,6 +449,30 @@ export class ${cls} extends IMQService { return { name, version, repository: repository?.url }; } + /** + * Reports this service's metadata, read from package.json: package name, + * description, semantic version and source repository URL. + * + * @return {{ + * name: string, + * description: string, + * version: string, + * repository?: string + * }} - the service metadata + */ + @logged() + @profile() + @expose() + public info(): { + name: string; + description: string; + version: string; + repository?: string; + } { + const { name, description, version, repository } = pkg; + return { name, description, version, repository: repository?.url }; + } + // Implement your service methods below this line } `, @@ -473,7 +498,7 @@ export function createServiceTestFile( import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { createRequire } from 'node:module'; -import { ${cls} } from '../../src/index.js'; +import { ${cls} } from '../../src/${cls}.js'; const require = createRequire(import.meta.url); @@ -503,7 +528,7 @@ describe('${cls}', () => { ` : `${tokens.LICENSE_HEADER} import { expect } from 'chai'; -import { ${cls} } from '../../src'; +import { ${cls} } from '../../src/${cls}'; describe('${cls}', () => { @@ -533,7 +558,562 @@ describe('${cls}', () => { }); `; - touch(resolve(path, 'test/src', `${cls}.ts`), content); + touch(resolve(path, 'test/src', `${cls}.spec.ts`), content); +} + +/** + * tsconfig.json for services that use native (TC39) decorators — required by + * `@imqueue/validation` and by the `@imqueue/pg-prisma` generated models + * (which declare RPC argument types explicitly, so no `reflect-metadata`). + */ +const NATIVE_DECORATOR_TSCONFIG = `{ + "compilerOptions": { + "target": "es2024", + "lib": ["es2024", "esnext.decorators"], + "moduleDetection": "force", + + "module": "nodenext", + "moduleResolution": "nodenext", + "resolveJsonModule": true, + "esModuleInterop": true, + + "types": ["node"], + + "declaration": true, + "sourceMap": true, + "inlineSources": true, + "removeComments": false, + "newLine": "lf", + + "skipLibCheck": true, + + "strict": true, + "strictPropertyInitialization": false, + "noUnusedLocals": false, + "noUnusedParameters": false + } +} +`; + +/** + * Applies the native (TC39) decorator tsconfig that `@imqueue/pg-prisma` and + * `@imqueue/validation` require. + * + * v2 templates are built for native decorators, so the canonical config is + * authoritative and written verbatim. v1 templates ship their own tsconfig - + * build layout, extra strictness, `exclude`/`include`, and frequently classic + * `experimentalDecorators` - which must not be silently discarded; there only + * the deltas the addons need are merged in and everything else is preserved. + * When the template was using classic decorators the switch to native + * decorators is a breaking change for existing decorator-based code, so it is + * surfaced with a warning rather than applied silently. + * + * @param {string} path - service directory + * @param {boolean} isV2 - whether the target template ships the v2 contract + */ +function applyNativeDecoratorTsconfig(path: string, isV2: boolean): void { + const tsconfigPath = resolve(path, 'tsconfig.json'); + + let existing: { + compilerOptions?: Record; + [key: string]: unknown; + } | null = null; + + if (!isV2 && fs.existsSync(tsconfigPath)) { + try { + existing = JSON.parse( + fs.readFileSync(tsconfigPath, { encoding: 'utf8' }), + ); + } catch { + existing = null; + } + } + + // v2 template, or no readable template tsconfig: the canonical + // native-decorator config is authoritative + if (!existing) { + fs.writeFileSync(tsconfigPath, NATIVE_DECORATOR_TSCONFIG, { + encoding: 'utf8', + }); + + return; + } + + const opts = (existing.compilerOptions ??= {}); + const usedClassicDecorators = opts.experimentalDecorators === true; + + // switch to native (TC39) decorators: drop the classic-decorator switches + // and the field-init override they pair with (native decorators need the + // es2024 default), and make sure the decorator lib types are available + delete opts.experimentalDecorators; + delete opts.emitDecoratorMetadata; + delete opts.useDefineForClassFields; + + const lib = Array.isArray(opts.lib) ? [...(opts.lib as string[])] : []; + + if (!lib.some(entry => entry.toLowerCase() === 'esnext.decorators')) { + lib.push('esnext.decorators'); + } + + if (lib.length) { + opts.lib = lib; + } + + // generated pg-prisma models declare (but don't ctor-initialise) decorated + // fields and carry unused imports/params, so relax exactly what the + // canonical config also relaxes + opts.strictPropertyInitialization = false; + opts.noUnusedLocals = false; + opts.noUnusedParameters = false; + + fs.writeFileSync(tsconfigPath, JSON.stringify(existing, null, 2) + '\n', { + encoding: 'utf8', + }); + + if (usedClassicDecorators) { + console.log( + styleText( + 'yellow', + 'This template used classic (experimental) decorators, but the ' + + 'selected pg-prisma/validation packages require native ' + + '(TC39) decorators - tsconfig.json was switched over. ' + + 'Review existing decorator-based code (e.g. @imqueue/rpc ' + + 'services relying on emitDecoratorMetadata) as it may need ' + + 'adjusting.', + ), + ); + } +} + +/** + * The generated telemetry.ts couples to two files that only v2 templates ship: + * a side-effect `src/env-defaults.ts` preload and a `src/config.ts` exporting + * `config.serviceName`. Legacy (v1) templates have neither - and may keep their + * config elsewhere under a different shape - so on v1 the generated file must be + * self-contained: the env-defaults/config imports are dropped and the service + * name is baked in at generation time (with an env override) instead of read + * from `config`. This keeps the OpenTelemetry preload compiling against any + * template. These helpers assemble the version-specific pieces so the two + * snippet builders below stay in sync. + */ +function telemetryEnvDefaultsImport(isV2: boolean): string { + return isV2 ? "import './env-defaults.js';\n" : ''; +} + +function telemetryConfigImport(isV2: boolean): string { + return isV2 ? "import { config } from './config.js';\n" : ''; +} + +function telemetryServiceName( + isV2: boolean, + serviceName: string, +): { decl: string; expr: string } { + return isV2 + ? { decl: '', expr: 'config.serviceName' } + : { + decl: + `const serviceName = process.env.IMQ_SERVICE_NAME` + + ` || '${serviceName}';\n\n`, + expr: 'serviceName', + }; +} + +/** + * Datadog APM setup. + * + * @remarks + * A separate module rather than an inline statement in the preload slot, and that + * is load-bearing. `%ADDON_PRELOAD` sits at the top of the generated + * `src/index.ts`, and ESM evaluates every import of a module before any of its + * body statements — so an inline `tracer.init()` there would run *after* + * `./config.js` and the service class module had already been evaluated, which is + * exactly what it needs to precede. The catalog's preload therefore imports this + * file, and the `init()` call happens during that import. + */ +function tracerModule(header: string): string { + return `${header} +import tracer from '@imqueue/datadog'; + +// Importing the package installs the tracing hooks; init() is what enables the +// imq integration and starts reporting. Every client and service constructed +// after this point is traced, with no change to application code. +tracer.init(); + +export default tracer; +`; +} + +/** OpenTelemetry setup without a trace exporter (add one, e.g. the gcp pkg). */ +function telemetryBase( + header: string, + isV2: boolean, + serviceName: string, +): string { + const name = telemetryServiceName(isV2, serviceName); + + return `${header} +${telemetryEnvDefaultsImport(isV2)}import { + ImqueueInstrumentation, + type RpcModule, +} from '@imqueue/opentelemetry'; +import { resourceFromAttributes } from '@opentelemetry/resources'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; +import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; +${telemetryConfigImport(isV2)} +${name.decl}try { + const provider = new NodeTracerProvider({ + resource: resourceFromAttributes({ + [ATTR_SERVICE_NAME]: ${name.expr}, + }), + // Wire your span exporter(s) here (e.g. add the "gcp" package to export + // to Google Cloud Trace). + spanProcessors: [], + }); + + provider.register(); +} catch {} + +try { + const rpc = (await import('@imqueue/rpc')) as unknown as RpcModule; + + new ImqueueInstrumentation().patch(rpc); +} catch {} +`; +} + +/** OpenTelemetry setup with the Google Cloud Trace exporter (gcp package). */ +function telemetryWithGcp( + header: string, + isV2: boolean, + serviceName: string, +): string { + const name = telemetryServiceName(isV2, serviceName); + + return `${header} +${telemetryEnvDefaultsImport(isV2)}import { TraceExporter } from '@google-cloud/opentelemetry-cloud-trace-exporter'; +import { + ImqueueInstrumentation, + type RpcModule, +} from '@imqueue/opentelemetry'; +import { resourceFromAttributes } from '@opentelemetry/resources'; +import { + BatchSpanProcessor, + NodeTracerProvider, +} from '@opentelemetry/sdk-trace-node'; +import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; +${telemetryConfigImport(isV2)} +// GCP Cloud Trace export is enabled when GOOGLE_APPLICATION_CREDENTIALS is set. +const gcpEnabled = Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS); + +${name.decl}try { + const provider = new NodeTracerProvider({ + resource: resourceFromAttributes({ + [ATTR_SERVICE_NAME]: ${name.expr}, + }), + spanProcessors: gcpEnabled + ? [new BatchSpanProcessor(new TraceExporter())] + : [], + }); + + provider.register(); +} catch {} + +try { + const rpc = (await import('@imqueue/rpc')) as unknown as RpcModule; + + new ImqueueInstrumentation().patch(rpc); +} catch {} +`; +} + +/** The basic Prisma schema generated for a pg-prisma service. */ +function prismaSchema(): string { + return `generator client { + provider = "prisma-client" + output = "../src/generated/prisma" + runtime = "nodejs" + moduleFormat = "esm" + importFileExtension = "js" +} + +generator codegen { + provider = "node ./node_modules/@imqueue/pg-prisma/src/codegen.js" + output = "../src/generated" + softDelete = "auto" + authorship = "auto" + audit = "auto" + accessScope = "user=createdBy" + validation = "auto" + scalars = "DateTime:string" +} + +datasource db { + provider = "postgresql" +} + +/// @scope(user) +model Example { + /// @scope(user) + id String @id @default(uuid()) + /// @validate .min(1).max(255) + name String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + createdBy String? + updatedBy String? + deletedBy String? +} + +model AuditLog { + id String @id @default(uuid()) + createdAt DateTime @default(now()) + principal Json? + action String + model String + recordId String + changes Json? +} +`; +} + +/** + * Generates optional add-on files for a scaffolded service based on the + * selected catalog packages: the OpenTelemetry preload, and the full + * @imqueue/pg-prisma persistence setup (schema, prisma config, request-context + * accessors and the extended client). Also swaps in a native-decorator + * tsconfig and patches package.json when pg-prisma/validation are selected. + * + * @param {string} path - service directory + * @param {string} header - resolved license header for generated files + * @param {string[]} packages - selected catalog package ids + * @param {boolean} isV2 - whether the target template ships the v2 contract + * (src/config.ts + src/env-defaults.ts); v1 templates get a self-contained + * telemetry file that does not import them + * @param {string} serviceName - service name baked into v1 telemetry as the + * OpenTelemetry resource attribute (v2 reads it from config.serviceName) + */ +export function generateAddons( + path: string, + header: string, + packages: string[], + isV2: boolean, + serviceName: string, +): void { + const has = (id: string): boolean => packages.includes(id); + const hasPgPrisma = has('pg-prisma'); + const hasValidation = has('validation'); + + if (has('opentelemetry')) { + console.log('Generating OpenTelemetry setup...'); + touch( + resolve(path, 'src', 'telemetry.ts'), + has('gcp') + ? telemetryWithGcp(header, isV2, serviceName) + : telemetryBase(header, isV2, serviceName), + ); + } + + if (has('dd-trace')) { + console.log('Generating Datadog setup...'); + touch(resolve(path, 'src', 'tracer.ts'), tracerModule(header)); + } + + if (hasPgPrisma) { + console.log('Generating @imqueue/pg-prisma setup...'); + + touch(resolve(path, 'prisma', 'schema.prisma'), prismaSchema()); + + touch( + resolve(path, 'prisma.config.ts'), + `${header} +import { defineConfig } from 'prisma/config'; + +try { + process.loadEnvFile('.env'); +} catch {} + +export default defineConfig({ + schema: 'prisma/schema.prisma', + datasource: { + url: process.env.DATABASE_URL, + shadowDatabaseUrl: process.env.SHADOW_DATABASE_URL, + }, +}); +`, + ); + + touch( + resolve(path, 'src', 'context.ts'), + `${header} +/** + * Request-context accessors used by the Prisma extensions. Wire these to your + * real request context (e.g. AsyncLocalStorage populated per RPC call) as the + * service grows; the defaults are safe no-ops for a fresh service. + */ +export function currentActorId(): string | null { + return null; +} + +export function currentPrincipal(): unknown { + return null; +} + +export function currentAccessScope( + _level: string, +): string | string[] | null | undefined { + return undefined; +} +`, + ); + + touch( + resolve(path, 'src', 'prisma.ts'), + `${header} +import { + accessScope, + audit, + authorship, + isoDates, + isSqlLogSuppressed, + prettifySql, + softDelete, +} from '@imqueue/pg-prisma'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { + currentAccessScope, + currentActorId, + currentPrincipal, +} from './context.js'; +import { + ACCESS_SCOPE_MODELS, + type AccessScopeResolvers, + AUDIT_CONFIG, + AUDIT_MODELS, + AUTHORSHIP_MODELS, + SOFT_DELETE_MODELS, +} from './generated/index.js'; +import { PrismaClient } from './generated/prisma/client.js'; + +const databaseUrl = process.env.DATABASE_URL ?? ''; + +const client = new PrismaClient({ + adapter: new PrismaPg(databaseUrl), + log: [{ level: 'query', emit: 'event' }], +}); + +client.$on('query', event => { + if (isSqlLogSuppressed()) { + return; + } + + console.log( + prettifySql(event.query) + + '\\n-- params: ' + + event.params + + ' (' + + event.duration + + 'ms)', + ); +}); + +// soft-delete needs an authorship-aware client so deletions are still stamped +const authored = client.$extends( + authorship({ models: AUTHORSHIP_MODELS, getActorId: currentActorId }), +); + +// NOTE: audit is added FIRST so its hook is the OUTERMOST — soft-deletes still +// reach the audit trail. Keep this ordering when adding extensions. +export const prisma = client + .$extends( + audit({ + client, + config: AUDIT_CONFIG, + models: AUDIT_MODELS, + getPrincipal: currentPrincipal, + }), + ) + .$extends( + authorship({ models: AUTHORSHIP_MODELS, getActorId: currentActorId }), + ) + .$extends( + softDelete({ + client: authored as unknown as PrismaClient, + models: SOFT_DELETE_MODELS, + }), + ) + .$extends( + accessScope({ + models: ACCESS_SCOPE_MODELS, + resolvers: { + user: () => currentAccessScope('user'), + } satisfies AccessScopeResolvers, + }), + ) + .$extends(isoDates()); +`, + ); + + patchPackageJsonForPrisma(path); + } + + // native decorators are required whenever pg-prisma or validation is used + if (hasPgPrisma || hasValidation) { + applyNativeDecoratorTsconfig(path, isV2); + } +} + +/** + * Patches a pg-prisma service's package.json: adds the subpath import aliases + * the generated code uses (#generated, #prisma) and makes the build/typecheck + * scripts run `prisma generate` first so the generated client is always fresh. + * + * @param {string} path - service directory + */ +function patchPackageJsonForPrisma(path: string): void { + const pkgPath = resolve(path, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(pkgPath, { encoding: 'utf8' })); + + pkg.imports = { + ...pkg.imports, + '#generated': './src/generated/index.js', + '#generated/*': './src/generated/*', + '#prisma': './src/prisma.js', + '#context': './src/context.js', + '#*': './src/*', + }; + + pkg.scripts = pkg.scripts || {}; + pkg.scripts['prisma:generate'] = 'prisma generate'; + pkg.scripts['migrate'] = 'prisma migrate dev'; + pkg.scripts['migrate:deploy'] = 'prisma migrate deploy'; + + // Prisma has no native "down"; @imqueue/pg-prisma ships one. Load .env so + // DATABASE_URL is available, then run (or only generate) the down migration. + const migrateDown = + 'set -a; [ -f .env ] && . ./.env; set +a; ' + + 'node ./node_modules/@imqueue/pg-prisma/src/migrate-down.js'; + pkg.scripts['migrate:down'] = + `${migrateDown} --database-url "$DATABASE_URL"`; + pkg.scripts['migrate:down:gen'] = + `${migrateDown} --generate-only --database-url "$DATABASE_URL"`; + + const prefixGenerate = (script: string): void => { + const cur = pkg.scripts[script]; + + if (cur && !cur.includes('prisma generate')) { + pkg.scripts[script] = 'prisma generate && ' + cur; + } + }; + + // generated sources must exist before any type-check / compile + prefixGenerate('build'); + prefixGenerate('build:bundle'); + prefixGenerate('typecheck'); + + fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', { + encoding: 'utf8', + }); } /** diff --git a/src/service/create.ts b/src/service/create.ts index 3f39898..ff20cd0 100644 --- a/src/service/create.ts +++ b/src/service/create.ts @@ -59,17 +59,35 @@ async function rollbackRepository(plan: CreatePlan): Promise { return; } - let doDelete = !plan.interactive ? false : true; + const repo = `${plan.config.vcs.namespace}/${plan.name}`; + + // interactive default: keep the repository. Deleting a remote repo is + // destructive and the local files/commit are usually fine - the failure + // is often just the push, which the user can retry manually. A + // non-interactive run never deletes. + let doDelete = false; if (plan.interactive) { + // spell out exactly what each answer does so the (Y/n) prompt is not + // ambiguous about the consequence of a destructive remote deletion + console.log( + styleText( + 'yellow', + `\nThe ${vcs.title} repository "${repo}" was created before ` + + 'creation failed.\n' + + ' • Yes → DELETE that remote repository (full roll back, ' + + 'nothing is kept).\n' + + ' • No → KEEP it (fix the problem and push manually, ' + + 'e.g. `git push origin`).', + ), + ); + const answer = await inquirer.prompt<{ del: boolean }>([ { type: 'confirm', name: 'del', - message: - `A ${vcs.title} repository was already created. Delete ` + - 'it to roll back?', - default: true, + message: `Delete the remote ${vcs.title} repository "${repo}"?`, + default: false, }, ] as QuestionCollection); @@ -80,7 +98,8 @@ async function rollbackRepository(plan: CreatePlan): Promise { console.log( styleText( 'yellow', - `Leaving the created ${vcs.title} repository in place.`, + `Leaving the created ${vcs.title} repository "${repo}" in ` + + 'place.', ), ); @@ -138,6 +157,14 @@ export const { command, describe, builder, handler } = { ) .string('u') + .describe( + 'git-protocol', + 'Git transport for the initial push: "https" (default, ' + + 'authenticated with the access token) or "ssh" (uses ' + + 'your ssh keys)', + ) + .choices('git-protocol', ['https', 'ssh']) + // declared as the positive `install` (default true) so that, under // yargs strict mode, the negated `--no-install` is a known flag .describe( diff --git a/src/service/packages.ts b/src/service/packages.ts index d4a3b9e..cd5ddc8 100644 --- a/src/service/packages.ts +++ b/src/service/packages.ts @@ -57,9 +57,14 @@ export const { command, describe, builder, handler } = { const byGroup = new Map(); for (const [id, entry] of Object.entries(catalog.packages)) { + // `pick` on its own indented line rather than appended: in an + // exclusive group it is the deciding information, and a caller + // skimming for the id should not have to read past a sentence + // to find the next one. const line = styleText('cyan', id) + - (entry.title ? ` - ${entry.title}` : ''); + (entry.title ? ` - ${entry.title}` : '') + + (entry.pick ? '\n ' + styleText('dim', entry.pick) : ''); const list = byGroup.get(entry.group) || []; @@ -71,13 +76,19 @@ export const { command, describe, builder, handler } = { const group = catalog.groups[groupId]; const title = group?.title || groupId; const kind = group?.exclusive - ? ' (pick at most one)' + ? ' (pick at most one, or none)' : ' (any number)'; process.stdout.write( '\n' + styleText(['bold', 'green'], title + kind) + '\n', ); + if (group?.pick) { + process.stdout.write( + ' ' + styleText('dim', group.pick) + '\n', + ); + } + for (const entry of entries) { process.stdout.write(' ' + entry + '\n'); } diff --git a/test/manual/README.md b/test/manual/README.md index f46cd75..e15c865 100644 --- a/test/manual/README.md +++ b/test/manual/README.md @@ -36,9 +36,13 @@ line. Copy the file first if you want to keep a filled-in record of a session. ## What it covers Sandbox setup (isolated `~/.imq`) plus every command group: global/branding, -`config`, `service packages`, `service create --dry-run` (axes, precedence, -guards), `ctl`/`log`/`up` fleet lifecycle, `client generate`, -`service update-version`, `completions`, and config security / v3 back-compat. +`config` (including git-transport auto-detection and `vcs.protocol`), +`service packages`, `service create --dry-run` (axes, precedence, guards, the +HTTPS/SSH `--git-protocol`), real repo creation (token-authenticated HTTPS push +and the rollback prompt), `ctl`/`log`/`up` fleet lifecycle, `client generate`, +`service update-version`, `completions`, config security / v3 back-compat, and +legacy (v1) template back-compat (self-contained OpenTelemetry preload + merged, +non-clobbering `tsconfig.json` for pg-prisma/validation). Sections are tagged **offline** / **net** / **redis** / **tty** so you can run the fast offline pass first and skip what needs external services. diff --git a/test/manual/test-checklist.html b/test/manual/test-checklist.html index 5119f8f..3ff7223 100644 --- a/test/manual/test-checklist.html +++ b/test/manual/test-checklist.html @@ -249,7 +249,9 @@

@imqueue/cli · local test checklist

{"id":"T2.8","tags":["offline"],"title":"config file is 0600","expect":"600 …","cmd":"stat -c '%a %n' \"$IMQ_CLI_HOME/.imq/config.json\""}, {"id":"T2.9","tags":["offline"],"title":"legacy keys mirrored","expect":"Structured keys and legacy equivalents (e.g. gitBaseUrl, useGit) both present.","cmd":"cat \"$IMQ_CLI_HOME/.imq/config.json\""}, {"id":"T2.10","tags":["offline"],"title":"init non-TTY is guarded","expect":"Clear “requires an interactive terminal” message + non-zero — not a hang.","cmd":"imq config init < /dev/null; echo \"exit=$?\""}, - {"id":"T2.11","tags":["tty"],"title":"init interactive wizard","expect":"Walks VCS→CI→registry→packages→author; token input masked (*); ends @imqueue/cli successfully configured!","cmd":"imq config init"} + {"id":"T2.11","tags":["tty"],"title":"init interactive wizard","expect":"Walks VCS→CI→registry→packages→author; token input masked (*); ends @imqueue/cli successfully configured!","cmd":"imq config init"}, + {"id":"T2.12","tags":["tty"],"title":"init auto-detects git transport","expect":"When the VCS host is enabled, prints Detected git transport for pushes: ssh|https and the following prompt is pre-selected to the detected value. Fake key → default SSH; empty dir → default HTTPS; you can override either.","cmd":"IMQ_SSH_DIR=\"$(mktemp -d)\"; : > \"$IMQ_SSH_DIR/id_ed25519\"\nIMQ_SSH_DIR=\"$IMQ_SSH_DIR\" imq config init # default SSH\nIMQ_SSH_DIR=\"$(mktemp -d)\" imq config init # default HTTPS"}, + {"id":"T2.13","tags":["offline"],"title":"vcs.protocol set + validation","expect":"ssh/https accepted; ftp → Invalid git protocol \"ftp\". Valid: https, ssh. + non-zero; config unchanged.","cmd":"imq config set vcs.protocol ssh && imq config get vcs.protocol\nimq config set vcs.protocol https && imq config get vcs.protocol\nimq config set vcs.protocol ftp; echo \"exit=$?\""} ]}, { "num":"3", "title":"service packages (catalog)", "tests":[ {"id":"T3.1","tags":["offline"],"title":"grouped catalog listing","expect":"Groups listed; exclusive groups (tracing, orm) marked; features group shown.","cmd":"imq service packages"}, @@ -265,12 +267,16 @@

@imqueue/cli · local test checklist

{"id":"T4.6","tags":["offline"],"title":"travis + non-dockerhub fails fast","expect":"Travis CI supports the dockerhub registry only… + non-zero.","cmd":"imq service create demo \"$SBX/demo\" -a J -e j@d.io --use-git -u me --vcs github \\\n --ci travis --registry google -D --dry-run < /dev/null; echo \"exit=$?\""}, {"id":"T4.7","tags":["offline"],"title":"required namespace fails, no dir leak","expect":"GitHub namespace required… + non-zero; no directory created.","cmd":"export IMQ_CLI_HOME=\"$(mktemp -d)\"\nimq service create demo \"$SBX/nsfail\" -a J -e j@d.io --use-git --vcs github < /dev/null; echo \"exit=$?\"\nls \"$SBX/nsfail\" 2>/dev/null && echo \"LEAKED (bad)\" || echo \"no dir (good)\""}, {"id":"T4.8","tags":["offline"],"title":"non-empty target guard + --force","expect":"First refuses: Target directory … is not empty … pass --force, non-zero; keep.txt untouched.","cmd":"mkdir -p \"$SBX/occupied\" && touch \"$SBX/occupied/keep.txt\"\nimq service create demo \"$SBX/occupied\" -a J -e j@d.io < /dev/null; echo \"exit=$?\"\nimq service create demo \"$SBX/occupied\" -a J -e j@d.io --force --dry-run < /dev/null"}, - {"id":"T4.9","tags":["offline"],"title":"custom template accepted","expect":"Plan reflects the requested template; no crash.","cmd":"imq service create demo \"$SBX/demo\" -a J -e j@d.io -t some-template --dry-run < /dev/null | grep -i template"} + {"id":"T4.9","tags":["offline"],"title":"custom template accepted","expect":"Plan reflects the requested template; no crash.","cmd":"imq service create demo \"$SBX/demo\" -a J -e j@d.io -t some-template --dry-run < /dev/null | grep -i template"}, + {"id":"T4.10","tags":["offline"],"title":"git transport in the plan (--git-protocol)","expect":"1st → vcs: github (me, private, https) (default); 2nd → … , ssh); 3rd → rejected by the flag's choices, non-zero. Absent flag falls back to vcs.protocol.","cmd":"imq service create demo \"$SBX/demo\" -a J -e j@d.io --use-git --vcs github -u me --dry-run < /dev/null | grep -i \"vcs:\"\nimq service create demo \"$SBX/demo\" -a J -e j@d.io --use-git --vcs github -u me --git-protocol ssh --dry-run < /dev/null | grep -i \"vcs:\"\nimq service create demo \"$SBX/demo\" -a J -e j@d.io --use-git --vcs github -u me --git-protocol ftp --dry-run < /dev/null; echo \"exit=$?\""} ]}, { "num":"5", "title":"service create — real repo creation (optional)", "tests":[ {"id":"T5.1","tags":["net"],"title":"real scaffold + repo push","expect":"Local scaffold created; git repo initialised and pushed to a throwaway namespace.","cmd":"imq config set vcs.auth.token \nimq service create --use-git --vcs github -u -y"}, {"id":"T5.2","tags":["net"],"title":".imqrc.json has no secrets","expect":"Resolved providers/packages present; no token/password/user fields.","cmd":"cat /.imqrc.json"}, - {"id":"T5.3","tags":["net"],"title":"honest secrets report","expect":"With cloud-registry env vars unset, output states which CI secrets were/weren't provisioned (no silent success).","cmd":""} + {"id":"T5.3","tags":["net"],"title":"honest secrets report","expect":"With cloud-registry env vars unset, output states which CI secrets were/weren't provisioned (no silent success).","cmd":""}, + {"id":"T5.4","tags":["net"],"title":"HTTPS token push to a private org repo","expect":"Push to a private org repo succeeds with no SSH access configured (the \"Repository not found\" regression). The pushed origin is clean: no token in the URL and no http.extraHeader persisted.","cmd":"git -C remote get-url origin\ngit -C config --get-regexp '^http\\.' || echo \"no extraheader persisted (good)\""}, + {"id":"T5.5","tags":["net"],"title":"SSH transport (--git-protocol ssh)","expect":"With --git-protocol ssh (or vcs.protocol ssh) and working keys, origin is git@<host>:<ns>/<name>.git; no token injected.","cmd":"git -C remote get-url origin"}, + {"id":"T5.6","tags":["net"],"title":"rollback prompt is clear + safe default","expect":"Force a post-create failure (e.g. ssh with no access). Interactively: prompt names the repo, spells out Yes=delete vs No=keep+fix, and defaults to No (keep). Non-interactively the repo is left in place with a notice (never deleted silently).","cmd":""} ]}, { "num":"6", "title":"ctl — start / stop / restart / status", "tests":[ {"id":"T6.0","tags":["offline"],"title":"create the local fleet","expect":"Three dummy services created under $FLEET: alpha, beta, gamma.","cmd":"__FLEET__"}, @@ -314,8 +320,18 @@

@imqueue/cli · local test checklist

{"id":"T12.1","tags":["offline"],"title":"token stays 0600 & unlisted","expect":"file mode 600; plain config get doesn't print the token.","cmd":"imq config set vcs.auth.token ghp_exampletoken123\nstat -c '%a' \"$IMQ_CLI_HOME/.imq/config.json\"\nimq config get | grep -i token || echo \"token not shown (good)\""}, {"id":"T12.2","tags":["offline"],"title":"v3 legacy config is read","expect":"Derives github + dockerhub (+ travis), namespace imqueue; no crash.","cmd":"D=\"$(mktemp -d)\"; export IMQ_CLI_HOME=\"$D\"; mkdir -p \"$D/.imq\"\ncat > \"$D/.imq/config.json\" <<'JSON'\n{ \"useGit\": true, \"gitBaseUrl\": \"git@github.com:imqueue\",\n \"gitHubAuthToken\": \"ghp_x\", \"gitRepoPrivate\": true,\n \"useDocker\": true, \"dockerHubNamespace\": \"imqueue\" }\nJSON\nimq service create demo \"$SBX/legacy\" -a J -e j@d.io --dry-run < /dev/null | grep -iE \"github|imqueue|dockerhub|travis\""} ]}, - { "num":"13", "title":"teardown", "tests":[ - {"id":"T13.1","tags":["offline"],"title":"remove sandbox, real ~/.imq intact","expect":"Sandbox dirs gone; your real ~/.imq unchanged.","cmd":"imq ctl stop -p \"$FLEET\" 2>/dev/null || true\nrm -rf \"$IMQ_CLI_HOME\" \"$SBX\"\nunset IMQ_CLI_HOME IMQ_NO_UPDATE_CHECK SBX FLEET"} + { "num":"13", "title":"legacy (v1) template backward-compat", "tests":[ + {"id":"T13.0","tags":["offline"],"title":"setup: build generators, pick a v1 template","expect":"Prints the resolved imq path (should be inside this checkout after npm link) and v1 template OK: …. Run from your @imqueue/cli checkout. T13.1–T13.4 import the built generators directly and need no link; T13.5–T13.7 use the real imq, so the link matters or you test the published CLI. Override V1TPL for any manifest-less template.","cmd":"export IMQ_REPO=\"$(pwd)\" # the cli checkout (run from here)\nnpm run build >/dev/null # compile the CLI + addon generators\nnpm link >/dev/null 2>&1 # point `imq` at THIS build (needed by T13.5-T13.7)\nexport V1TPL=\"${V1TPL:-$HOME/.imq/templates/sequelize}\" # any v1 template (no manifest)\ncommand -v imq >/dev/null && echo \"imq: $(readlink -f \"$(command -v imq)\")\"\ntest -f \"$V1TPL/imq-template.json\" && echo \"NOT v1 (has manifest)\" || echo \"v1 template OK: $V1TPL\""}, + {"id":"T13.1","tags":["offline"],"title":"OpenTelemetry preload is self-contained on v1","expect":"Prints PASS. Generated telemetry.ts has no ./env-defaults.js or ./config.js import; name comes from process.env.IMQ_SERVICE_NAME || 'demo'.","cmd":"cat > \"$SBX/t131.mjs\" <<'MJS'\nimport * as fs from \"fs\";\nconst { generateAddons } = await import(\n `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`);\nconst d = fs.mkdtempSync(\"/tmp/imq-t131-\");\ngenerateAddons(d, \"// HDR\", [\"opentelemetry\", \"gcp\"], false, \"demo\");\nconst t = fs.readFileSync(d + \"/src/telemetry.ts\", \"utf8\");\nconst bad = t.includes(\"env-defaults.js\") || t.includes(\"./config.js\");\nconsole.log(!bad && t.includes(\"process.env.IMQ_SERVICE_NAME\")\n ? \"PASS: v1 telemetry self-contained\" : \"FAIL:\\n\" + t);\nMJS\nnode \"$SBX/t131.mjs\""}, + {"id":"T13.2","tags":["offline"],"title":"v2 telemetry output unchanged","expect":"Prints PASS — the v2 (manifest) path still emits the coupled env-defaults/config imports and config.serviceName.","cmd":"cat > \"$SBX/t132.mjs\" <<'MJS'\nimport * as fs from \"fs\";\nconst { generateAddons } = await import(\n `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`);\nconst d = fs.mkdtempSync(\"/tmp/imq-t132-\");\ngenerateAddons(d, \"// HDR\", [\"opentelemetry\", \"gcp\"], true, \"demo\");\nconst t = fs.readFileSync(d + \"/src/telemetry.ts\", \"utf8\");\nconst ok = t.includes(\"import './env-defaults.js';\")\n && t.includes(\"import { config } from './config.js';\")\n && t.includes(\"config.serviceName\");\nconsole.log(ok ? \"PASS: v2 telemetry unchanged\" : \"FAIL:\\n\" + t);\nMJS\nnode \"$SBX/t132.mjs\""}, + {"id":"T13.3","tags":["offline"],"title":"pg-prisma merges v1 tsconfig + warns","expect":"A yellow warning (“…require native (TC39) decorators - tsconfig.json was switched over…”) and PASS. Template keys (exclude, noImplicitOverride) survive; classic-decorator switches removed; esnext.decorators + relaxations added.","cmd":"cat > \"$SBX/t133.mjs\" <<'MJS'\nimport * as fs from \"fs\";\nconst { generateAddons } = await import(\n `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`);\nconst d = fs.mkdtempSync(\"/tmp/imq-t133-\");\nfs.writeFileSync(d + \"/package.json\", JSON.stringify(\n { name: \"demo\", type: \"module\", scripts: { build: \"tsc\" } }, null, 2));\nfs.writeFileSync(d + \"/tsconfig.json\", JSON.stringify({ compilerOptions: {\n target: \"es2024\", experimentalDecorators: true, useDefineForClassFields: false,\n strict: true, noImplicitOverride: true }, exclude: [\"**/debug*\"] }, null, 2) + \"\\n\");\ngenerateAddons(d, \"// HDR\", [\"pg-prisma\"], false, \"demo\"); // prints a yellow warning\nconst c = JSON.parse(fs.readFileSync(d + \"/tsconfig.json\", \"utf8\"));\nconst o = c.compilerOptions;\nconst ok = JSON.stringify(c.exclude) === '[\"**/debug*\"]' && o.noImplicitOverride === true\n && !(\"experimentalDecorators\" in o) && !(\"useDefineForClassFields\" in o)\n && (o.lib || []).includes(\"esnext.decorators\") && o.strictPropertyInitialization === false;\nconsole.log(ok ? \"PASS: v1 tsconfig merged (kept exclude/noImplicitOverride, native decorators)\"\n : \"FAIL:\\n\" + JSON.stringify(c, null, 2));\nMJS\nnode \"$SBX/t133.mjs\""}, + {"id":"T13.4","tags":["offline"],"title":"v2 tsconfig stays canonical (no merge)","expect":"Prints PASS and no warning — v2 writes the canonical native-decorator config verbatim, no template residue (exclude not carried over).","cmd":"cat > \"$SBX/t134.mjs\" <<'MJS'\nimport * as fs from \"fs\";\nconst { generateAddons } = await import(\n `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`);\nconst d = fs.mkdtempSync(\"/tmp/imq-t134-\");\nfs.writeFileSync(d + \"/package.json\", JSON.stringify(\n { name: \"demo\", type: \"module\", scripts: { build: \"tsc\" } }, null, 2));\nfs.writeFileSync(d + \"/tsconfig.json\", JSON.stringify(\n { compilerOptions: { experimentalDecorators: true }, exclude: [\"**/debug*\"] }));\ngenerateAddons(d, \"// HDR\", [\"pg-prisma\"], true, \"demo\"); // isV2 = true\nconst c = JSON.parse(fs.readFileSync(d + \"/tsconfig.json\", \"utf8\"));\nconst ok = !(\"exclude\" in c) && !(\"experimentalDecorators\" in c.compilerOptions)\n && (c.compilerOptions.lib || []).includes(\"esnext.decorators\");\nconsole.log(ok ? \"PASS: v2 tsconfig canonical (no template residue)\"\n : \"FAIL:\\n\" + JSON.stringify(c, null, 2));\nMJS\nnode \"$SBX/t134.mjs\""}, + {"id":"T13.5","tags":["offline"],"title":"real create (OpenTelemetry) offline","expect":"exit=0; PASS: no coupled imports; the IMQ_SERVICE_NAME line is present with v1otel baked in.","cmd":"rm -rf \"$SBX/v1otel\"\nimq service create v1otel \"$SBX/v1otel\" -a J -e j@d.io -t \"$V1TPL\" \\\n --packages opentelemetry,gcp --no-install < /dev/null; echo \"exit=$?\"\ngrep -nE \"env-defaults\\.js|\\./config\\.js\" \"$SBX/v1otel/src/telemetry.ts\" \\\n && echo \"FAIL: coupled import present\" || echo \"PASS: no coupled imports\"\ngrep -n \"IMQ_SERVICE_NAME\" \"$SBX/v1otel/src/telemetry.ts\""}, + {"id":"T13.6","tags":["offline"],"title":"real create (pg-prisma) offline — warn + merge","expect":"Decorator warning printed during creation; resulting tsconfig.json shows experimentalDecorators present? false and the template’s exclude kept.","cmd":"rm -rf \"$SBX/v1prisma\"\nimq service create v1prisma \"$SBX/v1prisma\" -a J -e j@d.io -t \"$V1TPL\" \\\n --packages pg-prisma --no-install < /dev/null 2>&1 | tee \"$SBX/v1prisma.log\" \\\n | grep -i \"native (TC39) decorators\" && echo \"PASS: decorator warning shown\" \\\n || echo \"check log: $SBX/v1prisma.log\"\nnode -e 'const c=require(process.env.SBX+\"/v1prisma/tsconfig.json\");console.log(\"experimentalDecorators present?\",(\"experimentalDecorators\" in (c.compilerOptions||{})),\"| exclude kept?\",JSON.stringify(c.exclude))'"}, + {"id":"T13.7","tags":["net"],"title":"end-to-end repro: create + install + build","expect":"npm install (runs the template’s prepublish/build) exits 0 — no TS2882/TS2307 on ./env-defaults.js/./config.js — and telemetry.js is emitted. The exact scenario from the bug report.","cmd":"rm -rf \"$SBX/v1build\"\nimq service create v1build \"$SBX/v1build\" -a J -e j@d.io -t \"$V1TPL\" \\\n --packages opentelemetry,gcp < /dev/null; echo \"exit=$?\"\ntest -f \"$SBX/v1build/src/telemetry.js\" && echo \"PASS: telemetry compiled\" \\\n || echo \"FAIL: build did not emit telemetry.js\""} + ]}, + { "num":"14", "title":"teardown", "tests":[ + {"id":"T14.1","tags":["offline"],"title":"remove sandbox, real ~/.imq intact","expect":"Sandbox dirs gone; your real ~/.imq unchanged.","cmd":"imq ctl stop -p \"$FLEET\" 2>/dev/null || true\nrm -rf \"$IMQ_CLI_HOME\" \"$SBX\"\nunset IMQ_CLI_HOME IMQ_NO_UPDATE_CHECK SBX FLEET V1TPL IMQ_REPO"} ]} ] } diff --git a/test/manual/test-checklist.md b/test/manual/test-checklist.md index c4a5051..c91c3f5 100644 --- a/test/manual/test-checklist.md +++ b/test/manual/test-checklist.md @@ -1,7 +1,9 @@ # @imqueue/cli — Local Manual Test Plan (v4) > **Purpose:** verify every feature of the locally-linked `imq` (`npm link`) end-to-end -> before merge/publish. Local-only; this file is **not** committed. +> before merge/publish. This checklist is committed to the repo so it can be +> re-used for every manual testing session; run it against a throwaway sandbox +> (section 0) so your real config is never touched. > > **How to use:** > - Work top-to-bottom. Each test is a checkbox. @@ -13,8 +15,8 @@ ## Results summary (fill at the end) -- Core offline sections (1–4, 6–8, 11–12): ______ / ______ passed -- Optional (5, 9, 10): ______ / ______ passed +- Core offline sections (1–4, 6–8, 11–13): ______ / ______ passed +- Optional / net (5, 9, 10, T13.7): ______ / ______ passed - Blocking problems found: ______________________________________________ --- @@ -129,6 +131,22 @@ which imq && imq --version # sanity: should print 4.0.0 ↳ Notes: - [ ] **T2.11 [offline]** `imq config init` **interactively** (real terminal): walks VCS → CI → registry → packages → author, masks token input (`*`), ends with `@imqueue/cli successfully configured!`. Token echoes as `*`, never plaintext. ↳ Notes: +- [ ] **T2.12 [offline]** `imq config init` **auto-detects the git transport**: when the VCS host is enabled it prints `Detected git transport for pushes: ssh|https (...)`, and the following `Git transport for pushing new services:` prompt is **pre-selected** to the detected value. Force each branch and confirm the default flips: + ```bash + IMQ_SSH_DIR="$(mktemp -d)"; : > "$IMQ_SSH_DIR/id_ed25519" # fake key → detects ssh + IMQ_SSH_DIR="$IMQ_SSH_DIR" imq config init # default should be SSH + IMQ_SSH_DIR="$(mktemp -d)" imq config init # empty dir → default HTTPS + ``` + Expect: with a key present the prompt defaults to **SSH**; with an empty dir it defaults to **HTTPS**; in both cases you can override the choice. + ↳ Notes: +- [ ] **T2.13 [offline]** `vcs.protocol` set + validation: + ```bash + imq config set vcs.protocol ssh && imq config get vcs.protocol # → "ssh" + imq config set vcs.protocol https && imq config get vcs.protocol # → "https" + imq config set vcs.protocol ftp; echo "exit=$?" # → rejected + ``` + Expect: `ssh`/`https` accepted; `ftp` → `Invalid git protocol "ftp". Valid: https, ssh.` and non-zero exit; config unchanged. + ↳ Notes: --- @@ -215,6 +233,14 @@ which imq && imq --version # sanity: should print 4.0.0 ``` Expect: plan reflects the requested template; no crash. ↳ Notes: +- [ ] **T4.10** Git transport in the plan (`--git-protocol`): the `vcs:` line reports the transport, defaulting to `https`: + ```bash + imq service create demo "$SBX/demo" -a J -e j@d.io --use-git --vcs github -u me --dry-run < /dev/null | grep -i "vcs:" + imq service create demo "$SBX/demo" -a J -e j@d.io --use-git --vcs github -u me --git-protocol ssh --dry-run < /dev/null | grep -i "vcs:" + imq service create demo "$SBX/demo" -a J -e j@d.io --use-git --vcs github -u me --git-protocol ftp --dry-run < /dev/null; echo "exit=$?" + ``` + Expect: first → `vcs: github (me, private, https)`; second → `... , ssh)`; third → rejected by the flag's choices (non-zero). A per-service `.imqrc.json`/global `vcs.protocol` is used when the flag is absent. + ↳ Notes: --- @@ -232,6 +258,20 @@ which imq && imq --version # sanity: should print 4.0.0 ↳ Notes: - [ ] **T5.3 [net]** Honest secrets report: with cloud registry env vars unset, output states which CI secrets were/weren't provisioned (no silent success). ↳ Notes: +- [ ] **T5.4 [net]** HTTPS token push (default) to a **private org** repo succeeds **without** any SSH access configured for that org (this is the "Repository not found" regression). After creation, the pushed remote is clean/token-free: + ```bash + git -C remote get-url origin # → https:////.git, NO token in it + git -C config --get-regexp '^http\.' || echo "no extraheader persisted (good)" + ``` + Expect: repo is created, committed and pushed over HTTPS; the origin URL contains no credentials and no `http.extraHeader` is left in `.git/config`. + ↳ Notes: +- [ ] **T5.5 [net]** SSH transport: with `--git-protocol ssh` (or `vcs.protocol ssh`) and working SSH keys, the push uses `git@:/.git` and no token is injected: + ```bash + git -C remote get-url origin # → git@:/.git + ``` + ↳ Notes: +- [ ] **T5.6 [net]** Rollback prompt clarity: force a **post-create** failure (e.g. revoke push rights, or use `--git-protocol ssh` with no SSH access so the push fails after the repo exists). Interactively you get a clear prompt naming the repo, listing what **Yes** (delete/roll back) vs **No** (keep + fix manually) do, and **defaulting to No (keep)**. Non-interactively the repo is **left in place** with a notice (never deleted silently). + ↳ Notes: --- @@ -450,15 +490,156 @@ JSON --- -## 13. Teardown +## 13. Legacy (v1) template backward-compat — all [offline] except T13.7 + +> Verifies that **old (v1) templates** — those with **no `imq-template.json`** — still +> scaffold *and build* under the current CLI when addons that generate code are +> selected. Two addon generators used to assume the v2 layout and broke v1 +> templates: the **OpenTelemetry** preload imported `./env-defaults.js` + +> `./config.js` (files only v2 templates ship), and **pg-prisma/validation** +> overwrote the whole `tsconfig.json` (silently dropping template settings and +> flipping decorator mode). +> +> **Setup for this section** (run from your `@imqueue/cli` checkout): +> ```bash +> export IMQ_REPO="$(pwd)" # the cli checkout (run from here) +> npm run build >/dev/null # compile the CLI + addon generators +> npm link >/dev/null 2>&1 # point `imq` at THIS build (needed by T13.5–T13.7) +> export V1TPL="${V1TPL:-$HOME/.imq/templates/sequelize}" # any v1 template (no imq-template.json) +> command -v imq >/dev/null && echo "imq: $(readlink -f "$(command -v imq)")" +> test -f "$V1TPL/imq-template.json" && echo "NOT a v1 template (has manifest)" || echo "v1 template OK: $V1TPL" +> ``` +> T13.1–T13.4 import the freshly-built generators directly, so they verify the fix +> **regardless of which `imq` is on PATH** (deterministic, no network). T13.5–T13.7 +> instead exercise the real `imq service create`, so they need `imq` linked to this +> checkout (the `npm link` above) — otherwise you are testing the published CLI, not +> your changes. T13.5–T13.6 run offline (`--no-install`, no VCS); T13.7 is the +> original end-to-end repro and needs the network to install OpenTelemetry deps. + +- [ ] **T13.1 [offline]** OpenTelemetry preload is **self-contained** on a v1 template (no coupling to `env-defaults`/`config`): + ```bash + cat > "$SBX/t131.mjs" <<'MJS' + import * as fs from "fs"; + const { generateAddons } = await import( + `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`); + const d = fs.mkdtempSync("/tmp/imq-t131-"); + generateAddons(d, "// HDR", ["opentelemetry", "gcp"], false, "demo"); + const t = fs.readFileSync(d + "/src/telemetry.ts", "utf8"); + const bad = t.includes("env-defaults.js") || t.includes("./config.js"); + console.log(!bad && t.includes("process.env.IMQ_SERVICE_NAME") + ? "PASS: v1 telemetry self-contained" : "FAIL:\n" + t); +MJS + node "$SBX/t131.mjs" + ``` + Expect: `PASS`. The generated `telemetry.ts` has **no** `./env-defaults.js` or `./config.js` import and derives the name from `process.env.IMQ_SERVICE_NAME || 'demo'`. + ↳ Notes: +- [ ] **T13.2 [offline]** v2 telemetry output is **unchanged** (still uses the shared config): + ```bash + cat > "$SBX/t132.mjs" <<'MJS' + import * as fs from "fs"; + const { generateAddons } = await import( + `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`); + const d = fs.mkdtempSync("/tmp/imq-t132-"); + generateAddons(d, "// HDR", ["opentelemetry", "gcp"], true, "demo"); + const t = fs.readFileSync(d + "/src/telemetry.ts", "utf8"); + const ok = t.includes("import './env-defaults.js';") + && t.includes("import { config } from './config.js';") + && t.includes("config.serviceName"); + console.log(ok ? "PASS: v2 telemetry unchanged" : "FAIL:\n" + t); +MJS + node "$SBX/t132.mjs" + ``` + Expect: `PASS` — the v2 (manifest) path still emits the coupled imports. + ↳ Notes: +- [ ] **T13.3 [offline]** pg-prisma/validation **merges** the v1 `tsconfig.json` instead of clobbering it, and **warns** about the decorator switch: + ```bash + cat > "$SBX/t133.mjs" <<'MJS' + import * as fs from "fs"; + const { generateAddons } = await import( + `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`); + const d = fs.mkdtempSync("/tmp/imq-t133-"); + fs.writeFileSync(d + "/package.json", JSON.stringify( + { name: "demo", type: "module", scripts: { build: "tsc" } }, null, 2)); + fs.writeFileSync(d + "/tsconfig.json", JSON.stringify({ compilerOptions: { + target: "es2024", experimentalDecorators: true, useDefineForClassFields: false, + strict: true, noImplicitOverride: true }, exclude: ["**/debug*"] }, null, 2) + "\n"); + generateAddons(d, "// HDR", ["pg-prisma"], false, "demo"); // prints a yellow warning + const c = JSON.parse(fs.readFileSync(d + "/tsconfig.json", "utf8")); + const o = c.compilerOptions; + const ok = JSON.stringify(c.exclude) === '["**/debug*"]' && o.noImplicitOverride === true + && !("experimentalDecorators" in o) && !("useDefineForClassFields" in o) + && (o.lib || []).includes("esnext.decorators") && o.strictPropertyInitialization === false; + console.log(ok ? "PASS: v1 tsconfig merged (kept exclude/noImplicitOverride, native decorators)" + : "FAIL:\n" + JSON.stringify(c, null, 2)); +MJS + node "$SBX/t133.mjs" + ``` + Expect: a **yellow warning** ("...require native (TC39) decorators - tsconfig.json was switched over...") **and** `PASS`. Template keys (`exclude`, `noImplicitOverride`) survive; classic-decorator switches are removed; `esnext.decorators` + relaxations are added. + ↳ Notes: +- [ ] **T13.4 [offline]** On a v2 template pg-prisma still writes the **canonical** native-decorator tsconfig verbatim (no merge, no `exclude` leaking in): + ```bash + cat > "$SBX/t134.mjs" <<'MJS' + import * as fs from "fs"; + const { generateAddons } = await import( + `file://${process.env.IMQ_REPO}/src/service/create-scaffold.js`); + const d = fs.mkdtempSync("/tmp/imq-t134-"); + fs.writeFileSync(d + "/package.json", JSON.stringify( + { name: "demo", type: "module", scripts: { build: "tsc" } }, null, 2)); + fs.writeFileSync(d + "/tsconfig.json", JSON.stringify( + { compilerOptions: { experimentalDecorators: true }, exclude: ["**/debug*"] })); + generateAddons(d, "// HDR", ["pg-prisma"], true, "demo"); // isV2 = true + const c = JSON.parse(fs.readFileSync(d + "/tsconfig.json", "utf8")); + const ok = !("exclude" in c) && !("experimentalDecorators" in c.compilerOptions) + && (c.compilerOptions.lib || []).includes("esnext.decorators"); + console.log(ok ? "PASS: v2 tsconfig canonical (no template residue)" + : "FAIL:\n" + JSON.stringify(c, null, 2)); +MJS + node "$SBX/t134.mjs" + ``` + Expect: `PASS`, **no** warning (nothing was merged). + ↳ Notes: +- [ ] **T13.5 [offline]** Real `imq service create` from a v1 template (OpenTelemetry), offline, produces a self-contained `telemetry.ts`: + ```bash + rm -rf "$SBX/v1otel" + imq service create v1otel "$SBX/v1otel" -a J -e j@d.io -t "$V1TPL" \ + --packages opentelemetry,gcp --no-install < /dev/null; echo "exit=$?" + grep -nE "env-defaults\.js|\./config\.js" "$SBX/v1otel/src/telemetry.ts" \ + && echo "FAIL: coupled import present" || echo "PASS: no coupled imports" + grep -n "IMQ_SERVICE_NAME" "$SBX/v1otel/src/telemetry.ts" + ``` + Expect: exit 0; `PASS: no coupled imports`; the `IMQ_SERVICE_NAME` line is present with `v1otel` baked in. + ↳ Notes: +- [ ] **T13.6 [offline]** Real `imq service create` from a v1 template (pg-prisma), offline, warns and merges the tsconfig (template settings preserved): + ```bash + rm -rf "$SBX/v1prisma" + imq service create v1prisma "$SBX/v1prisma" -a J -e j@d.io -t "$V1TPL" \ + --packages pg-prisma --no-install < /dev/null 2>&1 | tee "$SBX/v1prisma.log" | grep -i "native (TC39) decorators" \ + && echo "PASS: decorator warning shown" || echo "check log: $SBX/v1prisma.log" + node -e 'const c=require("'"$SBX"'/v1prisma/tsconfig.json");console.log("experimentalDecorators present?",("experimentalDecorators" in (c.compilerOptions||{})),"| exclude kept?",JSON.stringify(c.exclude))' + ``` + Expect: the decorator warning is printed during creation; the resulting `tsconfig.json` has **no** `experimentalDecorators` but **keeps** the template's own top-level keys (e.g. `exclude`). + ↳ Notes: +- [ ] **T13.7 [net]** End-to-end repro of the original bug — create from a v1 template with OpenTelemetry and let it **install + build**: + ```bash + rm -rf "$SBX/v1build" + imq service create v1build "$SBX/v1build" -a J -e j@d.io -t "$V1TPL" \ + --packages opentelemetry,gcp < /dev/null; echo "exit=$?" + test -f "$SBX/v1build/src/telemetry.js" && echo "PASS: telemetry compiled" || echo "FAIL: build did not emit telemetry.js" + ``` + Expect: `npm install` (which runs the template's `prepublish`/`build`) exits **0** — no `TS2882`/`TS2307` on `./env-defaults.js` or `./config.js` — and `telemetry.js` is emitted. (This is the exact scenario from the bug report.) + ↳ Notes: + +--- + +## 14. Teardown ```bash imq ctl stop -p "$FLEET" 2>/dev/null || true rm -rf "$IMQ_CLI_HOME" "$SBX" -unset IMQ_CLI_HOME IMQ_NO_UPDATE_CHECK SBX FLEET +unset IMQ_CLI_HOME IMQ_NO_UPDATE_CHECK SBX FLEET V1TPL IMQ_REPO ``` -- [ ] **T13.1** Sandbox dirs removed; real `~/.imq` never touched (`ls ~/.imq` unchanged from before testing). +- [ ] **T14.1** Sandbox dirs removed; real `~/.imq` never touched (`ls ~/.imq` unchanged from before testing). ↳ Notes: --- diff --git a/test/src/catalog/catalog.spec.ts b/test/src/catalog/catalog.spec.ts index cdec077..962642c 100644 --- a/test/src/catalog/catalog.spec.ts +++ b/test/src/catalog/catalog.spec.ts @@ -101,9 +101,12 @@ describe('package catalog', () => { it('should aggregate deps, snippets, env and instructions', () => { const addons = resolveAddons(['dd-trace', 'pg-cache'], catalog); - assert.equal(addons.deps['@imqueue/dd-trace'], '*'); + assert.equal(addons.deps['@imqueue/datadog'], '*'); assert.equal(addons.deps['@imqueue/pg-cache'], '*'); - assert.match(addons.preload, /@imqueue\/dd-trace/); + // The preload imports the generated ./tracer.js rather than the + // package: a bare `import '@imqueue/datadog'` installs the hooks but + // never calls tracer.init(), so nothing is reported. + assert.match(addons.preload, /\.\/tracer\.js/); assert.ok(addons.hasSnippets); assert.ok(addons.env.includes('DD_AGENT_HOST')); assert.ok(addons.instructions.length > 0); @@ -117,10 +120,14 @@ describe('package catalog', () => { }); it('should merge prisma dev dependencies', () => { - const addons = resolveAddons(['prisma'], catalog); + // pg-prisma is the only Prisma entry: a bare `prisma` addon that + // installed the client with none of the @imqueue toolkit was a + // third member of an exclusive group that should offer two. + const addons = resolveAddons(['pg-prisma'], catalog); assert.equal(addons.devDeps['prisma'], '*'); assert.equal(addons.deps['@prisma/client'], '*'); + assert.equal(addons.deps['@imqueue/pg-prisma'], '*'); }); it('should skip an unknown package id instead of throwing', () => { diff --git a/test/src/catalog/fleet.spec.ts b/test/src/catalog/fleet.spec.ts new file mode 100644 index 0000000..371b49f --- /dev/null +++ b/test/src/catalog/fleet.spec.ts @@ -0,0 +1,598 @@ +/*! + * @imqueue/cli catalog: fleet analysis tests + * + * I'm Queue Software Project + * Copyright (C) 2026 imqueue.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you want to use this code in a closed source (commercial) project, you can + * purchase a proprietary commercial license. Please contact us at + * to get commercial licensing options. + */ +import assert from 'node:assert/strict'; +import { after, before, describe, it } from 'node:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { tmpdir } from 'os'; + +// IMQ_CLI_HOME reroutes every path the CLI writes, the analysis cache included, +// so it has to be set BEFORE the modules under test resolve their constants. +const SANDBOX = mkdtempSync(join(tmpdir(), 'imq-fleet-home-')); + +process.env.IMQ_CLI_HOME = SANDBOX; + +const { + analyseFleet, + fleetCachePath, + fleetDefaults, + fleetNote, + fleetNotes, + fleetProposal, + recommendedFor, + recordFleetChoices, +} = await import('../../../src/catalog/fleet.js'); + +/** The ORM view of an analysis, which most of these assertions are about. */ +const orm = (a: any) => a.groups.orm; +const tracing = (a: any) => a.groups.tracing; + +/** Gives a service a git remote, the only place a VCS host shows up. */ +function remote(root: string, name: string, url: string): void { + mkdirSync(join(root, name, '.git'), { recursive: true }); + writeFileSync( + join(root, name, '.git', 'config'), + `[remote "origin"]\n\turl = ${url}\n`, + ); +} + +/** Gives a service a CI config, the only place a CI provider shows up. */ +function ciConfig(root: string, name: string, file: string): void { + const at = join(root, name, file); + + mkdirSync(dirname(at), { recursive: true }); + writeFileSync(at, '# generated by a test\n'); +} + +/** Writes a service directory with the given dependencies. */ +function service(root: string, name: string, deps: string[]): void { + mkdirSync(join(root, name), { recursive: true }); + writeFileSync( + join(root, name, 'package.json'), + JSON.stringify({ + name, + dependencies: Object.fromEntries(deps.map(d => [d, '*'])), + }), + ); +} + +const RPC = '@imqueue/rpc'; +const OTEL = '@imqueue/opentelemetry'; +const DD = '@imqueue/datadog'; +const SEQ = '@imqueue/pg-sequelize'; +const PRISMA = '@imqueue/pg-prisma'; + +// The names these three shipped under before the rename. Existing services still +// declare them — deprecating a package does not uninstall it — so the probes must +// keep recognising them. Without these cases a rename that missed the old names +// would leave every unmigrated fleet reading as "nothing detected", and the suite +// would stay green because the assertions elsewhere are all about catalog ids. +const OTEL_OLD = '@imqueue/opentelemetry-instrumentation-imqueue'; +const DD_OLD = '@imqueue/dd-trace'; +const SEQ_OLD = '@imqueue/sequelize'; + +describe('analyseFleet()', () => { + const fleets: string[] = []; + + function fleet(): string { + const dir = mkdtempSync(join(tmpdir(), 'imq-fleet-')); + + fleets.push(dir); + + return dir; + } + + before(() => rmSync(fleetCachePath(), { force: true })); + after(() => { + for (const dir of fleets) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('reads a Sequelize fleet as sequelize', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + service(root, 'billing', [RPC, SEQ]); + service(root, 'gateway', [RPC]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, 'sequelize'); + assert.equal(orm(analysis).counts.sequelize, 2); + assert.equal(analysis.services, 3); + assert.equal(orm(analysis).source, 'scan'); + assert.deepEqual(fleetDefaults(analysis), ['sequelize']); + assert.match(fleetNotes(analysis).orm, /Preselected sequelize/); + // the whole point of preselecting sequelize is not to silence the + // alternative + assert.match( + fleetNotes(analysis).orm, + /pg-prisma is worth considering/, + ); + }); + + it('still reads a fleet on the pre-rename ORM name as sequelize', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ_OLD]); + service(root, 'billing', [RPC, SEQ_OLD]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, 'sequelize'); + assert.equal(orm(analysis).counts.sequelize, 2); + }); + + it('counts old and new ORM names as the same member', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + service(root, 'billing', [RPC, SEQ_OLD]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, 'sequelize'); + assert.equal(orm(analysis).counts.sequelize, 2); + }); + + it('reads a Prisma fleet as pg-prisma', () => { + const root = fleet(); + + service(root, 'lead', [RPC, PRISMA]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, 'pg-prisma'); + assert.deepEqual(fleetDefaults(analysis), ['pg-prisma']); + assert.match(fleetNotes(analysis).orm, /1 service in this fleet/); + }); + + it('recommends pg-prisma for a mixed fleet', () => { + const root = fleet(); + + service(root, 'old', [RPC, SEQ]); + service(root, 'new', [RPC, PRISMA]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, 'pg-prisma'); + assert.deepEqual(fleetDefaults(analysis), ['pg-prisma']); + assert.match(fleetNotes(analysis).orm, /uses more than one ORM/); + }); + + it('preselects nothing when no service uses an ORM', () => { + const root = fleet(); + + service(root, 'gateway', [RPC]); + + const analysis = analyseFleet(root); + + assert.equal(orm(analysis).propose, null); + // Guessing an ORM here would put a database in front of someone who + // never asked for one. + assert.deepEqual(fleetDefaults(analysis), []); + assert.equal(fleetNotes(analysis).orm, undefined); + }); + + it('ignores directories that are not @imqueue services', () => { + const root = fleet(); + + service(root, 'docs', [SEQ]); // no @imqueue/rpc + mkdirSync(join(root, 'node_modules'), { recursive: true }); + + assert.equal(analyseFleet(root).services, 0); + }); + + it('answers from cache on the second call', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + + assert.equal(orm(analyseFleet(root)).source, 'scan'); + assert.equal(orm(analyseFleet(root)).source, 'cache'); + }); + + it('rescans when the fleet gains a directory', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + assert.equal(orm(analyseFleet(root)).propose, 'sequelize'); + + service(root, 'lead', [RPC, PRISMA]); + + // A changed directory listing is one readdir to detect, which is what + // keeps the cache from going stale behind a new service. + const again = orm(analyseFleet(root)); + + assert.equal(again.source, 'scan'); + assert.equal(again.propose, 'pg-prisma'); + }); +}); + +describe('recordFleetChoices()', () => { + const fleets: string[] = []; + + function fleet(): string { + const dir = mkdtempSync(join(tmpdir(), 'imq-fleet-')); + + fleets.push(dir); + + return dir; + } + + after(() => { + for (const dir of fleets) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('remembers a choice that contradicts the scan', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + assert.equal(orm(analyseFleet(root)).propose, 'sequelize'); + + recordFleetChoices(root, ['pg-prisma']); + + const after = analyseFleet(root); + + assert.equal(orm(after).propose, 'pg-prisma'); + assert.equal(orm(after).source, 'override'); + assert.deepEqual(fleetDefaults(after), ['pg-prisma']); + assert.match(fleetNotes(after).orm, /your earlier choice here/); + }); + + it('keeps the override when the fleet changes but still disagrees', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + analyseFleet(root); + recordFleetChoices(root, ['pg-prisma']); + + service(root, 'audit', [RPC, SEQ]); + + // Intent outlives a rescan: the user said pg-prisma for this path. + assert.equal(orm(analyseFleet(root)).propose, 'pg-prisma'); + }); + + it('drops the override once the fleet agrees with it', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + analyseFleet(root); + recordFleetChoices(root, ['pg-prisma']); + + // fleet migrated: nothing left to override, so a later change is not + // masked by a stale intent + rmSync(join(root, 'auth'), { recursive: true, force: true }); + service(root, 'lead', [RPC, PRISMA]); + + const after = orm(analyseFleet(root)); + + assert.equal(after.propose, 'pg-prisma'); + assert.equal(after.source, 'scan'); + }); + + it('does not treat agreement, or no ORM, as an instruction', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + analyseFleet(root); + + recordFleetChoices(root, ['sequelize']); + assert.equal(orm(analyseFleet(root)).source, 'cache'); + + recordFleetChoices(root, ['pg-cache']); + assert.equal(orm(analyseFleet(root)).source, 'cache'); + }); +}); + +describe('analyseFleet() tracing', () => { + const fleets: string[] = []; + + function fleet(): string { + const dir = mkdtempSync(join(tmpdir(), 'imq-fleet-')); + + fleets.push(dir); + + return dir; + } + + after(() => { + for (const dir of fleets) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('proposes the tracing backend the fleet already uses', () => { + const root = fleet(); + + service(root, 'auth', [RPC, DD]); + service(root, 'billing', [RPC, DD]); + + const analysis = analyseFleet(root); + + assert.equal(tracing(analysis).propose, 'dd-trace'); + assert.deepEqual(fleetDefaults(analysis), ['dd-trace']); + assert.match(fleetNotes(analysis).tracing, /^Preselected dd-trace/); + }); + + it('still reads a fleet on the pre-rename tracing names', () => { + const root = fleet(); + + service(root, 'auth', [RPC, DD_OLD]); + service(root, 'billing', [RPC, DD_OLD]); + + const analysis = analyseFleet(root); + + assert.equal(tracing(analysis).propose, 'dd-trace'); + assert.equal(tracing(analysis).counts['dd-trace'], 2); + }); + + it('counts old and new OpenTelemetry names as the same member', () => { + const root = fleet(); + + service(root, 'auth', [RPC, OTEL]); + service(root, 'billing', [RPC, OTEL_OLD]); + + const analysis = analyseFleet(root); + + assert.equal(tracing(analysis).propose, 'opentelemetry'); + assert.equal(tracing(analysis).counts.opentelemetry, 2); + }); + + it('proposes the recommended backend when a fleet uses both', () => { + const root = fleet(); + + // Against the majority, even: opentelemetry is what the project + // recommends, the same rule the ORM group follows. Majority and + // tie-breaking still apply to the groups with no recommendation — the + // VCS host and the CI provider, covered below. + service(root, 'a', [RPC, DD]); + service(root, 'b', [RPC, DD]); + service(root, 'c', [RPC, OTEL]); + + const analysis = analyseFleet(root); + + assert.equal(tracing(analysis).propose, 'opentelemetry'); + assert.match( + fleetNotes(analysis).tracing, + /uses more than one tracing \(1 on opentelemetry, 2 on dd-trace\)/, + ); + }); + + it('tells a Datadog fleet that moving is worth considering', () => { + const root = fleet(); + + service(root, 'auth', [RPC, DD]); + + const analysis = analyseFleet(root); + + // Proposing what the fleet uses is not the same as endorsing it: the + // fleet's choice is what to pick now, the recommendation is elsewhere. + assert.equal(tracing(analysis).propose, 'dd-trace'); + assert.match( + fleetNotes(analysis).tracing, + /opentelemetry is worth considering/, + ); + }); + + it('proposes nothing when the fleet is not traced', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ]); + + const analysis = analyseFleet(root); + + assert.equal(tracing(analysis).propose, null); + assert.equal(fleetNotes(analysis).tracing, undefined); + // the ORM half of the same scan still answers + assert.deepEqual(fleetDefaults(analysis), ['sequelize']); + }); + + it('remembers a tracing choice that contradicts the scan', () => { + const root = fleet(); + + service(root, 'auth', [RPC, DD]); + analyseFleet(root); + + recordFleetChoices(root, ['opentelemetry']); + + const after = analyseFleet(root); + + assert.equal(tracing(after).propose, 'opentelemetry'); + assert.equal(tracing(after).source, 'override'); + }); + + it('records overrides for both groups from one selection', () => { + const root = fleet(); + + service(root, 'auth', [RPC, SEQ, DD]); + analyseFleet(root); + + recordFleetChoices(root, ['pg-prisma', 'opentelemetry']); + + const after = analyseFleet(root); + + assert.equal(orm(after).propose, 'pg-prisma'); + assert.equal(tracing(after).propose, 'opentelemetry'); + assert.deepEqual(fleetDefaults(after).sort(), [ + 'opentelemetry', + 'pg-prisma', + ]); + }); +}); + +describe('analyseFleet() vcs and ci', () => { + const fleets: string[] = []; + + function fleet(): string { + const dir = mkdtempSync(join(tmpdir(), 'imq-fleet-')); + + fleets.push(dir); + + return dir; + } + + after(() => { + for (const dir of fleets) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('reads the VCS host out of the git remotes', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + remote(root, 'auth', 'git@gitlab.example.com:acme/auth.git'); + service(root, 'billing', [RPC]); + remote(root, 'billing', 'https://gitlab.example.com/acme/billing.git'); + + const analysis = analyseFleet(root); + + // Matched on host, not domain: a self-hosted GitLab is still GitLab. + assert.equal(fleetProposal(analysis, 'vcs'), 'gitlab'); + assert.match(fleetNote(analysis, 'vcs'), /Preselected gitlab/); + // and never leaks into the catalog, which would reject it as a package + assert.deepEqual(fleetDefaults(analysis), []); + }); + + it('reads the CI provider out of its config files', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + ciConfig(root, 'auth', '.circleci/config.yml'); + service(root, 'billing', [RPC]); + ciConfig(root, 'billing', '.circleci/config.yml'); + + assert.equal(fleetProposal(analyseFleet(root), 'ci'), 'circleci'); + }); + + it('recognises a github-actions workflow directory', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + ciConfig(root, 'auth', '.github/workflows/build.yml'); + remote(root, 'auth', 'git@github.com:acme/auth.git'); + + const analysis = analyseFleet(root); + + assert.equal(fleetProposal(analysis, 'ci'), 'github-actions'); + assert.equal(fleetProposal(analysis, 'vcs'), 'github'); + }); + + it('says nothing about a host it cannot recognise', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + // GitHub Enterprise on a custom domain leaves no evidence, and no + // evidence is reported as no evidence rather than guessed at + remote(root, 'auth', 'git@git.acme.internal:acme/auth.git'); + + const analysis = analyseFleet(root); + + assert.equal(fleetProposal(analysis, 'vcs'), null); + assert.equal(fleetNote(analysis, 'vcs'), ''); + }); + + it('follows the majority host, and calls a tie a tie', () => { + const split = fleet(); + + service(split, 'a', [RPC]); + remote(split, 'a', 'git@github.com:acme/a.git'); + service(split, 'b', [RPC]); + remote(split, 'b', 'git@gitlab.com:acme/b.git'); + + assert.equal(fleetProposal(analyseFleet(split), 'vcs'), null); + assert.match(fleetNote(analyseFleet(split), 'vcs'), /split evenly/); + + const most = fleet(); + + service(most, 'a', [RPC]); + remote(most, 'a', 'git@github.com:acme/a.git'); + service(most, 'b', [RPC]); + remote(most, 'b', 'git@github.com:acme/b.git'); + service(most, 'c', [RPC]); + remote(most, 'c', 'git@gitlab.com:acme/c.git'); + + assert.equal(fleetProposal(analyseFleet(most), 'vcs'), 'github'); + }); + + it('remembers a VCS or CI choice that contradicts the scan', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + remote(root, 'auth', 'git@github.com:acme/auth.git'); + ciConfig(root, 'auth', '.github/workflows/build.yml'); + analyseFleet(root); + + recordFleetChoices(root, ['gitlab', 'circleci']); + + const after = analyseFleet(root); + + assert.equal(fleetProposal(after, 'vcs'), 'gitlab'); + assert.equal(fleetProposal(after, 'ci'), 'circleci'); + assert.match(fleetNote(after, 'vcs'), /your earlier choice here/); + }); + it('recommends what the fleet uses, and the baseline when it is silent', () => { + const empty = fleet(); + + // The edge case: nothing to go on, so the project's own preference — + // github, pg-prisma, github-actions, opentelemetry. + const none = analyseFleet(empty); + + assert.equal(recommendedFor(none, 'vcs'), 'github'); + assert.equal(recommendedFor(none, 'orm'), 'pg-prisma'); + assert.equal(recommendedFor(none, 'ci'), 'github-actions'); + assert.equal(recommendedFor(none, 'tracing'), 'opentelemetry'); + // ...and recommending is not preselecting: (none) still opens the list + assert.deepEqual(fleetDefaults(none), []); + + const existing = fleet(); + + service(existing, 'auth', [RPC, SEQ, DD]); + remote(existing, 'auth', 'git@gitlab.acme.io:acme/auth.git'); + ciConfig(existing, 'auth', '.circleci/config.yml'); + + // A fleet IS its own recommendation: matching it is what a new service + // joining it should do. + const used = analyseFleet(existing); + + assert.equal(recommendedFor(used, 'vcs'), 'gitlab'); + assert.equal(recommendedFor(used, 'orm'), 'sequelize'); + assert.equal(recommendedFor(used, 'ci'), 'circleci'); + assert.equal(recommendedFor(used, 'tracing'), 'dd-trace'); + }); + + it('recommends an override over the baseline', () => { + const root = fleet(); + + service(root, 'auth', [RPC]); + analyseFleet(root); + recordFleetChoices(root, ['sequelize']); + + assert.equal(recommendedFor(analyseFleet(root), 'orm'), 'sequelize'); + }); +}); diff --git a/test/src/lib/ssh.spec.ts b/test/src/lib/ssh.spec.ts new file mode 100644 index 0000000..ca2d39e --- /dev/null +++ b/test/src/lib/ssh.spec.ts @@ -0,0 +1,102 @@ +/*! + * @imqueue/cli Unit Tests: ssh key detection / git protocol default + * + * I'm Queue Software Project + * Copyright (C) 2026 imqueue.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you want to use this code in a closed source (commercial) project, you can + * purchase a proprietary commercial license. Please contact us at + * to get commercial licensing options. + */ +import { describe, it, after } from 'node:test'; +import assert from 'node:assert/strict'; +import '../../mocks/index.js'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { hasSshKeys, detectGitProtocol } from '../../../lib/ssh.js'; + +const roots: string[] = []; + +function ssh(files: string[]): string { + const dir = mkdtempSync(join(tmpdir(), 'imq-ssh-')); + + roots.push(dir); + + for (const f of files) { + writeFileSync(join(dir, f), 'x'); + } + + return dir; +} + +describe('ssh key detection', () => { + after(() => { + for (const r of roots) { + rmSync(r, { recursive: true, force: true }); + } + }); + + it('should detect a conventional private key', () => { + const dir = ssh(['id_ed25519', 'id_ed25519.pub', 'known_hosts']); + + assert.equal(hasSshKeys(dir), true); + assert.equal(detectGitProtocol(dir), 'ssh'); + }); + + it('should detect an rsa key pair', () => { + assert.equal(hasSshKeys(ssh(['id_rsa', 'id_rsa.pub'])), true); + }); + + it('should treat any *.pub as evidence of keys', () => { + assert.equal(hasSshKeys(ssh(['work_key.pub'])), true); + }); + + it('should report no keys for a dir with only config/known_hosts', () => { + const dir = ssh(['config', 'known_hosts']); + + assert.equal(hasSshKeys(dir), false); + assert.equal(detectGitProtocol(dir), 'https'); + }); + + it('should default to https when the ssh dir is absent', () => { + const dir = mkdtempSync(join(tmpdir(), 'imq-nossh-')); + + roots.push(dir); + // point at a non-existent subdir + const missing = join(dir, 'no-such-ssh'); + + assert.equal(hasSshKeys(missing), false); + assert.equal(detectGitProtocol(missing), 'https'); + }); + + it('should honor the IMQ_SSH_DIR override for the default dir', () => { + const dir = ssh(['id_ecdsa']); + const prev = process.env.IMQ_SSH_DIR; + + process.env.IMQ_SSH_DIR = dir; + + try { + assert.equal(detectGitProtocol(), 'ssh'); + } finally { + if (prev === undefined) { + delete process.env.IMQ_SSH_DIR; + } else { + process.env.IMQ_SSH_DIR = prev; + } + } + }); +}); diff --git a/test/src/providers/ci.spec.ts b/test/src/providers/ci.spec.ts index f3a54d8..c3d0651 100644 --- a/test/src/providers/ci.spec.ts +++ b/test/src/providers/ci.spec.ts @@ -76,9 +76,12 @@ describe('ci providers', () => { it('should emit a test-only workflow when not dockerizing', () => { const files = githubActions.files(baseCtx(false)); - assert.equal(files[0].relPath, '.github/workflows/build.yml'); - assert.match(files[0].content, /npm test/); + assert.equal(files[0].relPath, '.github/workflows/ci.yml'); + assert.match(files[0].content, /npm run test:unit/); assert.doesNotMatch(files[0].content, /docker build/); + // a composite setup action is shipped alongside the workflow + assert.equal(files[1].relPath, '.github/actions/setup/action.yml'); + assert.match(files[1].content, /using: composite/); }); it('should add a docker job when dockerizing', () => { diff --git a/test/src/providers/scm-git-auth.spec.ts b/test/src/providers/scm-git-auth.spec.ts new file mode 100644 index 0000000..ce0d494 --- /dev/null +++ b/test/src/providers/scm-git-auth.spec.ts @@ -0,0 +1,144 @@ +/*! + * @imqueue/cli Unit Tests: scm/git initAndPush() HTTPS token authentication + * + * I'm Queue Software Project + * Copyright (C) 2026 imqueue.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you want to use this code in a closed source (commercial) project, you can + * purchase a proprietary commercial license. Please contact us at + * to get commercial licensing options. + */ +import { describe, it, mock, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import '../../mocks/index.js'; + +// record every git invocation so we can assert on argv without a network or a +// real remote. node:test runs each spec file in its own process, so mocking +// the child_process builtin here does not leak into other specs. +interface Call { + cmd: string; + args: string[]; +} +const calls: Call[] = []; + +const execFileSync = (cmd: string, args: string[] = []) => { + calls.push({ cmd, args }); + + // the provider reads the current branch from `git rev-parse` + return args[0] === 'rev-parse' ? Buffer.from('main\n') : Buffer.from(''); +}; +// commandExists() probes with spawnSync; report git as present +const spawnSync = () => ({ status: 0 }); + +// `child_process` and `node:child_process` resolve to the same builtin, so a +// single mock covers both import specifiers. The wider module graph (lib) also +// imports execSync/spawn from child_process, so they must be present (as inert +// stubs) or linking the graph fails. +mock.module('child_process', { + cache: false, + namedExports: { + execFileSync, + spawnSync, + execSync: () => Buffer.from(''), + spawn: () => ({}), + }, +}); + +const { git } = await import('../../../src/providers/scm/git.js'); + +const ctx = { + path: '/tmp/does-not-matter', + version: '1.0.0', + author: 'Test', + email: 't@e.io', +} as any; + +const pushCalls = () => + calls.filter(c => c.cmd === 'git' && c.args.includes('push')); + +describe('scm/git initAndPush() https token auth', () => { + beforeEach(() => { + calls.length = 0; + }); + + it('should authenticate https pushes with an ephemeral extraHeader', async () => { + await git.initAndPush(ctx, 'https://github.com/acme/my-svc.git', { + user: 'x-access-token', + token: 's3cr3t', + }); + + // every push carries the auth header as a per-invocation -c option + const pushes = pushCalls(); + + assert.ok(pushes.length >= 2, 'branch and tag pushes happened'); + + for (const p of pushes) { + assert.equal( + p.args[0], + '-c', + 'auth is passed before the subcommand', + ); + assert.match(p.args[1], /^http\.extraHeader=Authorization: Basic /); + + const b64 = p.args[1].replace( + /^http\.extraHeader=Authorization: Basic /, + '', + ); + + assert.equal( + Buffer.from(b64, 'base64').toString(), + 'x-access-token:s3cr3t', + 'the token is sent as basic-auth password', + ); + } + }); + + it('should keep the token out of the persisted remote url', async () => { + await git.initAndPush(ctx, 'https://github.com/acme/my-svc.git', { + user: 'x-access-token', + token: 's3cr3t', + }); + + const remoteAdd = calls.find( + c => c.args[0] === 'remote' && c.args[1] === 'add', + ); + + assert.ok(remoteAdd, 'a remote was added'); + // the url written into .git/config must be clean (no embedded token) + assert.equal(remoteAdd.args[3], 'https://github.com/acme/my-svc.git'); + assert.doesNotMatch(remoteAdd.args[3], /s3cr3t/); + }); + + it('should not inject a header without auth or for a non-https remote', async () => { + await git.initAndPush(ctx, 'git@github.com:acme/my-svc.git'); + + for (const p of pushCalls()) { + assert.notEqual(p.args[0], '-c'); + } + + calls.length = 0; + + // even when auth is supplied, an ssh remote must not carry the header + await git.initAndPush(ctx, 'git@github.com:acme/my-svc.git', { + user: 'x-access-token', + token: 's3cr3t', + }); + + for (const p of pushCalls()) { + assert.notEqual(p.args[0], '-c'); + } + }); +}); diff --git a/test/src/service/create-plan.spec.ts b/test/src/service/create-plan.spec.ts index d4b2b01..fff4e5d 100644 --- a/test/src/service/create-plan.spec.ts +++ b/test/src/service/create-plan.spec.ts @@ -218,4 +218,69 @@ describe('service create plan', () => { assert.equal(plan.config.vcs.provider, 'gitlab'); }); }); + + describe('buildCreatePlan() git protocol resolution', () => { + it('should default the push protocol to https', async () => { + const plan = await buildCreatePlan(baseArgv, { + global: legacyConfig, + service: {}, + interactive: false, + dryRun: true, + }); + + assert.equal(plan.config.vcs.protocol, 'https'); + }); + + it('should let --git-protocol ssh win over the default', async () => { + const plan = await buildCreatePlan( + { ...baseArgv, gitProtocol: 'ssh' }, + { + global: legacyConfig, + service: {}, + interactive: false, + dryRun: true, + }, + ); + + assert.equal(plan.config.vcs.protocol, 'ssh'); + }); + + it('should honor a configured vcs.protocol', async () => { + const plan = await buildCreatePlan(baseArgv, { + global: { ...legacyConfig, vcs: { protocol: 'ssh' } }, + service: {}, + interactive: false, + dryRun: true, + }); + + assert.equal(plan.config.vcs.protocol, 'ssh'); + }); + + it('should let a per-service protocol override the global', async () => { + const plan = await buildCreatePlan(baseArgv, { + global: { ...legacyConfig, vcs: { protocol: 'ssh' } }, + service: { vcs: { protocol: 'https' } }, + interactive: false, + dryRun: true, + }); + + assert.equal(plan.config.vcs.protocol, 'https'); + }); + + it('should reject an invalid protocol value', async () => { + await assert.rejects( + () => + buildCreatePlan( + { ...baseArgv, gitProtocol: 'ftp' }, + { + global: legacyConfig, + service: {}, + interactive: false, + dryRun: true, + }, + ), + /Invalid git protocol/, + ); + }); + }); }); diff --git a/test/src/service/create-scaffold.spec.ts b/test/src/service/create-scaffold.spec.ts index 210e084..0832fa6 100644 --- a/test/src/service/create-scaffold.spec.ts +++ b/test/src/service/create-scaffold.spec.ts @@ -38,6 +38,7 @@ import { buildServiceTokens, compileTemplate, ensureTemplate, + generateAddons, isEsmService, loadTemplateManifest, overlayFragments, @@ -227,4 +228,43 @@ describe('service create scaffolding', () => { ); }); }); + + describe('generateAddons()', () => { + function addons(id: string): string { + const sub = join(dir, `addons-${id}`); + + mkdirSync(join(sub, 'src'), { recursive: true }); + generateAddons(sub, '// header', [id], true, 'svc'); + + return sub; + } + + it('should write a telemetry module for opentelemetry', () => { + const sub = addons('opentelemetry'); + const src = readFileSync(join(sub, 'src', 'telemetry.ts'), 'utf8'); + + // the import specifier is generated source: tsc cannot check it, + // and a stale one only fails at the user's npm install + assert.match(src, /from '@imqueue\/opentelemetry'/); + assert.doesNotMatch(src, /opentelemetry-instrumentation-imqueue/); + }); + + it('should write a tracer module for dd-trace that calls init()', () => { + const sub = addons('dd-trace'); + const src = readFileSync(join(sub, 'src', 'tracer.ts'), 'utf8'); + + assert.match(src, /from '@imqueue\/datadog'/); + // init() is the whole point of the file. Importing the package alone + // installs the hooks but reports nothing, which is what the previous + // bare-import preload did. + assert.match(src, /tracer\.init\(\);/); + }); + + it('should write nothing for a deps-only addon', () => { + const sub = addons('pg-cache'); + + assert.ok(!existsSync(join(sub, 'src', 'telemetry.ts'))); + assert.ok(!existsSync(join(sub, 'src', 'tracer.ts'))); + }); + }); }); diff --git a/test/src/service/write-service-config.spec.ts b/test/src/service/write-service-config.spec.ts index 9939841..10a3551 100644 --- a/test/src/service/write-service-config.spec.ts +++ b/test/src/service/write-service-config.spec.ts @@ -44,6 +44,7 @@ describe('writeServiceConfig()', () => { provider: 'github', namespace: 'acme', private: true, + protocol: 'ssh', auth: { token: 'ghp_SUPER_SECRET' }, }, ci: { provider: 'circleci', auth: { token: 'circle-secret' } }, @@ -65,6 +66,7 @@ describe('writeServiceConfig()', () => { // structural expectations are preserved... assert.equal(parsed.vcs.provider, 'github'); assert.equal(parsed.vcs.namespace, 'acme'); + assert.equal(parsed.vcs.protocol, 'ssh'); assert.equal(parsed.ci.provider, 'circleci'); assert.equal(parsed.registry.provider, 'dockerhub'); assert.deepEqual(parsed.packages, ['pg-cache']); diff --git a/wiki/Clients-and-Versioning.md b/wiki/Clients-and-Versioning.md index 933978a..c31c231 100644 --- a/wiki/Clients-and-Versioning.md +++ b/wiki/Clients-and-Versioning.md @@ -6,26 +6,43 @@ service — the service must be up (and Redis reachable) so its interface can be introspected; otherwise generation fails. +**The generated client is a file you commit.** It is written into your repository +like any other source, which is what gives the service's interface a reviewable +artifact: change a method signature, regenerate, and the change appears as a +**diff in the pull request that causes it**. The reviewer reads the contract +change instead of inferring it. There is no separate schema file to check in, +because the committed client *is* the checked-in contract — generated from the +implementation rather than hand-maintained beside it. + ```bash imq client generate [path] ``` | Flag | Meaning | |---|---| -| (positional) `name` | service name to generate a client for (required) | +| (positional) `name` | the service's **queue** name (required) — see below | | (positional) `path` | directory to place the client file (default: cwd) | | `-o, --overwrite` | overwrite an existing client without prompting | +| `-w, --timeout` | seconds to wait for the service to respond before giving up (default `30`; `0` waits forever) | + +The name is the queue the service listens on, which `IMQService` defaults to its +own class name (`this.name = name || this.constructor.name`), and the CLI passes +it straight to `IMQClient.create()`. So it is `BillingService`, not `billing` — +and in particular it is **not** the project directory name that `imq ctl -s` +takes. Get it wrong and generation waits for a queue nobody is listening on, then +times out. ```bash -# from within a project, service "billing" running locally -imq client generate billing ./src/clients -o +# from within a project, with the BillingService class running locally +imq client generate BillingService ./src/clients -o ``` -Typical flow during development: +Typical flow during development. The two names in it are different things: `-s` +selects the local service by directory, while `generate` takes the queue name: ```bash imq ctl start -s billing -c # bring the service up and wait for readiness -imq client generate billing ./src/clients +imq client generate BillingService ./src/clients imq ctl stop -s billing ``` @@ -71,3 +88,22 @@ imq service update-version ./services main -n patch | Touches deps? | no | yes (`ncu -u` + reinstall) | | Git flow | checkout → pull → version → push | (optionally) commit → version → push | | Branch control | `-b/[branch]` | uses current branch | + +## FAQ + +### Is the generated client committed to the repository? + +Yes. `imq client generate` writes the client into your source tree and it is +committed like any other file. That is deliberate: it is what makes an interface +change reviewable. Regenerating after a signature change produces a diff in the +pull request that causes it, so the contract change is visible at review time +rather than discovered at runtime by a caller. + +### Should I generate clients in CI instead of committing them? + +No, and it is usually impractical. Generation introspects a **running** service, +so a CI job would have to start the service and a Redis for every build just to +produce a file that is deterministic anyway. Committing it is cheaper, and it +keeps the property that matters — the diff. Regenerate locally with +`imq client generate -o` as part of the change that alters the +interface, and commit the result alongside it. diff --git a/wiki/Configuration.md b/wiki/Configuration.md index 924ba97..05dc93c 100644 --- a/wiki/Configuration.md +++ b/wiki/Configuration.md @@ -21,7 +21,11 @@ imq config init ``` An interactive wizard walks you through the four axes and stores your answers -globally. Do this once after installation to make later commands short. +globally. Do this once after installation to make later commands short. When +you enable a VCS host, the wizard **auto-detects the git transport**: it +defaults to `ssh` if you have SSH keys in `~/.ssh` (overridable with +`IMQ_SSH_DIR`) and `https` otherwise, reports which it picked and why, and lets +you change it — see [Git transport](#git-transport-for-the-initial-push-https-vs-ssh). ## Managing config values @@ -54,6 +58,7 @@ still works if the CLI is downgraded to v3. | `vcs.provider` | `github` \| `gitlab` \| `bitbucket` | | `vcs.namespace` | user / organization / workspace that owns new repos | | `vcs.private` | create repositories as private (`true`/`false`) | +| `vcs.protocol` | git transport for the create-time push: `https` (default) \| `ssh` | | `vcs.auth.token` | API/personal-access token for repo creation & secrets | ### `ci` — continuous integration @@ -79,7 +84,7 @@ still works if the CLI is downgraded to v3. | Key | Meaning | |---|---| | `packages` | default addon packages added to new services (array) | -| `templatesRef` | git ref of the templates repo to use (default `v4`) | +| `templatesRef` | git ref of the templates repo to use (default `master`) | Example `~/.imq/config.json`: @@ -89,7 +94,7 @@ Example `~/.imq/config.json`: "ci": { "provider": "github-actions" }, "registry": { "provider": "google", "project": "my-gcp-proj", "region": "europe-west1" }, "packages": ["opentelemetry", "pg-cache"], - "templatesRef": "v4" + "templatesRef": "master" } ``` @@ -121,6 +126,35 @@ Tokens can be provided by (in order of preference): Because the config file may contain these, it is always written `0600`. Prefer per-invocation flags or environment injection in shared CI environments. +## Git transport for the initial push (HTTPS vs SSH) + +When `imq service create` commits and pushes the new repository, it uses one of +two transports, selected by `vcs.protocol` (or the `--git-protocol` flag): + +| `vcs.protocol` | Push behavior | +|---|---| +| `https` (**default**) | Push over `https://…` **authenticated with the access token** that created the repo. The token is used **only for that push** (via an ephemeral `http.extraHeader`) and is never written into the repository's `.git/config`, which keeps a clean, token-free remote URL. | +| `ssh` | Push over the host's `git@…:…` SSH URL using **your own SSH keys/agent**. No token is injected — you need working SSH access to the namespace. | + +Precedence is the usual one: `--git-protocol` flag → `.imqrc.json` → +global config → the `https` default. + +**Why HTTPS is the default.** The access token that just created the repo is +guaranteed to have write access, so the push succeeds even for a private +organization repo where your SSH key — or a *different* "active" git/gh +account — has no access (the classic misleading `Repository not found` on +push). Choose `ssh` when you specifically rely on SSH keys (e.g. org policy, +hardware-key signing, or an SSH-only host): + +```bash +imq config set vcs.protocol ssh # make ssh the default for new services +imq service create my-svc ./my-svc --git-protocol https # or override per run +``` + +> `IMQ_GIT_REMOTE_BASE` still overrides the push target entirely (custom / +> self-hosted git or integration testing) and takes precedence over +> `vcs.protocol`; no token is injected in that mode. + ## Backward compatibility A configuration written by 3.x uses legacy keys (`gitBaseUrl`, @@ -147,6 +181,7 @@ You do not need to migrate anything by hand. | `IMQ_CIRCLECI_API_URL` | CircleCI API base. | | `IMQ_TRAVIS_API_URL` | Travis API base. | | `IMQ_GIT_REMOTE_BASE` | Base for the git remote used on commit/push (testing seam). | +| `IMQ_SSH_DIR` | SSH directory inspected for keys when auto-detecting the git transport (defaults to `~/.ssh`). | | `CIRCLE_TOKEN` | CircleCI token fallback (used when `ci.auth.token` is unset). | These are also the seams used by the test harness; in production they enable @@ -154,6 +189,12 @@ enterprise / self-hosted deployments without any code change. See [Providers](Providers#enterprise--self-hosted) and [Extensibility](Extensibility). +Every variable above is read by **`imq` itself**. A service the CLI generates +reads its own, separate set at runtime — `SERVICE_NAME`, the `IMQ_*` queue +settings in its `src/config.ts`, and whatever the addons you selected require. +For the tracing ones see +[Package Catalog](Package-Catalog#the-name-a-traced-service-reports). + ### Cloud-registry credentials (read at create time) When a service is dockerized against a cloud registry, `imq service create` diff --git a/wiki/Creating-Services.md b/wiki/Creating-Services.md index 266f5cd..812dbfe 100644 --- a/wiki/Creating-Services.md +++ b/wiki/Creating-Services.md @@ -15,15 +15,28 @@ If omitted, `name` defaults to the current directory's name and `path` to `.` Service creation is organized around four independent, pluggable axes, so you can mix the tools you actually use. Each resolves via the standard precedence -(flag → `.imqrc.json` → global config → prompt → default). +(flag → `.imqrc.json` → global config → fleet → prompt → default). -| Axis | Flag | Choices (default **bold**) | +| Axis | Flag | Choices (fallback **bold**) | |---|---|---| | VCS host | `--vcs` | **github**, gitlab, bitbucket | | CI provider | `--ci` | **github-actions**, circleci, travis | | Container registry | `--registry` | **dockerhub**, google, aws-ecr, azure-acr | | Addon packages | `--packages` | (none) — see [Package Catalog](Package-Catalog) | +The bold value is the fallback, not a fixed default. With nothing configured, +`imq service create` reads the git remotes and CI config of the services that +already sit alongside the new one and proposes what they use — a service +joining services hosted on GitLab is going on GitLab. The bold value applies +when there is no fleet to learn from, or when the fleet does not agree with +itself. [Package Catalog](Package-Catalog#following-the-fleet) describes the +analysis and its cache. + +A VCS host and a CI provider get picked either way — unlike an addon, choosing +none is not an option — so this applies to non-interactive runs too. If you +script `imq service create` inside a fleet and want a specific host or +provider regardless of its neighbours, pass `--vcs` / `--ci` explicitly. + CI choices are filtered to those compatible with the selected VCS host. See [Providers](Providers) for the details and tokens each one needs. @@ -94,7 +107,15 @@ run performs, in order: 7. **Install** dependencies (`npm install`) unless `--no-install`. 8. **Initialize git** locally (sets a local commit identity from the author/ email so it works even without a global git identity), **commit**, add the - **remote**, **push**, and **tag** the initial version. + **remote**, **push**, and **tag** the initial version. By default the push + is sent over **HTTPS and authenticated with the same access token** that + created the repo (injected only for that push, never written into the + repository's git config). This is what makes a push to a private org repo + succeed even when your SSH key — or a different "active" git/gh account — has + no access to it. The remote left in `.git/config` is the clean, token-free + HTTPS URL. To push over **SSH** with your own keys instead, pass + `--git-protocol ssh` (or set `vcs.protocol: ssh`) — see + [Configuration → Git transport](Configuration#git-transport-for-the-initial-push-https-vs-ssh). 9. **Report** any addon instructions and environment variables you must set. Without repo creation, the remote/CI-secret/commit/push steps (4, 5, 8) are @@ -107,8 +128,10 @@ still run. a pre-existing directory (or the current/home directory) is never deleted. A non-empty target is refused up front unless you pass `--force`. - If the remote repository was already created when a later step fails, you are - offered (interactively) to delete it to roll back; non-interactively it is - left in place with a notice so nothing is destroyed silently. + asked (interactively) whether to **delete** it (full roll back) or **keep** it + and fix the problem manually — the prompt spells out both outcomes and + **defaults to keeping** it. Non-interactively it is always left in place with + a notice, so nothing is destroyed silently. - Enabling CI and provisioning secrets are **non-fatal**: on failure the CLI prints what to do manually and continues. It reports which registry secrets were actually provisioned rather than assuming success. diff --git a/wiki/Custom-Templates.md b/wiki/Custom-Templates.md index ef00a58..afb27ad 100644 --- a/wiki/Custom-Templates.md +++ b/wiki/Custom-Templates.md @@ -15,7 +15,7 @@ own — pointed at by name, git URL, or local path. | **local directory** | `-t ./my-template` | With no flag, the default template is fetched over public **HTTPS** and pinned -to the `templatesRef` from your config (default `v4`). Override the source repo +to the `templatesRef` from your config (default `master`). Override the source repo entirely with `IMQ_TEMPLATES_REPO` (e.g. your fork, or an SSH URL for contributors): diff --git a/wiki/Installation.md b/wiki/Installation.md index bd05275..8402f78 100644 --- a/wiki/Installation.md +++ b/wiki/Installation.md @@ -42,10 +42,10 @@ export IMQ_NO_UPDATE_CHECK=1 ### Upgrading from 3.x -The three standalone shell tools were folded into the `imq` binary. Update any -scripts or aliases: +In 4.0 the three standalone shell tools were folded into the `imq` binary. +Update any scripts or aliases: -| 3.x | 4.x | +| 3.x | 4.x and later | |---|---| | `imqctl start …` | `imq ctl start …` | | `imqlog …` | `imq log …` | @@ -63,9 +63,10 @@ imq completions on # append the completion block to ~/.bashrc or ~/.zshrc imq completions off # remove it ``` -Then reload your shell or `source ~/.bashrc` (or `~/.zshrc`). The shell is -detected from your login shell, not from transient `ZSH_*` variables, so it -behaves correctly inside subshells. +Then reload your shell or `source ~/.bashrc` (or `~/.zshrc`). zsh is detected +from `ZSH_VERSION` or a `$SHELL` ending in `zsh` — not from any `ZSH*` variable +that happens to be set, so the `ZSH`/`ZSH_THEME` pair that oh-my-zsh exports +into bash subshells no longer misidentifies the shell. ## Files the CLI creates diff --git a/wiki/Package-Catalog.md b/wiki/Package-Catalog.md index 542949c..2fc74aa 100644 --- a/wiki/Package-Catalog.md +++ b/wiki/Package-Catalog.md @@ -27,12 +27,31 @@ imq service packages --json # machine-readable Packages belong to groups. **Exclusive** groups accept at most one member; selecting two members of the same exclusive group is rejected with an error. +At most one, not exactly one — selecting none is a normal answer, and for a +service that talks to no database it is the right one. | Group | Exclusive? | Members | |---|---|---| | **Tracing / APM** | yes | `opentelemetry`, `dd-trace` | -| **ORM / database** | yes | `sequelize`, `prisma` | -| **Service features** | no | `pg-cache`, `pg-pubsub`, `tag-cache`, `job`, `net`, `http-protect`, `graphql-dependency`, `type-graphql-dependency` | +| **ORM / database** | yes | `pg-prisma`, `sequelize` | +| **Service features** | no | `pg-cache`, `pg-pubsub`, `tag-cache`, `job`, `net`, `http-protect`, `graphql-dependency`, `type-graphql-dependency`, `validation`, `core`, `gcp` | + +Three feature entries are worth a word, since they are not capabilities in the +same sense as the rest: + +- `validation` — `@imqueue/validation` plus `zod`, for `@validatable` / + `@validate` argument classes and `@validated` methods. +- `core` — adds `@imqueue/core` as a **direct** dependency. It arrives + transitively through `@imqueue/rpc` anyway; take this only if you import from + it directly. +- `gcp` — the Google Cloud Trace exporter. It needs `opentelemetry` selected as + well, and exports traces once `GOOGLE_APPLICATION_CREDENTIALS` is set. + +These are catalog **ids** — what `--packages` takes and what a saved config +holds — not npm package names, and two of them no longer match. `dd-trace` +installs `@imqueue/datadog` and `sequelize` installs `@imqueue/pg-sequelize`, +both renamed while the ids stayed put so that existing configs and `.imqrc.json` +files keep working. ## What each addon does when selected @@ -48,6 +67,34 @@ For every selected package the scaffolder: 4. **Prints required environment variables** after creation (e.g. tracing endpoints, database URLs), so you know exactly what to configure. +Those printed variables are the ones an addon *needs* +(`OTEL_EXPORTER_OTLP_ENDPOINT`, `DD_AGENT_HOST`, `DATABASE_URL`, …). Beyond them, +the generated code reads a few of its own — see below. + +### The name a traced service reports + +Both tracing addons write their bootstrap into a module of their own +(`src/telemetry.ts` for `opentelemetry`, `src/tracer.ts` for `dd-trace`), which +the preload token imports before anything else. Where OpenTelemetry gets the +`service.name` on its spans from depends on the template's contract version: + +| [Template](Custom-Templates#template-versions-v1-vs-v2) | Variable | How it resolves | +|---|---|---| +| **v2** (the shipped default) | `SERVICE_NAME` | Read through `src/config.ts` as `config.serviceName`. It is zod-validated and **defaults to the service name you scaffolded with**, so it only needs setting to report something else. | +| **v1** (a template with no `imq-template.json`) | `IMQ_SERVICE_NAME` | The CLI inlines `const serviceName = process.env.IMQ_SERVICE_NAME \|\| ''` straight into the generated `src/telemetry.ts`. | + +Check which one applies by looking at the file: a v2 service's `telemetry.ts` +imports `config`, a v1 service's declares `serviceName` at the top. Neither +variable is printed after creation, because neither has to be set. + +`dd-trace` is not in that table on purpose — its module takes no service name at +all. Datadog resolves its own, so use `DD_SERVICE` (or the rest of `dd-trace`'s +configuration) there, exactly as you would outside @imqueue. + +Do not confuse either variable with the `%SERVICE_NAME` **template token**, which +is substituted once, at scaffold time — see +[Custom Templates](Custom-Templates#token-substitution). + ## Choosing addons interactively Run `imq config init` or `imq service create` on a TTY without `--packages` @@ -55,6 +102,43 @@ and you will get a multi-select for the feature group and single-selects for the exclusive groups. Non-interactive runs use your config/flags and never prompt. +Each exclusive list marks one member **(recommended)**, and `(none)` is always +the first choice. The recommendation is `pg-prisma` for the ORM and +`opentelemetry` for tracing — unless the fleet says otherwise. + +### Following the fleet + +`imq service create` looks at the directory the new service is being created +into, and treats every sibling directory whose `package.json` depends on +`@imqueue/rpc` as part of your fleet. If those services already agree on an +ORM or a tracing backend, that member becomes both the preselected and the +recommended one, with a line above the list saying why: + +``` +? Select ORM / database: + Only if the service uses a database — none is normal. + Preselected sequelize to match 2 services in this fleet. Moving the fleet to + pg-prisma is worth considering — as its own piece of work, not as part of this. + (none) + Prisma ORM + @imqueue/pg-prisma toolkit +❯ Sequelize ORM + @imqueue/pg-sequelize toolkit (recommended) +``` + +A new service in an established fleet belongs on the fleet's stack: matching +what is already there beats taking the default. + +A fleet that disagrees with itself gets no proposal: with a strict majority the +majority wins, and on a tie nothing is preselected and only the fallback is +marked. The same analysis drives the VCS host and CI provider prompts — see +[Creating Services](Creating-Services). + +Scanning is cheap but not free, so the result is cached in +`~/.imq/var/fleet.json`, keyed by directory (`IMQ_CLI_HOME` relocates it with +the rest of the CLI's files). The cache is invalidated when the set of sibling +directories changes. Choosing against the analysis is taken as intent: your +choice is recorded as an override for that directory and proposed next time, +until a later scan agrees with it on its own. + ## Extending the catalog Because the catalog is data, you can publish new addons by editing diff --git a/wiki/Providers.md b/wiki/Providers.md index 4488749..b2f039d 100644 --- a/wiki/Providers.md +++ b/wiki/Providers.md @@ -20,6 +20,14 @@ SCMs could be added later). Provide the token with `-T/--github-token` (works for any host) or via `vcs.auth.token` in the config. +The initial commit/push transport is set by `vcs.protocol` (`--git-protocol`): +`https` (default) authenticates the push with the access token — injected only +for that push, never persisted to `.git/config` — while `ssh` pushes over the +host's SSH URL with your own keys. Each host declares the basic-auth username +its token uses for HTTPS (`x-access-token` for GitHub, `oauth2` for GitLab, +`x-token-auth` for Bitbucket). See +[Configuration → Git transport](Configuration#git-transport-for-the-initial-push-https-vs-ssh). + ## CI providers (`--ci`) | Provider | Secret mechanism | Token | API base override | diff --git a/wiki/Real-World-Scenarios.md b/wiki/Real-World-Scenarios.md index 6c94f9a..f652205 100644 --- a/wiki/Real-World-Scenarios.md +++ b/wiki/Real-World-Scenarios.md @@ -16,7 +16,10 @@ imq service create billing ./billing -y \ This scaffolds the service, creates the `acme/billing` repo, provisions GitHub Actions sealed secrets, commits, pushes and tags `1.0.0-0`, and enables -dockerized CI builds pushing to `acme/billing` on Docker Hub. +dockerized CI builds pushing to `acme/billing` on Docker Hub. The push goes +over HTTPS authenticated with your token by default, so it works even for a +private org repo your SSH key can't reach; add `--git-protocol ssh` to push +with your own keys instead. ## 2. GitLab + CircleCI + Google Artifact Registry @@ -65,8 +68,9 @@ imq ctl start -u -c # watch combined, colour-prefixed logs imq log -# generate a client for one of them while it runs (in another terminal) -imq client generate billing ./billing/src/clients -o +# generate a client for one of them while it runs (in another terminal). +# note the queue/class name here, not the directory name used with -s +imq client generate BillingService ./billing/src/clients -o # restart a couple after code changes imq ctl restart -s billing,orders diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md index 7d5a798..c35133e 100644 --- a/wiki/Troubleshooting.md +++ b/wiki/Troubleshooting.md @@ -32,6 +32,25 @@ for org repos / Actions secrets), GitLab needs `api`, Bitbucket needs a repository-scoped access token (sent as a Bearer token). Pass it with `-T` or set `vcs.auth.token`. +## Push fails with "Repository not found" (repo *was* created) + +The remote repository is created, but the final commit/push fails with +`ERROR: Repository not found` / `Could not read from remote repository`. This +is an SSH access problem: your SSH key (or the currently "active" git/gh +account, if you have several) has no push access to the namespace — common with +a private organization repo. + +By default the CLI now pushes over **HTTPS authenticated with the access token +that created the repo**, which avoids this entirely. If you have explicitly +selected SSH (`vcs.protocol: ssh` or `--git-protocol ssh`), either: + +- switch that service/config back to HTTPS — + `imq config set vcs.protocol https` (or pass `--git-protocol https`); or +- fix your SSH access to the namespace (add the key to the right account / add + the account to the org), then re-run or push manually. + +See [Configuration → Git transport](Configuration#git-transport-for-the-initial-push-https-vs-ssh). + ## Nothing happens on an enterprise/self-hosted host Set the matching API base URL and (if the git host differs) the remote base: