diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 0000000..e5b6d8d --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,8 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works +with multi-package repos, or single-package repos to help you version and publish your code. You can +find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in +[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000..319f163 --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@4.0.1/schema.json", + "changelog": "@changesets/cli/changelog", + "commit": false, + "fixed": [], + "linked": [], + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": [] +} diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md new file mode 100644 index 0000000..6235c7b --- /dev/null +++ b/.changeset/first-release-cli.md @@ -0,0 +1,12 @@ +--- +'@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. `--engine` chooses how the backend runs, from the engines the starter lists or `none` for a backend that exists already. `init` keeps that engine's files only and warns when its commands are not on `PATH`. +- `drx module list`, `drx module search` and `drx module info` read the Druxt module registry, and in a project show what is installed and whether each module's range admits the Druxt there. +- `drx add` installs a module and lists it in the Nuxt config. It also requires and enables the Drupal modules the module needs, through the backend's engine. `drx remove` takes it out again. Both take `--dry-run`. +- `drx info` prints the versions of the CLI, Node and the packages of each part of a project. +- At a terminal, bare `drx` opens a menu and `drx init` is a guided run that asks before it writes. `--no-interactive`, `DRX_NO_INTERACTIVE=1`, `CI` or no terminal turn every prompt off. +- 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/.cspell-project-words.txt b/.cspell-project-words.txt new file mode 100644 index 0000000..5d4a1e2 --- /dev/null +++ b/.cspell-project-words.txt @@ -0,0 +1,42 @@ +# Add a term here rather than switching the check off for a file. +# Words this project uses that the standard dictionaries do not carry. +actionlint +automerge +citty +clack +commitlint +consola +corepack +cspell +dbaeumer +DDEV +druxt +druxtjs +esbenp +giget +gitleaks +interruptible +knip +Ksection +Lando +lndo +markdownlint +mise +Nuxt +nvmrc +opencode +unjs +unstub +vitest +yamllint +drush +PATHEXT +alacritty +COLORTERM +truecolor +wordmark +magicast +cweagans +docroot +relock +repatch diff --git a/.cspell.json b/.cspell.json new file mode 100644 index 0000000..533ce18 --- /dev/null +++ b/.cspell.json @@ -0,0 +1,25 @@ +{ + "files": ["**/*.{js,mjs,ts,json,jsonc,md,yml,yaml}"], + "language": "en,en-GB", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./.cspell-project-words.txt" + } + ], + "dictionaries": ["project-words", "bash", "misc", "node", "softwareTerms"], + "ignorePaths": [ + ".git/", + "node_modules/", + "**/node_modules/", + "**/dist/", + "coverage/", + "reports/", + "**/CHANGELOG.md", + "package-lock.json", + ".vale/", + "packages/cli/starters/", + "packages/cli/test/fixtures/" + ], + "useGitignore": true +} 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/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..6735462 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,7 @@ +#!/usr/bin/env sh +# Conventional Commits, checked before the commit exists. +# +# This repository squash-merges, so the merge request or pull request title +# becomes the commit subject too. A prose title breaks the next push to the +# target branch for everyone, not only its author. +exec npx --no -- commitlint --edit "$1" diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..36b3ad4 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,9 @@ +#!/usr/bin/env sh +# The fast half of CI: every linter, the type check, then the unit tests. +# +# The end-to-end test is not here. It downloads a real starter over the +# network, and a hook that needs the network gets bypassed with --no-verify. +set -e +npm run --silent lint +npm run --silent typecheck +npm test --silent diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..e406596 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,31 @@ +--- +name: Bug report +about: Something does not work as documented +title: '' +labels: bug +assignees: '' +--- + +## What happened + +## What you expected + +## How to reproduce + +The command you ran, with its options: + +```bash + +``` + +## Versions + +Paste the output of `npx @druxt/cli info`, run inside the project if there is one. + +```text + +``` + +## Anything else + +The full output of the command, or a link to a reproduction. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..d2c86a0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest something the CLI should do +title: '' +labels: enhancement +assignees: '' +--- + +## The problem + +What are you trying to do that the CLI makes hard or impossible? + +## What you would like + +## Alternatives you have considered + +## Anything else diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6f74451 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ + + +## What changed + +## Why + +## How it was checked + +- [ ] `npm run lint` and `npm run typecheck` pass +- [ ] `npm test` passes, and coverage did not drop +- [ ] A changeset is included, if a published package changed +- [ ] Nothing that resolves only on a private network reached a tracked file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ff73091 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,153 @@ +--- +name: CI + +# The same lint and test set as .gitlab-ci.yml. Nothing on this side lints this +# file: the GitLab pipeline runs actionlint over it. +# +# There is no publish job. A release is cut by hand from the changesets until +# a workflow with its own token is added on purpose. + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + # Actions are pinned to commit SHAs, not tags. A tag is a mutable + # reference to code that runs with this repository's credentials. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + # The attribution and prose checks read the pull request's own + # commits, so its base has to be present. + fetch-depth: 0 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + # corepack reads the packageManager field, so the manager the lockfile was + # written by is the one that installs it, and this file never names one. + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - run: npm run lint:js + + - run: npm run lint:format + + - run: npm run typecheck + + - run: npm run lint:md + + - run: npm run lint:cspell + + - run: npm run lint:knip + + # This repository is public. A host only the author can reach must never + # reach a tracked file. + - run: npm run lint:private + + - name: Lint commit messages + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: npm run lint:commit -- --from "$BASE_SHA" --to HEAD --verbose + + # The work is the author's. No commit, pull request description or + # tracked file may credit an AI tool as author, co-author or generator. + - name: Check for AI attribution + env: + ATTRIBUTION_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + run: bash .gitlab/scripts/check-attribution.sh + + # Project voice over the markdown a change touches, its commit messages + # and the pull request description. + - name: Lint prose + env: + PROSE_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + PROSE_LINT_GLOB: "!.changeset/README.md" + run: | + bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles + bash .gitlab/scripts/lint-prose.sh + + - run: npm run lint:audit + + test: + 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 + + # 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 + if: always() + 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 unattended path, as a pipeline runs it: no prompt, defaults applied. + ./node_modules/.bin/drx init pack-site --yes --no-interactive --json + test -f pack-site/drx.config.json + + # 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 new file mode 100644 index 0000000..2811c6c --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,296 @@ +--- +# CI for the Druxt CLI. See the Druxt repository standard for what each job is +# for. +# +# GitHub Actions (.github/workflows/ci.yml) runs the same lint and test set. +# Keep the two in step: nothing on the GitHub side lints that workflow, so +# lint:yaml here runs actionlint over it in return. +# +# Secret scanning is gitleaks, not GitLab's Security/Secret-Detection template. +# That template is an Ultimate-tier feature: on a non-Ultimate instance the +# include produces no job at all, so the configuration reads as coverage while +# scanning nothing. + +stages: + - lint + - test + +workflow: + rules: + - if: $CI_PIPELINE_SOURCE == 'merge_request_event' + - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS + when: never + - if: $CI_COMMIT_BRANCH + +default: + tags: [docker] + timeout: 15m + before_script: + - 'section_start() { local n="$1" t="${2:-$1}"; printf "\e[0Ksection_start:%s:%s\r\e[0K%s\n" "$(date +%s)" "$n" "$t"; }' + - 'section_end() { printf "\e[0Ksection_end:%s:%s\r\e[0K\n" "$(date +%s)" "$1"; }' + +# Shared Node setup. `corepack prepare --activate` reads the packageManager +# field, so this block names no manager version. The cache is keyed by the +# lockfile hash: a dependency bump misses once and hits after that. +.node: + image: node:24.18.0 + interruptible: true + cache: + key: + files: + - package-lock.json + prefix: node-24.18.0 + paths: + - .npm/ + before_script: + - !reference [default, before_script] + - corepack enable + - corepack prepare --activate + - npm ci --cache .npm --prefer-offline + +# +# --- Lint --- +# + +lint:js: + extends: .node + stage: lint + script: + - section_start "eslint" "Linting sources, tests and scripts" + - npm run lint:js + - section_end "eslint" + - section_start "prettier" "Checking formatting" + - npm run lint:format + - section_end "prettier" + - section_start "typecheck" "Type checking" + - npm run typecheck + - section_end "typecheck" + +lint:md: + extends: .node + stage: lint + script: + - section_start "markdownlint" "Linting Markdown" + - npm run lint:md + - section_end "markdownlint" + +lint:cspell: + extends: .node + stage: lint + script: + - section_start "cspell" "Spell checking" + - npm run lint:cspell + - section_end "cspell" + +# This repository is public, and the registry it carries is read by every copy +# of the CLI. A host only the author can reach must never reach a tracked file. +lint:private: + extends: .node + stage: lint + script: + - section_start "private-refs" "Checking for private host references" + - npm run lint:private + - section_end "private-refs" + +lint:knip: + extends: .node + stage: lint + script: + - section_start "knip" "Checking for unused and undeclared dependencies" + - npm run lint:knip + - section_end "knip" + +# Production only. A shipped runtime dependency is what reaches a user. A +# devDependency advisory is worth knowing about and not worth blocking on. +lint:audit: + extends: .node + stage: lint + script: + - section_start "audit" "Auditing shipped dependencies" + - npm run lint:audit + - section_end "audit" + +# yamllint covers this file. actionlint covers the GitHub workflow, which +# nothing on the GitHub side lints before a push. +lint:yaml: + stage: lint + image: python:3.12-slim + interruptible: true + variables: + ACTIONLINT_VERSION: '1.7.12' + ACTIONLINT_SHA256: '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8' + script: + - section_start "yamllint" "Linting YAML" + - pip install --quiet yamllint + - yamllint .gitlab-ci.yml .github/workflows/ + - section_end "yamllint" + - section_start "actionlint" "Linting GitHub workflows" + - apt-get update -qq && apt-get install -y -qq curl > /dev/null + - curl -sSLo actionlint.tar.gz "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + - echo "${ACTIONLINT_SHA256} actionlint.tar.gz" | sha256sum -c - + - tar -xzf actionlint.tar.gz actionlint + - ./actionlint -color + - section_end "actionlint" + +# The merge request's own commits, not the whole history. This repository +# squash-merges, so a prose title becomes the commit subject and breaks the +# next push to the target branch. +lint:commit: + extends: .node + stage: lint + rules: + - if: $CI_PIPELINE_SOURCE == 'merge_request_event' + script: + - section_start "commitlint" "Validating commit messages" + - git fetch origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" --depth 50 + - npm run lint:commit -- --from "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" --to HEAD --verbose + - section_end "commitlint" + +# The work is the author's. No commit, merge request description or tracked +# file may credit an AI tool as author, co-author or generator. Full history, +# because the range is the merge request's own and its base has to be present. +lint:attribution: + image: node:24.18.0 + stage: lint + interruptible: true + variables: + GIT_DEPTH: 0 + script: + - section_start "attribution" "Checking for AI attribution" + - bash .gitlab/scripts/check-attribution.sh + - section_end "attribution" + +# Project voice over the markdown a change touches, its commit messages and the +# merge request description. The changesets README is third-party text. +lint:prose: + image: node:24.18.0 + stage: lint + interruptible: true + variables: + GIT_DEPTH: 0 + PROSE_LINT_GLOB: "!.changeset/README.md" + cache: + key: vale-3.17.1 + paths: + - .vale/ + script: + - section_start "prose" "Linting prose with Vale" + - bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles + - bash .gitlab/scripts/lint-prose.sh + - section_end "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 + needs: [] + script: + - section_start "vitest" "Running unit tests" + - npm test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml + - section_end "vitest" + artifacts: + when: always + reports: + junit: reports/junit/junit.xml + paths: + - coverage/ + expire_in: 1 week + # 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 + # The unattended path, as a pipeline runs it: no prompt, defaults applied. + - ./node_modules/.bin/drx init pack-site --yes --no-interactive --json + - test -f pack-site/drx.config.json + - 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 --- +# + +secret-detection: + stage: lint + image: alpine:3.21 + interruptible: true + dependencies: [] + variables: + GITLEAKS_VERSION: '8.30.1' + GITLEAKS_SHA256: '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb' + script: + - section_start "gitleaks" "Scanning for committed secrets" + - apk add --no-cache curl tar git > /dev/null + - curl -sSLo gitleaks.tar.gz "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" + - echo "${GITLEAKS_SHA256} gitleaks.tar.gz" | sha256sum -c - + - tar -xzf gitleaks.tar.gz gitleaks + - ./gitleaks detect --source . --no-banner --redact --verbose + - section_end "gitleaks" + # A scan that finds nothing looks identical to a scan that cannot find + # anything. Plant three credentials outside the repository and assert all + # three are reported, so a bad download, a config change or a widened + # allowlist fails the job. + # + # Each value is split across its own prefix so no fragment in this file + # triggers the rule it is meant to exercise: the repository scan above runs + # over this file too, and a canary that flags itself would need an ignore + # entry, which is the thing being guarded against. + # + # Fixed values, not generated ones. Detection is keyword-driven, not + # entropy-driven, so a generated credential fires only sometimes. A value + # verified once keeps firing. + # + # Invented, not copied from any vendor's documentation: gitleaks allowlists + # documentation keys, and a canary built from one would never fire. + - section_start "canary" "Checking that the scanner still detects" + - | + canary="$(mktemp -d)" + pat="gh""p_8fK2mQ7xR4tV9nB3jH6yW1sZ5cD8gL0aE4uY" + stripe="sk""_live_51aBcD2eFgH3iJkL4mNoP5qR6sTuV7wXyZ8a" + slack="xo""xb-263594753641-2529420432-J1n4h6a9pQrStUvWxYz1AbCd" + printf 'a = "%s"\nb = "%s"\nc = "%s"\n' "$pat" "$stripe" "$slack" > "$canary/canary.txt" + ./gitleaks detect --no-git --source "$canary" --no-banner --redact \ + --report-format json --report-path "$canary/report.json" || true + found=$(grep -c '"RuleID"' "$canary/report.json" || true) + rm -rf "$canary" + if [ "$found" != "3" ]; then + echo "The canary planted 3 credentials and gitleaks reported $found." + echo "The scan above proves nothing while this is true." + exit 1 + fi + echo "Canary detected 3 of 3 planted credentials." + - section_end "canary" diff --git a/.gitlab/issue_templates/Default.md b/.gitlab/issue_templates/Default.md new file mode 100644 index 0000000..c93e419 --- /dev/null +++ b/.gitlab/issue_templates/Default.md @@ -0,0 +1,19 @@ +## What happened + +## What you expected + +## How to reproduce + +The command you ran, with its options: + +```bash + +``` + +## Versions + +Paste the output of `npx @druxt/cli info`, run inside the project if there is one. + +```text + +``` diff --git a/.gitlab/merge_request_templates/Default.md b/.gitlab/merge_request_templates/Default.md new file mode 100644 index 0000000..9419241 --- /dev/null +++ b/.gitlab/merge_request_templates/Default.md @@ -0,0 +1,19 @@ + + +## What changed + +## Why + +## How it was checked + +- [ ] `npm run lint` and `npm run typecheck` pass +- [ ] `npm test` passes, and coverage did not drop +- [ ] A changeset is included, if a published package changed +- [ ] Nothing that resolves only on a private network reached a tracked file diff --git a/.gitlab/scripts/check-attribution.sh b/.gitlab/scripts/check-attribution.sh new file mode 100755 index 0000000..857b430 --- /dev/null +++ b/.gitlab/scripts/check-attribution.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Rejects AI authorship claims in commits, the merge request description and +# tracked files. The work is the author's; a tool takes no credit for it. +# +# Usage: check-attribution.sh [--files-only] [] +# +# Commits: the range ..HEAD. Without an argument the base is read from +# ATTRIBUTION_BASE_SHA, then CI_MERGE_REQUEST_DIFF_BASE_SHA, then +# CI_COMMIT_BEFORE_SHA. With none of those only HEAD is read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# When GITLAB_API_TOKEN, CI_API_V4_URL, CI_PROJECT_ID and CI_MERGE_REQUEST_IID +# are all set the description is fetched instead, because the variable is cut +# at 2700 characters and a footer sits at the end. On a merge request pipeline +# with no description from either source the check refuses: passing over a +# description it never read is not a pass. +# +# Files: every tracked text file, whatever the range. +# +# Exit codes: 0 clean, 1 attribution found, 2 cannot run. +# +# The rejected strings are assembled from fragments below, so this file passes +# its own scan. Keep them that way. + +set -uo pipefail + +files_only=0 +base="" +for arg in "$@"; do + case "$arg" in + --files-only) files_only=1 ;; + -h|--help) sed -n '2,22p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +if ! git rev-parse --show-toplevel >/dev/null 2>&1; then + echo "[ERROR] not inside a git repository; nothing to check." >&2 + exit 2 +fi + +# Tool names that must not appear as an author, co-author or generator. +tools='claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm' + +# Each alternative in pieces: the trailer key, the footer, the session link +# and the noreply address are the four shapes seen in practice. +trailer='co-authored'"-by:.*(${tools})" +footer="generated (with|by).*(${tools}|\\bai\\b)" +session='claude-'"session:|claude\\.ai/code/session" +address='noreply'"@anthropic\\.com" +pattern="(${trailer})|(${footer})|(${session})|(${address})" + +failures=0 +report() { + echo "[FAIL] $1" + failures=$((failures + 1)) +} + +# --- commits ----------------------------------------------------------------- + +commits_checked=0 +if [ "$files_only" -eq 0 ]; then + if [ -z "$base" ]; then + base="${ATTRIBUTION_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" + fi + if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" + fi + + # An all-zero sha is what GitHub passes as the previous commit of a first + # push, and what GitLab passes as CI_COMMIT_BEFORE_SHA for a new branch. + case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac + + if [ -n "$base" ]; then + if ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 + fi + shas="$(git rev-list "${base}..HEAD")" + else + shas="$(git rev-parse HEAD)" + fi + + for sha in $shas; do + commits_checked=$((commits_checked + 1)) + short="$(git rev-parse --short "$sha")" + while IFS= read -r line; do + [ -n "$line" ] && report "commit ${short}: ${line}" + done < <(git log -1 --format=%B "$sha" | grep -iE "$pattern" || true) + done +fi + +# --- merge request description ----------------------------------------------- + +description_checked=0 +if [ "$files_only" -eq 0 ]; then + description="" + have_description=0 + + if [ -n "${GITLAB_API_TOKEN:-}" ] && [ -n "${CI_API_V4_URL:-}" ] \ + && [ -n "${CI_PROJECT_ID:-}" ] && [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}" + payload="$(curl -sSf --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" "$url" 2>/dev/null || true)" + if [ -n "$payload" ]; then + if command -v python3 >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("description") or "")')" + elif command -v node >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>process.stdout.write(JSON.parse(d).description||""))')" + fi + have_description=1 + fi + fi + + if [ "$have_description" -eq 0 ]; then + if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$MERGE_REQUEST_DESCRIPTION" + have_description=1 + elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$CI_MERGE_REQUEST_DESCRIPTION" + have_description=1 + if [ "${#description}" -ge 2700 ]; then + echo "[WARN] CI_MERGE_REQUEST_DESCRIPTION is cut at 2700 characters; set GITLAB_API_TOKEN so the full description is read." >&2 + fi + elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 + fi + fi + + if [ "$have_description" -eq 1 ]; then + description_checked=1 + while IFS= read -r line; do + [ -n "$line" ] && report "merge request description: ${line}" + done < <(printf '%s\n' "$description" | grep -iE "$pattern" || true) + fi +fi + +# --- tracked files ----------------------------------------------------------- + +files_checked="$(git ls-files | wc -l | tr -d ' ')" +while IFS= read -r line; do + [ -n "$line" ] && report "$line" +done < <(git grep -nIiE "$pattern" -- . || true) + +# --- verdict ----------------------------------------------------------------- + +scope="${files_checked} tracked files" +if [ "$files_only" -eq 0 ]; then + scope="${commits_checked} commits, $([ "$description_checked" -eq 1 ] && echo 'the merge request description' || echo 'no description'), ${scope}" +fi + +if [ "$failures" -gt 0 ]; then + echo "[FAIL] ${failures} attribution line(s) across ${scope}. The work is the author's; remove the credit." + exit 1 +fi +echo "[PASS] no AI attribution in ${scope}." diff --git a/.gitlab/scripts/install-vale.sh b/.gitlab/scripts/install-vale.sh new file mode 100755 index 0000000..10dd246 --- /dev/null +++ b/.gitlab/scripts/install-vale.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Installs a pinned Vale and the ai-tells style package, both checksum-verified. +# +# Usage: install-vale.sh [] +# +# Why not `vale sync`: it fetches whatever the package URL serves and verifies +# nothing. Here the version and its checksum move together, so a bump is a +# reviewed change rather than something that happens inside a job. +# +# Environment: +# VALE_VERSION pinned below. Overriding it requires VALE_SHA256 too, +# because the pinned checksums are for the pinned version. +# VALE_SHA256 expected checksum of the Vale archive for this platform. +# AI_TELLS_VERSION pinned below. Same rule: override both or neither. +# AI_TELLS_SHA256 expected checksum of the style package archive. +# +# Exit codes: 0 installed or already present, 1 checksum mismatch, 2 cannot run. + +set -euo pipefail + +bin_dir="${1:?usage: install-vale.sh []}" +styles_dir="${2:-}" + +pinned_vale="3.17.1" +pinned_ai_tells="1.31.0" +pinned_ai_tells_sha256="bc1267248f13e65928475c439ad7ae1bf806a20d09254c08d7d8c4a9c8b811f0" + +vale_version="${VALE_VERSION:-$pinned_vale}" +ai_tells_version="${AI_TELLS_VERSION:-$pinned_ai_tells}" + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) + asset="Linux_64-bit" + pinned_vale_sha256="db947f89f2292e6a0381a61de155f6a5f5cb4cb460ca178ea412ef605559cefd" ;; + Linux-aarch64|Linux-arm64) + asset="Linux_arm64" + pinned_vale_sha256="92d91ebf9ee69ec077379be95cd09e6710ab33d3d5bab66bb482e66ebc80dc23" ;; + Darwin-x86_64) + asset="macOS_64-bit" + pinned_vale_sha256="b37ab999dfd1414d041bd2e94ced103292d634da76f954c385bf789dc7f5f939" ;; + Darwin-arm64) + asset="macOS_arm64" + pinned_vale_sha256="80cacf85ef23f53cfdd77355ec41a6ef99aec136f15dfb3517723482f35593f9" ;; + *) + echo "Unsupported platform: $(uname -s) $(uname -m)" >&2 + exit 2 ;; +esac + +if [ "$vale_version" != "$pinned_vale" ] && [ -z "${VALE_SHA256:-}" ]; then + echo "VALE_VERSION=${vale_version} is not the pinned ${pinned_vale}; set VALE_SHA256 for it." >&2 + exit 2 +fi +if [ "$ai_tells_version" != "$pinned_ai_tells" ] && [ -z "${AI_TELLS_SHA256:-}" ]; then + echo "AI_TELLS_VERSION=${ai_tells_version} is not the pinned ${pinned_ai_tells}; set AI_TELLS_SHA256 for it." >&2 + exit 2 +fi +vale_sha256="${VALE_SHA256:-$pinned_vale_sha256}" +ai_tells_sha256="${AI_TELLS_SHA256:-$pinned_ai_tells_sha256}" + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# `sha256sum` on Linux, `shasum` on macOS. Either way the comparison is +# exact, and a mismatch removes the download so nothing later can run it. +verify() { + local file="$1" expected="$2" actual + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$file" | cut -d' ' -f1)" + else + actual="$(shasum -a 256 "$file" | cut -d' ' -f1)" + fi + if [ "$actual" != "$expected" ]; then + echo "checksum mismatch for $(basename "$file"): expected ${expected}, got ${actual}; refusing to install it." >&2 + rm -f "$file" + return 1 + fi +} + +fetch() { + curl -sSfL --retry 3 -o "$2" "$1" +} + +# --- Vale -------------------------------------------------------------------- + +if [ -x "$bin_dir/vale" ] && "$bin_dir/vale" --version 2>/dev/null | grep -q "$vale_version"; then + echo "vale ${vale_version} already installed in ${bin_dir}" +else + archive="$work/vale.tar.gz" + fetch "https://github.com/errata-ai/vale/releases/download/v${vale_version}/vale_${vale_version}_${asset}.tar.gz" "$archive" + verify "$archive" "$vale_sha256" || exit 1 + tar -xzf "$archive" -C "$work" vale + mkdir -p "$bin_dir" + install -m 0755 "$work/vale" "$bin_dir/vale" + echo "vale ${vale_version} installed in ${bin_dir}" +fi + +# --- ai-tells ---------------------------------------------------------------- + +if [ -z "$styles_dir" ]; then + exit 0 +fi + +marker="$styles_dir/ai-tells/.installed-version" +if [ -f "$marker" ] && [ "$(cat "$marker")" = "$ai_tells_version" ]; then + echo "ai-tells ${ai_tells_version} already installed in ${styles_dir}" + exit 0 +fi + +zip="$work/ai-tells.zip" +fetch "https://github.com/tbhb/vale-ai-tells/releases/download/v${ai_tells_version}/ai-tells.zip" "$zip" +verify "$zip" "$ai_tells_sha256" || exit 1 + +# The package is a zip. Not every image has unzip, and every image that runs +# this has one of the others. +if command -v unzip >/dev/null 2>&1; then + unzip -q -o "$zip" -d "$work/unpacked" +elif command -v python3 >/dev/null 2>&1; then + python3 -m zipfile -e "$zip" "$work/unpacked" +elif command -v bsdtar >/dev/null 2>&1; then + mkdir -p "$work/unpacked" && bsdtar -xf "$zip" -C "$work/unpacked" +else + echo "No unzip, python3 or bsdtar available to unpack the style package." >&2 + exit 2 +fi + +if [ ! -d "$work/unpacked/ai-tells/styles/ai-tells" ]; then + echo "The style package did not contain styles/ai-tells; its layout has changed." >&2 + exit 2 +fi +mkdir -p "$styles_dir" +rm -rf "$styles_dir/ai-tells" +cp -R "$work/unpacked/ai-tells/styles/ai-tells" "$styles_dir/ai-tells" +printf '%s\n' "$ai_tells_version" > "$marker" +echo "ai-tells ${ai_tells_version} installed in ${styles_dir}" diff --git a/.gitlab/scripts/lint-prose.sh b/.gitlab/scripts/lint-prose.sh new file mode 100755 index 0000000..1985c91 --- /dev/null +++ b/.gitlab/scripts/lint-prose.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# Lints prose with Vale: the markdown a change touches, the commit messages in +# its range, and the merge request description. All three are content someone +# wrote for this repository, and the project voice applies to all of it. +# +# Usage: lint-prose.sh [--all] [] +# +# Markdown: files added or modified in ..HEAD; with --all, every tracked +# markdown file. Without an argument the base is read from PROSE_BASE_SHA, +# then CI_MERGE_REQUEST_DIFF_BASE_SHA, then CI_COMMIT_BEFORE_SHA. With none of +# those the files and message of HEAD alone are read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# A merge request pipeline with neither is refused, as check-attribution.sh +# does and for the same reason. +# +# Environment: +# VALE_BIN path to vale; PATH otherwise. See install-vale.sh. +# PROSE_LINT_GLOB passed to `vale --glob` for the repository's markdown, +# to keep fixtures and vendored prose out. Never applied +# to commit messages or the description: those are never +# fixtures. +# +# Before any input is read, an em-dash is written to a file outside the tree +# and linted. If that does not fire, the .vale.ini has no section covering the +# generated inputs and the run would pass by linting nothing, so it refuses. +# +# Exit codes: 0 clean, 1 findings, 2 cannot run. + +set -uo pipefail + +all=0 +base="" +for arg in "$@"; do + case "$arg" in + --all) all=1 ;; + -h|--help) sed -n '2,28p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +root="$(git rev-parse --show-toplevel 2>/dev/null)" || { + echo "[ERROR] not inside a git repository; nothing to lint." >&2 + exit 2 +} + +# VALE_BIN, then PATH, then the repository's own .vale/bin, which is where +# install-vale.sh puts it when a repository installs it for itself. +vale="${VALE_BIN:-$(command -v vale 2>/dev/null || true)}" +if [ -z "$vale" ] && [ -x "$root/.vale/bin/vale" ]; then + vale="$root/.vale/bin/vale" +fi +if [ -z "$vale" ] || [ ! -x "$vale" ]; then + echo "[ERROR] vale is not installed. Run install-vale.sh .vale/bin .vale/styles in the repository root, or put vale on PATH." >&2 + exit 2 +fi + +ini="$root/.vale.ini" +if [ ! -f "$ini" ]; then + echo "[ERROR] no .vale.ini at ${root}; there is no project voice to apply." >&2 + exit 2 +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# --- canary ------------------------------------------------------------------ + +mkdir -p "$work/canary" +printf 'Canary text %s with a dash.\n' "$(printf '\xe2\x80\x94')" > "$work/canary/canary.md" +canary_out="$(cd "$work/canary" && "$vale" --config "$ini" --output=line canary.md 2>&1)" +canary_rc=$? +if [ "$canary_rc" -eq 0 ] || ! printf '%s' "$canary_out" | grep -q 'canary.md:'; then + echo "[ERROR] canary did not fire: .vale.ini applies no em-dash rule to files outside the tree, so commit messages and the description would be linted by nothing." >&2 + echo " Add a section such as [*.md] with BasedOnStyles = ai-tells. Vale said:" >&2 + printf '%s\n' "$canary_out" | sed 's/^/ /' >&2 + exit 2 +fi + +# --- range ------------------------------------------------------------------- + +if [ -z "$base" ]; then + base="${PROSE_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" +fi +if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" +fi +case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac +if [ -n "$base" ] && ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 +fi + +findings=0 + +# --- commit messages and the description ------------------------------------- + +inputs="$work/inputs" +mkdir -p "$inputs/commits" + +if [ -n "$base" ]; then + shas="$(git rev-list "${base}..HEAD")" +else + shas="$(git rev-parse HEAD)" +fi +commits=0 +for sha in $shas; do + commits=$((commits + 1)) + git log -1 --format=%B "$sha" > "$inputs/commits/$(git rev-parse --short "$sha").md" +done + +description_state="no description" +if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$CI_MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 +fi + +generated=() +for f in "$inputs"/commits/*.md "$inputs/merge-request.md"; do + [ -f "$f" ] && generated+=("${f#"$inputs"/}") +done +if [ "${#generated[@]}" -gt 0 ]; then + out="$(cd "$inputs" && "$vale" --config "$ini" --output=line "${generated[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- the repository's markdown ----------------------------------------------- + +markdown=() +if [ "$all" -eq 1 ]; then + mapfile -d '' -t markdown < <(git -C "$root" ls-files -z -- '*.md') +elif [ -n "$base" ]; then + mapfile -d '' -t markdown < <(git -C "$root" diff -z --name-only --diff-filter=AMR "$base" HEAD -- '*.md') +else + mapfile -d '' -t markdown < <(git -C "$root" diff-tree -z --no-commit-id -r --name-only --diff-filter=AMR HEAD -- '*.md') +fi +existing=() +for f in "${markdown[@]}"; do + [ -f "$root/$f" ] && existing+=("$f") +done + +if [ "${#existing[@]}" -gt 0 ]; then + glob=() + if [ -n "${PROSE_LINT_GLOB:-}" ]; then + glob=(--glob="$PROSE_LINT_GLOB") + fi + out="$(cd "$root" && "$vale" --config "$ini" --output=line "${glob[@]}" "${existing[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- verdict ----------------------------------------------------------------- + +scope="${commits} commit message(s), ${description_state}, ${#existing[@]} markdown file(s)" +if [ "$findings" -gt 0 ]; then + echo "[FAIL] prose findings across ${scope}." + exit 1 +fi +echo "[PASS] prose clean across ${scope}." diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000..9d5f5eb --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,21 @@ +{ + // MD013 (line length) is off: prose reflows, and a hard wrap in Markdown + // shows up as a diff on every edit to the paragraph, not the sentence. + // MD024 is scoped to siblings so a changelog can repeat "Fixed" per release. + // MD041 is off: a changeset starts with front matter, not a heading. + "config": { + "default": true, + "MD013": false, + "MD024": { "siblings_only": true }, + "MD041": false + }, + "ignores": [ + "node_modules/**", + "**/node_modules/**", + "**/dist/**", + "coverage/**", + ".vale/**", + "**/CHANGELOG.md", + ".changeset/**" + ] +} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..a8e1db8 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,17 @@ +node_modules/ +dist/ +coverage/ +reports/ +package-lock.json +CHANGELOG.md +.vale/ +packages/cli/starters/ + +# Copies of real files, kept byte for byte so an edit to one can be compared. +packages/cli/test/fixtures/ + +# Pipeline definitions are owned by yamllint, not prettier. The two disagree on +# comment spacing, and letting both format these files means each run of one +# undoes the other. +.gitlab-ci.yml +.github/workflows/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..0b5f863 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,23 @@ +{ + "printWidth": 80, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "tabWidth": 2, + "overrides": [ + { + "files": ["*.jsonc", "tsconfig*.json"], + "options": { + "parser": "jsonc", + "trailingComma": "none" + } + }, + { + "files": ["*.md"], + "options": { + "printWidth": 100, + "proseWrap": "preserve" + } + } + ] +} diff --git a/.vale.ini b/.vale.ini new file mode 100644 index 0000000..b6c5662 --- /dev/null +++ b/.vale.ini @@ -0,0 +1,11 @@ +# Project voice for everything written here: markdown, commit messages and +# merge request descriptions. .gitlab/scripts/lint-prose.sh feeds all three +# through this configuration. +# +# StylesPath is populated by .gitlab/scripts/install-vale.sh, pinned and +# verified by checksum, not by `vale sync`. +StylesPath = .vale/styles +MinAlertLevel = error + +[*.md] +BasedOnStyles = ai-tells diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..cc245ab --- /dev/null +++ b/.yamllint @@ -0,0 +1,10 @@ +--- +extends: default +rules: + # 200, not 80: pipeline scripts carry long commands, and wrapping them makes + # them harder to read rather than easier. + line-length: + max: 200 + level: warning + truthy: + check-keys: false diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ce8fd52 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,71 @@ +# Agent instructions + +The Druxt command-line tool: `@druxt/cli`, with the binary `drx`, and `create-druxt`. + +## Rules + +- **This repository is public.** Nothing that resolves only on a private + network may reach a tracked file: no internal URLs, hostnames, repository + names or issue links, in any file including comments and the starter + registry. `npm run lint:private` enforces the URL-shaped half of this and + runs in the pipeline. It cannot catch an internal name written as prose, so + that part is on you. +- **A private registry or source is never named in the code.** It belongs in + the user configuration file, on the user's machine. +- **The names of kinds stay in `packages/cli/src/adapters/`.** A part has a + role and a kind, and the kind is a value. No key, type or command outside + that directory may be named after a kind. `packages/cli/test/seams.test.ts` + fails when one is. +- **Every prompt has a flag,** and a command never waits for input when there + is no terminal. +- **stdout is the result, stderr is everything else.** A command with `--json` + prints one JSON document on stdout and nothing else there. +- **Check a library's API in its own package before using it.** The unjs + libraries change between minors. +- **Conventional Commits**, and the same for pull request and merge request + titles. This repository squash-merges, so the title becomes the commit + subject, and a prose title breaks the next push to the target branch. +- **The coverage floor in `vitest.config.ts` goes up, never down.** If a change + drops coverage, the change needs a test. +- **No AI tool is credited.** No co-author trailer naming an assistant, no + generated-with footer, no session link, in commits, merge request + descriptions or tracked files. The commit-msg hook rejects it locally, and + `npm run lint:attribution` and the pipeline check the rest. +- **Prose is linted with Vale.** It covers the markdown a change touches, its + commit messages and the merge request description. + `npm run lint:prose:install` once, then `npm run lint:prose`. +- **Nothing here publishes to npm.** There is no publish job in either + pipeline. Do not add one that would run without a token. + +## Layout + +| Path | Purpose | +| ---------------------------- | ------------------------------------------------------------------ | +| `packages/cli/` | `@druxt/cli`. `src/commands/` holds a file per command | +| `packages/cli/src/adapters/` | A file per kind of part, behind the interface in `adapter.ts` | +| `packages/cli/src/registry/` | Reading and checking the starter registry | +| `packages/create-druxt/` | `create-druxt`, which runs `drx init` | +| `starters/` | The public starter registry. The build copies it into `@druxt/cli` | +| `scripts/` | Repository tooling, excluded from the packages | +| `test/` | Tests of the repository tooling | +| `.githooks/` | Committed hooks, enabled by `npm install` | +| `.gitlab/scripts/` | Content checks, copied from the Druxt repository standard | + +## Commands + +```bash +npm install # dependencies, and enables the git hooks +npm run build # tsc for both packages, and the registry copy +npm run typecheck # sources, tests and configuration +npm test # vitest, coverage floor enforced, no network +npm run test:e2e # creates a site from the real starter, needs the network +npm run lint # every linter except prose +npm run lint:prose # Vale, after `npm run lint:prose:install` +``` + +## Toolchain + +Pinned in `.mise.toml`. The packages are TypeScript, built with `tsc` and no +bundler, as ES modules. `c12` stays on 3 while 4 is a release candidate, and +`typescript` stays on 6 until `typescript-eslint` supports 7. Renovate is +configured not to offer either. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..83a79b2 --- /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/main diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..3f07d74 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# Claude Code + +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..09507f4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contributing + +Thanks for helping. + +## Getting set up + +```bash +npm install +``` + +That installs dependencies and enables the git hooks. If you skipped install +scripts, run `npm run hooks:install` by hand, or the hooks stay on disk doing +nothing. + +The toolchain is pinned in `.mise.toml`. With [mise](https://mise.jdx.dev) +installed, `mise install` gives you the same Node the pipeline uses. + +To run the CLI from your checkout: + +```bash +npm run build +node packages/cli/dist/bin.js --help +``` + +## Before you push + +```bash +npm run lint # every check except prose, which needs Vale installed +npm run typecheck +npm test # vitest, with the coverage floor enforced +``` + +The pre-commit hook runs all three. Because the unit tests serve their own +fixture registry and tarball from a loopback port, they run offline. `npm run test:e2e` is the +one test that downloads the real starter, and it is not in the hook. + +## Tests + +Write the test before the code it covers, and see it fail. A change to a +command needs a test that runs the command through `runCli`, as +`packages/cli/test/helpers/run.ts` does. + +`vitest.config.ts` carries a coverage floor measured from the current tests. +Raise it when coverage improves. Do not lower it to make a change pass. + +## Adding a starter + +Add `starters/.json` and the name to `starters/index.json`. The format is +in the README. Set `maintained` to the date you last saw the starter work, and +run `npm run test:e2e` if the default starter changed. + +## Adding a kind + +Add a file to `packages/cli/src/adapters/` that exports a `KindAdapter`, and +add it to the list in `packages/cli/src/adapters/index.ts`. Nothing outside +that directory should need to change. + +## Changesets + +A change to a published package needs a changeset: + +```bash +npm run changeset +``` + +## Commit messages + +[Conventional Commits](https://www.conventionalcommits.org). The commit-msg +hook checks them, and the pipeline checks the whole merge-request range. + +This repository squash-merges, so the pull request or merge request **title** +becomes the commit subject. Title your pull request the same way you would +title a commit. + +## What not to put in a file + +This repository is public. Nothing that only resolves on a private network may +reach a tracked file, whether as a URL, in a comment or in the starter +registry. `npm run lint:private` checks this and runs in the pipeline. When you +need to cite something internal, describe it without the URL or point at a +public equivalent. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9b1780a --- /dev/null +++ b/README.md @@ -0,0 +1,488 @@ +# 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` | +| `--engine ` | The engine that runs the backend: one of the starter's engines, or `none` for a backend that exists already | Asked for, or the first engine whose commands are installed | +| `--database ` | The database, where the engine offers a choice | Asked for, or the engine's first | +| `--base-url ` | With `--engine none`: the URL of the backend | Asked for | +| `--keep-engines` | Keep the files of the engines that were not chosen | Remove them | +| `--setup` | Run the engine's steps after creating the site. Not available yet. | | +| `--no-banner` | Do not draw the wordmark at the start of a guided run | Draw it | +| `--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` is a guided run. It asks for whatever the flags left out, then shows a summary and waits for a yes before it writes. See [At a terminal](#at-a-terminal). 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. See [CI and scripts](#ci-and-scripts). + +#### Engines + +An engine is a way to run the site's backend on your machine. The starter lists the ones it supports, and `none` is always there for a backend that runs somewhere else. For the `quickstart` starter: + +| Engine | Needs on `PATH` | Database | What it is | +| ------- | ----------------- | --------- | -------------------------------------------------------------- | +| `php` | `php`, `composer` | `sqlite` | PHP's built-in server and SQLite, with no containers | +| `ddev` | `ddev` | `mariadb` | [DDEV](https://ddev.readthedocs.io) | +| `lando` | `lando` | `mariadb` | [Lando](https://lando.dev) | +| `none` | | | A Drupal that exists already, at the URL you give `--base-url` | + +- The prompt lists the engines whose commands are installed first, and marks the others as not installed. You can still choose one of those. `init` then warns which commands are missing, and creates the site. +- With `--yes` or no terminal, the engine is the first whose commands are all installed, or the starter's first when none is. +- `init` removes the files of the engines you did not choose, so a DDEV site has no `.lando.yml`. `--keep-engines` leaves them all. +- For an engine that serves the backend at a fixed URL, and for `none`, `init` writes the URL where the starter reads it. For the quickstart that is `BASE_URL` in `.env`. +- What the site needs and the steps to run next are the chosen engine's. +- An engine or a database the starter does not offer fails, with the names it does offer. + +```bash +npx @druxt/cli init my-site --engine ddev +npx @druxt/cli init my-site --engine none --base-url https://cms.example.com +``` + +`--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 module list` + +Lists the modules in the Druxt module registry: name, package, type, status and the Druxt versions each works with. + +```text +Name Package Type Status Druxt +auth druxt-auth official stable unknown +blocks druxt-blocks official stable ^0.25.1 +``` + +Inside a project it adds two columns for the frontend part: + +| Column | What it shows | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Installed` | The installed version, `declared` when `package.json` asks for the package and it is not installed, or `no` | +| `Compatible` | `yes` or `no` when the module's range can be compared with the part's Druxt version, and `unknown` when the module states no range or the part has no Druxt | + +The Druxt version compared is the one installed in the part, or the range the part asks for when none is installed. A module whose range is `unknown` or not stated is shown as `unknown`, never as compatible. + +| Option | What it does | +| ------------------------- | --------------------------------------------------------------- | +| `--all` | Include archived modules | +| `--type ` | Only modules of this type, such as `official` or `contrib` | +| `--category ` | Only modules in this category | +| `--module-registry ` | A module registry: a URL, or a name from the user configuration | +| `--refresh` | Read the registry again even when the cached copy is fresh | +| `--json` | Print the result as JSON on stdout | + +### `drx module search ` + +The same table, for the modules whose name, package name or description contains the text. Case is ignored. It takes the options of `drx module list`. + +### `drx add ` + +Adds one or more modules to the project, by registry name or package name. `drx module add` is the same command. + +```bash +npx @druxt/cli add breadcrumb +npx @druxt/cli add breadcrumb --dry-run +``` + +For each module it does two things: + +- **Frontend.** It installs the package with the package manager of the part's lock file, and adds the package to the `modules` array of `nuxt.config`. The rest of the file stays as you wrote it. When the config is a function, or its `modules` is not an array written out in the file, the package is installed, the file is left alone and the line to add is printed. +- **Backend.** For each Drupal module the entry lists, a contributed one is required with Composer and enabled with Drush, and a core one is only enabled. The commands run through the part's engine: `ddev composer`, `lando drush`, or `composer` and `vendor/bin/drush` for the `php` engine. + +| Option | What it does | +| ------------------------------------------------ | ---------------------------------------------------------------------------------- | +| `--dry-run` | Print every step, with each command line, and change nothing | +| `--force` | Add a module that is archived, or whose range does not admit the Druxt in the part | +| `--no-patches` | Leave out the patches the module needs, with a warning naming each | +| `--yes`, `-y` | Ask nothing | +| `--module-registry `, `--refresh`, `--json` | As for `drx module list` | + +What it refuses, before it takes any step: + +- An archived module, and one whose Druxt range excludes the Druxt in the frontend part. `--force` adds either. A module whose range is `unknown` is added with a warning. +- A module with no package, which is not released. `--force` does not change that. +- A Drupal module it cannot place as core or contributed. See below. + +**Where the backend is not run from here.** With the `none` engine, or in a project that does not record an engine, the frontend is done and the Composer and Drush lines are printed under "Left to do", for you to run where the backend is. + +**Patches.** A Drupal module in the registry may list patches. `add` shows each with its issue and writes it to `extra.patches` in the site's `composer.json`. It then runs `composer patches-relock`. When the site lacks `cweagans/composer-patches`, it allows the plugin and requires it. A patch is skipped when the installed package is at or past the version that has the fix, and when the site already has the same patch. + +**Setup.** Steps a module needs done by hand, such as creating a consumer, are printed under "Left to do". They are not run. + +**When a tool fails.** The run stops there. The tool's output is printed, then what was done and what was not. Nothing is recorded for that module. + +**Core or contributed.** The registry marks a core module with `core: true`, and a registry that marks any module is taken to mark them all. Against a registry that marks none, which is the published one today, `add` looks in the core the site has installed, under `web/core/modules`, and treats a package the site already requires as contributed. With no core installed it refuses that module and says to install the backend's dependencies first, since the CLI does not keep a list of core modules to guess from. + +At a terminal with no name, `drx add` lists the modules to pick from, shows the steps and asks before it changes anything. + +### `drx remove ` + +Takes a module out of the `modules` array and uninstalls its package. `drx module remove` is the same command. It takes `--dry-run`, `--yes`, `--module-registry`, `--refresh` and `--json`. + +The backend is left alone unless `--backend` is given. With it, `remove` uninstalls and removes only the Drupal modules that `drx add` required, and only the patches it wrote, which it knows from the record in `drx.config.json`. A Drupal module that another installed Druxt module needs stays. + +### `drx module` + +With no command, at a terminal: a list of the modules that narrows as you type. Pick one and it is shown as `drx module info` shows it. Anywhere else it fails and names the commands. + +### `drx module info ` + +Shows one module, found by its registry name or its package name: the package, type, status, category, Druxt range, repository and website, and the backend modules it needs, with the ones that are part of Drupal core marked. Inside a project it adds the installed version and the compatibility. It takes `--module-registry`, `--refresh` and `--json`. + +A name that matches nothing exits with 1 and prints the closest names. + +### `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. + +## At a terminal + +`drx` with no command opens a menu when a person is at the terminal. It names the project you are in, which it reads from `drx.config.json`. Below that are the actions for where you are: + +- Outside a project: create a site. +- Inside one: list, search or show modules, and show the project. Add or remove modules. Configuring a module and managing patches are listed as not available yet. + +Each entry runs the command it stands for, so the menu and the commands cannot differ. + +`drx init` with values missing is a guided run: + +1. It asks for the directory, the starter when the registry has more than one, the layout, the engine with its database or URL, and whether to install. +2. It lists what it will do, from the directory it will create to the files it will remove. +3. It asks before it writes. Answer no, or press Ctrl-C at any prompt, and nothing has been written. The exit code is 1. + +Every run that asked for something ends with the command that repeats it, with each choice as a flag: + +```text +Repeat this with: drx init my-site --starter quickstart --layout monorepo --engine ddev --database mariadb --no-install --yes +``` + +### The wordmark and the header + +The Druxt wordmark is drawn in two places only: at the start of a guided `init`, and above the menu. Other commands that print a report start with one line, `druxt` and the version. Both go to stderr. + +The wordmark is not drawn with `--json`, without a terminal, under `CI`, or in a terminal narrower than its 58 columns. To turn it off yourself: + +- `--no-banner` on `drx` or `drx init`, for one run. +- `"banner": false` in the [user configuration](#the-user-configuration), for every run. + +### Colour and marks + +Blue is the backend and green is the frontend: the wordmark runs from one to the other, and a part is printed in the colour of its role wherever parts are listed. The role is always there in words too. Each line on stderr starts with a mark, and the marks differ in shape as well as colour. A running step has one, a finished step another, and a warning and a failure have their own. `Warning:` and `Error:` are spelled out beside them. + +| Setting | What it does | +| -------------------- | ------------------------------------------------------------------------- | +| `NO_COLOR=1` | No colour anywhere. It wins over `FORCE_COLOR` | +| `FORCE_COLOR=1` | Colour with no terminal. `2` is 256 colours and `3` is 24-bit, `0` is off | +| `--json` | Plain text, without marks or the wordmark | +| No terminal, or `CI` | Plain text, without marks or the wordmark | + +A terminal with 16 colours gets its own blue and green. One that cannot draw Unicode gets `*`, `+`, `!` and `x` for the marks. + +## CI and scripts + +The CLI never asks anything when nobody is there to answer. Each of these is enough: + +| Condition | How | +| ---------------------- | ------------------------------------------------ | +| No terminal | stdin or stderr is not a terminal | +| `CI` is set | Most CI services set it | +| `DRX_NO_INTERACTIVE=1` | For a script run from a terminal | +| `--no-interactive` | The same, as a flag, before or after the command | +| `--json` | The command prints JSON and asks nothing | + +Prompts, the menu, the wordmark and animation are then all off. A value with a default takes it, and a value with none fails with a message naming the flag to pass. Bare `drx` prints its usage. `--yes` accepts the defaults and can be combined with any of them. `init` needs it only when no directory is given. + +A complete unattended `init`: + +```bash +npx @druxt/cli init my-site \ + --starter quickstart \ + --layout monorepo \ + --engine ddev \ + --no-install \ + --no-interactive \ + --json > result.json +``` + +stdout is the JSON result and nothing else. stderr has one plain line per step. + +| Exit code | Meaning | +| --------- | ------------------------------------------ | +| `0` | The command did what it was asked | +| `1` | It did not. The message on stderr says why | + +With `--json`, a failure prints `{ "ok": false, "error": { "code", "message" } }` on stdout, and `code` says which kind it was: `usage`, `not-available`, `registry`, `invalid-entry`, `unknown-starter`, `unknown-source`, `unknown-module`, `directory-not-empty`, `config`, `download`, `install` or `cancelled`. + +## 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", + "engine": "ddev", + "database": "mariadb" + } + ] +} +``` + +| 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. + +`drx add` keeps a record under `modules`, one entry for each module it added. An entry has the package, and for each backend part the Drupal modules `add` required and the patches it wrote. `drx remove --backend` undoes that and nothing else. + +A backend part also records the `engine` chosen at `init`, its `database` where the engine has one, and for the `none` engine the `baseUrl` of the backend. A file written before engines existed has none of the three and still reads. `drx info` prints them. + +## 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, or Lando"] + }, + "maintained": "2026-11-15", + "default": true, + "steps": ["npm run setup", "npm run dev"], + "backendUrl": { + "file": ".env", + "template": ".env.example", + "variable": "BASE_URL" + }, + "engines": [ + { + "name": "ddev", + "label": "DDEV", + "commands": ["ddev"], + "databases": ["mariadb"], + "baseUrl": "http://quickstart-druxtsite.ddev.site", + "steps": [ + "npm run setup", + { "run": "ddev start", "dir": "drupal" }, + { "run": "ddev drupal-install", "dir": "drupal" }, + { "run": "ddev druxt-add-consumer", "dir": "drupal" }, + "npm run dev" + ], + "notes": [ + "ddev druxt-add-consumer prints OAUTH_CLIENT_ID. Copy it into .env before npm run dev." + ], + "files": ["drupal/.ddev"] + } + ] + } +} +``` + +`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 | +| `requires.commands` | Superseded by `engines`. Still read from an entry that has no `engines` | +| `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, when no engine is chosen and for the `none` engine | +| `engines` | Optional. The ways the backend can be run, described below | +| `backendUrl` | Optional. The `file` and `variable` the starter reads its backend URL from, and a `template` to start the file from | + +`index.json` is `{ "starters": ["quickstart"] }`. + +An entry in `engines` has: + +| Key | What it holds | +| ----------- | ------------------------------------------------------------------------------------------------------------------ | +| `name` | The name `--engine` takes. Lower case. `none` is taken | +| `label` | What the prompt shows, and what `init` prints under "It needs" | +| `commands` | The commands the engine needs on `PATH`, as bare names | +| `databases` | Optional. The databases it can be set up with, the default first | +| `steps` | What to run in the new site, in order. A step is a command, or `{ "run", "dir" }` for a command run in a directory | +| `notes` | Optional. What to do by hand, printed after the steps | +| `files` | Optional. Paths in the starter that the engine needs, relative to its root | +| `baseUrl` | Optional. The URL the engine serves the backend at, when it is fixed | + +`init` removes the `files` of the engines that were not chosen. A path that two engines list is kept when either is chosen, and a directory that holds a kept path loses the rest of its contents. An absolute path, or one that leaves the starter, is refused when the entry is read, and again before anything is removed, which also stops a link in the starter from leading outside the site. + +`init` looks each of the chosen engine's commands up on `PATH` without running it. On Windows it tries the extensions in `PATHEXT`. When one is missing it prints one warning and still creates the site: + +```text +Warning: The ddev engine needs ddev. Not found on PATH: ddev. Install what is missing before you set up the site. +``` + +With `--json` the result has `engine`, `database`, `baseUrl`, `removed`, `notes` and a `commands` object with `satisfied`, `alternatives`, `found` and `missing`. + +`requires.commands`, a list of alternatives such as `[["php", "composer"], ["ddev"]]`, is what an entry used before `engines`. It is read only from an entry with no `engines`, and warns when no alternative is complete. + +`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 module registry + +The module commands read `https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json`, which the [druxt/modules](https://github.com/druxt/modules) repository publishes. The CLI reads `schemaVersion` 1. It refuses any other version with a message saying so, and ignores fields it has no use for. + +The registry is cached on disk: + +- A copy under an hour old is used without a request. `--refresh` reads the registry anyway. +- An older copy is replaced by a new read. +- When the registry cannot be read, the copy is used whatever its age, and the command says so and how old it is. +- With no copy and no registry, the command fails. + +`drx add` reads four optional fields of a Drupal module in an entry, and works without them: + +| Field | What it holds | +| ---------- | ------------------------------------------------------------------------------------------------------------------------- | +| `core` | `true` for a module that is part of Drupal core | +| `composer` | The `package`, and a `constraint`, when the package is not `drupal/` | +| `patches` | Each a `description` and a `url`, with the `package` it applies to, its `issue` and the version it is fixed in as `until` | +| `setup` | Steps to do by hand once the module is enabled, each with a `title` and optionally a `command` and a `url` | + +The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. `DRX_CACHE_DIR` names another directory. + +## The user configuration + +`~/.config/drx/config.json` names starter registries, module 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" + }, + "banner": false, + "moduleRegistries": { + "team": "https://example.com/modules.json" + }, + "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. +- `--module-registry team` reads modules from that URL, with `GIGET_AUTH` sent to it in the same way. +- `"banner": false` stops the wordmark being drawn. +- `--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`. +- `drx module configure`. The command exists and fails with a message. `drx add` does not ask for a module's options. +- Commands to list, check and relock patches. +- Running a module's setup steps. They are printed. +- Adding to a Nuxt 4 site through Nuxt's own CLI. `drx add` edits `nuxt.config` itself, for Nuxt 2 and later alike. +- A check that a Drupal module is already enabled. `drush en` is run for each one, and only the modules `drx add` required are recorded as its own. +- Making a wrapper component and upgrading a site. +- Kinds other than `nuxt` and `drupal`. +- `init --setup`, which would run the engine's steps. The flag exists and fails with a message, and `init` prints the steps. +- A database other than the one each quickstart engine is set up for. `--database` records the choice and does not change a file. +- A version check of the commands an engine needs. `init` checks that `php` is on `PATH`, not that it is 8.3 or newer. +- The same check in `drx info`. A project does not record what its starter requires, so `info` would have to read the registry again. +- 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/commitlint.config.mjs b/commitlint.config.mjs new file mode 100644 index 0000000..300421c --- /dev/null +++ b/commitlint.config.mjs @@ -0,0 +1,46 @@ +// Conventional Commits, unmodified, plus one project rule. +// +// The type list is deliberately the stock one. A repository-specific vocabulary +// means a contributor who has worked on another Druxt repository guesses wrong, +// and the value of the convention is that it is the same everywhere. +// +// no-ai-attribution: the work is the author's. A co-author trailer naming a +// coding assistant, a generated-with footer or a session link hands ownership +// to a tool. .gitlab/scripts/check-attribution.sh runs the same check over the +// merge request range and every tracked file in CI; this is the local half, +// run by the commit-msg hook. The pattern is assembled from pieces so that this +// file passes its own scan. +const tools = + 'claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm' +const attribution = new RegExp( + [ + 'co-authored' + `-by:.*(${tools})`, + `generated (with|by).*(${tools}|\\bai\\b)`, + 'claude-' + 'session:', + 'claude\\.ai/code/session', + 'noreply' + '@anthropic\\.com', + ].join('|'), + 'i' +) + +export default { + extends: ['@commitlint/config-conventional'], + plugins: [ + { + rules: { + 'no-ai-attribution': ({ raw }) => { + const hit = raw.match(attribution) + return [ + !hit, + hit + ? `AI attribution is not allowed: "${hit[0].trim()}". The work is the author's.` + : '', + ] + }, + }, + }, + ], + rules: { + 'no-ai-attribution': [2, 'always'], + }, +} diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..5efaf1b --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,28 @@ +import js from '@eslint/js' +import prettier from 'eslint-config-prettier' +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { + ignores: [ + '**/dist/**', + '**/node_modules/**', + 'coverage/**', + 'reports/**', + '.vale/**', + 'packages/cli/starters/**', + 'packages/cli/test/fixtures/**', + ], + }, + js.configs.recommended, + ...tseslint.configs.recommended, + prettier, + { + languageOptions: { + ecmaVersion: 2023, + sourceType: 'module', + globals: globals.node, + }, + } +) diff --git a/knip.jsonc b/knip.jsonc new file mode 100644 index 0000000..00b416e --- /dev/null +++ b/knip.jsonc @@ -0,0 +1,15 @@ +{ + "$schema": "https://unpkg.com/knip@6/schema.json", + // Copies of real files from other projects, with those projects' imports. + "ignore": ["packages/cli/test/fixtures/**"], + "workspaces": { + ".": { + "entry": ["scripts/*.mjs", "test/**/*.test.ts"], + "project": ["scripts/**/*.mjs", "test/**/*.ts"] + }, + "packages/*": { + "entry": ["src/index.ts", "src/bin.ts", "test/**/*.test.ts"], + "project": ["src/**/*.ts", "test/**/*.ts"] + } + } +} diff --git a/package-lock.json b/package-lock.json index 7f2edd2..10c1426 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@commitlint/config-conventional": "21.2.4", "@eslint/js": "10.0.1", "@types/node": "24.19.2", + "@types/semver": "7.8.0", "@vitest/coverage-v8": "5.1.0", "cspell": "10.5.1", "eslint": "10.15.0", @@ -61,7 +62,6 @@ "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, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -71,7 +71,6 @@ "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, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -81,7 +80,6 @@ "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, "license": "MIT", "dependencies": { "@babel/types": "^7.29.14" @@ -97,7 +95,6 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", - "dev": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.14", @@ -388,7 +385,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", @@ -403,7 +399,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", @@ -2902,6 +2897,13 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/unist": { "version": "2.0.11", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", @@ -3396,6 +3398,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", @@ -3515,6 +3545,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", @@ -3572,6 +3623,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", @@ -3913,6 +3970,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", @@ -3923,6 +3986,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", @@ -3948,6 +4017,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", @@ -4260,6 +4341,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", @@ -4325,14 +4412,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" @@ -4359,7 +4444,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" @@ -4541,6 +4625,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", @@ -4851,7 +4944,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" @@ -5373,7 +5465,6 @@ "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", - "dev": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -6198,6 +6289,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", @@ -6395,6 +6492,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", @@ -6415,6 +6524,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", @@ -6532,6 +6658,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", @@ -6542,6 +6678,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", @@ -6647,7 +6796,6 @@ "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -6696,7 +6844,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" @@ -6732,7 +6879,6 @@ "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, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -7328,6 +7474,14 @@ "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", + "magicast": "^0.5.5", + "semver": "^7.8.6" + }, "bin": { "drx": "dist/bin.js" }, @@ -7338,6 +7492,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/package.json b/package.json index acf5140..ce9cbeb 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "@commitlint/config-conventional": "21.2.4", "@eslint/js": "10.0.1", "@types/node": "24.19.2", + "@types/semver": "7.8.0", "@vitest/coverage-v8": "5.1.0", "cspell": "10.5.1", "eslint": "10.15.0", 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..6d2752e --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,23 @@ +# @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 | +| `drx module list`, `search`, `info` | Lists, searches and shows the modules in the Druxt module registry | +| `drx add`, `drx remove` | Adds a module to the frontend and backend of a project, or removes it | + +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..fafe93d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,7 +1,7 @@ { "name": "@druxt/cli", "version": "0.0.0", - "description": "The Druxt command-line tool: create a site from a starter and report on it.", + "description": "Command-line tool for Druxt: create a site, add modules and manage a decoupled Drupal project.", "keywords": [ "druxt", "cli" @@ -36,5 +36,13 @@ }, "publishConfig": { "access": "public" + }, + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1", + "magicast": "^0.5.5", + "semver": "^7.8.6" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts new file mode 100644 index 0000000..2ab56d6 --- /dev/null +++ b/packages/cli/src/adapters/adapter.ts @@ -0,0 +1,113 @@ +import type { BackendModule } from '../modules/entry.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 + /** + * The Druxt package of the part: the range it asks for and the version + * installed. Undefined when the part has none, or its kind never holds one. + */ + druxt(dir: string): Promise + /** + * One package of the part by name, or undefined when the part neither + * asks for it nor has it installed. + */ + package(dir: string, name: string): Promise + /** + * What adding a module to the part takes. Nothing is run or written here: + * the command prints the steps, and runs them unless it is a dry run. + */ + addModule(dir: string, request: AddRequest): Promise + /** What taking a module out of the part takes. */ + removeModule(dir: string, request: RemoveRequest): Promise +} + +/** A tool to run in the part, by the name the part's engine knows it by. */ +export interface ToolRun { + tool: string + args: string[] +} + +/** A file of the part to write, with its whole new content. */ +export interface FileEdit { + /** Relative to the part. */ + file: string + content: string + /** What the edit does, as one line. */ + summary: string +} + +/** What a module needs of a part. A kind reads the fields that apply to it. */ +export interface AddRequest { + /** The frontend package of the module. */ + package?: string + /** The backend modules it needs, of this part's kind. */ + needs: BackendModule[] + /** False to leave the patches of those modules out. */ + patches: boolean + /** True when the registry marks core modules, so one not marked is not core. */ + registryStatesCore: boolean +} + +export interface RemoveRequest { + package?: string + /** What an earlier add did to this part, from the project's record. */ + record?: BackendRecord + /** Backend modules another installed module needs, which must stay. */ + stillNeeded: string[] +} + +/** What an add did to a backend part, kept so a remove undoes that and no more. */ +export interface BackendRecord { + /** The modules it required and enabled, which were not there before. */ + modules: { name: string; package: string }[] + /** The patches it wrote. */ + patches: { package: string; description: string; url: string }[] +} + +/** The steps of a change to one part, in the order to take them. */ +export interface ModuleChange { + steps: ({ run: ToolRun } | { edit: FileEdit })[] + /** Reasons the change cannot be made. With any, no step is taken. */ + problems: string[] + warnings: string[] + /** What was found that needs no step. */ + notes: string[] + /** What the user has to do by hand, because the tool could not. */ + manual: string[] + /** What is left to do once the change is made. */ + after: string[] + /** What to keep in the project's record. */ + record?: BackendRecord +} + +export function emptyChange(): ModuleChange { + return { + steps: [], + problems: [], + warnings: [], + notes: [], + manual: [], + after: [], + } +} diff --git a/packages/cli/src/adapters/drupal-modules.ts b/packages/cli/src/adapters/drupal-modules.ts new file mode 100644 index 0000000..919631c --- /dev/null +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -0,0 +1,315 @@ +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import semver from 'semver' +import type { BackendModule } from '../modules/entry.js' +import { isRecord } from '../validate.js' +import { + emptyChange, + type AddRequest, + type BackendRecord, + type ModuleChange, + type RemoveRequest, +} from './adapter.js' + +/** The Composer plugin that applies patches, and the line the quickstart is on. */ +const PATCHES_PLUGIN = 'cweagans/composer-patches' +const PATCHES_PLUGIN_CONSTRAINT = '^2.0@beta' + +type Json = Record +type Patches = Record> + +interface Manifest { + source: string + json: Json + require: Record + patches: Patches +} + +async function readManifest(dir: string): Promise { + try { + const source = await readFile(join(dir, 'composer.json'), 'utf8') + const json: unknown = JSON.parse(source) + if (!isRecord(json)) return undefined + const extra = isRecord(json.extra) ? json.extra : {} + return { + source, + json, + require: isRecord(json.require) ? json.require : {}, + patches: (isRecord(extra.patches) ? extra.patches : {}) as Patches, + } + } catch { + return undefined + } +} + +/** The manifest as text, with the indent and final newline it had. */ +function write(manifest: Manifest, json: Json): string { + const indent = /^([ \t]+)"/m.exec(manifest.source)?.[1] ?? ' ' + const text = JSON.stringify(json, null, indent) + return manifest.source.endsWith('\n') ? `${text}\n` : text +} + +/** The directory core keeps its modules in, under the web root the site names. */ +function coreModulesDir(dir: string, manifest: Manifest): string { + const extra = isRecord(manifest.json.extra) ? manifest.json.extra : {} + const scaffold = extra['drupal-scaffold'] + const locations = isRecord(scaffold) ? scaffold.locations : undefined + const webRoot = isRecord(locations) ? locations['web-root'] : undefined + return join( + dir, + typeof webRoot === 'string' ? webRoot : 'web', + 'core', + 'modules' + ) +} + +/** The version of each package Composer has installed. */ +async function installedVersions(dir: string): Promise> { + const versions = new Map() + try { + const installed: unknown = JSON.parse( + await readFile(join(dir, 'vendor', 'composer', 'installed.json'), 'utf8') + ) + const packages = isRecord(installed) ? installed.packages : undefined + for (const entry of Array.isArray(packages) ? packages : []) { + if (isRecord(entry) && typeof entry.name === 'string') { + versions.set(entry.name, String(entry.version)) + } + } + } catch { + // Nothing is installed yet. + } + return versions +} + +const packageOf = (need: BackendModule) => + need.composer?.package ?? `drupal/${need.name}` + +/** + * Whether a module is core's own or a package to require. + * + * The registry's word is taken first. A registry that marks core modules + * marks all of them, so in one that does, a module not marked is a package. A + * package the site already requires is plainly a package. Past that the only + * honest source is the core the site has installed, and without it the + * answer is `unknown`. There is no list of core modules here to go stale. + */ +function origin( + need: BackendModule, + request: AddRequest, + manifest: Manifest, + coreDir: string +): 'core' | 'package' | 'unknown' { + if (need.core) return 'core' + if (request.registryStatesCore || need.composer) return 'package' + if (packageOf(need) in manifest.require) return 'package' + if (!existsSync(coreDir)) return 'unknown' + return existsSync(join(coreDir, need.name)) ? 'core' : 'package' +} + +/** The steps that add the backend modules a Druxt module needs. */ +export async function planBackendAdd( + dir: string, + request: AddRequest +): Promise { + const change = emptyChange() + const { needs } = request + if (needs.length === 0) return change + + const manifest = await readManifest(dir) + if (!manifest) { + change.problems.push( + `There is no composer.json to add ${needs.map(({ name }) => name).join(', ')} to.` + ) + return change + } + + const coreDir = coreModulesDir(dir, manifest) + const versions = await installedVersions(dir) + const record: BackendRecord = { modules: [], patches: [] } + const toRequire: string[] = [] + const patches: Patches = structuredClone(manifest.patches) + let repatch = false + + for (const need of needs) { + const pkg = packageOf(need) + const from = origin(need, request, manifest, coreDir) + if (from === 'unknown') { + change.problems.push( + `Cannot tell whether ${need.name} is part of core or a package to require: the module registry does not say, and core is not installed in this part to look in. Install the dependencies of the backend, then run this again.` + ) + continue + } + if (from === 'package') { + if (pkg in manifest.require) { + change.notes.push(`${pkg} is already required in composer.json.`) + } else { + toRequire.push( + need.composer?.constraint ? `${pkg}:${need.composer.constraint}` : pkg + ) + record.modules.push({ name: need.name, package: pkg }) + } + } + + for (const patch of need.patches ?? []) { + const target = patch.package ?? pkg + if (!request.patches) { + change.warnings.push( + `The patch "${patch.description}" for ${target} was not applied. ${need.label} may not work without it.` + ) + continue + } + const has = versions.get(target) + const fixed = patch.until ? semver.coerce(patch.until) : null + const installed = has ? semver.coerce(has) : null + if (fixed && installed && semver.gte(installed, fixed)) { + change.notes.push( + `The patch "${patch.description}" is not needed: ${target} ${has} has the fix, which came in ${patch.until}.` + ) + continue + } + if (Object.values(patches[target] ?? {}).includes(patch.url)) { + change.notes.push( + `The patch "${patch.description}" is already in composer.json.` + ) + continue + } + patches[target] = { ...patches[target], [patch.description]: patch.url } + record.patches.push({ + package: target, + description: patch.description, + url: patch.url, + }) + change.notes.push( + `Patch for ${target}: ${patch.description}${patch.issue ? ` (${patch.issue})` : ''}` + ) + // A package that is installed already has to be patched in place. + if (target !== pkg || pkg in manifest.require) repatch = true + } + + for (const step of need.setup ?? []) { + change.after.push(`${need.label}: ${step.title}`) + if (step.command) change.after.push(` ${step.command}`) + if (step.url) change.after.push(` ${step.url}`) + } + } + + if (change.problems.length > 0) return change + const composer = (...args: string[]) => + change.steps.push({ run: { tool: 'composer', args } }) + + if (record.patches.length > 0) { + const json = structuredClone(manifest.json) + json.extra = { ...(isRecord(json.extra) ? json.extra : {}), patches } + const hasPlugin = PATCHES_PLUGIN in manifest.require + if (!hasPlugin) { + // Allowed before it is required, or Composer stops to ask. + const config = isRecord(json.config) ? json.config : {} + const allowed = isRecord(config['allow-plugins']) + ? config['allow-plugins'] + : {} + json.config = { + ...config, + 'allow-plugins': { ...allowed, [PATCHES_PLUGIN]: true }, + } + } + const count = record.patches.length + change.steps.push({ + edit: { + file: 'composer.json', + content: write(manifest, json), + summary: `Add ${count} patch${count === 1 ? '' : 'es'} to composer.json`, + }, + }) + if (!hasPlugin) { + composer('require', `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`) + } + composer('patches-relock') + } + if (toRequire.length > 0) composer('require', ...toRequire) + if (record.patches.length > 0 && repatch) composer('patches-repatch') + change.steps.push({ + run: { + tool: 'drush', + args: ['en', '-y', ...needs.map(({ name }) => name)], + }, + }) + + change.record = record + return change +} + +/** + * The steps that undo what an add did to the part: the modules it required + * and the patches it wrote, and nothing the site's owner put there. + */ +export async function planBackendRemove( + dir: string, + request: RemoveRequest +): Promise { + const change = emptyChange() + const record = request.record + if (!record) return change + + const going = record.modules.filter( + ({ name }) => !request.stillNeeded.includes(name) + ) + for (const { name } of record.modules) { + if (!going.some((module) => module.name === name)) { + change.notes.push(`${name} stays: another installed module needs it.`) + } + } + if (going.length > 0) { + change.steps.push({ + run: { + tool: 'drush', + args: ['pmu', '-y', ...going.map(({ name }) => name)], + }, + }) + } + + // The record does not say which module a patch was for, so while any of + // them stays, every patch does. + const manifest = await readManifest(dir) + let relock = false + if (manifest && going.length === record.modules.length) { + const patches: Patches = structuredClone(manifest.patches) + let removed = 0 + for (const patch of record.patches) { + const forPackage = patches[patch.package] + if (forPackage?.[patch.description] !== patch.url) continue + delete forPackage[patch.description] + if (Object.keys(forPackage).length === 0) delete patches[patch.package] + removed += 1 + } + if (removed > 0) { + const json = structuredClone(manifest.json) + const extra = { ...(isRecord(json.extra) ? json.extra : {}) } + if (Object.keys(patches).length === 0) delete extra.patches + else extra.patches = patches + json.extra = extra + change.steps.push({ + edit: { + file: 'composer.json', + content: write(manifest, json), + summary: `Remove ${removed} patch${removed === 1 ? '' : 'es'} from composer.json`, + }, + }) + relock = true + } + } + + if (going.length > 0) { + change.steps.push({ + run: { + tool: 'composer', + args: ['remove', ...going.map((module) => module.package)], + }, + }) + } + if (relock) { + change.steps.push({ run: { tool: 'composer', args: ['patches-relock'] } }) + } + return change +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts new file mode 100644 index 0000000..e114b89 --- /dev/null +++ b/packages/cli/src/adapters/drupal.ts @@ -0,0 +1,62 @@ +import { join } from 'node:path' +import { isRecord } from '../validate.js' +import type { KindAdapter, PackageVersion } from './adapter.js' +import { planBackendAdd, planBackendRemove } from './drupal-modules.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, + }) + ) + }, + + // The Druxt packages a module registry lists are frontend packages. + druxt: async () => undefined, + package: async () => undefined, + + addModule: planBackendAdd, + removeModule: planBackendRemove, +} diff --git a/packages/cli/src/adapters/index.ts b/packages/cli/src/adapters/index.ts new file mode 100644 index 0000000..95ad7da --- /dev/null +++ b/packages/cli/src/adapters/index.ts @@ -0,0 +1,24 @@ +import type { Role } from '../parts.js' +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) +} + +/** The kinds a part of the given role can be. */ +export function kindsWithRole(role: Role): string[] { + return ADAPTERS.filter((adapter) => adapter.role === role).map( + (adapter) => adapter.kind + ) +} diff --git a/packages/cli/src/adapters/nuxt-config.ts b/packages/cli/src/adapters/nuxt-config.ts new file mode 100644 index 0000000..0ecd56a --- /dev/null +++ b/packages/cli/src/adapters/nuxt-config.ts @@ -0,0 +1,72 @@ +import { generateCode, parseModule } from 'magicast' +import { getDefaultExportOptions } from 'magicast/helpers' + +/** The key Druxt modules are listed under, in Nuxt 2 and later alike. */ +const KEY = 'modules' + +/** The result of trying to change the modules list of a config. */ +export type ConfigEdit = + | { kind: 'changed'; content: string } + | { kind: 'unchanged' } + /** The file is not a shape that can be edited without guessing. */ + | { kind: 'unsafe' } + +/** The name of one entry of the list: a string, or the first of an array. */ +function entryName(entry: unknown): string | undefined { + if (typeof entry === 'string') return entry + if ( + Array.isArray(entry) || + (entry as { $type?: string })?.$type === 'array' + ) { + const first = (entry as unknown[])[0] + return typeof first === 'string' ? first : undefined + } + return undefined +} + +/** + * Adds a module to, or removes it from, the `modules` array of a Nuxt + * config, keeping the rest of the file as it is written. + * + * It edits a config that exports an object, or a call such as + * `defineNuxtConfig` with one, whose `modules` is an array written out in + * the file. Anything else, such as a function or a list held in a variable, + * is reported as unsafe and left for a person. + */ +export function editModules( + source: string, + name: string, + action: 'add' | 'remove' +): ConfigEdit { + try { + const module = parseModule(source) + const config = getDefaultExportOptions(module) + if (config?.$type !== 'object') return { kind: 'unsafe' } + + const list = config[KEY] + if (list === undefined) { + if (action === 'remove') return { kind: 'unchanged' } + config[KEY] = [name] + } else { + if (list.$type !== 'array') return { kind: 'unsafe' } + const index = [...list].findIndex((entry) => entryName(entry) === name) + if (action === 'add') { + if (index !== -1) return { kind: 'unchanged' } + list.push(name) + } else { + if (index === -1) return { kind: 'unchanged' } + list.splice(index, 1) + } + } + + const { code } = generateCode(module) + // The printer drops the newline a file ends with. + return { + kind: 'changed', + content: + source.endsWith('\n') && !code.endsWith('\n') ? `${code}\n` : code, + } + } catch { + return { kind: 'unsafe' } + } +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts new file mode 100644 index 0000000..24e32c5 --- /dev/null +++ b/packages/cli/src/adapters/nuxt.ts @@ -0,0 +1,169 @@ +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + emptyChange, + type KindAdapter, + type ModuleChange, + type PackageVersion, +} from './adapter.js' +import { editModules } from './nuxt-config.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\/.+)$/ + +/** The package that is Druxt itself, under each naming scheme. */ +const DRUXT_CORE = ['druxt', '@druxt/core'] + +async function declared(dir: string): Promise> { + const manifest = await readJsonObject(join(dir, 'package.json')) + return { + ...stringMap(manifest, 'devDependencies'), + ...stringMap(manifest, 'dependencies'), + } +} + +/** The version of a package in the part's node_modules, or null. */ +async function installedVersion( + dir: string, + name: string +): Promise { + const manifest = await readJsonObject( + join(dir, 'node_modules', name, 'package.json') + ) + return typeof manifest?.version === 'string' ? manifest.version : null +} + +async function packageVersion( + dir: string, + name: string +): Promise { + const range = (await declared(dir))[name] ?? null + const installed = await installedVersion(dir, name) + if (range === null && installed === null) return undefined + return { name, range, installed } +} + +/** The package manager of a part, by the lock file it keeps. */ +const MANAGERS = [ + { lock: 'pnpm-lock.yaml', tool: 'pnpm', add: 'add', remove: 'remove' }, + { lock: 'yarn.lock', tool: 'yarn', add: 'add', remove: 'remove' }, + { lock: 'bun.lock', tool: 'bun', add: 'add', remove: 'remove' }, + { lock: 'bun.lockb', tool: 'bun', add: 'add', remove: 'remove' }, +] as const +const NPM = { tool: 'npm', add: 'install', remove: 'uninstall' } as const + +function packageManager(dir: string) { + return MANAGERS.find(({ lock }) => existsSync(join(dir, lock))) ?? NPM +} + +/** + * The steps that add a package to the part and list it in the config, or + * that take both away again. The install comes first, so a failed one leaves + * the config as it was. + */ +async function changeModule( + dir: string, + name: string | undefined, + action: 'add' | 'remove' +): Promise { + const change = emptyChange() + if (!name) return change + + const manager = packageManager(dir) + const dependency = name in (await declared(dir)) + if (action === 'add' && dependency) { + change.notes.push(`${name} is already a dependency in package.json.`) + } else if (action === 'add' || dependency) { + change.steps.push({ + run: { tool: manager.tool, args: [manager[action], name] }, + }) + } + + const file = CONFIG_FILES.find((candidate) => + existsSync(join(dir, candidate)) + ) + if (!file) { + if (action === 'add') { + change.manual.push( + `Add '${name}' to the modules array of the config. No config file was found.` + ) + } + return change + } + + const edit = editModules( + await readFile(join(dir, file), 'utf8'), + name, + action + ) + if (edit.kind === 'changed') { + change.steps.push({ + edit: { + file, + content: edit.content, + summary: + action === 'add' + ? `Add '${name}' to modules in ${file}` + : `Remove '${name}' from modules in ${file}`, + }, + }) + } else if (edit.kind === 'unsafe') { + change.manual.push( + action === 'add' + ? `Add '${name}' to the modules array in ${file}. It could not be edited safely.` + : `Remove '${name}' from the modules array in ${file}. It could not be edited safely.` + ) + } else if (action === 'add') { + change.notes.push(`${name} is already in modules in ${file}.`) + } + return change +} + +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) { + versions.push({ + name, + range: ranges[name] ?? null, + installed: await installedVersion(dir, name), + }) + } + return versions + }, + + async druxt(dir) { + for (const name of DRUXT_CORE) { + const found = await packageVersion(dir, name) + if (found) return found + } + return undefined + }, + + package: packageVersion, + + addModule: (dir, request) => changeModule(dir, request.package, 'add'), + removeModule: (dir, request) => changeModule(dir, request.package, 'remove'), +} 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..8c75ade --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,168 @@ +import { stripVTControlCharacters } from 'node:util' +import { + defineCommand, + renderUsage, + runCommand, + type ArgsDef, + type CommandDef, +} from 'citty' +import { addCommand, removeCommand } from './commands/change.js' +import { infoCommand } from './commands/info.js' +import { initCommand } from './commands/init.js' +import { runMenu } from './commands/menu.js' +import { moduleCommand } from './commands/module.js' +import { defaultContext, type CliContext, type TextStream } from './context.js' +import { DrxError } from './errors.js' +import { createOutput } from './output.js' +import { cliVersion } from './package-root.js' + +function mainCommand(context: CliContext): CommandDef { + return defineCommand({ + meta: { + name: 'drx', + version: cliVersion(), + description: 'The Druxt command-line tool', + }, + args: { + interactive: { + type: 'boolean', + default: true, + description: 'Ask for what is missing when there is a terminal', + negativeDescription: + 'Never ask, draw or wait: for CI and scripts. DRX_NO_INTERACTIVE=1 does the same', + }, + }, + subCommands: { + init: initCommand(context), + info: infoCommand(context), + add: addCommand(context), + remove: removeCommand(context), + module: moduleCommand(context, { + add: addCommand(context, 'module add'), + remove: removeCommand(context, 'module remove'), + }), + }, + }) +} + +/** 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. A command + * may hold commands of its own, so the names are followed as far as they go. + */ +async function usage(main: CommandDef, argv: string[]): Promise { + let command = main + let parent: CommandDef | undefined + let path = 'drx' + for (const name of argv.filter((argument) => !argument.startsWith('-'))) { + const next = ( + command.subCommands as Record | undefined + )?.[name] + if (!next) break + parent = { meta: { name: path } } + path = `${path} ${name}` + command = next + } + return renderUsage(command, parent) +} + +/** 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), + } +} + +/** The flag that turns every prompt off. It goes before or after a command. */ +const NO_INTERACTIVE = '--no-interactive' + +/** + * Whether anything may be asked. A terminal is needed, and `CI`, + * `DRX_NO_INTERACTIVE` and `--no-interactive` each say no whatever the + * terminal is. A command then takes its defaults, and fails naming the flag + * of a value that has none. + */ +function mayAsk(context: CliContext, argv: string[]): boolean { + const off = (value: string | undefined) => + value !== undefined && value !== '' && value !== '0' && value !== 'false' + return ( + context.interactive && + !argv.includes(NO_INTERACTIVE) && + !off(context.env.DRX_NO_INTERACTIVE) && + !off(context.env.CI) + ) +} + +/** Runs one command line in a context that is already settled. */ +async function execute(argv: string[], context: CliContext): Promise { + const main = mainCommand(context) + const { stdout, stderr } = context + const json = argv.includes('--json') + + try { + if (argv.includes('--help') || argv.includes('-h')) { + stdout.write(`${plain(stdout, await usage(main, argv))}\n`) + return 0 + } + if (argv.length === 1 && ['--version', '-v'].includes(argv[0] ?? '')) { + stdout.write(`${cliVersion()}\n`) + return 0 + } + // Bare `drx`: a menu for a person, the usage for anything else. + if (argv.every((argument) => argument === '--no-banner')) { + if (context.interactive) { + return await runMenu(context, { banner: argv.length === 0 }, (next) => + execute(next, context) + ) + } + stderr.write(`${plain(stderr, await renderUsage(main))}\n`) + return 1 + } + await runCommand(main, { rawArgs: argv }) + return 0 + } catch (error) { + const failure = describe(error) + if (json) { + stdout.write( + `${JSON.stringify({ ok: false, error: failure }, null, 2)}\n` + ) + } + // In a terminal the line carries the mark for a failure. The word stays. + const output = createOutput(context, json) + const mark = output.decorated ? `${output.err.mark('failed')} ` : '' + stderr.write(`${mark}Error: ${failure.message}\n`) + return 1 + } +} + +/** + * 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 } + return execute( + argv.filter((argument) => argument !== NO_INTERACTIVE), + { ...context, interactive: mayAsk(context, argv) } + ) +} diff --git a/packages/cli/src/commands-on-path.ts b/packages/cli/src/commands-on-path.ts new file mode 100644 index 0000000..8dab810 --- /dev/null +++ b/packages/cli/src/commands-on-path.ts @@ -0,0 +1,107 @@ +import { accessSync, constants, statSync } from 'node:fs' +import { extname, join } from 'node:path' + +type Env = Record + +/** The extensions Windows tries when PATHEXT is not set. */ +const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD' + +/** A name a registry entry may ask to be looked up: no path, no spaces. */ +export function isCommandName(value: unknown): value is string { + return typeof value === 'string' && /^[a-z0-9][a-z0-9._+-]*$/i.test(value) +} + +function isRunnable(file: string, windows: boolean): boolean { + try { + if (!statSync(file).isFile()) return false + // Windows decides by extension, and has no executable bit to read. + if (!windows) accessSync(file, constants.X_OK) + return true + } catch { + return false + } +} + +/** + * The file a command name resolves to on PATH, or undefined. It reads the + * directories itself and runs nothing, so no shell is involved. + * + * On Windows the variable may be spelled `Path`, the separator is `;`, and a + * name with no extension is tried with each extension in PATHEXT. + */ +export function findOnPath( + name: string, + env: Env = process.env, + platform: string = process.platform +): string | undefined { + const windows = platform === 'win32' + const key = windows + ? Object.keys(env).find((candidate) => candidate.toUpperCase() === 'PATH') + : 'PATH' + const directories = (env[key ?? 'PATH'] ?? '') + .split(windows ? ';' : ':') + .filter(Boolean) + + let names = [name] + if (windows && extname(name) === '') { + names = (env.PATHEXT || DEFAULT_PATHEXT) + .split(';') + .filter(Boolean) + // The file system ignores case there. Trying the lower-case spelling + // first gives the same answer on one that does not. + .flatMap((extension) => [extension.toLowerCase(), extension]) + .map((extension) => name + extension) + } + + for (const directory of directories) { + for (const candidate of names) { + const file = join(directory, candidate) + if (isRunnable(file, windows)) return file + } + } + return undefined +} + +/** What a starter's commands look like on this machine. */ +export interface CommandCheck { + /** True when every command of at least one alternative was found. */ + satisfied: boolean + /** The alternatives, as the registry entry gives them. */ + alternatives: string[][] + found: string[] + missing: string[] +} + +/** + * Looks up every command of every alternative, each once, in the order the + * entry names them. + */ +export function checkCommands( + alternatives: string[][], + find: (name: string) => string | undefined +): CommandCheck { + const present = new Map() + for (const name of alternatives.flat()) { + if (!present.has(name)) present.set(name, find(name) !== undefined) + } + const names = [...present.keys()] + return { + satisfied: alternatives.some((commands) => + commands.every((name) => present.get(name)) + ), + alternatives, + found: names.filter((name) => present.get(name)), + missing: names.filter((name) => !present.get(name)), + } +} + +/** The alternatives as a phrase: "one and two, or three". */ +export function describeAlternatives(alternatives: string[][]): string { + return alternatives + .map((commands) => + commands.length > 1 + ? `${commands.slice(0, -1).join(', ')} and ${commands.at(-1)}` + : (commands[0] ?? '') + ) + .join(', or ') +} diff --git a/packages/cli/src/commands/change.ts b/packages/cli/src/commands/change.ts new file mode 100644 index 0000000..bc1972b --- /dev/null +++ b/packages/cli/src/commands/change.ts @@ -0,0 +1,266 @@ +import { defineCommand, type ArgsDef, type CommandDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + carryOut, + planAdd, + planData, + planLines, + planRemove, + type ChangeOptions, + type ModulePlan, + type Project, +} from '../modules/change.js' +import type { ModuleEntry } from '../modules/entry.js' +import { createOutput } from '../output.js' +import { CONFIG_FILE, findProjectRoot, loadProjectConfig } from '../project.js' +import { repeatCommand } from '../repeat.js' +import { findModule, openModules, registryArgs } from './module.js' + +type Action = 'add' | 'remove' + +const WORDS = { + add: { did: 'Added', example: 'drx add blocks' }, + remove: { did: 'Removed', example: 'drx remove blocks' }, +} as const + +const shared = { + module: { + type: 'positional', + required: false, + description: 'One or more modules, by registry name or package name', + }, + 'dry-run': { + type: 'boolean', + description: 'Print every step and change nothing', + }, + yes: { + type: 'boolean', + alias: 'y', + description: 'Ask nothing', + }, + ...registryArgs, +} satisfies ArgsDef + +const ARGS = { + add: { + ...shared, + force: { + type: 'boolean', + description: + 'Add a module that is archived, or whose range does not admit the Druxt here', + }, + patches: { + type: 'boolean', + default: true, + description: 'Write the patches the module needs', + negativeDescription: 'Leave the patches out, with a warning', + }, + }, + remove: { + ...shared, + backend: { + type: 'boolean', + description: 'Also undo what drx add did to the backend', + }, + }, +} satisfies Record + +/** The modules of the registry that the picker offers for an action. */ +async function candidates( + action: Action, + modules: ModuleEntry[], + project: Project, + options: ChangeOptions +): Promise { + const sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) + if (action === 'add') { + return sorted.filter((module) => !module.archived && module.npm) + } + const present: ModuleEntry[] = [] + for (const module of sorted) { + const plan = await planRemove(module, project, options) + if (plan.refusals.length === 0) present.push(module) + } + return present +} + +/** + * `drx add` and `drx remove`: the same run for both, with the plan made by + * the adapters of the project's parts and carried out here. + */ +function changeCommand( + context: CliContext, + action: Action, + name: string +): CommandDef { + const args: ArgsDef = ARGS[action] + const words = WORDS[action] + return defineCommand({ + meta: { + name: action, + description: + action === 'add' + ? 'Install a module, list it in the config and set up what it needs in the backend' + : 'Take a module out of the config and uninstall it', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, name) + const flags = parsed as Record + const dryRun = flags['dry-run'] === true + const output = createOutput(context, flags.json === true) + output.header() + + const root = findProjectRoot(context.cwd) + if (!root) { + throw new DrxError( + 'usage', + `drx ${action} works inside a project, and there is no ${CONFIG_FILE} in ${context.cwd} or above it.` + ) + } + const project: Project = { root, config: await loadProjectConfig(root) } + + const canAsk = context.interactive && !output.json && flags.yes !== true + let names = parsed._.map(String) + if (names.length === 0 && !canAsk) { + throw new DrxError( + 'usage', + `Give the name of a module, as in "${words.example}".` + ) + } + + const loaded = await openModules(context, flags, output) + const options: ChangeOptions = { + force: flags.force === true, + patches: flags.patches !== false, + backend: flags.backend === true, + // A registry that marks any module as core is taken to mark them all. + registryStatesCore: loaded.modules.some((module) => + module.backend.some((need) => need.core) + ), + registry: loaded.modules, + names: [], + } + + const picked = names.length === 0 + if (picked) { + const offered = await candidates( + action, + loaded.modules, + project, + options + ) + if (offered.length === 0) { + throw new DrxError( + 'usage', + `There is no module to ${action} in this project.` + ) + } + names = await context.prompter.pickMany({ + message: 'Which modules?', + choices: offered.map((module) => ({ + value: module.name, + label: module.name, + hint: `${module.npm ?? 'not published'}. ${module.description}`.trim(), + })), + }) + } + + const modules = names.map((wanted) => findModule(loaded.modules, wanted)) + options.names = modules.map((module) => module.name) + const plans: ModulePlan[] = [] + for (const module of modules) { + plans.push( + action === 'add' + ? await planAdd(module, project, options) + : await planRemove(module, project, options) + ) + } + + // Every refusal is found before any step is taken, so one module that + // cannot be changed leaves the others as they were too. + const refused = plans.flatMap((plan) => + plan.refusals + .filter((refusal) => !(options.force && refusal.forceable)) + .map( + (refusal) => + `Cannot ${action} ${plan.module.name}: ${refusal.reason}${refusal.forceable ? ` Pass --force to ${action} it all the same.` : ''}` + ) + ) + if (refused.length > 0) throw new DrxError('refused', refused.join('\n')) + + for (const plan of plans) { + for (const refusal of plan.refusals) output.warn(refusal.reason) + for (const warning of plan.warnings) output.warn(warning) + for (const note of plan.notes) output.line(note) + } + + const shown = plans.flatMap((plan, index) => [ + ...(index > 0 ? [''] : []), + ...planLines(plan), + ]) + const data = plans.map((plan) => ({ + name: plan.module.name, + package: plan.package, + steps: planData(plan), + leftToDo: plan.after, + })) + + if (dryRun) { + output.result( + { ok: true, dryRun: true, modules: data }, + [...shown, '', 'Nothing was changed: this was a dry run.'].join('\n') + ) + return + } + + if (picked) { + output.line() + for (const line of shown) output.line(line) + output.line() + const go = await context.prompter.confirm({ + message: 'Make these changes?', + initial: true, + }) + if (!go) { + throw new DrxError('cancelled', 'Cancelled. Nothing was changed.') + } + } + + await carryOut(plans, project, context, output) + + const left = plans.flatMap((plan) => plan.after) + output.result( + { ok: true, dryRun: false, modules: data }, + [ + ...plans.map((plan) => `${words.did} ${plan.module.name}.`), + ...(left.length > 0 + ? ['', 'Left to do:', ...left.map((line) => ` ${line}`)] + : []), + ].join('\n') + ) + + if (picked) { + output.line() + output.line( + `Repeat this with: ${repeatCommand([ + action, + ...options.names, + ...(options.force ? ['--force'] : []), + ...(options.patches ? [] : ['--no-patches']), + ...(options.backend ? ['--backend'] : []), + '--yes', + ])}` + ) + } + }, + }) +} + +export const addCommand = (context: CliContext, name = 'add') => + changeCommand(context, 'add', name) + +export const removeCommand = (context: CliContext, name = 'remove') => + changeCommand(context, 'remove', name) diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts new file mode 100644 index 0000000..7a2b082 --- /dev/null +++ b/packages/cli/src/commands/info.ts @@ -0,0 +1,151 @@ +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, type Output } 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, output: Output): string[] { + const heading = [ + // The role is in words and in its colour: blue backend, green frontend. + output.out.role(part.role, `${part.role} ${part.kind} ${part.path}/`), + ...columns( + [ + ...(part.engine ? [['Engine', part.engine]] : []), + ...(part.database ? [['Database', part.database]] : []), + ...(part.baseUrl ? [['Backend URL', part.baseUrl]] : []), + ], + ' ' + ), + ] + 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, output: Output): 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, output)) + } + 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) + output.header() + + 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, output)) + }, + }) +} diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts new file mode 100644 index 0000000..321bdf0 --- /dev/null +++ b/packages/cli/src/commands/init.ts @@ -0,0 +1,704 @@ +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 { + checkCommands, + describeAlternatives, + type CommandCheck, +} from '../commands-on-path.js' +import type { Choice, CliContext, Prompter } from '../context.js' +import { writeBackendUrl } from '../engines/backend-url.js' +import { + assertBaseUrl, + chooseEngine, + missingCommandsWarning, + stepLines, + type EngineChoice, +} from '../engines/choose.js' +import { removeEngineFiles } from '../engines/files.js' +import { DrxError } from '../errors.js' +import { + assertLayoutAvailable, + AVAILABLE_LAYOUTS, + isLayout, + LAYOUTS, + type Layout, +} from '../layouts.js' +import { columns, createOutput, type Output } from '../output.js' +import { writeProjectConfig, type ProjectConfig } from '../project.js' +import type { StarterEntry } from '../registry/entry.js' +import { repeatCommand } from '../repeat.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})`, + }, + engine: { + type: 'string', + valueHint: 'name', + description: + 'How the backend runs: an engine of the starter, or none for a backend that exists already', + }, + database: { + type: 'string', + valueHint: 'name', + description: 'The database, where the engine offers a choice', + }, + 'base-url': { + type: 'string', + valueHint: 'url', + description: 'With --engine none: the URL of the backend', + }, + 'keep-engines': { + type: 'boolean', + description: 'Keep the files of the engines that were not chosen', + }, + banner: { + type: 'boolean', + description: 'Draw the wordmark at the start of a guided run', + negativeDescription: 'Do not draw the wordmark', + }, + setup: { + type: 'boolean', + description: + 'Run the steps of the engine after creating the site (not available yet)', + }, + 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 + engine?: string + database?: string + baseUrl?: string + keepEngines: boolean + setup: boolean + /** False when --no-banner was given. */ + banner?: boolean + 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 +} + +/** One starter as a choice: its line, the Node it needs and what it is. */ +function starterChoice(entry: StarterEntry): Choice { + const { line, requires, description } = entry.druxt + const about = description ?? requires.tools.join('; ') + return { + value: entry.name, + label: entry.name, + hint: `${line}, Node ${requires.node}. ${about}`.trim(), + } +} + +/** The starter the flags name, or the default of the registry. */ +async function namedOrDefaultStarter( + registry: Registry, + options: InitOptions +): Promise { + if (options.starter) return registry.entry(options.starter) + const entry = await defaultStarter(registry) + if (!entry) { + const names = await registry.names() + throw new DrxError( + 'unknown-starter', + `The registry marks no starter as the default. Pass --starter with one of: ${names.join(', ')}.` + ) + } + return entry +} + +async function askStarter( + registry: Registry, + names: string[], + context: CliContext +): Promise { + const entries: StarterEntry[] = [] + for (const name of names) entries.push(await registry.entry(name)) + const initial = entries.find((entry) => entry.druxt.default)?.name + const chosen = await context.prompter.select({ + message: 'Which starter?', + choices: entries.map(starterChoice), + ...(initial ? { initial } : {}), + }) + return entries.find((entry) => entry.name === chosen) as StarterEntry +} + +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', disabled: true }), + })), + 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, + engine: EngineChoice | undefined, + target: string, + context: CliContext, + output: Output +): CommandCheck | null { + 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.` + ) + } + } + + if (engine) { + // The chosen engine's commands are the ones that matter. An engine with + // none, such as a backend that exists already, has nothing to check. + if (engine.commands.length === 0) return null + const check = checkCommands([engine.commands], context.findCommand) + if (!check.satisfied) { + output.warn( + missingCommandsWarning(engine.name, engine.commands, check.missing) + ) + } + return check + } + + if (!requires.commands) return null + const commands = checkCommands(requires.commands, context.findCommand) + if (!commands.satisfied) { + const advice = + commands.alternatives.length > 1 + ? 'Install the commands of one alternative' + : 'Install what is missing' + output.warn( + `The ${entry.name} starter needs ${describeAlternatives(commands.alternatives)}. Not found on PATH: ${commands.missing.join(', ')}. ${advice} before you set up the site.` + ) + } + return commands +} + +/** Everything `init` has settled before it writes anything. */ +interface Plan { + entry: StarterEntry + layout: Layout + engine: EngineChoice | undefined + dir: string + target: string + install: boolean +} + +/** What a guided run is about to do, for the user to confirm. */ +function summary(plan: Plan, options: InitOptions, output: Output): string[] { + const { entry, engine } = plan + const rows = [ + ['Create', plan.target], + [ + 'From', + `the ${entry.name} starter (${entry.druxt.line}), ${plan.layout} layout`, + ], + ] + if (engine) { + rows.push([ + 'Backend', + engine.baseUrl + ? `a backend that exists already, at ${engine.baseUrl}` + : `${engine.name} engine${engine.database ? `, ${engine.database} database` : ''}`, + ]) + if (engine.remove.length > 0) { + rows.push( + options.keepEngines + ? ['Keep', 'the files of every engine'] + : ['Remove', 'the files of the other engines'] + ) + } + const where = entry.druxt.backendUrl + if (engine.writeUrl && where) { + rows.push([ + 'Write', + `${where.variable}=${engine.writeUrl} to ${where.file}`, + ]) + } + } + rows.push(['Install', plan.install ? 'yes' : 'no']) + + return [ + 'This will:', + // The label of the backend row is in the colour of a backend part. + ...columns(rows, ' ').map((line) => + line.replace( + /^( +)(Backend)/, + (_, indent: string, label: string) => + `${indent}${output.err.role('backend', label)}` + ) + ), + ] +} + +/** The arguments that run the same `init` again with nothing to ask. */ +function repeatArguments(plan: Plan, options: InitOptions): string[] { + const { engine } = plan + return [ + 'init', + plan.dir, + '--starter', + plan.entry.name, + '--layout', + plan.layout, + ...(engine ? ['--engine', engine.name] : []), + ...(engine?.database ? ['--database', engine.database] : []), + ...(engine?.baseUrl ? ['--base-url', engine.baseUrl] : []), + ...(options.registry ? ['--registry', options.registry] : []), + ...(options.source ? ['--source', options.source] : []), + ...(options.keepEngines ? ['--keep-engines'] : []), + plan.install ? '--install' : '--no-install', + ...(options.force ? ['--force'] : []), + '--yes', + ] +} + +/** + * Settles every choice, asking for what the flags left out. Nothing is + * written here, so cancelling a prompt leaves the disk as it was. + */ +async function plan( + registry: Registry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + // With one starter, or one named, there is no starter to ask about and the + // directory prompt can offer that starter's own default. + const names = options.starter ? [] : await registry.names() + const askForStarter = canAsk && names.length > 1 + let entry = askForStarter + ? undefined + : await namedOrDefaultStarter(registry, options) + + const defaultDir = (entry ?? (await defaultStarter(registry)))?.defaultDir + const dir = + options.dir ?? + (canAsk + ? await context.prompter.text({ + message: 'Where should the site be created?', + initial: defaultDir ?? entry?.name ?? 'my-druxt-site', + }) + : (defaultDir ?? (entry as StarterEntry).name)) + const target = targetDirectory(context.cwd, dir, options.force) + + entry ??= await askStarter(registry, names, context) + const layout = await chooseLayout(entry, options, context, canAsk) + const engine = await chooseEngine(entry, options, context, canAsk) + const install = + options.install ?? + (canAsk + ? await context.prompter.confirm({ + message: 'Install its dependencies now?', + initial: false, + }) + : false) + + return { entry, layout, engine, dir, target, install } +} + +async function runInit( + options: InitOptions, + shared: CliContext, + output: Output +): Promise { + // --json never asks: a script reading stdout cannot answer. + const canAsk = shared.interactive && !options.yes && !output.json + 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.' + ) + } + if (options.setup) { + throw new DrxError( + 'not-available', + '--setup is not available yet. init prints the steps for you to run.' + ) + } + if (options.baseUrl) assertBaseUrl(options.baseUrl) + + // Everything that can fail without the network is checked before it is used. + const userConfig = await loadUserConfig(shared.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 + + // A run that will ask for the basics is a guided one, and opens with the + // wordmark. Any other run gets the small header. + const guided = + canAsk && (!options.dir || !options.layout || options.install === undefined) + const drawn = + guided && + output.banner({ + ...(options.banner === undefined ? {} : { flag: options.banner }), + ...(userConfig.banner === undefined + ? {} + : { configured: userConfig.banner }), + }) + if (!drawn) output.header() + + // The prompts are counted, so a run that asked for something can end by + // saying how to repeat it without being asked. + let asked = 0 + const counting = + (ask: (...args: T) => Promise) => + (...args: T) => { + asked += 1 + return ask(...args) + } + const context: CliContext = { + ...shared, + prompter: { + text: counting(shared.prompter.text), + select: counting(shared.prompter.select) as Prompter['select'], + search: counting(shared.prompter.search) as Prompter['search'], + pickMany: shared.prompter.pickMany, + confirm: counting(shared.prompter.confirm), + }, + } + + 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 if (output.decorated) { + output.done(`Read the starters from ${registry.location}.`) + } else { + output.note(`Reading starters from ${registry.location}.`) + } + + let settled: Plan + try { + settled = await plan(registry, options, context, canAsk) + if (asked > 0) { + output.line() + for (const line of summary(settled, options, output)) output.line(line) + output.line() + const go = await context.prompter.confirm({ + message: 'Create the site?', + initial: true, + }) + if (!go) throw new DrxError('cancelled', 'Cancelled.') + } + } catch (error) { + if (error instanceof DrxError && error.code === 'cancelled') { + throw new DrxError('cancelled', 'Cancelled. Nothing was written.') + } + throw error + } + const { entry, layout, engine, target, install } = settled + + 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}` + ) + } + output.done(`Fetched the ${entry.name} starter.`) + + let removed: string[] = [] + if (engine && !options.keepEngines) { + removed = await removeEngineFiles(target, engine.remove, engine.keep) + if (removed.length > 0) { + output.did( + `Removed the files of the engines not chosen: ${removed.join(', ')}.` + ) + } + } + if (engine?.writeUrl) { + const where = entry.druxt.backendUrl + if (where) { + await writeBackendUrl(target, where, engine.writeUrl) + output.did(`Wrote ${where.variable}=${engine.writeUrl} to ${where.file}.`) + } else if (engine.baseUrl) { + output.warn( + `The ${entry.name} starter does not say where it reads its backend URL from. Point it at ${engine.baseUrl} yourself.` + ) + } + } + + const config: ProjectConfig = { + layout, + line: entry.druxt.line, + starter: entry.name, + source: source.name, + // The choice is recorded on every backend part, for the commands that + // will run tools in it. + parts: entry.druxt.parts.map((part) => + engine && part.role === 'backend' + ? { + ...part, + engine: engine.name, + ...(engine.database ? { database: engine.database } : {}), + ...(engine.baseUrl ? { baseUrl: engine.baseUrl } : {}), + } + : part + ), + } + await writeProjectConfig(target, config) + const commands = warnAboutStarter(entry, engine, 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}` + ) + } + output.done('Installed dependencies.') + } + + const fromCwd = relative(context.cwd, target) + const inside = fromCwd !== '' && !fromCwd.startsWith('..') + const next = [ + `cd ${inside && !isAbsolute(fromCwd) ? fromCwd : target}`, + ...stepLines(engine ? engine.steps : (entry.druxt.steps ?? [])), + ] + const { requires } = entry.druxt + const needs = engine ? [engine.label] : requires.tools + const notes = engine?.notes ?? [] + + output.result( + { + ok: true, + directory: target, + registry: { origin: registry.origin, location: registry.location }, + ...config, + installed: install, + requires, + engine: engine?.name ?? null, + database: engine?.database ?? null, + baseUrl: engine?.baseUrl ?? null, + removed, + commands, + next, + notes, + }, + [ + `Created a Druxt site in ${target} from the ${entry.name} starter.`, + '', + 'It needs:', + ` Node ${requires.node}`, + ...needs.map((tool) => ` ${tool}`), + '', + 'Next:', + ...next.map((step) => ` ${step}`), + ...(notes.length > 0 + ? ['', 'Note:', ...notes.map((note) => ` ${note}`)] + : []), + ].join('\n') + ) + + if (asked > 0) { + output.line() + output.line( + `Repeat this with: ${repeatCommand(repeatArguments(settled, options))}` + ) + } +} + +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, + keepEngines: parsed['keep-engines'] === true, + setup: parsed.setup === true, + } + const engine = valueOf('engine', parsed.engine) + const database = valueOf('database', parsed.database) + const baseUrl = valueOf('base-url', parsed['base-url']) + if (engine) options.engine = engine + if (database) options.database = database + if (baseUrl) options.baseUrl = baseUrl + 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 + if (typeof parsed.banner === 'boolean') options.banner = parsed.banner + + await runInit( + options, + context, + createOutput(context, parsed.json === true) + ) + }, + }) +} diff --git a/packages/cli/src/commands/menu.ts b/packages/cli/src/commands/menu.ts new file mode 100644 index 0000000..1c1c505 --- /dev/null +++ b/packages/cli/src/commands/menu.ts @@ -0,0 +1,108 @@ +import type { Choice, CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { createOutput } from '../output.js' +import { findProjectRoot, loadProjectConfig } from '../project.js' +import { repeatCommand } from '../repeat.js' +import { loadUserConfig } from '../user-config.js' + +const NOT_YET = { hint: 'not available yet', disabled: true } + +const OUTSIDE: Choice[] = [ + { value: 'init', label: 'Create a site' }, + { value: 'quit', label: 'Quit' }, +] + +/** What can be done in a project. What is not built is shown, and says so. */ +const INSIDE: Choice[] = [ + { value: 'list', label: 'List the modules' }, + { value: 'search', label: 'Search the modules' }, + { value: 'show', label: 'Show a module' }, + { value: 'info', label: 'Show this project' }, + { value: 'add', label: 'Add a module' }, + { value: 'remove', label: 'Remove a module' }, + { value: 'configure', label: 'Configure a module', ...NOT_YET }, + { value: 'patches', label: 'Manage patches', ...NOT_YET }, + { value: 'quit', label: 'Quit' }, +] + +/** + * What bare `drx` shows a person at a terminal: the wordmark, the project + * they are in, and the actions that apply there. Each action is run as the + * command it stands for, through `run`, so the menu has no behaviour of its + * own to keep in step. + */ +export async function runMenu( + context: CliContext, + options: { banner: boolean }, + run: (argv: string[]) => Promise +): Promise { + const output = createOutput(context, false) + const userConfig = await loadUserConfig(context.env) + const drawn = output.banner({ + ...(options.banner ? {} : { flag: false }), + ...(userConfig.banner === undefined + ? {} + : { configured: userConfig.banner }), + }) + if (!drawn) output.header() + + const root = findProjectRoot(context.cwd) + if (root) { + const config = await loadProjectConfig(root) + output.line(`Project ${root}`) + output.line( + ` ${config.starter} starter, ${config.layout} layout, ${config.line}` + ) + for (const part of config.parts) { + const engine = part.engine ? ` ${part.engine} engine` : '' + output.line( + ` ${output.err.role(part.role, `${part.role} ${part.kind} ${part.path}/`)}${engine}` + ) + } + } else { + output.line(`No Druxt project in ${context.cwd}.`) + } + output.line() + + const choice = await context.prompter.select({ + message: 'What would you like to do?', + choices: root ? INSIDE : OUTSIDE, + }) + + /** Runs a command and then says how to run it without the menu. */ + const repeatable = async (argv: string[]) => { + const code = await run(argv) + if (code === 0) { + output.line() + output.line(`Repeat this with: ${repeatCommand(argv)}`) + } + return code + } + + switch (choice) { + case 'quit': + return 0 + // The wordmark is on the screen already. These two say how to repeat + // themselves, since only they know what was chosen along the way. + case 'init': + return run(['init', '--no-banner']) + case 'show': + return run(['module']) + case 'list': + return repeatable(['module', 'list']) + case 'info': + return repeatable(['info']) + case 'search': { + const text = await context.prompter.text({ message: 'Search for what?' }) + return repeatable(['module', 'search', text]) + } + // Each of these picks its modules and says how to repeat itself. + case 'add': + case 'remove': + return run([choice]) + case 'configure': + return run(['module', choice]) + default: + throw new DrxError('not-available', `"${choice}" is not available yet.`) + } +} diff --git a/packages/cli/src/commands/module.ts b/packages/cli/src/commands/module.ts new file mode 100644 index 0000000..49aa53c --- /dev/null +++ b/packages/cli/src/commands/module.ts @@ -0,0 +1,556 @@ +import { defineCommand, type ArgsDef, type CommandDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import type { ModuleEntry } from '../modules/entry.js' +import { + moduleProject, + type ModuleInPart, + type ModuleProject, +} from '../modules/project.js' +import { + describeAge, + loadModules, + type LoadedModules, +} from '../modules/registry.js' +import { columns, createOutput, type Output } from '../output.js' +import { repeatCommand } from '../repeat.js' +import { loadUserConfig, resolveModuleRegistryUrl } from '../user-config.js' + +export const registryArgs = { + 'module-registry': { + type: 'string', + valueHint: 'url', + description: + 'A module registry: a URL, or a name from the user configuration', + }, + refresh: { + type: 'boolean', + description: 'Read the registry again even when the cached copy is fresh', + }, + json: { + type: 'boolean', + description: 'Print the result as JSON on stdout', + }, +} satisfies ArgsDef + +const filterArgs = { + all: { + type: 'boolean', + description: 'Include archived modules', + }, + type: { + type: 'string', + valueHint: 'type', + description: 'Only modules of this type, such as official or contrib', + }, + category: { + type: 'string', + valueHint: 'category', + description: 'Only modules in this category', + }, +} satisfies ArgsDef + +type Parsed = Record + +/** A string option's value, or an error when it was given with none. */ +function valueOf(parsed: Parsed, name: string): string | undefined { + const value = parsed[name] + if (value === undefined) return undefined + if (typeof value !== 'string' || value.trim() === '') { + throw new DrxError('usage', `--${name} needs a value.`) + } + return value +} + +/** Loads the registry the flags name and says on stderr where it came from. */ +export async function openModules( + context: CliContext, + parsed: Parsed, + output: Output +): Promise { + const named = valueOf(parsed, 'module-registry') + const url = named + ? resolveModuleRegistryUrl(named, await loadUserConfig(context.env)) + : context.defaultModuleRegistry + + const loaded = await loadModules({ + url, + cacheDir: context.cacheDir, + now: context.now, + fetch: context.fetch, + refresh: parsed.refresh === true, + // The token goes to a registry the user named, never to the public one. + ...(named && context.env.GIGET_AUTH + ? { auth: context.env.GIGET_AUTH } + : {}), + }) + + const age = describeAge(loaded.ageMs) + if (loaded.reason) { + output.note(loaded.reason) + output.note(`Using the copy of the registry read ${age} ago.`) + } else if (loaded.origin === 'cache') { + output.note(`Modules from ${loaded.url}, read ${age} ago.`) + } else { + output.note(`Modules from ${loaded.url}.`) + } + return loaded +} + +/** Says on stderr which Druxt the modules are compared with. */ +function noteProject(project: ModuleProject, output: Output): void { + for (const part of project.parts) { + const druxt = part.druxt + const has = !druxt + ? 'has no druxt' + : druxt.installed + ? `has ${druxt.name} ${druxt.installed} installed` + : `asks for ${druxt.name} ${druxt.range} and has none installed` + output.note(`Project ${project.root}: ${part.path}/ ${has}.`) + } +} + +function registryReport(loaded: LoadedModules) { + const { url, origin, fetchedAt, ageMs, reason } = loaded + return { url, origin, fetchedAt, ageMs, ...(reason ? { reason } : {}) } +} + +function projectReport(project: ModuleProject | undefined) { + return project ? { root: project.root, parts: project.parts } : null +} + +function rowReport(module: ModuleEntry) { + return { + name: module.name, + npm: module.npm ?? null, + type: module.type, + status: module.status, + category: module.category, + archived: module.archived, + description: module.description, + druxt: module.druxt ?? null, + } +} + +const status = (module: ModuleEntry) => + module.archived ? `${module.status} (archived)` : module.status + +const YES_NO = { compatible: 'yes', incompatible: 'no', unknown: 'unknown' } + +/** One cell for all parts: the bare value for one part, labelled for more. */ +function acrossParts( + states: ModuleInPart[], + value: (state: ModuleInPart) => string +): string { + return states.length === 1 + ? value(states[0] as ModuleInPart) + : states.map((state) => `${state.path}: ${value(state)}`).join(', ') +} + +function installedCell(module: ModuleEntry, state: ModuleInPart): string { + if (!module.npm) return '-' + return state.installed ?? (state.declared ? 'declared' : 'no') +} + +/** Prints modules as a table, or as JSON, with their state in a project. */ +async function printModules( + modules: ModuleEntry[], + loaded: LoadedModules, + project: ModuleProject | undefined, + output: Output +): Promise { + const sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) + const states = new Map() + if (project) { + for (const module of sorted) states.set(module, await project.state(module)) + } + + const header = ['Name', 'Package', 'Type', 'Status', 'Druxt'] + if (project) header.push('Installed', 'Compatible') + const rows = sorted.map((module) => { + const row = [ + module.name, + module.npm ?? '-', + module.type, + status(module), + module.druxt ?? 'not stated', + ] + const inParts = states.get(module) + if (inParts) { + row.push( + acrossParts(inParts, (state) => installedCell(module, state)), + acrossParts(inParts, (state) => YES_NO[state.compatibility]) + ) + } + return row + }) + + output.result( + { + registry: registryReport(loaded), + project: projectReport(project), + modules: sorted.map((module) => ({ + ...rowReport(module), + ...(project ? { parts: states.get(module) } : {}), + })), + }, + rows.length === 0 + ? 'No modules match.' + : columns([header, ...rows]).join('\n') + ) +} + +/** Applies `--all`, `--type` and `--category`. */ +function filtered(modules: ModuleEntry[], parsed: Parsed): ModuleEntry[] { + const type = valueOf(parsed, 'type')?.toLowerCase() + const category = valueOf(parsed, 'category')?.toLowerCase() + return modules.filter( + (module) => + (parsed.all === true || !module.archived) && + (!type || module.type.toLowerCase() === type) && + (!category || module.category.toLowerCase() === category) + ) +} + +function listCommand(context: CliContext) { + const args = { ...filterArgs, ...registryArgs } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'list', + description: 'List the modules in the registry', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module list') + const output = createOutput(context, parsed.json === true) + output.header() + const loaded = await openModules(context, parsed, output) + const project = await moduleProject(context.cwd) + if (project) noteProject(project, output) + await printModules( + filtered(loaded.modules, parsed), + loaded, + project, + output + ) + }, + }) +} + +function searchCommand(context: CliContext) { + const args = { + text: { + type: 'positional', + required: false, + description: 'Text to find in a name, a package name or a description', + }, + ...filterArgs, + ...registryArgs, + } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'search', + description: 'Search the modules in the registry', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module search') + const text = String(parsed.text ?? '') + .trim() + .toLowerCase() + if (!text) { + throw new DrxError( + 'usage', + 'Give the text to search for, as in "drx module search menu".' + ) + } + const output = createOutput(context, parsed.json === true) + output.header() + const loaded = await openModules(context, parsed, output) + const project = await moduleProject(context.cwd) + if (project) noteProject(project, output) + const matches = filtered(loaded.modules, parsed).filter((module) => + [module.name, module.npm ?? '', module.description].some((field) => + field.toLowerCase().includes(text) + ) + ) + await printModules(matches, loaded, project, output) + }, + }) +} + +/** The number of single-character edits between two strings. */ +function editDistance(a: string, b: string): number { + let previous = Array.from({ length: b.length + 1 }, (_, index) => index) + for (let i = 1; i <= a.length; i++) { + const current = [i] + for (let j = 1; j <= b.length; j++) { + current[j] = Math.min( + (previous[j] ?? 0) + 1, + (current[j - 1] ?? 0) + 1, + (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1) + ) + } + previous = current + } + return previous[b.length] ?? 0 +} + +/** Up to three registry names near a name that matched nothing. */ +function closestNames(modules: ModuleEntry[], wanted: string): string[] { + const limit = Math.max(2, Math.floor(wanted.length / 3)) + return modules + .map((module) => ({ + name: module.name, + distance: Math.min( + ...[module.name, module.npm ?? module.name].map((candidate) => + candidate.toLowerCase().includes(wanted) + ? 0 + : editDistance(wanted, candidate.toLowerCase()) + ) + ), + })) + .filter(({ distance }) => distance <= limit) + .sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name)) + .slice(0, 3) + .map(({ name }) => name) +} + +export function findModule( + modules: ModuleEntry[], + wanted: string +): ModuleEntry { + const name = wanted.toLowerCase() + const found = modules.find( + (module) => + module.name.toLowerCase() === name || module.npm?.toLowerCase() === name + ) + if (found) return found + const closest = closestNames(modules, name) + throw new DrxError( + 'unknown-module', + closest.length > 0 + ? `There is no module named "${wanted}". Closest: ${closest.join(', ')}.` + : `There is no module named "${wanted}". Run "drx module list --all" to see every name.` + ) +} + +/** A link to the module's source. The registry names a GitHub repository. */ +function repositoryUrl(module: ModuleEntry): string { + const base = /^https?:\/\//.test(module.repo) + ? module.repo + : `https://github.com/${module.repo}` + return module.path ? `${base}/tree/HEAD/${module.path}` : base +} + +function infoText( + module: ModuleEntry, + project: ModuleProject | undefined, + states: ModuleInPart[], + output: Output +): string { + const lines = [module.name] + if (module.description) lines.push(module.description) + lines.push( + '', + ...columns( + [ + ['Package', module.npm ?? 'not published'], + ['Type', module.type], + ['Status', status(module)], + ['Category', module.category], + ['Druxt', module.druxt ?? 'not stated'], + ['Repository', repositoryUrl(module)], + ...(module.website ? [['Website', module.website]] : []), + ], + '' + ), + '' + ) + + if (module.backend.length === 0) { + lines.push('Backend modules it needs: none listed.') + } else { + lines.push( + 'Backend modules it needs:', + ...columns( + module.backend.map((needed) => [ + needed.kind, + needed.name, + needed.label, + [needed.core ? '(core)' : '', needed.url ?? ''].join(' ').trim(), + ]), + ' ' + ) + ) + } + + for (const [index, state] of states.entries()) { + const druxt = project?.parts[index]?.druxt + const asked = state.declared ? ` (asked for as ${state.declared})` : '' + lines.push( + '', + // Every part a module is installed in is a frontend part. + output.out.role('frontend', `In ${state.path}/:`), + ...columns( + [ + ['Installed', `${state.installed ?? 'no'}${asked}`], + [ + 'Druxt', + !druxt + ? 'none' + : druxt.installed + ? `${druxt.installed} installed` + : `${druxt.range} asked for, none installed`, + ], + ['Compatible', YES_NO[state.compatibility]], + ], + ' ' + ) + ) + } + return lines.join('\n') +} + +function infoCommand(context: CliContext) { + const args = { + name: { + type: 'positional', + required: false, + description: 'The name of a module, or of its package', + }, + ...registryArgs, + } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'info', + description: 'Show one module: its package, range, needs and links', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module info') + const wanted = String(parsed.name ?? '').trim() + if (!wanted) { + throw new DrxError( + 'usage', + 'Give the name of a module, as in "drx module info blocks".' + ) + } + const output = createOutput(context, parsed.json === true) + output.header() + const loaded = await openModules(context, parsed, output) + await showModule( + findModule(loaded.modules, wanted), + loaded, + context, + output + ) + }, + }) +} + +/** Prints one module in full, with its state in the project around `cwd`. */ +async function showModule( + module: ModuleEntry, + loaded: LoadedModules, + context: CliContext, + output: Output +): Promise { + const project = await moduleProject(context.cwd) + const states = project ? await project.state(module) : [] + output.result( + { + registry: registryReport(loaded), + project: projectReport(project), + module: { + ...rowReport(module), + repository: repositoryUrl(module), + ...(module.website ? { website: module.website } : {}), + backend: module.backend, + ...(project ? { parts: states } : {}), + }, + }, + infoText(module, project, states, output) + ) +} + +/** + * `drx module` with no command, in a terminal: a list of the modules to + * narrow by typing, then the one picked shown as `drx module info` shows it. + */ +async function pickModule( + context: CliContext, + parsed: Parsed, + output: Output +): Promise { + output.header() + const loaded = await openModules(context, parsed, output) + const listed = loaded.modules + .filter((module) => !module.archived) + .sort((a, b) => a.name.localeCompare(b.name)) + const name = await context.prompter.search({ + message: 'Which module?', + choices: listed.map((module) => ({ + value: module.name, + label: module.name, + hint: `${module.npm ?? 'not published'}. ${module.description}`.trim(), + })), + }) + await showModule(findModule(listed, name), loaded, context, output) + output.line() + output.line(`Repeat this with: ${repeatCommand(['module', 'info', name])}`) +} + +/** + * A command that changes a project. The name is taken now, so scripts and + * documentation can rely on it, and it fails until it is built. + */ +function notAvailable(name: string, description: string) { + return defineCommand({ + meta: { name, description: `${description} (not available yet)` }, + run() { + throw new DrxError( + 'not-available', + `drx module ${name} is not available yet. This version can list, search and show modules.` + ) + }, + }) +} + +/** + * The `module` group. The commands that change a project are handed in, as + * they are the top-level `add` and `remove` under a second name. + */ +export function moduleCommand( + context: CliContext, + changing: Record +) { + const subCommands = { + list: listCommand(context), + search: searchCommand(context), + info: infoCommand(context), + ...changing, + configure: notAvailable('configure', 'Set the options of a module'), + } + return defineCommand({ + meta: { + name: 'module', + description: 'List, search and show the modules in the Druxt registry', + }, + args: registryArgs, + subCommands, + // citty runs this after a subcommand as well as in place of one. + async run({ args: parsed, rawArgs }) { + if (rawArgs.some((argument) => argument in subCommands)) return + if (!context.interactive || parsed.json === true) { + throw new DrxError( + 'usage', + 'No command specified. Run "drx module --help" for the module commands.' + ) + } + assertKnownOptions(rawArgs, registryArgs, 'module') + await pickModule(context, parsed, createOutput(context, false)) + }, + }) +} diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts new file mode 100644 index 0000000..ef7253e --- /dev/null +++ b/packages/cli/src/context.ts @@ -0,0 +1,116 @@ +import { downloadTemplate } from 'giget' +import { findOnPath } from './commands-on-path.js' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { runTool, type RunTool } from './exec.js' +import { installDependencies } from './install.js' +import { DEFAULT_MODULE_REGISTRY } from './modules/registry.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 + /** The width of the terminal, when the stream is one. */ + columns?: number +} + +export interface Choice { + value: T + label: string + hint?: string + /** Shown, and not selectable. */ + disabled?: boolean +} + +/** 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 + /** A list the user narrows by typing, for more choices than fit a screen. */ + search(question: { + message: string + choices: Choice[] + }): Promise + /** A list to narrow by typing, of which any number can be picked. */ + pickMany(question: { + message: string + choices: Choice[] + }): 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 + /** The module registry used when `--module-registry` is not given. */ + defaultModuleRegistry: string + /** The directory the CLI keeps what it can fetch again in. */ + cacheDir: 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 + /** Runs a tool of the project, such as its package manager. */ + exec: RunTool + /** The file a command name resolves to on PATH, or undefined. */ + findCommand: (name: string) => string | undefined +} + +/** + * `DRX_CACHE_DIR`, or `drx` under the user's cache directory. + */ +export function cacheDirectory( + env: Record +): string { + if (env.DRX_CACHE_DIR) return env.DRX_CACHE_DIR + const base = env.XDG_CACHE_HOME ?? join(env.HOME ?? homedir(), '.cache') + return join(base, 'drx') +} + +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(), + defaultModuleRegistry: DEFAULT_MODULE_REGISTRY, + cacheDir: cacheDirectory(process.env), + download: downloadTemplate, + install: (dir) => installDependencies(dir), + exec: runTool, + findCommand: (name) => findOnPath(name), + } +} diff --git a/packages/cli/src/engines/backend-url.ts b/packages/cli/src/engines/backend-url.ts new file mode 100644 index 0000000..2072882 --- /dev/null +++ b/packages/cli/src/engines/backend-url.ts @@ -0,0 +1,37 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import type { BackendUrlTarget } from '../registry/entry.js' + +async function read(file: string): Promise { + try { + return await readFile(file, 'utf8') + } catch { + return undefined + } +} + +/** + * Writes the URL of the backend where the starter reads it: one variable in + * a file of `NAME=value` lines. The file is started from the starter's + * template when it does not exist, and every other line is left as it is. + */ +export async function writeBackendUrl( + root: string, + target: BackendUrlTarget, + url: string +): Promise { + const file = join(root, target.file) + const start = + (await read(file)) ?? + (target.template ? await read(join(root, target.template)) : undefined) ?? + '' + + const line = `${target.variable}=${url}` + const assignment = new RegExp(`^${target.variable}=.*$`, 'm') + const content = assignment.test(start) + ? start.replace(assignment, line) + : `${start}${start === '' || start.endsWith('\n') ? '' : '\n'}${line}\n` + + await mkdir(dirname(file), { recursive: true }) + await writeFile(file, content) +} diff --git a/packages/cli/src/engines/choose.ts b/packages/cli/src/engines/choose.ts new file mode 100644 index 0000000..45c9011 --- /dev/null +++ b/packages/cli/src/engines/choose.ts @@ -0,0 +1,258 @@ +import { checkCommands, describeAlternatives } from '../commands-on-path.js' +import type { Choice, CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + EXISTING_BACKEND, + type EngineStep, + type StarterEngine, + type StarterEntry, +} from '../registry/entry.js' +import { isHttpUrl } from '../validate.js' + +/** What the flags say about the engine. Each is undefined when not given. */ +export interface EngineOptions { + engine?: string + database?: string + baseUrl?: string +} + +/** The engine a site is created with, and what follows from the choice. */ +export interface EngineChoice { + name: string + /** What the site needs for this engine, as a phrase. */ + label: string + /** The commands the engine needs on PATH. */ + commands: string[] + database?: string + /** The URL of a backend that exists already. Recorded in the project. */ + baseUrl?: string + /** The URL to write where the starter reads its backend URL from. */ + writeUrl?: string + steps: EngineStep[] + notes: string[] + /** The paths the chosen engine needs. */ + keep: string[] + /** The paths of the engines that were not chosen. */ + remove: string[] +} + +/** Fails unless the value of `--base-url` is a URL a site can fetch from. */ +export function assertBaseUrl(value: string): void { + if (!isHttpUrl(value)) { + throw new DrxError( + 'usage', + `--base-url must be an http or https URL: "${value}".` + ) + } +} + +const missingFrom = (engine: StarterEngine, context: CliContext) => + checkCommands([engine.commands], context.findCommand).missing + +async function chooseName( + entry: StarterEntry, + engines: StarterEngine[], + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const names = [...engines.map(({ name }) => name), EXISTING_BACKEND] + if (options.engine) { + if (!names.includes(options.engine)) { + throw new DrxError( + 'usage', + `The ${entry.name} starter has no engine named "${options.engine}". It offers: ${names.join(', ')}.` + ) + } + return options.engine + } + + const missing = new Map( + engines.map((engine) => [engine.name, missingFrom(engine, context)]) + ) + const present = engines.filter(({ name }) => missing.get(name)?.length === 0) + const absent = engines.filter((engine) => !present.includes(engine)) + // The first engine that can run on this machine, or the starter's first. + const fallback = (present[0] ?? engines[0]) as StarterEngine + if (!canAsk) return fallback.name + + const choices: Choice[] = [ + ...present.map(({ name, label }) => ({ value: name, label })), + ...absent.map(({ name, label }) => ({ + value: name, + label, + hint: `not installed: ${missing.get(name)?.join(', ')}`, + })), + { + value: EXISTING_BACKEND, + label: 'None: use a backend that exists already', + }, + ] + return context.prompter.select({ + message: 'How should the backend run?', + choices, + initial: fallback.name, + }) +} + +async function chooseDatabase( + entry: StarterEntry, + engine: StarterEngine, + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const databases = engine.databases + const of = `The ${engine.name} engine of the ${entry.name} starter` + if (!databases) { + if (options.database) { + throw new DrxError('usage', `${of} offers no choice of database.`) + } + return undefined + } + if (options.database) { + if (!databases.includes(options.database)) { + throw new DrxError( + 'usage', + `${of} has no database named "${options.database}". It offers: ${databases.join(', ')}.` + ) + } + return options.database + } + if (canAsk && databases.length > 1) { + return context.prompter.select({ + message: 'Which database?', + choices: databases.map((name) => ({ value: name, label: name })), + initial: databases[0] as string, + }) + } + return databases[0] +} + +async function existingBackend( + entry: StarterEntry, + engines: StarterEngine[], + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + if (options.database) { + throw new DrxError( + 'usage', + `--database does not go with --engine ${EXISTING_BACKEND}. The backend has its database already.` + ) + } + let baseUrl = options.baseUrl + if (!baseUrl) { + if (!canAsk) { + throw new DrxError( + 'usage', + `--engine ${EXISTING_BACKEND} needs --base-url, the URL of the backend that exists already.` + ) + } + baseUrl = await context.prompter.text({ + message: 'What is the URL of the backend?', + }) + assertBaseUrl(baseUrl) + } + return { + name: EXISTING_BACKEND, + label: `A backend that exists already, at ${baseUrl}`, + commands: [], + baseUrl, + writeUrl: baseUrl, + steps: entry.druxt.steps ?? [], + notes: [], + keep: [], + remove: engines.flatMap((engine) => engine.files ?? []), + } +} + +/** + * Settles which engine the site is created with: the flag, the answer to a + * prompt, or the first engine of the starter whose commands are on PATH. + * + * Undefined for a starter that lists no engines when none was asked for. The + * engine for a backend that exists already is offered by every starter. + */ +export async function chooseEngine( + entry: StarterEntry, + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const engines = entry.druxt.engines ?? [] + if (engines.length === 0 && !options.engine) { + for (const [flag, value] of [ + ['--database', options.database], + ['--base-url', options.baseUrl], + ]) { + if (value) { + throw new DrxError( + 'usage', + `${flag} goes with --engine, and the ${entry.name} starter lists no engines. Only --engine ${EXISTING_BACKEND} can be used with it.` + ) + } + } + return undefined + } + + const name = await chooseName(entry, engines, options, context, canAsk) + if (name === EXISTING_BACKEND) { + return existingBackend(entry, engines, options, context, canAsk) + } + + const engine = engines.find((candidate) => candidate.name === name) + if (!engine) throw new Error(`No engine named ${name}.`) + if (options.baseUrl) { + throw new DrxError( + 'usage', + `--base-url goes with --engine ${EXISTING_BACKEND}. The ${name} engine serves the backend itself.` + ) + } + const database = await chooseDatabase(entry, engine, options, context, canAsk) + return { + name, + label: engine.label, + commands: engine.commands, + ...(database ? { database } : {}), + ...(engine.baseUrl ? { writeUrl: engine.baseUrl } : {}), + steps: engine.steps, + notes: engine.notes ?? [], + keep: engine.files ?? [], + remove: engines + .filter((other) => other !== engine) + .flatMap((other) => other.files ?? []), + } +} + +/** + * The steps as lines to type, starting in the site's root: a `cd` wherever + * the directory changes, and one back to the root when a step returns there. + */ +export function stepLines(steps: EngineStep[]): string[] { + const lines: string[] = [] + let here = '' + for (const step of steps) { + const dir = typeof step === 'string' ? '' : step.dir.replace(/\/+$/, '') + if (dir !== here) { + const back = here + .split('/') + .filter(Boolean) + .map(() => '..') + lines.push(`cd ${[...back, dir].filter(Boolean).join('/')}`) + here = dir + } + lines.push(typeof step === 'string' ? step : step.run) + } + return lines +} + +/** The warning for an engine whose commands are not all on PATH. */ +export function missingCommandsWarning( + name: string, + commands: string[], + missing: string[] +): string { + return `The ${name} engine needs ${describeAlternatives([commands])}. Not found on PATH: ${missing.join(', ')}. Install what is missing before you set up the site.` +} diff --git a/packages/cli/src/engines/ddev.ts b/packages/cli/src/engines/ddev.ts new file mode 100644 index 0000000..2edad36 --- /dev/null +++ b/packages/cli/src/engines/ddev.ts @@ -0,0 +1,4 @@ +import { wrappingEngine } from './engine.js' + +/** DDEV runs a tool in its web container: `ddev composer`, `ddev drush`. */ +export const ddevEngine = wrappingEngine('ddev') diff --git a/packages/cli/src/engines/engine.ts b/packages/cli/src/engines/engine.ts new file mode 100644 index 0000000..fb1ba13 --- /dev/null +++ b/packages/cli/src/engines/engine.ts @@ -0,0 +1,42 @@ +import type { Part } from '../parts.js' + +/** A command line, and the directory to run it in, from the project root. */ +export interface EngineCommand { + command: string + args: string[] + cwd: string +} + +/** + * How the tools of a backend part are run when the part is run a certain + * way. A command that changes the backend asks the part's engine for the + * command line, and never names an engine itself. A new engine is a new file + * in this directory and a line in index.ts. + */ +export interface EngineAdapter { + /** The value a part's `engine` holds. */ + readonly name: string + /** False when the backend is somewhere this machine cannot run tools in. */ + readonly local: boolean + /** + * The command line that runs a backend tool, such as its package manager, + * with the given arguments. + */ + run(part: Part, command: string, args: string[]): EngineCommand +} + +/** + * An engine that runs every tool as an argument of its own command, in the + * part's directory, as container tools do. + */ +export function wrappingEngine(name: string): EngineAdapter { + return { + name, + local: true, + run: (part, command, args) => ({ + command: name, + args: [command, ...args], + cwd: part.path, + }), + } +} diff --git a/packages/cli/src/engines/files.ts b/packages/cli/src/engines/files.ts new file mode 100644 index 0000000..b5c973f --- /dev/null +++ b/packages/cli/src/engines/files.ts @@ -0,0 +1,74 @@ +import { existsSync, lstatSync, realpathSync } from 'node:fs' +import { readdir, rm } from 'node:fs/promises' +import { dirname, join, sep } from 'node:path' +import { DrxError } from '../errors.js' +import { isInsidePath } from '../validate.js' + +/** A relative path with forward slashes and no `.` segments. */ +function normalise(path: string): string { + return path + .split(/[\\/]/) + .filter((segment) => segment !== '' && segment !== '.') + .join('/') +} + +/** + * Fails unless the path names something inside the site, by its spelling + * and by where the directory holding it is on disk. The second check is for + * a link in the starter that points out of the site. + */ +function assertInsideSite(root: string, path: string): void { + const refuse = () => + new DrxError( + 'invalid-entry', + `Refusing to remove ${path}: it is not inside the site.` + ) + if (!isInsidePath(path)) throw refuse() + + const realRoot = realpathSync(root) + let holder = dirname(join(root, normalise(path))) + while (!existsSync(holder)) holder = dirname(holder) + const realHolder = realpathSync(holder) + if (realHolder !== realRoot && !realHolder.startsWith(realRoot + sep)) { + throw refuse() + } +} + +/** + * Removes the paths of the engines that were not chosen, and returns what it + * removed. A path in `keep`, or inside one, stays. A directory that holds a + * kept path loses everything else in it. + * + * Every path is checked before anything is removed, so a bad one removes + * nothing. A link is removed as a link, never followed. + */ +export async function removeEngineFiles( + root: string, + remove: string[], + keep: string[] +): Promise { + for (const path of remove) assertInsideSite(root, path) + + const kept = keep.map(normalise) + const isKept = (path: string) => + kept.some((other) => path === other || path.startsWith(`${other}/`)) + const holdsKept = (path: string) => + kept.some((other) => other.startsWith(`${path}/`)) + + const removed: string[] = [] + const visit = async (path: string): Promise => { + const file = join(root, path) + const stat = lstatSync(file, { throwIfNoEntry: false }) + if (!stat || isKept(path)) return + if (holdsKept(path) && stat.isDirectory()) { + for (const child of (await readdir(file)).sort()) { + await visit(`${path}/${child}`) + } + return + } + await rm(file, { recursive: true, force: true }) + removed.push(path) + } + for (const path of remove) await visit(normalise(path)) + return removed +} diff --git a/packages/cli/src/engines/index.ts b/packages/cli/src/engines/index.ts new file mode 100644 index 0000000..0a6ac35 --- /dev/null +++ b/packages/cli/src/engines/index.ts @@ -0,0 +1,23 @@ +import { ddevEngine } from './ddev.js' +import type { EngineAdapter } from './engine.js' +import { landoEngine } from './lando.js' +import { noEngine } from './none.js' +import { phpEngine } from './php.js' + +export type { EngineAdapter, EngineCommand } from './engine.js' + +/** Every engine this version can run tools through. */ +const ENGINES: readonly EngineAdapter[] = [ + phpEngine, + ddevEngine, + landoEngine, + noEngine, +] + +export function engineFor(name: string): EngineAdapter | undefined { + return ENGINES.find((engine) => engine.name === name) +} + +export function knownEngines(): string[] { + return ENGINES.map((engine) => engine.name) +} diff --git a/packages/cli/src/engines/lando.ts b/packages/cli/src/engines/lando.ts new file mode 100644 index 0000000..560a1a9 --- /dev/null +++ b/packages/cli/src/engines/lando.ts @@ -0,0 +1,4 @@ +import { wrappingEngine } from './engine.js' + +/** Lando runs a tool through its tooling: `lando composer`, `lando drush`. */ +export const landoEngine = wrappingEngine('lando') diff --git a/packages/cli/src/engines/none.ts b/packages/cli/src/engines/none.ts new file mode 100644 index 0000000..07a6d8e --- /dev/null +++ b/packages/cli/src/engines/none.ts @@ -0,0 +1,15 @@ +import { DrxError } from '../errors.js' +import { EXISTING_BACKEND } from '../registry/entry.js' +import type { EngineAdapter } from './engine.js' + +/** A backend that runs somewhere else. Nothing can be run in it from here. */ +export const noEngine: EngineAdapter = { + name: EXISTING_BACKEND, + local: false, + run(_part, command, args) { + throw new DrxError( + 'not-available', + `The backend of this project is not on this machine, so ${command} cannot be run from here. Run "${[command, ...args].join(' ')}" where the backend is.` + ) + }, +} diff --git a/packages/cli/src/engines/php.ts b/packages/cli/src/engines/php.ts new file mode 100644 index 0000000..ca368de --- /dev/null +++ b/packages/cli/src/engines/php.ts @@ -0,0 +1,16 @@ +import type { EngineAdapter } from './engine.js' + +/** + * PHP on the machine itself. Composer is on PATH. Every other tool is one + * Composer installed for the project, so it is run from Composer's bin + * directory and needs no global install. + */ +export const phpEngine: EngineAdapter = { + name: 'php', + local: true, + run: (part, command, args) => ({ + command: command === 'composer' ? command : `vendor/bin/${command}`, + args, + cwd: part.path, + }), +} diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..6b03c40 --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,30 @@ +/** What went wrong, for a caller reading `--json` output. */ +export type DrxErrorCode = + | 'usage' + | 'not-available' + | 'registry' + | 'invalid-entry' + | 'unknown-starter' + | 'unknown-source' + | 'unknown-module' + | 'directory-not-empty' + | 'config' + | 'download' + | 'install' + | 'refused' + | 'step-failed' + | '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/exec.ts b/packages/cli/src/exec.ts new file mode 100644 index 0000000..d6bc858 --- /dev/null +++ b/packages/cli/src/exec.ts @@ -0,0 +1,37 @@ +import { spawn } from 'node:child_process' + +export interface ToolResult { + code: number + /** What the tool printed, stdout and stderr together in order. */ + output: string +} + +/** Runs a tool and waits for it, keeping its output to show if it fails. */ +export type RunTool = ( + command: string, + args: string[], + options: { cwd: string } +) => Promise + +/** + * Runs a command with no shell. A tool that cannot be started is a failure + * like any other, with the reason as its output. + */ +export const runTool: RunTool = (command, args, { cwd }) => + new Promise((resolve) => { + let output = '' + const child = spawn(command, args, { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + shell: process.platform === 'win32', + }) + child.stdout.on('data', (chunk: Buffer) => (output += chunk.toString())) + child.stderr.on('data', (chunk: Buffer) => (output += chunk.toString())) + child.on('error', (error) => + resolve({ + code: 127, + output: `${command} could not be started: ${error.message}`, + }) + ) + child.on('close', (code) => resolve({ code: code ?? 1, output })) + }) diff --git a/packages/cli/src/fetch-json.ts b/packages/cli/src/fetch-json.ts new file mode 100644 index 0000000..70aa6ca --- /dev/null +++ b/packages/cli/src/fetch-json.ts @@ -0,0 +1,39 @@ +import { DrxError } from './errors.js' + +const TIMEOUT_MS = 10_000 + +/** + * Fetches a URL and parses it as JSON. Every way it can fail is one error + * that starts "Could not read ", so a caller can fall back on it. + */ +export async function fetchJson( + url: string, + fetcher: typeof fetch = fetch, + auth?: string +): Promise { + let response: Response + try { + response = await fetcher(url, { + headers: auth ? { authorization: `Bearer ${auth}` } : {}, + signal: AbortSignal.timeout(TIMEOUT_MS), + }) + } catch (error) { + const cause = error instanceof Error ? (error.cause ?? error) : error + const detail = cause instanceof Error ? cause.message : String(cause) + throw new DrxError('registry', `Could not read ${url}: ${detail}.`) + } + if (!response.ok) { + throw new DrxError( + 'registry', + `Could not read ${url}: ${response.status} ${response.statusText}.` + ) + } + try { + return JSON.parse(await response.text()) as unknown + } catch { + throw new DrxError( + 'registry', + `Could not read ${url}: it is not valid JSON.` + ) + } +} 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/modules/change.ts b/packages/cli/src/modules/change.ts new file mode 100644 index 0000000..d5d672a --- /dev/null +++ b/packages/cli/src/modules/change.ts @@ -0,0 +1,475 @@ +import { existsSync } from 'node:fs' +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { adapterFor, type KindAdapter } from '../adapters/index.js' +import type { BackendRecord, ModuleChange } from '../adapters/adapter.js' +import type { CliContext } from '../context.js' +import { engineFor } from '../engines/index.js' +import { DrxError } from '../errors.js' +import type { Output } from '../output.js' +import type { Part } from '../parts.js' +import { + writeProjectConfig, + type ModuleRecord, + type ProjectConfig, +} from '../project.js' +import { compatibility } from './compatibility.js' +import type { ModuleEntry } from './entry.js' + +/** One thing to do to the project, as it will be shown and done. */ +export type PlannedStep = + | { + type: 'run' + command: string + args: string[] + cwd: string + display: string + } + | { type: 'edit'; file: string; content: string; display: string } + +/** The steps for one part, or what to do where a backend that is elsewhere is. */ +export interface PartPlan { + path: string + steps: PlannedStep[] + /** Why the steps cannot be taken from here, and the lines to run instead. */ + elsewhere?: { reason: string; lines: string[] } + record?: BackendRecord +} + +/** Why a module cannot be changed. `--force` goes past a forceable one. */ +interface Refusal { + reason: string + forceable: boolean +} + +export interface ModulePlan { + action: 'add' | 'remove' + module: ModuleEntry + package: string + parts: PartPlan[] + refusals: Refusal[] + warnings: string[] + notes: string[] + /** What is left for the user once the steps are done. */ + after: string[] + /** The record to keep, or to drop when it is undefined on a removal. */ + record?: ModuleRecord +} + +export interface Project { + root: string + config: ProjectConfig +} + +export interface ChangeOptions { + force: boolean + patches: boolean + backend: boolean + registryStatesCore: boolean + /** Every module of the registry, to see what else needs a backend module. */ + registry: ModuleEntry[] + /** The names being changed in this run. */ + names: string[] +} + +interface Located { + part: Part + dir: string + adapter: KindAdapter +} + +/** The parts of one role that exist and have an adapter. */ +function located(project: Project, role: Part['role']): Located[] { + return project.config.parts.flatMap((part) => { + const adapter = adapterFor(part.kind) + const dir = join(project.root, part.path) + return part.role === role && adapter && existsSync(dir) + ? [{ part, dir, adapter }] + : [] + }) +} + +const pluralPatches = (count: number) => + `${count} patch${count === 1 ? '' : 'es'}` + +/** The steps of a frontend part, which are run in it as they are. */ +function frontendPlan(at: Located, change: ModuleChange): PartPlan { + return { + path: at.part.path, + steps: change.steps.map((step): PlannedStep => + 'run' in step + ? { + type: 'run', + command: step.run.tool, + args: step.run.args, + cwd: at.dir, + display: [step.run.tool, ...step.run.args].join(' '), + } + : { + type: 'edit', + file: join(at.dir, step.edit.file), + content: step.edit.content, + display: step.edit.summary, + } + ), + } +} + +/** + * The steps of a backend part, with each tool turned into the command line + * of the part's engine. A backend that is not run from this machine gets no + * steps: the lines are kept to print, for whoever is where it runs. + */ +function backendPlan( + project: Project, + at: Located, + change: ModuleChange +): PartPlan { + const { part } = at + const engine = part.engine ? engineFor(part.engine) : undefined + + if (!engine?.local) { + const lines = [ + ...(change.record?.patches ?? []).map( + (patch) => + `Patch ${patch.package} with ${patch.url} (${patch.description})` + ), + ...change.steps.flatMap((step) => + 'run' in step ? [[step.run.tool, ...step.run.args].join(' ')] : [] + ), + ] + return { + path: part.path, + steps: [], + ...(lines.length > 0 + ? { + elsewhere: { + reason: engine + ? 'The backend of this project is not on this machine. Where it is:' + : `This project does not record how ${part.path}/ is run. In it:`, + lines, + }, + } + : {}), + } + } + + return { + path: part.path, + steps: change.steps.map((step): PlannedStep => { + if ('edit' in step) { + return { + type: 'edit', + file: join(at.dir, step.edit.file), + content: step.edit.content, + display: step.edit.summary, + } + } + const line = engine.run(part, step.run.tool, step.run.args) + return { + type: 'run', + command: line.command, + args: line.args, + cwd: join(project.root, line.cwd), + display: [line.command, ...line.args].join(' '), + } + }), + ...(change.record ? { record: change.record } : {}), + } +} + +/** Folds what an adapter found into the plan of the module. */ +function absorb(plan: ModulePlan, change: ModuleChange): void { + plan.refusals.push( + ...change.problems.map((reason) => ({ reason, forceable: false })) + ) + plan.warnings.push(...change.warnings) + plan.notes.push(...change.notes) + plan.after.push(...change.manual, ...change.after) +} + +function elsewhereLines(part: PartPlan): string[] { + return part.elsewhere + ? [ + part.elsewhere.reason, + ...part.elsewhere.lines.map((line) => ` ${line}`), + ] + : [] +} + +/** Everything adding one module to the project takes. Nothing is done here. */ +export async function planAdd( + module: ModuleEntry, + project: Project, + options: ChangeOptions +): Promise { + const plan: ModulePlan = { + action: 'add', + module, + package: module.npm ?? '', + parts: [], + refusals: [], + warnings: [], + notes: [], + after: [], + } + if (module.archived) { + plan.refusals.push({ + reason: `${module.name} is archived.`, + forceable: true, + }) + } + if (!module.npm) { + plan.refusals.push({ + reason: `${module.name} has no package to install: it is not released.`, + forceable: false, + }) + return plan + } + + for (const at of located(project, 'frontend')) { + const druxt = await at.adapter.druxt(at.dir) + const fit = compatibility(module.druxt, druxt) + if (fit === 'incompatible' && druxt) { + const has = druxt.installed ?? `asked for as ${druxt.range}` + plan.refusals.push({ + reason: `${module.name} works with ${druxt.name} ${module.druxt}, and ${at.part.path}/ has ${druxt.name} ${has}.`, + forceable: true, + }) + } else if (fit === 'unknown' && druxt) { + plan.warnings.push( + `${module.name} does not say which ${druxt.name} it works with, so it may not work with the one in ${at.part.path}/.` + ) + } + const change = await at.adapter.addModule(at.dir, { + package: module.npm, + needs: [], + patches: options.patches, + registryStatesCore: options.registryStatesCore, + }) + absorb(plan, change) + plan.parts.push(frontendPlan(at, change)) + } + + const record: ModuleRecord = { + name: module.name, + package: module.npm, + backend: [], + } + for (const at of located(project, 'backend')) { + const needs = module.backend.filter((need) => need.kind === at.part.kind) + if (needs.length === 0) continue + const change = await at.adapter.addModule(at.dir, { + needs, + patches: options.patches, + registryStatesCore: options.registryStatesCore, + }) + const part = backendPlan(project, at, change) + // What is left by hand: first the commands for a backend that is + // elsewhere, then the setup the module needs wherever it runs. + plan.after.push(...elsewhereLines(part)) + absorb(plan, change) + plan.parts.push(part) + const done = part.record + if (done && done.modules.length + done.patches.length > 0) { + record.backend.push({ path: at.part.path, ...done }) + } + } + plan.record = record + return plan +} + +/** True when the project has the package of a module in a frontend part. */ +async function hasPackage(project: Project, name: string): Promise { + for (const at of located(project, 'frontend')) { + if (await at.adapter.package(at.dir, name)) return true + } + return false +} + +/** Everything taking one module out of the project takes. */ +export async function planRemove( + module: ModuleEntry, + project: Project, + options: ChangeOptions +): Promise { + const plan: ModulePlan = { + action: 'remove', + module, + package: module.npm ?? '', + parts: [], + refusals: [], + warnings: [], + notes: [], + after: [], + } + const recorded = project.config.modules?.find( + (entry) => entry.name === module.name + ) + const present = module.npm ? await hasPackage(project, module.npm) : false + if (!present && !recorded) { + plan.refusals.push({ + reason: `${module.npm ?? module.name} is not in this project.`, + forceable: false, + }) + return plan + } + + for (const at of located(project, 'frontend')) { + const change = await at.adapter.removeModule(at.dir, { + ...(module.npm ? { package: module.npm } : {}), + stillNeeded: [], + }) + absorb(plan, change) + plan.parts.push(frontendPlan(at, change)) + } + + const backend = recorded?.backend ?? [] + if (backend.length === 0) return plan + if (!options.backend) { + for (const entry of backend) { + const put = [ + ...entry.modules.map(({ name }) => name), + ...(entry.patches.length > 0 + ? [pluralPatches(entry.patches.length)] + : []), + ] + plan.after.push( + `The backend was left as it is. drx remove ${module.name} --backend takes out what drx add put in ${entry.path}/: ${put.join(', ')}.` + ) + } + // The record stays, so the backend can still be undone. + if (recorded) plan.record = recorded + return plan + } + + // A backend module stays while any other module in the project needs it. + const stillNeeded = new Set() + for (const other of options.registry) { + if (options.names.includes(other.name) || !other.npm) continue + const kept = + (await hasPackage(project, other.npm)) || + project.config.modules?.some((entry) => entry.name === other.name) + if (kept) for (const need of other.backend) stillNeeded.add(need.name) + } + for (const at of located(project, 'backend')) { + const entry = backend.find(({ path }) => path === at.part.path) + if (!entry) continue + const change = await at.adapter.removeModule(at.dir, { + record: { modules: entry.modules, patches: entry.patches }, + stillNeeded: [...stillNeeded], + }) + const part = backendPlan(project, at, change) + plan.after.push(...elsewhereLines(part)) + absorb(plan, change) + plan.parts.push(part) + } + return plan +} + +/** A plan as the lines a person reads before it is carried out. */ +export function planLines(plan: ModulePlan): string[] { + const verb = plan.action === 'add' ? 'Add' : 'Remove' + const lines = [`${verb} ${plan.module.name} (${plan.package})`] + for (const part of plan.parts) { + if (part.steps.length === 0 && !part.elsewhere) continue + lines.push(` ${part.path}/`) + for (const step of part.steps) { + lines.push( + ` ${step.type === 'run' ? 'run ' : 'edit'} ${step.display}` + ) + } + lines.push(...elsewhereLines(part).map((line) => ` ${line}`)) + } + return lines +} + +/** A plan's steps as data, for `--json`. */ +export function planData(plan: ModulePlan) { + return plan.parts.flatMap((part) => [ + ...part.steps.map((step) => + step.type === 'run' + ? { part: part.path, run: step.display } + : { part: part.path, edit: step.display } + ), + ...(part.elsewhere + ? [{ part: part.path, elsewhere: part.elsewhere.lines }] + : []), + ]) +} + +/** + * Carries out the plans in order and keeps the project's record in step. + * The first tool that fails stops everything: its output is shown, with what + * had been done by then and what had not. + */ +export async function carryOut( + plans: ModulePlan[], + project: Project, + context: CliContext, + output: Output +): Promise { + const all = plans.flatMap((plan) => + plan.parts.flatMap((part) => + part.steps.map((step) => ({ + step, + label: `${part.path}/: ${step.display}`, + path: part.path, + })) + ) + ) + let done = 0 + let config = project.config + + for (const plan of plans) { + for (const part of plan.parts) { + for (const step of part.steps) { + if (step.type === 'edit') { + await mkdir(dirname(step.file), { recursive: true }) + await writeFile(step.file, step.content) + output.did(`${part.path}/: ${step.display}`) + } else { + output.note(`${part.path}/: ${step.display}`) + const result = await context.exec(step.command, step.args, { + cwd: step.cwd, + }) + if (result.code !== 0) { + const list = (title: string, labels: string[]) => + labels.length > 0 + ? [title, ...labels.map((label) => ` ${label}`)] + : [] + throw new DrxError( + 'step-failed', + [ + `${step.display} failed in ${part.path}/ with exit code ${result.code}.`, + result.output.trimEnd(), + ...list( + 'Done:', + all.slice(0, done).map(({ label }) => label) + ), + ...list( + 'Not done:', + all.slice(done).map(({ label }) => label) + ), + ] + .filter((line) => line !== '') + .join('\n') + ) + } + } + done += 1 + } + } + + // The record is written once the module is wholly done, so a remove + // never undoes something an add did not finish. + const others = (config.modules ?? []).filter( + (entry) => entry.name !== plan.module.name + ) + const modules = plan.record ? [...others, plan.record] : others + const rest: ProjectConfig = { ...config } + delete rest.modules + config = modules.length > 0 ? { ...rest, modules } : rest + await writeProjectConfig(project.root, config) + } +} diff --git a/packages/cli/src/modules/compatibility.ts b/packages/cli/src/modules/compatibility.ts new file mode 100644 index 0000000..3464cfa --- /dev/null +++ b/packages/cli/src/modules/compatibility.ts @@ -0,0 +1,39 @@ +import semver from 'semver' +import type { PackageVersion } from '../adapters/index.js' + +/** + * Whether a module works with the Druxt of a part. `unknown` covers a module + * that states no range, and a part with no Druxt version to compare. It is + * never read as compatible. + */ +export type Compatibility = 'compatible' | 'incompatible' | 'unknown' + +/** + * Compares the range a module states with the Druxt a part's adapter + * reports: the installed version when there is one, and the range the part + * asks for when nothing is installed yet. + */ +export function compatibility( + moduleRange: string | undefined, + druxt: PackageVersion | undefined +): Compatibility { + if (!moduleRange || moduleRange === 'unknown') return 'unknown' + if (!druxt || semver.validRange(moduleRange) === null) return 'unknown' + + if (druxt.installed !== null) { + if (semver.valid(druxt.installed) === null) return 'unknown' + // A prerelease of a version inside the range counts as inside it. + return semver.satisfies(druxt.installed, moduleRange, { + includePrerelease: true, + }) + ? 'compatible' + : 'incompatible' + } + + if (druxt.range === null || semver.validRange(druxt.range) === null) { + return 'unknown' + } + return semver.intersects(druxt.range, moduleRange) + ? 'compatible' + : 'incompatible' +} diff --git a/packages/cli/src/modules/entry.ts b/packages/cli/src/modules/entry.ts new file mode 100644 index 0000000..1fe91bd --- /dev/null +++ b/packages/cli/src/modules/entry.ts @@ -0,0 +1,257 @@ +import { kindsWithRole } from '../adapters/index.js' +import { DrxError } from '../errors.js' +import { isHttpUrl, isNonEmptyString, isRecord } from '../validate.js' + +/** The registry format this version reads. */ +export const MODULE_SCHEMA_VERSION = 1 + +/** A backend module a Druxt module needs, and the kind of backend it is for. */ +export interface BackendModule { + kind: string + /** The machine name of the module. */ + name: string + label: string + /** True when the registry says the backend ships the module itself. */ + core: boolean + url?: string + /** The package that provides the module, where its name does not say. */ + composer?: { package: string; constraint?: string } + /** What is left to do by hand once the module is enabled. */ + setup?: SetupStep[] + /** Patches the module needs until a fix is released. */ + patches?: ModulePatch[] +} + +export interface SetupStep { + title: string + command?: string + url?: string +} + +export interface ModulePatch { + description: string + url: string + /** The package the patch applies to, when it is not the module's own. */ + package?: string + issue?: string + /** The version of the patched package that holds the fix. */ + until?: string +} + +/** + * One module of the registry, with the fields the CLI uses. The registry + * holds more, and is free to add to them. + */ +export interface ModuleEntry { + name: string + /** The package to install. A module that is not released has none. */ + npm?: string + repo: string + /** Where the module is inside its repository. */ + path?: string + category: string + status: string + type: string + archived: boolean + description: string + website?: string + /** + * The Druxt versions the module works with, as the registry states it: a + * semver range, the word `unknown`, or undefined when it says nothing. + */ + druxt?: string + backend: BackendModule[] +} + +type Raw = Record + +class Invalid extends Error {} + +function requiredString(raw: Raw, key: string, at: string): string { + if (!isNonEmptyString(raw[key])) { + throw new Invalid(`${at}.${key} must be a non-empty string`) + } + return raw[key] +} + +function optionalString(raw: Raw, key: string, at: string): string | undefined { + const value = raw[key] + if (value !== undefined && typeof value !== 'string') { + throw new Invalid(`${at}.${key} must be a string`) + } + return value +} + +function optionalBoolean(raw: Raw, key: string, at: string): boolean { + const value = raw[key] + if (value !== undefined && typeof value !== 'boolean') { + throw new Invalid(`${at}.${key} must be true or false`) + } + return value ?? false +} + +/** A value with its undefined keys left out. */ +function compact(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, inner]) => inner !== undefined) + ) as T +} + +function listOf( + raw: Raw, + key: string, + at: string +): [Raw, string][] | undefined { + const list = raw[key] + if (list === undefined) return undefined + if (!Array.isArray(list)) throw new Invalid(`${at}.${key} must be an array`) + return list.map((item, index) => { + const here = `${at}.${key}[${index}]` + if (!isRecord(item)) throw new Invalid(`${here} must be an object`) + return [item, here] + }) +} + +/** The optional fields that say how a backend module is added. */ +function additions(item: Raw, at: string) { + let composer: BackendModule['composer'] + if (item.composer !== undefined) { + if (!isRecord(item.composer)) { + throw new Invalid(`${at}.composer must be an object`) + } + composer = compact({ + package: requiredString(item.composer, 'package', `${at}.composer`), + constraint: optionalString(item.composer, 'constraint', `${at}.composer`), + }) as NonNullable + } + + const setup = listOf(item, 'setup', at)?.map( + ([step, here]) => + compact({ + title: requiredString(step, 'title', here), + command: optionalString(step, 'command', here), + url: optionalString(step, 'url', here), + }) as SetupStep + ) + + const patches = listOf(item, 'patches', at)?.map(([patch, here]) => { + const description = requiredString(patch, 'description', here) + if (!isHttpUrl(patch.url)) { + throw new Invalid(`${here}.url must be an http or https URL`) + } + return compact({ + description, + url: patch.url, + package: optionalString(patch, 'package', here), + issue: optionalString(patch, 'issue', here), + until: optionalString(patch, 'until', here), + }) as ModulePatch + }) + + return compact({ composer, setup, patches }) as Pick< + BackendModule, + 'composer' | 'setup' | 'patches' + > +} + +/** + * The backend modules of an entry. The registry lists them under a key named + * after the kind of backend, so each backend kind that has an adapter is + * looked up by its own name. + */ +function backendModules(raw: Raw, at: string): BackendModule[] { + const modules: BackendModule[] = [] + for (const kind of kindsWithRole('backend')) { + const list = raw[kind] + if (list === undefined) continue + if (!Array.isArray(list)) + throw new Invalid(`${at}.${kind} must be an array`) + for (const [index, item] of list.entries()) { + const here = `${at}.${kind}[${index}]` + if (!isRecord(item)) throw new Invalid(`${here} must be an object`) + const url = optionalString(item, 'url', here) + modules.push({ + kind, + name: requiredString(item, 'name', here), + label: requiredString(item, 'label', here), + core: optionalBoolean(item, 'core', here), + ...(url === undefined ? {} : { url }), + ...additions(item, here), + }) + } + } + return modules +} + +function moduleEntry(raw: unknown, at: string): ModuleEntry { + if (!isRecord(raw)) throw new Invalid(`${at} must be an object`) + + const compatibility = raw.compatibility + if (compatibility !== undefined && !isRecord(compatibility)) { + throw new Invalid(`${at}.compatibility must be an object`) + } + const druxt = compatibility + ? optionalString(compatibility, 'druxt', `${at}.compatibility`) + : undefined + + const name = requiredString(raw, 'name', at) + const repo = requiredString(raw, 'repo', at) + const category = requiredString(raw, 'category', at) + const status = requiredString(raw, 'status', at) + const type = requiredString(raw, 'type', at) + const npm = optionalString(raw, 'npm', at) + const path = optionalString(raw, 'path', at) + const website = optionalString(raw, 'website', at) + + return { + name, + ...(npm === undefined ? {} : { npm }), + repo, + ...(path === undefined ? {} : { path }), + category, + status, + type, + archived: optionalBoolean(raw, 'archived', at), + description: optionalString(raw, 'description', at) ?? '', + ...(website === undefined ? {} : { website }), + ...(druxt === undefined ? {} : { druxt }), + backend: backendModules(raw, at), + } +} + +/** + * Checks a module registry and returns its entries. A field the CLI does not + * use is ignored. A `schemaVersion` it does not know is refused, since the + * fields it does use may have changed meaning. + */ +export function parseModuleRegistry( + raw: unknown, + location: string +): ModuleEntry[] { + const invalid = (problem: string) => + new DrxError( + 'registry', + `The module registry at ${location} is invalid: ${problem}.` + ) + + if (!isRecord(raw)) throw invalid('it must be an object') + if (typeof raw.schemaVersion !== 'number') { + throw invalid('schemaVersion must be a number') + } + if (raw.schemaVersion !== MODULE_SCHEMA_VERSION) { + throw new DrxError( + 'registry', + `The module registry at ${location} has schemaVersion ${raw.schemaVersion}, and this version of the CLI reads schemaVersion ${MODULE_SCHEMA_VERSION}. Update @druxt/cli to read it.` + ) + } + if (!Array.isArray(raw.modules)) throw invalid('modules must be an array') + + try { + return raw.modules.map((entry, index) => + moduleEntry(entry, `modules[${index}]`) + ) + } catch (error) { + if (error instanceof Invalid) throw invalid(error.message) + throw error + } +} diff --git a/packages/cli/src/modules/project.ts b/packages/cli/src/modules/project.ts new file mode 100644 index 0000000..d117fa4 --- /dev/null +++ b/packages/cli/src/modules/project.ts @@ -0,0 +1,86 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { + adapterFor, + type KindAdapter, + type PackageVersion, +} from '../adapters/index.js' +import type { Part } from '../parts.js' +import { findProjectRoot, loadProjectConfig } from '../project.js' +import { compatibility, type Compatibility } from './compatibility.js' +import type { ModuleEntry } from './entry.js' + +/** A frontend part of the project, and the Druxt its adapter reports. */ +export interface ModulePart { + path: string + kind: string + druxt: PackageVersion | null +} + +/** One module in one part. */ +export interface ModuleInPart { + path: string + /** The version installed, or null. */ + installed: string | null + /** The range the part asks for, or null. */ + declared: string | null + compatibility: Compatibility +} + +export interface ModuleProject { + root: string + parts: ModulePart[] + /** How a module stands in each part, in the order of `parts`. */ + state(module: ModuleEntry): Promise +} + +/** + * The project around `cwd` as the module commands see it: its frontend parts + * that exist and have an adapter. Undefined outside a project, and in one + * with no such part. + */ +export async function moduleProject( + cwd: string +): Promise { + const root = findProjectRoot(cwd) + if (!root) return undefined + const config = await loadProjectConfig(root) + + const found: { + part: Part + adapter: KindAdapter + dir: string + druxt: PackageVersion | undefined + }[] = [] + for (const part of config.parts) { + const adapter = adapterFor(part.kind) + const dir = join(root, part.path) + if (part.role !== 'frontend' || !adapter || !existsSync(dir)) continue + found.push({ part, adapter, dir, druxt: await adapter.druxt(dir) }) + } + if (found.length === 0) return undefined + + return { + root, + parts: found.map(({ part, druxt }) => ({ + path: part.path, + kind: part.kind, + druxt: druxt ?? null, + })), + async state(module) { + const states: ModuleInPart[] = [] + for (const { part, adapter, dir, druxt } of found) { + const own = module.npm + ? await adapter.package(dir, module.npm) + : undefined + states.push({ + path: part.path, + installed: own?.installed ?? null, + declared: own?.range ?? null, + compatibility: compatibility(module.druxt, druxt), + }) + } + return states + }, + } +} diff --git a/packages/cli/src/modules/registry.ts b/packages/cli/src/modules/registry.ts new file mode 100644 index 0000000..db5770c --- /dev/null +++ b/packages/cli/src/modules/registry.ts @@ -0,0 +1,137 @@ +import { createHash } from 'node:crypto' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { DrxError } from '../errors.js' +import { fetchJson } from '../fetch-json.js' +import { isRecord } from '../validate.js' +import { parseModuleRegistry, type ModuleEntry } from './entry.js' + +/** The published Druxt module registry. */ +export const DEFAULT_MODULE_REGISTRY = + 'https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json' + +/** + * A cached copy younger than this is used with no request. The registry + * changes when a module is released, and the CDN in front of it holds a + * branch for hours, so asking more often than hourly finds nothing new. + */ +export const FRESH_FOR_MS = 60 * 60 * 1000 + +export interface LoadedModules { + modules: ModuleEntry[] + url: string + /** `remote` when the registry was read now, `cache` for the copy on disk. */ + origin: 'remote' | 'cache' + /** When the registry was read from its URL, as an ISO date and time. */ + fetchedAt: string + ageMs: number + /** Why the registry could not be read, when an old copy stood in for it. */ + reason?: string +} + +export interface LoadModulesOptions { + url: string + /** The directory the copy is kept in. */ + cacheDir: string + now?: () => Date + fetch?: typeof fetch + /** Read the registry even when the copy is fresh. */ + refresh?: boolean + /** A bearer token for a registry the user named. */ + auth?: string +} + +interface Cached { + modules: ModuleEntry[] + fetchedAt: Date +} + +/** One file per registry URL, named by a hash of the URL. */ +function cacheFile(cacheDir: string, url: string): string { + const key = createHash('sha256').update(url).digest('hex').slice(0, 16) + return join(cacheDir, 'modules', `${key}.json`) +} + +/** The copy on disk, or undefined when there is none that can be read. */ +async function readCache( + file: string, + url: string +): Promise { + try { + const stored: unknown = JSON.parse(await readFile(file, 'utf8')) + if (!isRecord(stored) || stored.url !== url) return undefined + const fetchedAt = new Date(String(stored.fetchedAt)) + if (Number.isNaN(fetchedAt.getTime())) return undefined + return { modules: parseModuleRegistry(stored.registry, url), fetchedAt } + } catch { + return undefined + } +} + +/** + * Loads the module registry. + * + * A copy on disk under an hour old is used as it is. Otherwise the registry + * is read from its URL and the copy replaced. When that read fails, a copy of + * any age is used and the result says why. A registry that is read but is + * invalid, or of another schema version, is an error and never falls back. + */ +export async function loadModules( + options: LoadModulesOptions +): Promise { + const { url, cacheDir } = options + const now = (options.now ?? (() => new Date()))() + const file = cacheFile(cacheDir, url) + const cached = await readCache(file, url) + + const fromCache = (copy: Cached, reason?: string): LoadedModules => ({ + modules: copy.modules, + url, + origin: 'cache', + fetchedAt: copy.fetchedAt.toISOString(), + ageMs: Math.max(0, now.getTime() - copy.fetchedAt.getTime()), + ...(reason === undefined ? {} : { reason }), + }) + + if ( + cached && + !options.refresh && + now.getTime() - cached.fetchedAt.getTime() < FRESH_FOR_MS + ) { + return fromCache(cached) + } + + let registry: unknown + try { + registry = await fetchJson(url, options.fetch, options.auth) + } catch (error) { + if (!(error instanceof DrxError)) throw error + if (cached) return fromCache(cached, error.message) + throw new DrxError( + 'registry', + `${error.message} There is no cached copy to use.` + ) + } + + const modules = parseModuleRegistry(registry, url) + const fetchedAt = now.toISOString() + try { + await mkdir(join(cacheDir, 'modules'), { recursive: true }) + await writeFile(file, JSON.stringify({ url, fetchedAt, registry })) + } catch { + // A cache directory that cannot be written costs a request next time. + } + return { modules, url, origin: 'remote', fetchedAt, ageMs: 0 } +} + +/** An age as a phrase: "less than a minute", "3 hours", "2 days". */ +export function describeAge(ms: number): string { + const count = (value: number, unit: string) => + `${value} ${unit}${value === 1 ? '' : 's'}` + const minutes = Math.floor(ms / 60_000) + if (minutes < 1) return 'less than a minute' + if (minutes < 60) return count(minutes, 'minute') + const hours = Math.floor(minutes / 60) + if (hours < 48) return count(hours, 'hour') + return count(Math.floor(hours / 24), 'day') +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts new file mode 100644 index 0000000..0ae87a1 --- /dev/null +++ b/packages/cli/src/output.ts @@ -0,0 +1,111 @@ +import type { CliContext } from './context.js' +import { cliVersion } from './package-root.js' +import { + bannerAllowed, + presentationFor, + type Presentation, +} from './presentation.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. + * + * In a terminal the lines on stderr carry a mark. Anywhere else they are the + * plain sentences, with nothing added, so a log reads the same as before. + */ +export interface Output { + readonly json: boolean + /** True when stderr is a terminal a person is reading. */ + readonly decorated: boolean + /** How to dress text for stdout. */ + readonly out: Presentation + /** How to dress text for stderr. */ + readonly err: Presentation + /** A step that is starting, on stderr. */ + note(message: string): void + /** A step that finished. Printed in a terminal only. */ + done(message: string): void + /** Something that was done, said once it is done. Printed everywhere. */ + did(message: string): void + /** Something the user should know that does not stop the command. */ + warn(message: string): void + /** A line on stderr with nothing added. */ + line(message?: string): void + /** + * The small header, `druxt` and the version, for a command that prints + * more than a line or two. Printed once, in a terminal only. + */ + header(): void + /** + * The wordmark, when the terminal and the settings allow it. Returns + * whether it was drawn. The small header is not printed after it. + */ + banner(settings: { flag?: boolean; configured?: boolean }): boolean + /** 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 { + const { stdout, stderr, env } = context + const out = presentationFor(stdout, env, json) + const err = presentationFor(stderr, env, json) + const decorated = stderr.isTTY === true && !json + const write = (text: string) => stderr.write(`${text}\n`) + const marked = (kind: Parameters[0], text: string) => + decorated ? `${err.mark(kind)} ${text}` : text + let headed = false + + return { + json, + decorated, + out, + err, + note: (message) => write(marked('working', message)), + done: (message) => { + if (decorated) write(marked('done', message)) + }, + did: (message) => write(marked('done', message)), + warn: (message) => write(marked('warning', `Warning: ${message}`)), + line: (message = '') => write(message), + header() { + if (!decorated || headed) return + headed = true + write(marked('working', err.bold(`druxt ${cliVersion()}`))) + }, + banner({ flag, configured }) { + const allowed = bannerAllowed({ + env, + isTTY: stderr.isTTY === true, + columns: stderr.columns, + json, + flag, + configured, + }) + if (!allowed) return false + headed = true + write(`\n${err.wordmark()}\n`) + return true + }, + result: (data, text) => + 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..5903428 --- /dev/null +++ b/packages/cli/src/parts.ts @@ -0,0 +1,62 @@ +import { + isHttpUrl, + isInsidePath, + 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 + /** How a backend part is run on this machine, by the name of its engine. */ + engine?: string + /** The database the engine was set up with, where it offers a choice. */ + database?: string + /** The URL of a backend that is not run on this machine. */ + baseUrl?: string +} + +/** + * The first problem with a list of parts, as "