From 18b8677373704eb81e1023279d7d15b27408a50d Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 03:26:25 +0000 Subject: [PATCH 01/14] feat: add drx init, drx info and create-druxt The first commands of @druxt/cli, with the drx binary, and create-druxt. - drx init creates a site from a starter. The starter comes from a registry in giget's format, read from the starters directory of this repository on the 0.x branch, with a copy bundled in the package as the fallback. - Sources and registries can be named in the user configuration file, so a private one is never named in the code. - A part of a project has a role and a kind. An adapter per kind, for Nuxt and Drupal, reads what is installed. - drx.config.json records a project's layout and parts, and drx info reports them with the versions of their packages. - create-druxt runs drx init with the arguments given, so that npm create druxt works. - The pipelines gain a job that packs both packages, installs the tarballs and runs the binaries, an end-to-end test against the real quickstart, and a coverage floor. - A README for the repository and for each package, the changelog, the first changesets and a devcontainer. --- .changeset/first-release-cli.md | 9 + .changeset/first-release-create-druxt.md | 5 + .devcontainer/devcontainer.json | 30 ++ .github/workflows/ci.yml | 38 ++ .gitlab-ci.yml | 36 ++ CHANGELOG.md | 22 + README.md | 193 ++++++++ package-lock.json | 180 +++++++- packages/cli/LICENSE | 21 + packages/cli/README.md | 21 + packages/cli/package.json | 6 + packages/cli/src/adapters/adapter.ts | 33 ++ packages/cli/src/adapters/drupal.ts | 60 +++ packages/cli/src/adapters/index.ts | 16 + packages/cli/src/adapters/nuxt.ts | 59 +++ packages/cli/src/adapters/read-json.ts | 28 ++ packages/cli/src/args.ts | 33 ++ packages/cli/src/bin.ts | 4 + packages/cli/src/cli.ts | 97 ++++ packages/cli/src/commands/info.ts | 133 ++++++ packages/cli/src/commands/init.ts | 382 +++++++++++++++ packages/cli/src/context.ts | 74 +++ packages/cli/src/errors.ts | 27 ++ packages/cli/src/index.ts | 11 + packages/cli/src/install.ts | 54 +++ packages/cli/src/layouts.ts | 24 + packages/cli/src/output.ts | 46 ++ packages/cli/src/package-root.ts | 39 ++ packages/cli/src/parts.ts | 50 ++ packages/cli/src/project.ts | 93 ++++ packages/cli/src/prompts.ts | 54 +++ packages/cli/src/registry/entry.ts | 112 +++++ packages/cli/src/registry/registry.ts | 180 ++++++++ packages/cli/src/sources.ts | 70 +++ packages/cli/src/user-config.ts | 114 +++++ packages/cli/src/validate.ts | 22 + packages/cli/test/adapters/adapters.test.ts | 143 ++++++ packages/cli/test/cli.test.ts | 64 +++ packages/cli/test/commands/info.test.ts | 185 ++++++++ packages/cli/test/commands/init.test.ts | 484 ++++++++++++++++++++ packages/cli/test/e2e/quickstart.test.ts | 55 +++ packages/cli/test/helpers/entry.ts | 35 ++ packages/cli/test/helpers/run.ts | 36 ++ packages/cli/test/helpers/server.ts | 50 ++ packages/cli/test/helpers/starter.ts | 55 +++ packages/cli/test/helpers/tmp.ts | 31 ++ packages/cli/test/install.test.ts | 75 +++ packages/cli/test/project.test.ts | 87 ++++ packages/cli/test/prompts.test.ts | 80 ++++ packages/cli/test/registry/entry.test.ts | 112 +++++ packages/cli/test/registry/registry.test.ts | 208 +++++++++ packages/cli/test/seams.test.ts | 44 ++ packages/cli/test/sources.test.ts | 81 ++++ packages/cli/test/user-config.test.ts | 143 ++++++ packages/create-druxt/LICENSE | 21 + packages/create-druxt/README.md | 13 + packages/create-druxt/package.json | 3 + packages/create-druxt/src/bin.ts | 4 + packages/create-druxt/src/index.ts | 18 + packages/create-druxt/test/create.test.ts | 36 ++ scripts/copy-starters.mjs | 20 + starters/index.json | 3 + starters/quickstart.json | 21 + vitest.config.ts | 8 + 64 files changed, 4478 insertions(+), 13 deletions(-) create mode 100644 .changeset/first-release-cli.md create mode 100644 .changeset/first-release-create-druxt.md create mode 100644 .devcontainer/devcontainer.json create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 packages/cli/LICENSE create mode 100644 packages/cli/README.md create mode 100644 packages/cli/src/adapters/adapter.ts create mode 100644 packages/cli/src/adapters/drupal.ts create mode 100644 packages/cli/src/adapters/index.ts create mode 100644 packages/cli/src/adapters/nuxt.ts create mode 100644 packages/cli/src/adapters/read-json.ts create mode 100644 packages/cli/src/args.ts create mode 100644 packages/cli/src/bin.ts create mode 100644 packages/cli/src/cli.ts create mode 100644 packages/cli/src/commands/info.ts create mode 100644 packages/cli/src/commands/init.ts create mode 100644 packages/cli/src/context.ts create mode 100644 packages/cli/src/errors.ts create mode 100644 packages/cli/src/index.ts create mode 100644 packages/cli/src/install.ts create mode 100644 packages/cli/src/layouts.ts create mode 100644 packages/cli/src/output.ts create mode 100644 packages/cli/src/package-root.ts create mode 100644 packages/cli/src/parts.ts create mode 100644 packages/cli/src/project.ts create mode 100644 packages/cli/src/prompts.ts create mode 100644 packages/cli/src/registry/entry.ts create mode 100644 packages/cli/src/registry/registry.ts create mode 100644 packages/cli/src/sources.ts create mode 100644 packages/cli/src/user-config.ts create mode 100644 packages/cli/src/validate.ts create mode 100644 packages/cli/test/adapters/adapters.test.ts create mode 100644 packages/cli/test/cli.test.ts create mode 100644 packages/cli/test/commands/info.test.ts create mode 100644 packages/cli/test/commands/init.test.ts create mode 100644 packages/cli/test/e2e/quickstart.test.ts create mode 100644 packages/cli/test/helpers/entry.ts create mode 100644 packages/cli/test/helpers/run.ts create mode 100644 packages/cli/test/helpers/server.ts create mode 100644 packages/cli/test/helpers/starter.ts create mode 100644 packages/cli/test/helpers/tmp.ts create mode 100644 packages/cli/test/install.test.ts create mode 100644 packages/cli/test/project.test.ts create mode 100644 packages/cli/test/prompts.test.ts create mode 100644 packages/cli/test/registry/entry.test.ts create mode 100644 packages/cli/test/registry/registry.test.ts create mode 100644 packages/cli/test/seams.test.ts create mode 100644 packages/cli/test/sources.test.ts create mode 100644 packages/cli/test/user-config.test.ts create mode 100644 packages/create-druxt/LICENSE create mode 100644 packages/create-druxt/README.md create mode 100644 packages/create-druxt/src/bin.ts create mode 100644 packages/create-druxt/src/index.ts create mode 100644 packages/create-druxt/test/create.test.ts create mode 100644 scripts/copy-starters.mjs create mode 100644 starters/index.json create mode 100644 starters/quickstart.json diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md new file mode 100644 index 0000000..04fd6fa --- /dev/null +++ b/.changeset/first-release-cli.md @@ -0,0 +1,9 @@ +--- +'@druxt/cli': minor +--- + +First release of the Druxt command-line tool, with the binary `drx`. + +- `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. +- `drx info` prints the versions of the CLI, Node and the packages of each part of a project. +- The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/.changeset/first-release-create-druxt.md b/.changeset/first-release-create-druxt.md new file mode 100644 index 0000000..86f7f31 --- /dev/null +++ b/.changeset/first-release-create-druxt.md @@ -0,0 +1,5 @@ +--- +'create-druxt': minor +--- + +First release. `npm create druxt my-site` runs `drx init my-site` from `@druxt/cli`. diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..ff40edd --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,30 @@ +{ + "name": "Druxt CLI", + "image": "mcr.microsoft.com/devcontainers/base:trixie", + "features": { + // The version in .nvmrc, which the pipelines build on. Node 16 is for running a site made from the 0.x + // starter: `nvm use 16.18.1` in the site's directory. + "ghcr.io/devcontainers/features/node:1": { + "version": "24.18.0", + "additionalVersions": "16.18.1" + }, + // For the Drupal part of a site `drx init` creates. The feature builds PHP from source, against trixie's + // SQLite, which meets Drupal 11's minimum. + "ghcr.io/devcontainers/features/php:1": { + "version": "8.4", + "installComposer": true + }, + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + // Installs the dependencies and builds both packages, so `drx` runs as soon as the container is up. + "postCreateCommand": "npm ci && npm run build && npm link --workspace @druxt/cli --workspace create-druxt", + "customizations": { + "vscode": { + "extensions": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "vitest.explorer" + ] + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb8c696..03e5422 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -107,6 +107,7 @@ jobs: - run: npm ci + # The coverage floor in vitest.config.ts is what fails here. - run: npm test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -114,3 +115,40 @@ jobs: with: name: test-results path: reports/junit/ + + # A published install reads each package's files allowlist and links its + # binaries, which the unit tests do not. + pack: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - run: npm run build + + - name: Pack, install and run the packages + run: | + mkdir -p "$RUNNER_TEMP/pack-check" + npm pack --workspaces --pack-destination "$RUNNER_TEMP/pack-check" + version="$(node -p "require('./packages/cli/package.json').version")" + cd "$RUNNER_TEMP/pack-check" + npm init -y > /dev/null + npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + test "$(./node_modules/.bin/drx --version)" = "$version" + test -f node_modules/@druxt/cli/starters/index.json + ./node_modules/.bin/drx info + ./node_modules/.bin/create-druxt --help + + # The one step that needs the network: a site from the real quickstart + # tarball the registry entry points at. + - run: npm run test:e2e diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f8ae19d..979a200 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -192,6 +192,9 @@ lint:prose: # --- Test --- # +# No network: the tests serve their own registry and tarball from a loopback +# port. The coverage floor in vitest.config.ts is what fails this job when +# coverage drops. test:unit: extends: .node stage: test @@ -210,6 +213,39 @@ test:unit: # Puts the coverage percentage in the merge request widget. coverage: '/All files\s*\|\s*([\d.]+)/' +# A published install reads each package's files allowlist and links its +# binaries. The unit tests read the sources and do neither, so this is the job +# that proves the packages a user downloads can be installed and run. +test:pack: + extends: .node + stage: test + needs: [] + script: + - section_start "build" "Building both packages" + - npm run build + - section_end "build" + - section_start "pack" "Packing and installing the tarballs" + - mkdir -p "$CI_PROJECT_DIR/pack-check" + - npm pack --workspaces --pack-destination "$CI_PROJECT_DIR/pack-check" + - cd "$CI_PROJECT_DIR/pack-check" && npm init -y > /dev/null + - npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + - test "$(./node_modules/.bin/drx --version)" = "$(node -p "require('$CI_PROJECT_DIR/packages/cli/package.json').version")" + - test -f node_modules/@druxt/cli/starters/index.json + - ./node_modules/.bin/drx info + - ./node_modules/.bin/create-druxt --help + - section_end "pack" + +# The one job that needs the network: it creates a site from the real +# quickstart tarball the registry entry points at, and reads it back. +test:e2e: + extends: .node + stage: test + needs: [] + script: + - section_start "e2e" "Creating a site from the real starter" + - npm run test:e2e + - section_end "e2e" + # # --- Secret detection --- # diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..03d7689 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +Each package keeps its own changelog, written by [changesets](https://github.com/changesets/changesets) +when a release is cut: + +- `@druxt/cli`: `packages/cli/CHANGELOG.md` +- `create-druxt`: `packages/create-druxt/CHANGELOG.md` + +Changes that are merged and not yet released are the files in `.changeset/`. + +Changes to the repository that are in no package, such as its pipelines, are recorded here. + +## [Unreleased] + +### Added + +- The workspace, with `@druxt/cli` and `create-druxt`, on the Druxt repository standard: committed + git hooks, linting, a GitLab pipeline and a GitHub Actions workflow, secret scanning with a + detection canary, a private-host check, an attribution check and prose linting. +- The starter registry under `starters/`, with one entry, `quickstart`. + +[Unreleased]: https://github.com/druxt/cli/commits/0.x diff --git a/README.md b/README.md new file mode 100644 index 0000000..77ed121 --- /dev/null +++ b/README.md @@ -0,0 +1,193 @@ +# Druxt CLI + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +This repository holds two packages: + +| Package | What it is | +| -------------- | ------------------------------------------------------------- | +| `@druxt/cli` | The CLI. Its binary is `drx`. | +| `create-druxt` | `npm create druxt`. It runs `drx init` and does nothing else. | + +## Quickstart + +```bash +npm create druxt@latest my-site +cd my-site +npx @druxt/cli info +``` + +You will need Node 22.12 or newer to run the CLI. The site it creates has its own requirements, which `drx init` prints. + +## Running it + +| You want to | Run | +| ------------------- | -------------------------------------------------------------------------------------------- | +| Create a site | `npm create druxt@latest [dir]` | +| Run any command | `npx @druxt/cli ` | +| Use it in a project | `npm install -D @druxt/cli`, then `drx ` in a package script or `npx drx ` | + +`npx drx` does not work outside a project that has `@druxt/cli` installed. Another package holds the name `drx` on npm, so `npx drx` downloads that package and not this one. Use `npx @druxt/cli`. + +## Commands + +### `drx init [dir]` + +Creates a site from a starter in a registry, writes `drx.config.json` at its root, and prints what the site needs and what to run next. + +| Option | What it does | Default | +| --------------------------- | ----------------------------------------------------------------- | ------------------------------------------------ | +| `[dir]` | The directory to create the site in | Asked for, or the starter's default with `--yes` | +| `--starter ` | The starter to create the site from | The registry's default | +| `--layout ` | `monorepo`, `split` or `workspace`. Only `monorepo` is available. | The starter's layout | +| `--registry ` | A starter registry: a URL, or a name from the user configuration | The public registry | +| `--source ` | Where the Druxt packages come from. Only `npm` is available. | `npm` | +| `--install`, `--no-install` | Install the site's dependencies after creating it, or do not | Asked for, or no | +| `--force` | Write into a directory that exists and is not empty | Refuse | +| `--yes`, `-y` | Accept the default for everything not given, and ask nothing | | +| `--json` | Print the result as JSON on stdout | | + +At a terminal, `init` asks for the directory, the starter when the registry has more than one, the layout, and whether to install. A flag answers each question, so the command runs unattended: + +```bash +npx @druxt/cli init my-site --yes --json +``` + +With no terminal, `init` uses the defaults and never waits for input. It needs the directory or `--yes`, and fails with a message saying so when it has neither. + +`--install` runs the install of the package manager the starter declares. For the `quickstart` starter that is `npm install`, which also sets up the Drupal backend when PHP and Composer are present. + +### `drx info` + +Prints the versions of the CLI and Node. Inside a project it adds the layout and, for each part, the packages that matter: `nuxt` and every `druxt`, `druxt-*` or `@druxt/*` package for a Nuxt part, and Drupal core and the Druxt module for a Drupal part. Run it from any directory in the project. + +| Option | What it does | +| -------- | ---------------------------------- | +| `--json` | Print the report as JSON on stdout | + +Outside a project it says so and prints the two versions. + +### `drx --help`, `drx --help`, `drx --version` + +Usage for the CLI or one command, and the version. + +### Output and exit codes + +- The result of a command goes to stdout: text, or one JSON document with `--json`. +- Progress, warnings, errors and prompts go to stderr. +- A command that fails exits with 1. With `--json` it also prints `{ "ok": false, "error": { "code", "message" } }` on stdout. + +## The project configuration + +`drx init` writes `drx.config.json` at the root of the site. Later commands find the project by it. + +```json +{ + "layout": "monorepo", + "line": "0.x", + "starter": "quickstart", + "source": "npm", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ] +} +``` + +| Key | What it holds | +| --------- | ---------------------------------------------------------------------------------------------------- | +| `layout` | The arrangement of the parts: `monorepo`, `split` or `workspace` | +| `line` | The Druxt release line | +| `starter` | The name of the starter the site was created from | +| `source` | The name of the source its Druxt packages come from | +| `parts` | Each part of the site: its `role` (`frontend` or `backend`), its `kind` and its `path` from the root | + +A kind is `nuxt` or `drupal` in this version. + +## The starter registry + +A registry is a URL that answers `/.json` for each starter, in the format [giget](https://github.com/unjs/giget) defines, and `/index.json` with the names. The public registry is the [`starters/`](starters/) directory of this repository. + +```json +{ + "name": "quickstart", + "tar": "https://codeload.github.com/druxt/quickstart/tar.gz/refs/heads/develop", + "defaultDir": "my-druxt-site", + "url": "https://github.com/druxt/quickstart", + "druxt": { + "line": "0.x", + "layout": "monorepo", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ], + "requires": { + "node": "16.18.1", + "tools": ["PHP 8.3 or newer with Composer, or DDEV"] + }, + "maintained": "2026-11-15", + "default": true, + "steps": ["npm run setup", "npm run dev"] + } +} +``` + +`name`, `tar`, `defaultDir`, `url`, `subdir` and `headers` are giget's fields. giget ignores the `druxt` object, so the same file works with `npx giget --registry quickstart`. + +| Key in `druxt` | What it holds | +| ---------------- | -------------------------------------------------------------------------- | +| `line` | The Druxt release line | +| `layout` | The layout the starter has | +| `parts` | The parts of the starter, as in the project configuration | +| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | +| `requires.tools` | What else the site needs, each as a phrase to show the user | +| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | +| `default` | `true` for the starter `init` uses when none is named | +| `steps` | Optional. The commands to run in the new site, in order | + +`index.json` is `{ "starters": ["quickstart"] }`. + +`init` checks an entry before it downloads anything, and fails with a message naming the field that is wrong. It warns when the starter was last maintained more than a year ago, and when the running Node is not the one the starter needs. + +The package includes a copy of the public registry. When the public registry cannot be read, `init` uses the copy and says so. A registry you name with `--registry` is never replaced by the copy. + +## The user configuration + +`~/.config/drx/config.json` names registries and sources of your own. `DRX_CONFIG` points at another file, and `XDG_CONFIG_HOME` is used when it is set. + +```json +{ + "registries": { + "team": "https://example.com/starters" + }, + "sources": { + "next": { "type": "npm", "tag": "next" }, + "branch": { "type": "git", "url": "https://example.com/druxt.git", "ref": "main" } + } +} +``` + +- `--registry team` reads starters from that URL. `GIGET_AUTH` is giget's own variable, and giget sends it as a bearer token with every tarball it downloads. The CLI also sends it to a registry you name, and never to the public registry. +- `--source` takes `npm`, `git:#`, or a name defined here. Only `npm` creates a site in this version. The others are read and answer that they are not available yet. + +## Not there yet + +- The `split` and `workspace` layouts. `--layout` accepts them and fails with a message. +- Sources other than `npm`. +- Adding a module, making a wrapper component and upgrading a site. +- Kinds other than `nuxt` and `drupal`. +- A published public registry. Until this repository is public, `init` reads the copy in the package. + +## Development + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +```bash +npm install +npm run build +npm test +``` + +## Licence + +[MIT](LICENSE) diff --git a/package-lock.json b/package-lock.json index 40e5409..bf3aa7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62,7 +62,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -72,7 +72,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -82,7 +82,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.29.14" @@ -98,7 +98,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.14", @@ -389,7 +389,6 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.6.0.tgz", "integrity": "sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-width": "^3.0.2", @@ -404,7 +403,6 @@ "version": "1.9.0", "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.9.0.tgz", "integrity": "sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==", - "dev": true, "license": "MIT", "dependencies": { "@clack/core": "1.6.0", @@ -3397,6 +3395,34 @@ "node": ">=8" } }, + "node_modules/c12": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", + "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "confbox": "^0.2.4", + "defu": "^6.1.6", + "dotenv": "^17.3.1", + "exsolve": "^1.0.8", + "giget": "^3.2.0", + "jiti": "^2.6.1", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^2.1.0", + "pkg-types": "^2.3.0", + "rc9": "^3.0.1" + }, + "peerDependencies": { + "magicast": "*" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, "node_modules/cac": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/cac/-/cac-7.1.0.tgz", @@ -3516,6 +3542,27 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "license": "MIT" + }, "node_modules/cliui": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", @@ -3573,6 +3620,12 @@ "node": ">= 6" } }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "license": "MIT" + }, "node_modules/conventional-changelog-angular": { "version": "9.4.0", "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-9.4.0.tgz", @@ -3914,6 +3967,12 @@ "dev": true, "license": "MIT" }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -3924,6 +3983,12 @@ "node": ">=6" } }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -3949,6 +4014,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/emoji-regex": { "version": "10.6.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", @@ -4261,6 +4338,12 @@ "node": ">=12.0.0" } }, + "node_modules/exsolve": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "integrity": "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==", + "license": "MIT" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -4326,14 +4409,12 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", - "dev": true, "license": "MIT" }, "node_modules/fast-string-width": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-truncated-width": "^3.0.2" @@ -4360,7 +4441,6 @@ "version": "0.2.2", "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-width": "^3.0.2" @@ -4542,6 +4622,15 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/giget": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", + "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", + "license": "MIT", + "bin": { + "giget": "dist/cli.mjs" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -4852,7 +4941,6 @@ "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", - "dev": true, "license": "MIT", "bin": { "jiti": "lib/jiti-cli.mjs" @@ -5374,7 +5462,7 @@ "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -6250,6 +6338,12 @@ "node": ">=12.20.0" } }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "license": "MIT" + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -6447,6 +6541,18 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -6467,6 +6573,23 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkg-types": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "integrity": "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==", + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.3", + "pathe": "^2.0.3" + } + }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "integrity": "sha512-ZUAKhKlkCOrIGKc8cj7zek9s9z1mveHif/25nUshI2BzCRzF7KH7KHa+Lnh2ubq+e1tIlaFuP763mzW4qVoehg==", + "license": "MIT" + }, "node_modules/postcss": { "version": "8.5.33", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", @@ -6584,6 +6707,16 @@ ], "license": "MIT" }, + "node_modules/rc9": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", + "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", + "license": "MIT", + "dependencies": { + "defu": "^6.1.7", + "destr": "^2.0.5" + } + }, "node_modules/re2js": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/re2js/-/re2js-2.9.1.tgz", @@ -6594,6 +6727,19 @@ "node": ">=20.0.0" } }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -6748,7 +6894,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-2.0.0.tgz", "integrity": "sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==", - "dev": true, "license": "MIT", "engines": { "node": ">=20" @@ -6784,7 +6929,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -7380,6 +7525,12 @@ "name": "@druxt/cli", "version": "0.0.0", "license": "MIT", + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" + }, "bin": { "drx": "dist/bin.js" }, @@ -7390,6 +7541,9 @@ "packages/create-druxt": { "version": "0.0.0", "license": "MIT", + "dependencies": { + "@druxt/cli": "^0.0.0" + }, "bin": { "create-druxt": "dist/bin.js" }, diff --git a/packages/cli/LICENSE b/packages/cli/LICENSE new file mode 100644 index 0000000..51b53d2 --- /dev/null +++ b/packages/cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DruxtJS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..335895d --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,21 @@ +# @druxt/cli + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +```bash +npx @druxt/cli init my-site +npx @druxt/cli info +``` + +The binary is `drx`. Install the package in a project to use that name: `npm install -D @druxt/cli`, then `drx ` in a package script. `npx drx` without the package installed downloads another package that holds the name on npm. + +| Command | What it does | +| ---------------- | ------------------------------------------------------------------------- | +| `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | +| `drx info` | Prints the versions of the CLI, Node and the packages of each part | + +The options, the registry format and the configuration files are in the [repository README](https://github.com/druxt/cli#readme). + +## Licence + +[MIT](LICENSE) diff --git a/packages/cli/package.json b/packages/cli/package.json index 4749cba..5784807 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -36,5 +36,11 @@ }, "publishConfig": { "access": "public" + }, + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts new file mode 100644 index 0000000..623b547 --- /dev/null +++ b/packages/cli/src/adapters/adapter.ts @@ -0,0 +1,33 @@ +import { DrxError } from '../errors.js' +import type { Role } from '../parts.js' + +/** One package a part depends on. */ +export interface PackageVersion { + name: string + /** The range the part asks for, or null when it does not declare one. */ + range: string | null + /** The version that is installed, or null when none is. */ + installed: string | null +} + +/** + * Everything the CLI knows about one kind of part. The commands call this + * interface and never a kind by name, so a new kind is a new file in this + * directory and one line in index.ts. + */ +export interface KindAdapter { + /** The value a part's `kind` holds. */ + readonly kind: string + readonly role: Role + /** True when the directory holds a part of this kind. */ + detect(dir: string): Promise + /** The packages `info` reports for a part of this kind. */ + packages(dir: string): Promise + /** Installs a module into the part and registers it. Not available yet. */ + addModule(dir: string, name: string): Promise +} + +/** The `addModule` of every adapter until the `add` command exists. */ +export async function addModuleNotAvailable(): Promise { + throw new DrxError('not-available', 'Adding a module is not available yet.') +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts new file mode 100644 index 0000000..e043157 --- /dev/null +++ b/packages/cli/src/adapters/drupal.ts @@ -0,0 +1,60 @@ +import { join } from 'node:path' +import { isRecord } from '../validate.js' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +/** Any of these in `require` makes a Composer project a Drupal site. */ +const CORE = ['drupal/core-recommended', 'drupal/core'] +const REPORTED = [...CORE, 'drupal/druxt'] + +async function required(dir: string): Promise> { + return stringMap(await readJsonObject(join(dir, 'composer.json')), 'require') +} + +/** The version of each package Composer has installed, which is none until `composer install` has run. */ +async function installed(dir: string): Promise> { + const manifest = await readJsonObject( + join(dir, 'vendor', 'composer', 'installed.json') + ) + const versions = new Map() + const packages = manifest?.packages + if (!Array.isArray(packages)) return versions + for (const entry of packages) { + if ( + isRecord(entry) && + typeof entry.name === 'string' && + typeof entry.version === 'string' + ) { + versions.set(entry.name, entry.version) + } + } + return versions +} + +export const drupalAdapter: KindAdapter = { + kind: 'drupal', + role: 'backend', + + async detect(dir) { + const requires = await required(dir) + return CORE.some((name) => name in requires) + }, + + async packages(dir) { + const requires = await required(dir) + const versions = await installed(dir) + return REPORTED.filter((name) => name in requires).map( + (name): PackageVersion => ({ + name, + range: requires[name] ?? null, + installed: versions.get(name) ?? null, + }) + ) + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/index.ts b/packages/cli/src/adapters/index.ts new file mode 100644 index 0000000..e8dfaef --- /dev/null +++ b/packages/cli/src/adapters/index.ts @@ -0,0 +1,16 @@ +import type { KindAdapter } from './adapter.js' +import { drupalAdapter } from './drupal.js' +import { nuxtAdapter } from './nuxt.js' + +export type { KindAdapter, PackageVersion } from './adapter.js' + +/** Every kind this version knows. A new kind is a new file and a line here. */ +const ADAPTERS: readonly KindAdapter[] = [nuxtAdapter, drupalAdapter] + +export function adapterFor(kind: string): KindAdapter | undefined { + return ADAPTERS.find((adapter) => adapter.kind === kind) +} + +export function knownKinds(): string[] { + return ADAPTERS.map((adapter) => adapter.kind) +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts new file mode 100644 index 0000000..aa62f99 --- /dev/null +++ b/packages/cli/src/adapters/nuxt.ts @@ -0,0 +1,59 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +const CONFIG_FILES = ['js', 'ts', 'mjs', 'cjs', 'mts'].map( + (extension) => `nuxt.config.${extension}` +) + +/** The framework itself, then the Druxt packages of either naming scheme. */ +const FRAMEWORK = 'nuxt' +const DRUXT_PACKAGE = /^(druxt|druxt-.+|@druxt\/.+)$/ + +async function declared(dir: string): Promise> { + const manifest = await readJsonObject(join(dir, 'package.json')) + return { + ...stringMap(manifest, 'devDependencies'), + ...stringMap(manifest, 'dependencies'), + } +} + +export const nuxtAdapter: KindAdapter = { + kind: 'nuxt', + role: 'frontend', + + async detect(dir) { + if (CONFIG_FILES.some((file) => existsSync(join(dir, file)))) return true + return FRAMEWORK in (await declared(dir)) + }, + + async packages(dir) { + const ranges = await declared(dir) + const names = Object.keys(ranges) + .filter((name) => name === FRAMEWORK || DRUXT_PACKAGE.test(name)) + .sort((a, b) => + a === FRAMEWORK ? -1 : b === FRAMEWORK ? 1 : a.localeCompare(b) + ) + + const versions: PackageVersion[] = [] + for (const name of names) { + const installed = await readJsonObject( + join(dir, 'node_modules', name, 'package.json') + ) + versions.push({ + name, + range: ranges[name] ?? null, + installed: + typeof installed?.version === 'string' ? installed.version : null, + }) + } + return versions + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/read-json.ts b/packages/cli/src/adapters/read-json.ts new file mode 100644 index 0000000..11b6f00 --- /dev/null +++ b/packages/cli/src/adapters/read-json.ts @@ -0,0 +1,28 @@ +import { readFile } from 'node:fs/promises' +import { isRecord } from '../validate.js' + +/** A JSON file's object, or undefined when it is missing or not an object. */ +export async function readJsonObject( + file: string +): Promise | undefined> { + try { + const parsed: unknown = JSON.parse(await readFile(file, 'utf8')) + return isRecord(parsed) ? parsed : undefined + } catch { + return undefined + } +} + +/** The string values of one key of an object, such as `dependencies`. */ +export function stringMap( + object: Record | undefined, + key: string +): Record { + const value = object?.[key] + if (!isRecord(value)) return {} + return Object.fromEntries( + Object.entries(value).filter( + (entry): entry is [string, string] => typeof entry[1] === 'string' + ) + ) +} diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts new file mode 100644 index 0000000..f4e9ecc --- /dev/null +++ b/packages/cli/src/args.ts @@ -0,0 +1,33 @@ +import type { ArgsDef } from 'citty' +import { DrxError } from './errors.js' + +/** + * Fails on an option the command does not define. citty accepts any flag + * and hands it to the command, so a mistyped one would otherwise be ignored. + */ +export function assertKnownOptions( + rawArgs: string[], + definitions: ArgsDef, + command: string +): void { + const known = new Set() + for (const [name, definition] of Object.entries(definitions)) { + if (definition.type === 'positional') continue + known.add(name) + if (definition.type === 'boolean') known.add(`no-${name}`) + const alias = 'alias' in definition ? definition.alias : undefined + for (const short of [alias ?? []].flat()) known.add(short) + } + + for (const argument of rawArgs) { + if (argument === '--') return + if (!argument.startsWith('-') || argument === '-') continue + const name = argument.replace(/^--?/, '').split('=')[0] ?? '' + if (!known.has(name)) { + throw new DrxError( + 'usage', + `Unknown option ${argument.split('=')[0]}. Run "drx ${command} --help" for the options.` + ) + } + } +} diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts new file mode 100644 index 0000000..a566d17 --- /dev/null +++ b/packages/cli/src/bin.ts @@ -0,0 +1,4 @@ +#!/usr/bin/env node +import { runCli } from './cli.js' + +process.exitCode = await runCli(process.argv.slice(2)) diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts new file mode 100644 index 0000000..44f075e --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,97 @@ +import { stripVTControlCharacters } from 'node:util' +import { defineCommand, renderUsage, runCommand, type CommandDef } from 'citty' +import { infoCommand } from './commands/info.js' +import { initCommand } from './commands/init.js' +import { defaultContext, type CliContext, type TextStream } from './context.js' +import { DrxError } from './errors.js' +import { cliVersion } from './package-root.js' + +function mainCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'drx', + version: cliVersion(), + description: 'The Druxt command-line tool', + }, + subCommands: { + init: initCommand(context), + info: infoCommand(context), + }, + }) +} + +/** citty colours its output whatever it writes to. A pipe gets plain text. */ +function plain(stream: TextStream, text: string): string { + return stream.isTTY ? text : stripVTControlCharacters(text) +} + +/** The usage of the command the arguments name, or of `drx` itself. */ +async function usage( + main: CommandDef, + subCommands: Record, + argv: string[] +): Promise { + const name = argv.find((argument) => !argument.startsWith('-')) + const command = name ? subCommands[name] : undefined + return command ? renderUsage(command, main) : renderUsage(main) +} + +/** The code and message to report for anything a command throws. */ +function describe(error: unknown): { code: string; message: string } { + if (error instanceof DrxError) { + return { code: error.code, message: error.message } + } + // citty's own error for a bad argument or command. The class is not + // exported, so it is recognised by name. + if (error instanceof Error && error.name === 'CLIError') { + return { + code: 'usage', + message: `${stripVTControlCharacters(error.message)}. Run "drx --help" for the commands and "drx --help" for their options.`, + } + } + return { + code: 'unexpected', + message: + error instanceof Error ? (error.stack ?? error.message) : String(error), + } +} + +/** + * Runs the CLI with the given arguments and returns the exit code. It never + * exits the process or throws, so a caller decides what to do with the code. + */ +export async function runCli( + argv: string[], + overrides: Partial = {} +): Promise { + const context = { ...defaultContext(), ...overrides } + const main = mainCommand(context) + const subCommands = main.subCommands as Record + const { stdout, stderr } = context + + try { + if (argv.includes('--help') || argv.includes('-h')) { + stdout.write(`${plain(stdout, await usage(main, subCommands, argv))}\n`) + return 0 + } + if (argv.length === 1 && ['--version', '-v'].includes(argv[0] ?? '')) { + stdout.write(`${cliVersion()}\n`) + return 0 + } + if (argv.length === 0) { + stderr.write(`${plain(stderr, await renderUsage(main))}\n`) + return 1 + } + await runCommand(main, { rawArgs: argv }) + return 0 + } catch (error) { + const failure = describe(error) + if (argv.includes('--json')) { + stdout.write( + `${JSON.stringify({ ok: false, error: failure }, null, 2)}\n` + ) + } + stderr.write(`Error: ${failure.message}\n`) + return 1 + } +} diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts new file mode 100644 index 0000000..8cf8775 --- /dev/null +++ b/packages/cli/src/commands/info.ts @@ -0,0 +1,133 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { adapterFor, type PackageVersion } from '../adapters/index.js' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { columns, createOutput } from '../output.js' +import { cliVersion } from '../package-root.js' +import type { Part } from '../parts.js' +import { + CONFIG_FILE, + findProjectRoot, + loadProjectConfig, + type ProjectConfig, +} from '../project.js' + +interface PartReport extends Part { + /** False when the part's directory is not there. */ + exists: boolean + /** True when the adapter for its kind recognises the directory. */ + detected: boolean + packages: PackageVersion[] +} + +interface InfoReport { + cli: { name: string; version: string } + node: string + project: + | (Omit & { + root: string + parts: PartReport[] + }) + | null +} + +async function reportPart(root: string, part: Part): Promise { + const dir = join(root, part.path) + const adapter = adapterFor(part.kind) + const exists = existsSync(dir) + const detected = exists && adapter ? await adapter.detect(dir) : false + return { + ...part, + exists, + detected, + packages: detected && adapter ? await adapter.packages(dir) : [], + } +} + +function partLines(part: PartReport): string[] { + const heading = `${part.role} ${part.kind} ${part.path}/` + if (!adapterFor(part.kind)) { + return [heading, ` This version has no adapter for the ${part.kind} kind.`] + } + if (!part.exists) return [heading, ' The directory does not exist.'] + if (!part.detected) { + return [heading, ` The directory does not look like a ${part.kind} part.`] + } + if (part.packages.length === 0) { + return [heading, ' No packages to report.'] + } + const rows = part.packages.map((entry) => [ + entry.name, + entry.range ?? '', + entry.installed ? `installed ${entry.installed}` : 'not installed', + ]) + return [heading, ...columns(rows, ' ')] +} + +function text(report: InfoReport, cwd: string): string { + const lines = columns([ + ['drx', report.cli.version], + ['Node', report.node], + ]) + lines.push('') + const project = report.project + if (!project) { + lines.push( + `Not inside a Druxt project: no ${CONFIG_FILE} in ${cwd} or above it.` + ) + return lines.join('\n') + } + lines.push( + ...columns([ + ['Project', project.root], + ['Layout', project.layout], + ['Line', project.line], + ['Starter', project.starter], + ['Source', project.source], + ]) + ) + for (const part of project.parts) { + lines.push('', ...partLines(part)) + } + return lines.join('\n') +} + +const args = { + json: { + type: 'boolean', + description: 'Print the report as JSON on stdout', + }, +} satisfies ArgsDef + +export function infoCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'info', + description: + 'Print the versions of the CLI, Node and the packages of each part of the project', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'info') + const output = createOutput(context, parsed.json === true) + + const report: InfoReport = { + cli: { name: '@druxt/cli', version: cliVersion() }, + node: context.nodeVersion, + project: null, + } + const root = findProjectRoot(context.cwd) + if (root) { + const config = await loadProjectConfig(root) + const parts: PartReport[] = [] + for (const part of config.parts) { + parts.push(await reportPart(root, part)) + } + report.project = { root, ...config, parts } + } + output.result(report, text(report, context.cwd)) + }, + }) +} diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts new file mode 100644 index 0000000..f23fb2e --- /dev/null +++ b/packages/cli/src/commands/init.ts @@ -0,0 +1,382 @@ +import { existsSync, readdirSync, statSync } from 'node:fs' +import { isAbsolute, join, relative, resolve } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + assertLayoutAvailable, + AVAILABLE_LAYOUTS, + isLayout, + LAYOUTS, + type Layout, +} from '../layouts.js' +import { createOutput, type Output } from '../output.js' +import { writeProjectConfig, type ProjectConfig } from '../project.js' +import type { StarterEntry } from '../registry/entry.js' +import { + defaultStarter, + openRegistry, + type Registry, +} from '../registry/registry.js' +import { + assertSourceAvailable, + DEFAULT_SOURCE, + resolveSource, +} from '../sources.js' +import { loadUserConfig, resolveRegistryUrl } from '../user-config.js' + +/** A starter not maintained for this long gets a warning. */ +const STALE_AFTER_DAYS = 365 + +const args = { + dir: { + type: 'positional', + required: false, + description: 'The directory to create the site in', + }, + starter: { + type: 'string', + valueHint: 'name', + description: + 'The starter to create the site from (default: the default of the registry)', + }, + layout: { + type: 'enum', + options: [...LAYOUTS], + description: `How the parts of the site are put together (available: ${AVAILABLE_LAYOUTS.join(', ')})`, + }, + registry: { + type: 'string', + valueHint: 'url', + description: + 'A starter registry: a URL, or a name from the user configuration', + }, + source: { + type: 'string', + valueHint: 'name', + description: `Where the Druxt packages come from (default: ${DEFAULT_SOURCE})`, + }, + install: { + type: 'boolean', + description: 'Install the dependencies of the site after creating it', + negativeDescription: 'Do not install the dependencies of the site', + }, + force: { + type: 'boolean', + description: 'Write into a directory that exists and is not empty', + }, + yes: { + type: 'boolean', + alias: 'y', + description: 'Accept the default for everything not given, and ask nothing', + }, + json: { + type: 'boolean', + description: 'Print the result as JSON on stdout', + }, +} satisfies ArgsDef + +interface InitOptions { + dir?: string + starter?: string + layout?: Layout + registry?: string + source?: string + install?: boolean + force: boolean + yes: boolean +} + +/** A string option's value, or an error when it was given with none. */ +function valueOf(name: string, value: unknown): string | undefined { + if (value === undefined) return undefined + if (typeof value !== 'string' || value.trim() === '') { + throw new DrxError('usage', `--${name} needs a value.`) + } + return value +} + +async function chooseStarter( + registry: Registry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + if (options.starter) return registry.entry(options.starter) + + const names = await registry.names() + if (canAsk && names.length > 1) { + const chosen = await context.prompter.select({ + message: 'Which starter?', + choices: names.map((name) => ({ value: name, label: name })), + }) + return registry.entry(chosen) + } + + const entry = await defaultStarter(registry) + if (!entry) { + throw new DrxError( + 'unknown-starter', + `The registry marks no starter as the default. Pass --starter with one of: ${names.join(', ')}.` + ) + } + return entry +} + +async function chooseLayout( + entry: StarterEntry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + const own = entry.druxt.layout + let layout = options.layout + if (!layout && canAsk) { + layout = await context.prompter.select({ + message: 'Which layout?', + choices: LAYOUTS.map((value) => ({ + value, + label: value, + ...(AVAILABLE_LAYOUTS.includes(value) + ? {} + : { hint: 'not available yet' }), + })), + initial: own, + }) + } + layout ??= own + assertLayoutAvailable(layout) + if (layout !== own) { + throw new DrxError( + 'not-available', + `The ${entry.name} starter has the ${own} layout and cannot be created as ${layout}.` + ) + } + return layout +} + +/** The directory to create, checked against what is already there. */ +function targetDirectory(cwd: string, dir: string, force: boolean): string { + const target = resolve(cwd, dir) + if (!existsSync(target)) return target + if (!statSync(target).isDirectory()) { + throw new DrxError( + 'directory-not-empty', + `${target} is a file, not a directory.` + ) + } + if (!force && readdirSync(target).length > 0) { + throw new DrxError( + 'directory-not-empty', + `${target} exists and is not empty. Choose another directory, or pass --force to write into it.` + ) + } + return target +} + +/** True when `running` is the version `needed` names, or one inside it. */ +function nodeSatisfies(running: string, needed: string): boolean { + const version = needed.replace(/^v/, '') + return running === version || running.startsWith(`${version}.`) +} + +function warnAboutStarter( + entry: StarterEntry, + target: string, + context: CliContext, + output: Output +): void { + const { requires, maintained, parts } = entry.druxt + if (!nodeSatisfies(context.nodeVersion, requires.node)) { + output.warn( + `The ${entry.name} starter needs Node ${requires.node} and this is Node ${context.nodeVersion}. Switch before you install or run the site.` + ) + } + const age = context.now().getTime() - new Date(maintained).getTime() + if (age > STALE_AFTER_DAYS * 24 * 60 * 60 * 1000) { + output.warn( + `The ${entry.name} starter was last maintained on ${maintained} and may no longer work.` + ) + } + for (const part of parts) { + if (!existsSync(join(target, part.path))) { + output.warn( + `The starter has no ${part.path}/ directory, which its registry entry names as the ${part.role} part.` + ) + } + } +} + +async function runInit( + options: InitOptions, + context: CliContext, + output: Output +): Promise { + const canAsk = context.interactive && !options.yes + if (!options.dir && !canAsk && !options.yes) { + throw new DrxError( + 'usage', + 'No directory was given and there is no terminal to ask on. Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.' + ) + } + + // Everything that can fail without the network is checked before it is used. + const userConfig = await loadUserConfig(context.env) + const source = resolveSource(options.source ?? DEFAULT_SOURCE, userConfig) + assertSourceAvailable(source) + if (options.layout) assertLayoutAvailable(options.layout) + const registryUrl = options.registry + ? resolveRegistryUrl(options.registry, userConfig) + : undefined + + const registry = await openRegistry({ + ...(registryUrl ? { url: registryUrl } : {}), + defaultUrl: context.defaultRegistry, + bundledDir: context.bundledRegistryDir, + fetch: context.fetch, + ...(context.env.GIGET_AUTH ? { auth: context.env.GIGET_AUTH } : {}), + }) + if (registry.origin === 'bundled') { + output.note(`${registry.fallbackReason}`) + output.note('Reading starters from the copy bundled with this version.') + } else { + output.note(`Reading starters from ${registry.location}.`) + } + + const entry = await chooseStarter(registry, options, context, canAsk) + const layout = await chooseLayout(entry, options, context, canAsk) + + const defaultDir = entry.defaultDir ?? entry.name + const dir = + options.dir ?? + (canAsk + ? await context.prompter.text({ + message: 'Where should the site be created?', + initial: defaultDir, + }) + : defaultDir) + const target = targetDirectory(context.cwd, dir, options.force) + + const install = + options.install ?? + (canAsk + ? await context.prompter.confirm({ + message: 'Install its dependencies now?', + initial: false, + }) + : false) + + output.note(`Fetching the ${entry.name} starter from ${entry.tar}.`) + try { + await context.download(`starter:${entry.name}`, { + // The entry is already read and checked, so giget is handed it as it + // is and looks nothing up. + providers: { + starter: () => ({ + name: entry.name, + tar: entry.tar, + ...(entry.subdir ? { subdir: entry.subdir } : {}), + ...(entry.headers ? { headers: entry.headers } : {}), + }), + }, + registry: false, + dir: target, + // The directory was checked above, with --force taken into account. + force: true, + silent: true, + }) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'download', + `Could not fetch the ${entry.name} starter: ${detail}` + ) + } + + const config: ProjectConfig = { + layout, + line: entry.druxt.line, + starter: entry.name, + source: source.name, + parts: entry.druxt.parts, + } + await writeProjectConfig(target, config) + warnAboutStarter(entry, target, context, output) + + if (install) { + output.note('Installing dependencies.') + try { + await context.install(target) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'install', + `The site was created in ${target}, but installing its dependencies failed: ${detail}` + ) + } + } + + const fromCwd = relative(context.cwd, target) + const inside = fromCwd !== '' && !fromCwd.startsWith('..') + const next = [ + `cd ${inside && !isAbsolute(fromCwd) ? fromCwd : target}`, + ...(entry.druxt.steps ?? []), + ] + const { requires } = entry.druxt + + output.result( + { + ok: true, + directory: target, + registry: { origin: registry.origin, location: registry.location }, + ...config, + installed: install, + requires, + next, + }, + [ + `Created a Druxt site in ${target} from the ${entry.name} starter.`, + '', + 'It needs:', + ` Node ${requires.node}`, + ...requires.tools.map((tool) => ` ${tool}`), + '', + 'Next:', + ...next.map((step) => ` ${step}`), + ].join('\n') + ) +} + +export function initCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'init', + description: 'Create a Druxt site from a starter', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'init') + const options: InitOptions = { + force: parsed.force === true, + yes: parsed.yes === true, + } + const dir = valueOf('dir', parsed.dir) + const starter = valueOf('starter', parsed.starter) + const registry = valueOf('registry', parsed.registry) + const source = valueOf('source', parsed.source) + if (dir) options.dir = dir + if (starter) options.starter = starter + if (registry) options.registry = registry + if (source) options.source = source + if (isLayout(parsed.layout)) options.layout = parsed.layout + if (typeof parsed.install === 'boolean') options.install = parsed.install + + await runInit( + options, + context, + createOutput(context, parsed.json === true) + ) + }, + }) +} diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts new file mode 100644 index 0000000..b4458d8 --- /dev/null +++ b/packages/cli/src/context.ts @@ -0,0 +1,74 @@ +import { downloadTemplate } from 'giget' +import { installDependencies } from './install.js' +import { bundledRegistryDir } from './package-root.js' +import { terminalPrompter } from './prompts.js' +import { DEFAULT_REGISTRY } from './registry/registry.js' + +/** The part of a stream the CLI writes to. */ +export interface TextStream { + write(chunk: string): unknown + isTTY?: boolean +} + +export interface Choice { + value: T + label: string + hint?: string +} + +/** The questions a command may ask a person at the terminal. */ +export interface Prompter { + text(question: { message: string; initial?: string }): Promise + select(question: { + message: string + choices: Choice[] + initial?: T + }): Promise + confirm(question: { message: string; initial: boolean }): Promise +} + +/** + * Everything a command takes from the process it runs in. The tests pass + * their own, so no command reads `process` directly. + */ +export interface CliContext { + cwd: string + env: Record + /** The result of a command: its text, or its JSON with `--json`. */ + stdout: TextStream + /** Progress, warnings, errors and prompts. */ + stderr: TextStream + /** True when a person is at the terminal to answer a prompt. */ + interactive: boolean + /** The running Node version, without the leading `v`. */ + nodeVersion: string + now: () => Date + fetch: typeof fetch + prompter: Prompter + /** The registry used when `--registry` is not given. */ + defaultRegistry: string + /** The copy of the registry used when the default cannot be read. */ + bundledRegistryDir: string + /** Fetches and unpacks a template. giget's `downloadTemplate`. */ + download: typeof downloadTemplate + /** Installs the dependencies of the site in a directory. */ + install: (dir: string) => Promise +} + +export function defaultContext(): CliContext { + return { + cwd: process.cwd(), + env: process.env, + stdout: process.stdout, + stderr: process.stderr, + interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY), + nodeVersion: process.versions.node, + now: () => new Date(), + fetch: globalThis.fetch, + prompter: terminalPrompter(), + defaultRegistry: DEFAULT_REGISTRY, + bundledRegistryDir: bundledRegistryDir(), + download: downloadTemplate, + install: (dir) => installDependencies(dir), + } +} diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..ef3e6ee --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,27 @@ +/** What went wrong, for a caller reading `--json` output. */ +export type DrxErrorCode = + | 'usage' + | 'not-available' + | 'registry' + | 'invalid-entry' + | 'unknown-starter' + | 'unknown-source' + | 'directory-not-empty' + | 'config' + | 'download' + | 'install' + | 'cancelled' + +/** + * A failure the user can act on. Its message is printed as it is, with no + * stack trace, and the process exits non-zero. + */ +export class DrxError extends Error { + readonly code: DrxErrorCode + + constructor(code: DrxErrorCode, message: string) { + super(message) + this.name = 'DrxError' + this.code = code + } +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 0000000..90930bb --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,11 @@ +export { runCli } from './cli.js' +export type { CliContext, Prompter } from './context.js' +export { DrxError, type DrxErrorCode } from './errors.js' +export type { KindAdapter, PackageVersion } from './adapters/index.js' +export type { Layout } from './layouts.js' +export type { Part, Role } from './parts.js' +export type { ProjectConfig } from './project.js' +export type { StarterDetails, StarterEntry } from './registry/entry.js' +export { DEFAULT_REGISTRY } from './registry/registry.js' +export type { Source, SourceDefinition } from './sources.js' +export type { UserConfig } from './user-config.js' diff --git a/packages/cli/src/install.ts b/packages/cli/src/install.ts new file mode 100644 index 0000000..221ab27 --- /dev/null +++ b/packages/cli/src/install.ts @@ -0,0 +1,54 @@ +import { spawn } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' + +const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const +type Manager = (typeof MANAGERS)[number] + +/** + * The package manager a directory declares in the `packageManager` field of + * its package.json, or npm when it declares none. Undefined when there is no + * package.json to install from. + */ +export async function packageManagerOf( + dir: string +): Promise { + let manifest: { packageManager?: unknown } + try { + manifest = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) + } catch { + return undefined + } + const declared = String(manifest.packageManager ?? '').split('@')[0] + return MANAGERS.find((manager) => manager === declared) ?? 'npm' +} + +/** + * Runs the install of the directory's package manager. Its output goes to + * stderr, so the stdout of the CLI stays the result of the command. + */ +export async function installDependencies( + dir: string, + env: NodeJS.ProcessEnv = process.env +): Promise { + const manager = await packageManagerOf(dir) + if (!manager) { + throw new Error(`${dir} has no package.json to install from`) + } + await new Promise((resolve, reject) => { + const child = spawn(manager, ['install'], { + cwd: dir, + env, + stdio: ['ignore', process.stderr, process.stderr], + shell: process.platform === 'win32', + }) + child.on('error', (error) => + reject(new Error(`${manager} install could not start: ${error.message}`)) + ) + child.on('close', (code) => + code === 0 + ? resolve() + : reject(new Error(`${manager} install exited with code ${code}`)) + ) + }) +} diff --git a/packages/cli/src/layouts.ts b/packages/cli/src/layouts.ts new file mode 100644 index 0000000..ce61241 --- /dev/null +++ b/packages/cli/src/layouts.ts @@ -0,0 +1,24 @@ +import { DrxError } from './errors.js' + +/** + * How the parts of a site are put together: one repository, a repository per + * part, or a parent repository with each part as a submodule. + */ +export const LAYOUTS = ['monorepo', 'split', 'workspace'] as const +export type Layout = (typeof LAYOUTS)[number] + +/** The layouts `init` can create. */ +export const AVAILABLE_LAYOUTS: readonly Layout[] = ['monorepo'] + +export function isLayout(value: unknown): value is Layout { + return LAYOUTS.includes(value as Layout) +} + +export function assertLayoutAvailable(layout: Layout): void { + if (!AVAILABLE_LAYOUTS.includes(layout)) { + throw new DrxError( + 'not-available', + `The ${layout} layout is not available yet. Use --layout ${AVAILABLE_LAYOUTS.join(' or ')}.` + ) + } +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts new file mode 100644 index 0000000..0fb5a58 --- /dev/null +++ b/packages/cli/src/output.ts @@ -0,0 +1,46 @@ +import type { CliContext } from './context.js' + +/** + * Where a command writes. The result goes to stdout: text, or JSON with + * `--json`. Everything said along the way goes to stderr, so stdout can be + * piped or parsed whichever form it takes. + */ +export interface Output { + readonly json: boolean + /** Progress, on stderr. */ + note(message: string): void + /** Something the user should know that does not stop the command. */ + warn(message: string): void + /** The result, on stdout. `text` is used unless `--json` was given. */ + result(data: unknown, text: string): void +} + +export function createOutput(context: CliContext, json: boolean): Output { + return { + json, + note: (message) => context.stderr.write(`${message}\n`), + warn: (message) => context.stderr.write(`Warning: ${message}\n`), + result: (data, text) => + context.stdout.write( + json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n` + ), + } +} + +/** Lines of cells, with every column padded to its widest cell. */ +export function columns(rows: string[][], indent = ''): string[] { + const widths: number[] = [] + for (const row of rows) { + for (const [index, cell] of row.entries()) { + widths[index] = Math.max(widths[index] ?? 0, cell.length) + } + } + return rows.map( + (row) => + indent + + row + .map((cell, index) => cell.padEnd(widths[index] ?? 0)) + .join(' ') + .trimEnd() + ) +} diff --git a/packages/cli/src/package-root.ts b/packages/cli/src/package-root.ts new file mode 100644 index 0000000..d845098 --- /dev/null +++ b/packages/cli/src/package-root.ts @@ -0,0 +1,39 @@ +import { existsSync, readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * The directory of this package, found from this file. The sources sit in + * src/ and the build in dist/, at different depths, so the nearest + * package.json is the fixed point. + */ +export function packageRoot(): string { + let dir = dirname(fileURLToPath(import.meta.url)) + while (!existsSync(join(dir, 'package.json'))) { + const parent = dirname(dir) + if (parent === dir) { + throw new Error('No package.json found above the CLI sources.') + } + dir = parent + } + return dir +} + +export function cliVersion(): string { + const manifest = JSON.parse( + readFileSync(join(packageRoot(), 'package.json'), 'utf8') + ) as { version: string } + return manifest.version +} + +/** + * The registry files that ship with the package. The build copies them into + * the package. In a checkout that has not been built they are read from the + * repository root. + */ +export function bundledRegistryDir(): string { + const root = packageRoot() + const packaged = join(root, 'starters') + if (existsSync(join(packaged, 'index.json'))) return packaged + return join(root, '..', '..', 'starters') +} diff --git a/packages/cli/src/parts.ts b/packages/cli/src/parts.ts new file mode 100644 index 0000000..881c2bf --- /dev/null +++ b/packages/cli/src/parts.ts @@ -0,0 +1,50 @@ +import { isNonEmptyString, isRecord } from './validate.js' + +export const ROLES = ['frontend', 'backend'] as const +export type Role = (typeof ROLES)[number] + +/** + * One side of a site. The role says what it is for and the kind says what it + * is built with. The kind is a plain string, so a new one needs an adapter + * and no change to this type. + */ +export interface Part { + role: Role + kind: string + /** Relative to the project root, with forward slashes. */ + path: string +} + +/** True for a path that stays inside the directory it is resolved against. */ +function isInsidePath(value: unknown): value is string { + if (!isNonEmptyString(value)) return false + if (value.startsWith('/') || /^[a-z]:/i.test(value)) return false + return !value.split(/[\\/]/).includes('..') +} + +/** + * The first problem with a list of parts, as "