From e88195821119d390f73121b05269a510df799cce Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 03:26:25 +0000 Subject: [PATCH 01/33] ci: add linting, commit hooks, the pipelines and the contributor guides The tooling every later change runs on, before any code of the packages. - ESLint, Prettier, markdownlint, cspell, knip and the type check, each with a script in the root package.json. - Committed git hooks, enabled by npm install: commitlint on the message, and the linters, the type check and the tests before a commit. - A check that no URL in a tracked file resolves only on a private network, with its own tests, and a check that no AI tool is credited. - Prose linting with Vale, installed at a pinned version and verified by checksum. - A GitHub Actions workflow and a GitLab pipeline with the lint and unit test jobs. Both run on the 0.x branch. - The Renovate policy, the changesets configuration, the issue, pull request and merge request templates, and the contributor and agent guides. --- .changeset/README.md | 8 + .changeset/config.json | 11 + .cspell-project-words.txt | 42 ++++ .cspell.json | 24 ++ .githooks/commit-msg | 7 + .githooks/pre-commit | 9 + .github/ISSUE_TEMPLATE/bug_report.md | 31 +++ .github/ISSUE_TEMPLATE/feature_request.md | 17 ++ .github/PULL_REQUEST_TEMPLATE.md | 19 ++ .github/workflows/ci.yml | 112 +++++++++ .gitlab-ci.yml | 257 +++++++++++++++++++++ .gitlab/issue_templates/Default.md | 19 ++ .gitlab/merge_request_templates/Default.md | 19 ++ .gitlab/scripts/check-attribution.sh | 158 +++++++++++++ .gitlab/scripts/install-vale.sh | 134 +++++++++++ .gitlab/scripts/lint-prose.sh | 178 ++++++++++++++ .markdownlint-cli2.jsonc | 21 ++ .prettierignore | 14 ++ .prettierrc.json | 23 ++ .vale.ini | 11 + .yamllint | 10 + AGENTS.md | 71 ++++++ CLAUDE.md | 3 + CONTRIBUTING.md | 81 +++++++ commitlint.config.mjs | 46 ++++ eslint.config.mjs | 27 +++ knip.jsonc | 13 ++ renovate.json | 36 +++ scripts/lint-private-refs.mjs | 178 ++++++++++++++ scripts/postinstall.mjs | 35 +++ test/private-refs.test.ts | 92 ++++++++ vitest.config.ts | 22 ++ 32 files changed, 1728 insertions(+) create mode 100644 .changeset/README.md create mode 100644 .changeset/config.json create mode 100644 .cspell-project-words.txt create mode 100644 .cspell.json create mode 100755 .githooks/commit-msg create mode 100755 .githooks/pre-commit create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/ci.yml create mode 100644 .gitlab-ci.yml create mode 100644 .gitlab/issue_templates/Default.md create mode 100644 .gitlab/merge_request_templates/Default.md create mode 100755 .gitlab/scripts/check-attribution.sh create mode 100755 .gitlab/scripts/install-vale.sh create mode 100755 .gitlab/scripts/lint-prose.sh create mode 100644 .markdownlint-cli2.jsonc create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 .vale.ini create mode 100644 .yamllint create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md create mode 100644 commitlint.config.mjs create mode 100644 eslint.config.mjs create mode 100644 knip.jsonc create mode 100644 renovate.json create mode 100644 scripts/lint-private-refs.mjs create mode 100644 scripts/postinstall.mjs create mode 100644 test/private-refs.test.ts create mode 100644 vitest.config.ts 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..44ec9ad --- /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": "0.x", + "updateInternalDependencies": "patch", + "ignore": [] +} 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..942f080 --- /dev/null +++ b/.cspell.json @@ -0,0 +1,24 @@ +{ + "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/" + ], + "useGitignore": true +} 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..a623341 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,112 @@ +--- +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: ["0.x"] + pull_request: + branches: ["0.x"] + +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 + + - 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/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..47adef5 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,257 @@ +--- +# 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 --- +# + +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.]+)/' + +# +# --- 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..58399a0 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,14 @@ +node_modules/ +dist/ +coverage/ +reports/ +package-lock.json +CHANGELOG.md +.vale/ +packages/cli/starters/ + +# 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/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/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..60af4ad --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,27 @@ +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/**', + ], + }, + 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..2a2c97d --- /dev/null +++ b/knip.jsonc @@ -0,0 +1,13 @@ +{ + "$schema": "https://unpkg.com/knip@6/schema.json", + "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/renovate.json b/renovate.json new file mode 100644 index 0000000..4be9e84 --- /dev/null +++ b/renovate.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:recommended"], + "baseBranches": ["0.x"], + "automerge": false, + "rangeStrategy": "bump", + "dependencyDashboard": true, + "branchPrefix": "deps/", + "labels": ["dependencies"], + "enabledManagers": ["github-actions", "npm"], + "packageRules": [ + { + "description": "Pin GitHub Actions to commit SHAs. A tag is a mutable reference to code that runs with repository credentials. npm packages already carry integrity hashes in the lockfile.", + "matchManagers": ["github-actions"], + "pinDigests": true + }, + { + "description": "Held on purpose. c12 4 is a release candidate, and typescript-eslint does not support TypeScript 7 yet. Bump each by hand when that changes.", + "matchManagers": ["npm"], + "matchPackageNames": ["c12", "typescript"], + "enabled": false + }, + { + "description": "Majors need a person. An automated major lands a breaking change on a branch nobody chose to upgrade.", + "matchManagers": ["npm", "github-actions"], + "matchUpdateTypes": ["major"], + "enabled": false + }, + { + "description": "One pull request for everything else. Ungrouped updates produce a pull request per dependency and the whole set gets ignored together.", + "matchPackageNames": ["*"], + "groupName": "all dependencies", + "groupSlug": "all" + } + ] +} diff --git a/scripts/lint-private-refs.mjs b/scripts/lint-private-refs.mjs new file mode 100644 index 0000000..a325555 --- /dev/null +++ b/scripts/lint-private-refs.mjs @@ -0,0 +1,178 @@ +/** + * Fail if a tracked file points at a host only the author can reach. + * + * This repository is public, and the starter registry it carries is read by + * every copy of the CLI, so a private URL here reaches everyone who runs it. + * + * The rule is the shape of the host, not a list of known hostnames - + * anything resolvable only inside a LAN. localhost, loopback and the + * DDEV and Lando development domains are how a site runs locally, so + * they are the exceptions. + * + * Known gap: this matches host shape, so it catches `scheme://host/...` + * and scp-style git remotes. It cannot catch an internal project or + * repository name written as prose, which has no shape to match. A + * green run here is not a statement about that class. + */ + +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') + +/** Development hosts that are meant to be here. */ +const ALLOWED = [ + /^localhost$/i, + /^127\./, + /^::1$/, + /\.ddev\.site$/i, + /\.lndo\.site$/i, +] + +/** Hosts nobody outside the author's network can resolve. */ +const PRIVATE_HOST = [ + /^[a-z0-9-]+(\.[a-z0-9-]+)*\.(local|internal|lan|home|corp|intranet)$/i, + /^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, + /^192\.168\.\d{1,3}\.\d{1,3}$/, + /^172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}$/, + /^f[cd][0-9a-f]{2}:/i, + /^fe[89ab][0-9a-f]:/i, +] + +/** + * Scheme, then the authority's host. + * + * Userinfo has to be stepped over rather than captured, because a git + * remote usually carries it - `https://oauth2:TOKEN@host/path` - and + * capturing `oauth2` instead of the host let the whole URL through. + */ +// The bracket class takes dots as well as hex: an IPv4-mapped literal such as +// [::ffff:10.0.0.8] is a bracketed host that carries an RFC1918 address. +const URL_HOST = + /(?:[a-z][a-z0-9+.-]*:\/\/(?:[^/@\s]*@)?|\bgit@)(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)/g + +/** + * The IPv4 address inside an IPv4-mapped IPv6 literal, else the host as given. + * + * A mapped address has four spellings, compressed or expanded, with the last + * 32 bits written as dotted decimal or as two hex groups. Matching the dotted + * spelling alone let `[0:0:0:0:0:ffff:0a00:0008]` name a private endpoint that + * every pattern below then read as a public one. + */ +export function mappedToIpv4(host) { + if (!/^[0-9a-f:.]+$/i.test(host) || !host.includes(':')) return host + + // A trailing dotted quad occupies the last two groups. Rewriting it as hex + // first means the zero-fill below only ever counts groups. + const text = host.replace( + /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/, + (_, a, b, c, d) => + [((+a << 8) | +b).toString(16), ((+c << 8) | +d).toString(16)].join(':') + ) + + const [head, tail] = text.split('::') + const left = head ? head.split(':') : [] + const right = tail === undefined ? [] : tail ? tail.split(':') : [] + const groups = + tail === undefined + ? left + : left.concat(Array(8 - left.length - right.length).fill('0'), right) + + if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) { + return host + } + const value = groups.map((g) => parseInt(g, 16)) + if (!value.slice(0, 5).every((g) => g === 0) || value[5] !== 0xffff) { + return host + } + return [value[6] >> 8, value[6] & 0xff, value[7] >> 8, value[7] & 0xff].join( + '.' + ) +} + +/** Every private host referenced by `text`, with the line it sits on. */ +export function findPrivateRefs(text) { + const found = [] + text.split('\n').forEach((line, index) => { + for (const match of line.matchAll(URL_HOST)) { + const host = mappedToIpv4( + match[1].replace(/^\[|\]$/g, '').replace(/[.:]+$/, '') + ) + if (ALLOWED.some((pattern) => pattern.test(host))) { + continue + } + if (PRIVATE_HOST.some((pattern) => pattern.test(host))) { + found.push({ line: index + 1, host }) + } + } + }) + return found +} + +/** Tracked files, which is the set that actually gets published. */ +export function trackedFiles(root = ROOT) { + return execFileSync('git', ['-C', root, 'ls-files', '-z'], { + encoding: 'utf8', + }) + .split('\0') + .filter(Boolean) +} + +/** + * The rule's own source and test state private hosts on purpose - the + * patterns here, the examples there. Nothing else gets an exemption: + * an opt-out marker anyone could paste would eventually be pasted over + * a real leak. + */ +const SELF = ['scripts/lint-private-refs.mjs', 'test/private-refs.test.ts'] + +export function lintPrivateRefs(root = ROOT) { + const problems = [] + for (const file of trackedFiles(root)) { + if (SELF.includes(file)) { + continue + } + const absolute = path.join(root, file) + let text + try { + text = fs.readFileSync(absolute, 'utf8') + } catch { + continue + } + if (text.includes('\0')) { + continue + } + for (const hit of findPrivateRefs(text)) { + problems.push(`${file}:${hit.line}: ${hit.host}`) + } + } + return problems +} + +export function main(root = ROOT) { + const problems = lintPrivateRefs(root) + if (problems.length > 0) { + console.error( + [ + '', + 'These tracked files reference a host that only resolves on a private network:', + '', + ...problems.map((problem) => ` ${problem}`), + '', + 'This repository is public. Replace the reference with a public one,', + 'or describe the thing without a URL.', + '', + ].join('\n') + ) + process.exit(1) + } + console.log('No private hosts referenced by tracked files.') +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + // An explicit root keeps the tests honest: they run the real command + // against a throwaway repository rather than this one. + main(process.argv[2] ? path.resolve(process.argv[2]) : ROOT) +} diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs new file mode 100644 index 0000000..213e635 --- /dev/null +++ b/scripts/postinstall.mjs @@ -0,0 +1,35 @@ +/** + * Point git at the committed hooks directory. + * + * The hooks live in .githooks/ and are activated with + * `git config core.hooksPath`, which is a per-clone setting rather than + * something the repository carries. Without this step a fresh clone has the + * hooks on disk and none of them running, which is worse than having no hooks + * at all: the repository looks protected and is not. + * + * A committed directory, not husky: it is the same in every Druxt repository, + * including the ones with no package.json, and costs no dependency. + * + * Quiet on failure. A CI install runs this too, and there is nothing to gain + * from failing an install because a hook could not be configured in a + * container that will never make a commit. + */ + +import { execFileSync } from 'node:child_process' + +try { + execFileSync('git', ['rev-parse', '--git-dir'], { stdio: 'ignore' }) +} catch { + // Not a git checkout: a published tarball, or a vendored copy. Nothing to do. + process.exit(0) +} + +try { + execFileSync('git', ['config', 'core.hooksPath', '.githooks'], { + stdio: 'ignore', + }) + console.log('Git hooks enabled from .githooks/') +} catch (error) { + console.warn(`Could not enable git hooks: ${error.message}`) + console.warn('Run `npm run hooks:install` by hand if you intend to commit.') +} diff --git a/test/private-refs.test.ts b/test/private-refs.test.ts new file mode 100644 index 0000000..8be6658 --- /dev/null +++ b/test/private-refs.test.ts @@ -0,0 +1,92 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' +import { findPrivateRefs } from '../scripts/lint-private-refs.mjs' + +const SCRIPT = fileURLToPath( + new URL('../scripts/lint-private-refs.mjs', import.meta.url) +) + +const hostsIn = (text: string) => findPrivateRefs(text).map((ref) => ref.host) + +// The hosts below are private on purpose. The rule exempts this file by path, +// which is why it can state them plainly. +describe('findPrivateRefs', () => { + test('finds a private host by name', () => { + expect(hostsIn('see http://gitlab.example.local/x')).toEqual([ + 'gitlab.example.local', + ]) + }) + + test('finds RFC1918 addresses', () => { + expect(hostsIn('http://10.0.0.8/ http://192.168.1.1/')).toEqual([ + '10.0.0.8', + '192.168.1.1', + ]) + expect(hostsIn('http://172.16.0.1/')).toEqual(['172.16.0.1']) + }) + + test('finds an RFC1918 address inside an IPv4-mapped IPv6 literal', () => { + expect(hostsIn('https://[::ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[::ffff:0a00:0008]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[0:0:0:0:0:ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('http://[::ffff:c0a8:0101]/')).toEqual(['192.168.1.1']) + }) + + test('finds a link-local IPv6 address', () => { + expect(hostsIn('http://[fe80::1]/')).toEqual(['fe80::1']) + }) + + test('leaves public hosts alone', () => { + expect(hostsIn('https://druxtjs.org/docs')).toEqual([]) + expect(hostsIn('http://[2001:db8::1]/')).toEqual([]) + expect(hostsIn('http://[::ffff:8.8.8.8]/')).toEqual([]) + }) + + test('leaves the local development hosts alone', () => { + expect(hostsIn('http://localhost:3000/ http://127.0.0.1:8888/')).toEqual([]) + expect(hostsIn('http://[::1]/ https://example.ddev.site/')).toEqual([]) + }) + + test('reads the host, not the userinfo a git remote carries', () => { + expect(hostsIn('https://oauth2:token@gitlab.example.local/a')).toEqual([ + 'gitlab.example.local', + ]) + }) +}) + +describe('the lint:private command', () => { + let repo: string | undefined + + afterEach(() => { + if (repo) rmSync(repo, { recursive: true, force: true }) + }) + + const repoWith = (content: string) => { + repo = mkdtempSync(join(tmpdir(), 'drx-private-')) + execFileSync('git', ['init', '-q', repo]) + writeFileSync(join(repo, 'README.md'), content) + execFileSync('git', ['-C', repo, 'add', 'README.md']) + return repo + } + + const run = (root: string) => { + try { + execFileSync(process.execPath, [SCRIPT, root], { stdio: 'pipe' }) + return 0 + } catch (error) { + return (error as { status: number }).status + } + } + + test('passes a repository with public references only', () => { + expect(run(repoWith('See https://druxtjs.org.\n'))).toBe(0) + }) + + test('fails a repository whose tracked file names a private host', () => { + expect(run(repoWith('See http://gitlab.example.local/x.\n'))).toBe(1) + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..733ce78 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,22 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + resolve: { + // create-druxt imports the CLI by its package name. The tests read the + // CLI's sources, so they do not depend on a build having run. + alias: { + '@druxt/cli': fileURLToPath( + new URL('./packages/cli/src/index.ts', import.meta.url) + ), + }, + }, + test: { + include: ['packages/*/test/**/*.test.ts', 'test/**/*.test.ts'], + coverage: { + provider: 'v8', + include: ['packages/*/src/**/*.ts', 'scripts/lint-private-refs.mjs'], + reporter: ['text', 'lcov'], + }, + }, +}) From 742cf9dec4637358a7ec44d03c93c55fb568f231 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 03:26:25 +0000 Subject: [PATCH 02/33] feat: add drx init, drx info and create-druxt The first commands of @druxt/cli, with the drx binary, and create-druxt. - drx init creates a site from a starter. The starter comes from a registry in giget's format, read from the starters directory of this repository on the 0.x branch, with a copy bundled in the package as the fallback. - Sources and registries can be named in the user configuration file, so a private one is never named in the code. - A part of a project has a role and a kind. An adapter per kind, for Nuxt and Drupal, reads what is installed. - drx.config.json records a project's layout and parts, and drx info reports them with the versions of their packages. - create-druxt runs drx init with the arguments given, so that npm create druxt works. - The pipelines gain a job that packs both packages, installs the tarballs and runs the binaries, an end-to-end test against the real quickstart, and a coverage floor. - A README for the repository and for each package, the changelog, the first changesets and a devcontainer. --- .changeset/first-release-cli.md | 9 + .changeset/first-release-create-druxt.md | 5 + .devcontainer/devcontainer.json | 30 ++ .github/workflows/ci.yml | 38 ++ .gitlab-ci.yml | 36 ++ CHANGELOG.md | 22 + README.md | 193 ++++++++ package-lock.json | 180 +++++++- packages/cli/LICENSE | 21 + packages/cli/README.md | 21 + packages/cli/package.json | 6 + packages/cli/src/adapters/adapter.ts | 33 ++ packages/cli/src/adapters/drupal.ts | 60 +++ packages/cli/src/adapters/index.ts | 16 + packages/cli/src/adapters/nuxt.ts | 59 +++ packages/cli/src/adapters/read-json.ts | 28 ++ packages/cli/src/args.ts | 33 ++ packages/cli/src/bin.ts | 4 + packages/cli/src/cli.ts | 97 ++++ packages/cli/src/commands/info.ts | 133 ++++++ packages/cli/src/commands/init.ts | 382 +++++++++++++++ packages/cli/src/context.ts | 74 +++ packages/cli/src/errors.ts | 27 ++ packages/cli/src/index.ts | 11 + packages/cli/src/install.ts | 54 +++ packages/cli/src/layouts.ts | 24 + packages/cli/src/output.ts | 46 ++ packages/cli/src/package-root.ts | 39 ++ packages/cli/src/parts.ts | 50 ++ packages/cli/src/project.ts | 93 ++++ packages/cli/src/prompts.ts | 54 +++ packages/cli/src/registry/entry.ts | 112 +++++ packages/cli/src/registry/registry.ts | 180 ++++++++ packages/cli/src/sources.ts | 70 +++ packages/cli/src/user-config.ts | 114 +++++ packages/cli/src/validate.ts | 22 + packages/cli/test/adapters/adapters.test.ts | 143 ++++++ packages/cli/test/cli.test.ts | 64 +++ packages/cli/test/commands/info.test.ts | 185 ++++++++ packages/cli/test/commands/init.test.ts | 484 ++++++++++++++++++++ packages/cli/test/e2e/quickstart.test.ts | 55 +++ packages/cli/test/helpers/entry.ts | 35 ++ packages/cli/test/helpers/run.ts | 36 ++ packages/cli/test/helpers/server.ts | 50 ++ packages/cli/test/helpers/starter.ts | 55 +++ packages/cli/test/helpers/tmp.ts | 31 ++ packages/cli/test/install.test.ts | 75 +++ packages/cli/test/project.test.ts | 87 ++++ packages/cli/test/prompts.test.ts | 80 ++++ packages/cli/test/registry/entry.test.ts | 112 +++++ packages/cli/test/registry/registry.test.ts | 208 +++++++++ packages/cli/test/seams.test.ts | 44 ++ packages/cli/test/sources.test.ts | 81 ++++ packages/cli/test/user-config.test.ts | 143 ++++++ packages/create-druxt/LICENSE | 21 + packages/create-druxt/README.md | 13 + packages/create-druxt/package.json | 3 + packages/create-druxt/src/bin.ts | 4 + packages/create-druxt/src/index.ts | 18 + packages/create-druxt/test/create.test.ts | 36 ++ scripts/copy-starters.mjs | 20 + starters/index.json | 3 + starters/quickstart.json | 21 + vitest.config.ts | 8 + 64 files changed, 4478 insertions(+), 13 deletions(-) create mode 100644 .changeset/first-release-cli.md create mode 100644 .changeset/first-release-create-druxt.md create mode 100644 .devcontainer/devcontainer.json create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 packages/cli/LICENSE create mode 100644 packages/cli/README.md create mode 100644 packages/cli/src/adapters/adapter.ts create mode 100644 packages/cli/src/adapters/drupal.ts create mode 100644 packages/cli/src/adapters/index.ts create mode 100644 packages/cli/src/adapters/nuxt.ts create mode 100644 packages/cli/src/adapters/read-json.ts create mode 100644 packages/cli/src/args.ts create mode 100644 packages/cli/src/bin.ts create mode 100644 packages/cli/src/cli.ts create mode 100644 packages/cli/src/commands/info.ts create mode 100644 packages/cli/src/commands/init.ts create mode 100644 packages/cli/src/context.ts create mode 100644 packages/cli/src/errors.ts create mode 100644 packages/cli/src/index.ts create mode 100644 packages/cli/src/install.ts create mode 100644 packages/cli/src/layouts.ts create mode 100644 packages/cli/src/output.ts create mode 100644 packages/cli/src/package-root.ts create mode 100644 packages/cli/src/parts.ts create mode 100644 packages/cli/src/project.ts create mode 100644 packages/cli/src/prompts.ts create mode 100644 packages/cli/src/registry/entry.ts create mode 100644 packages/cli/src/registry/registry.ts create mode 100644 packages/cli/src/sources.ts create mode 100644 packages/cli/src/user-config.ts create mode 100644 packages/cli/src/validate.ts create mode 100644 packages/cli/test/adapters/adapters.test.ts create mode 100644 packages/cli/test/cli.test.ts create mode 100644 packages/cli/test/commands/info.test.ts create mode 100644 packages/cli/test/commands/init.test.ts create mode 100644 packages/cli/test/e2e/quickstart.test.ts create mode 100644 packages/cli/test/helpers/entry.ts create mode 100644 packages/cli/test/helpers/run.ts create mode 100644 packages/cli/test/helpers/server.ts create mode 100644 packages/cli/test/helpers/starter.ts create mode 100644 packages/cli/test/helpers/tmp.ts create mode 100644 packages/cli/test/install.test.ts create mode 100644 packages/cli/test/project.test.ts create mode 100644 packages/cli/test/prompts.test.ts create mode 100644 packages/cli/test/registry/entry.test.ts create mode 100644 packages/cli/test/registry/registry.test.ts create mode 100644 packages/cli/test/seams.test.ts create mode 100644 packages/cli/test/sources.test.ts create mode 100644 packages/cli/test/user-config.test.ts create mode 100644 packages/create-druxt/LICENSE create mode 100644 packages/create-druxt/README.md create mode 100644 packages/create-druxt/src/bin.ts create mode 100644 packages/create-druxt/src/index.ts create mode 100644 packages/create-druxt/test/create.test.ts create mode 100644 scripts/copy-starters.mjs create mode 100644 starters/index.json create mode 100644 starters/quickstart.json diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md new file mode 100644 index 0000000..04fd6fa --- /dev/null +++ b/.changeset/first-release-cli.md @@ -0,0 +1,9 @@ +--- +'@druxt/cli': minor +--- + +First release of the Druxt command-line tool, with the binary `drx`. + +- `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. +- `drx info` prints the versions of the CLI, Node and the packages of each part of a project. +- The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/.changeset/first-release-create-druxt.md b/.changeset/first-release-create-druxt.md new file mode 100644 index 0000000..86f7f31 --- /dev/null +++ b/.changeset/first-release-create-druxt.md @@ -0,0 +1,5 @@ +--- +'create-druxt': minor +--- + +First release. `npm create druxt my-site` runs `drx init my-site` from `@druxt/cli`. diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..ff40edd --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,30 @@ +{ + "name": "Druxt CLI", + "image": "mcr.microsoft.com/devcontainers/base:trixie", + "features": { + // The version in .nvmrc, which the pipelines build on. Node 16 is for running a site made from the 0.x + // starter: `nvm use 16.18.1` in the site's directory. + "ghcr.io/devcontainers/features/node:1": { + "version": "24.18.0", + "additionalVersions": "16.18.1" + }, + // For the Drupal part of a site `drx init` creates. The feature builds PHP from source, against trixie's + // SQLite, which meets Drupal 11's minimum. + "ghcr.io/devcontainers/features/php:1": { + "version": "8.4", + "installComposer": true + }, + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + // Installs the dependencies and builds both packages, so `drx` runs as soon as the container is up. + "postCreateCommand": "npm ci && npm run build && npm link --workspace @druxt/cli --workspace create-druxt", + "customizations": { + "vscode": { + "extensions": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "vitest.explorer" + ] + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a623341..670a632 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,6 +103,7 @@ jobs: - run: npm ci + # The coverage floor in vitest.config.ts is what fails here. - run: npm test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -110,3 +111,40 @@ jobs: with: name: test-results path: reports/junit/ + + # A published install reads each package's files allowlist and links its + # binaries, which the unit tests do not. + pack: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - run: npm run build + + - name: Pack, install and run the packages + run: | + mkdir -p "$RUNNER_TEMP/pack-check" + npm pack --workspaces --pack-destination "$RUNNER_TEMP/pack-check" + version="$(node -p "require('./packages/cli/package.json').version")" + cd "$RUNNER_TEMP/pack-check" + npm init -y > /dev/null + npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + test "$(./node_modules/.bin/drx --version)" = "$version" + test -f node_modules/@druxt/cli/starters/index.json + ./node_modules/.bin/drx info + ./node_modules/.bin/create-druxt --help + + # The one step that needs the network: a site from the real quickstart + # tarball the registry entry points at. + - run: npm run test:e2e diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 47adef5..1e691e2 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -183,6 +183,9 @@ lint:prose: # --- Test --- # +# No network: the tests serve their own registry and tarball from a loopback +# port. The coverage floor in vitest.config.ts is what fails this job when +# coverage drops. test:unit: extends: .node stage: test @@ -201,6 +204,39 @@ test:unit: # Puts the coverage percentage in the merge request widget. coverage: '/All files\s*\|\s*([\d.]+)/' +# A published install reads each package's files allowlist and links its +# binaries. The unit tests read the sources and do neither, so this is the job +# that proves the packages a user downloads can be installed and run. +test:pack: + extends: .node + stage: test + needs: [] + script: + - section_start "build" "Building both packages" + - npm run build + - section_end "build" + - section_start "pack" "Packing and installing the tarballs" + - mkdir -p "$CI_PROJECT_DIR/pack-check" + - npm pack --workspaces --pack-destination "$CI_PROJECT_DIR/pack-check" + - cd "$CI_PROJECT_DIR/pack-check" && npm init -y > /dev/null + - npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + - test "$(./node_modules/.bin/drx --version)" = "$(node -p "require('$CI_PROJECT_DIR/packages/cli/package.json').version")" + - test -f node_modules/@druxt/cli/starters/index.json + - ./node_modules/.bin/drx info + - ./node_modules/.bin/create-druxt --help + - section_end "pack" + +# The one job that needs the network: it creates a site from the real +# quickstart tarball the registry entry points at, and reads it back. +test:e2e: + extends: .node + stage: test + needs: [] + script: + - section_start "e2e" "Creating a site from the real starter" + - npm run test:e2e + - section_end "e2e" + # # --- Secret detection --- # diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..03d7689 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +Each package keeps its own changelog, written by [changesets](https://github.com/changesets/changesets) +when a release is cut: + +- `@druxt/cli`: `packages/cli/CHANGELOG.md` +- `create-druxt`: `packages/create-druxt/CHANGELOG.md` + +Changes that are merged and not yet released are the files in `.changeset/`. + +Changes to the repository that are in no package, such as its pipelines, are recorded here. + +## [Unreleased] + +### Added + +- The workspace, with `@druxt/cli` and `create-druxt`, on the Druxt repository standard: committed + git hooks, linting, a GitLab pipeline and a GitHub Actions workflow, secret scanning with a + detection canary, a private-host check, an attribution check and prose linting. +- The starter registry under `starters/`, with one entry, `quickstart`. + +[Unreleased]: https://github.com/druxt/cli/commits/0.x diff --git a/README.md b/README.md new file mode 100644 index 0000000..77ed121 --- /dev/null +++ b/README.md @@ -0,0 +1,193 @@ +# Druxt CLI + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +This repository holds two packages: + +| Package | What it is | +| -------------- | ------------------------------------------------------------- | +| `@druxt/cli` | The CLI. Its binary is `drx`. | +| `create-druxt` | `npm create druxt`. It runs `drx init` and does nothing else. | + +## Quickstart + +```bash +npm create druxt@latest my-site +cd my-site +npx @druxt/cli info +``` + +You will need Node 22.12 or newer to run the CLI. The site it creates has its own requirements, which `drx init` prints. + +## Running it + +| You want to | Run | +| ------------------- | -------------------------------------------------------------------------------------------- | +| Create a site | `npm create druxt@latest [dir]` | +| Run any command | `npx @druxt/cli ` | +| Use it in a project | `npm install -D @druxt/cli`, then `drx ` in a package script or `npx drx ` | + +`npx drx` does not work outside a project that has `@druxt/cli` installed. Another package holds the name `drx` on npm, so `npx drx` downloads that package and not this one. Use `npx @druxt/cli`. + +## Commands + +### `drx init [dir]` + +Creates a site from a starter in a registry, writes `drx.config.json` at its root, and prints what the site needs and what to run next. + +| Option | What it does | Default | +| --------------------------- | ----------------------------------------------------------------- | ------------------------------------------------ | +| `[dir]` | The directory to create the site in | Asked for, or the starter's default with `--yes` | +| `--starter ` | The starter to create the site from | The registry's default | +| `--layout ` | `monorepo`, `split` or `workspace`. Only `monorepo` is available. | The starter's layout | +| `--registry ` | A starter registry: a URL, or a name from the user configuration | The public registry | +| `--source ` | Where the Druxt packages come from. Only `npm` is available. | `npm` | +| `--install`, `--no-install` | Install the site's dependencies after creating it, or do not | Asked for, or no | +| `--force` | Write into a directory that exists and is not empty | Refuse | +| `--yes`, `-y` | Accept the default for everything not given, and ask nothing | | +| `--json` | Print the result as JSON on stdout | | + +At a terminal, `init` asks for the directory, the starter when the registry has more than one, the layout, and whether to install. A flag answers each question, so the command runs unattended: + +```bash +npx @druxt/cli init my-site --yes --json +``` + +With no terminal, `init` uses the defaults and never waits for input. It needs the directory or `--yes`, and fails with a message saying so when it has neither. + +`--install` runs the install of the package manager the starter declares. For the `quickstart` starter that is `npm install`, which also sets up the Drupal backend when PHP and Composer are present. + +### `drx info` + +Prints the versions of the CLI and Node. Inside a project it adds the layout and, for each part, the packages that matter: `nuxt` and every `druxt`, `druxt-*` or `@druxt/*` package for a Nuxt part, and Drupal core and the Druxt module for a Drupal part. Run it from any directory in the project. + +| Option | What it does | +| -------- | ---------------------------------- | +| `--json` | Print the report as JSON on stdout | + +Outside a project it says so and prints the two versions. + +### `drx --help`, `drx --help`, `drx --version` + +Usage for the CLI or one command, and the version. + +### Output and exit codes + +- The result of a command goes to stdout: text, or one JSON document with `--json`. +- Progress, warnings, errors and prompts go to stderr. +- A command that fails exits with 1. With `--json` it also prints `{ "ok": false, "error": { "code", "message" } }` on stdout. + +## The project configuration + +`drx init` writes `drx.config.json` at the root of the site. Later commands find the project by it. + +```json +{ + "layout": "monorepo", + "line": "0.x", + "starter": "quickstart", + "source": "npm", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ] +} +``` + +| Key | What it holds | +| --------- | ---------------------------------------------------------------------------------------------------- | +| `layout` | The arrangement of the parts: `monorepo`, `split` or `workspace` | +| `line` | The Druxt release line | +| `starter` | The name of the starter the site was created from | +| `source` | The name of the source its Druxt packages come from | +| `parts` | Each part of the site: its `role` (`frontend` or `backend`), its `kind` and its `path` from the root | + +A kind is `nuxt` or `drupal` in this version. + +## The starter registry + +A registry is a URL that answers `/.json` for each starter, in the format [giget](https://github.com/unjs/giget) defines, and `/index.json` with the names. The public registry is the [`starters/`](starters/) directory of this repository. + +```json +{ + "name": "quickstart", + "tar": "https://codeload.github.com/druxt/quickstart/tar.gz/refs/heads/develop", + "defaultDir": "my-druxt-site", + "url": "https://github.com/druxt/quickstart", + "druxt": { + "line": "0.x", + "layout": "monorepo", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ], + "requires": { + "node": "16.18.1", + "tools": ["PHP 8.3 or newer with Composer, or DDEV"] + }, + "maintained": "2026-11-15", + "default": true, + "steps": ["npm run setup", "npm run dev"] + } +} +``` + +`name`, `tar`, `defaultDir`, `url`, `subdir` and `headers` are giget's fields. giget ignores the `druxt` object, so the same file works with `npx giget --registry quickstart`. + +| Key in `druxt` | What it holds | +| ---------------- | -------------------------------------------------------------------------- | +| `line` | The Druxt release line | +| `layout` | The layout the starter has | +| `parts` | The parts of the starter, as in the project configuration | +| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | +| `requires.tools` | What else the site needs, each as a phrase to show the user | +| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | +| `default` | `true` for the starter `init` uses when none is named | +| `steps` | Optional. The commands to run in the new site, in order | + +`index.json` is `{ "starters": ["quickstart"] }`. + +`init` checks an entry before it downloads anything, and fails with a message naming the field that is wrong. It warns when the starter was last maintained more than a year ago, and when the running Node is not the one the starter needs. + +The package includes a copy of the public registry. When the public registry cannot be read, `init` uses the copy and says so. A registry you name with `--registry` is never replaced by the copy. + +## The user configuration + +`~/.config/drx/config.json` names registries and sources of your own. `DRX_CONFIG` points at another file, and `XDG_CONFIG_HOME` is used when it is set. + +```json +{ + "registries": { + "team": "https://example.com/starters" + }, + "sources": { + "next": { "type": "npm", "tag": "next" }, + "branch": { "type": "git", "url": "https://example.com/druxt.git", "ref": "main" } + } +} +``` + +- `--registry team` reads starters from that URL. `GIGET_AUTH` is giget's own variable, and giget sends it as a bearer token with every tarball it downloads. The CLI also sends it to a registry you name, and never to the public registry. +- `--source` takes `npm`, `git:#`, or a name defined here. Only `npm` creates a site in this version. The others are read and answer that they are not available yet. + +## Not there yet + +- The `split` and `workspace` layouts. `--layout` accepts them and fails with a message. +- Sources other than `npm`. +- Adding a module, making a wrapper component and upgrading a site. +- Kinds other than `nuxt` and `drupal`. +- A published public registry. Until this repository is public, `init` reads the copy in the package. + +## Development + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +```bash +npm install +npm run build +npm test +``` + +## Licence + +[MIT](LICENSE) diff --git a/package-lock.json b/package-lock.json index 7f2edd2..51d69ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -61,7 +61,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -71,7 +71,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -81,7 +81,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.29.14" @@ -97,7 +97,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.14", @@ -388,7 +388,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 +402,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", @@ -3396,6 +3394,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 +3541,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 +3619,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 +3966,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 +3982,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 +4013,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 +4337,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 +4408,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 +4440,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 +4621,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 +4940,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 +5461,7 @@ "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -6198,6 +6286,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 +6489,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 +6521,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 +6655,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 +6675,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", @@ -6696,7 +6842,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 +6877,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -7328,6 +7473,12 @@ "name": "@druxt/cli", "version": "0.0.0", "license": "MIT", + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" + }, "bin": { "drx": "dist/bin.js" }, @@ -7338,6 +7489,9 @@ "packages/create-druxt": { "version": "0.0.0", "license": "MIT", + "dependencies": { + "@druxt/cli": "^0.0.0" + }, "bin": { "create-druxt": "dist/bin.js" }, diff --git a/packages/cli/LICENSE b/packages/cli/LICENSE new file mode 100644 index 0000000..51b53d2 --- /dev/null +++ b/packages/cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DruxtJS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..335895d --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,21 @@ +# @druxt/cli + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +```bash +npx @druxt/cli init my-site +npx @druxt/cli info +``` + +The binary is `drx`. Install the package in a project to use that name: `npm install -D @druxt/cli`, then `drx ` in a package script. `npx drx` without the package installed downloads another package that holds the name on npm. + +| Command | What it does | +| ---------------- | ------------------------------------------------------------------------- | +| `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | +| `drx info` | Prints the versions of the CLI, Node and the packages of each part | + +The options, the registry format and the configuration files are in the [repository README](https://github.com/druxt/cli#readme). + +## Licence + +[MIT](LICENSE) diff --git a/packages/cli/package.json b/packages/cli/package.json index 4749cba..5784807 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -36,5 +36,11 @@ }, "publishConfig": { "access": "public" + }, + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts new file mode 100644 index 0000000..623b547 --- /dev/null +++ b/packages/cli/src/adapters/adapter.ts @@ -0,0 +1,33 @@ +import { DrxError } from '../errors.js' +import type { Role } from '../parts.js' + +/** One package a part depends on. */ +export interface PackageVersion { + name: string + /** The range the part asks for, or null when it does not declare one. */ + range: string | null + /** The version that is installed, or null when none is. */ + installed: string | null +} + +/** + * Everything the CLI knows about one kind of part. The commands call this + * interface and never a kind by name, so a new kind is a new file in this + * directory and one line in index.ts. + */ +export interface KindAdapter { + /** The value a part's `kind` holds. */ + readonly kind: string + readonly role: Role + /** True when the directory holds a part of this kind. */ + detect(dir: string): Promise + /** The packages `info` reports for a part of this kind. */ + packages(dir: string): Promise + /** Installs a module into the part and registers it. Not available yet. */ + addModule(dir: string, name: string): Promise +} + +/** The `addModule` of every adapter until the `add` command exists. */ +export async function addModuleNotAvailable(): Promise { + throw new DrxError('not-available', 'Adding a module is not available yet.') +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts new file mode 100644 index 0000000..e043157 --- /dev/null +++ b/packages/cli/src/adapters/drupal.ts @@ -0,0 +1,60 @@ +import { join } from 'node:path' +import { isRecord } from '../validate.js' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +/** Any of these in `require` makes a Composer project a Drupal site. */ +const CORE = ['drupal/core-recommended', 'drupal/core'] +const REPORTED = [...CORE, 'drupal/druxt'] + +async function required(dir: string): Promise> { + return stringMap(await readJsonObject(join(dir, 'composer.json')), 'require') +} + +/** The version of each package Composer has installed, which is none until `composer install` has run. */ +async function installed(dir: string): Promise> { + const manifest = await readJsonObject( + join(dir, 'vendor', 'composer', 'installed.json') + ) + const versions = new Map() + const packages = manifest?.packages + if (!Array.isArray(packages)) return versions + for (const entry of packages) { + if ( + isRecord(entry) && + typeof entry.name === 'string' && + typeof entry.version === 'string' + ) { + versions.set(entry.name, entry.version) + } + } + return versions +} + +export const drupalAdapter: KindAdapter = { + kind: 'drupal', + role: 'backend', + + async detect(dir) { + const requires = await required(dir) + return CORE.some((name) => name in requires) + }, + + async packages(dir) { + const requires = await required(dir) + const versions = await installed(dir) + return REPORTED.filter((name) => name in requires).map( + (name): PackageVersion => ({ + name, + range: requires[name] ?? null, + installed: versions.get(name) ?? null, + }) + ) + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/index.ts b/packages/cli/src/adapters/index.ts new file mode 100644 index 0000000..e8dfaef --- /dev/null +++ b/packages/cli/src/adapters/index.ts @@ -0,0 +1,16 @@ +import type { KindAdapter } from './adapter.js' +import { drupalAdapter } from './drupal.js' +import { nuxtAdapter } from './nuxt.js' + +export type { KindAdapter, PackageVersion } from './adapter.js' + +/** Every kind this version knows. A new kind is a new file and a line here. */ +const ADAPTERS: readonly KindAdapter[] = [nuxtAdapter, drupalAdapter] + +export function adapterFor(kind: string): KindAdapter | undefined { + return ADAPTERS.find((adapter) => adapter.kind === kind) +} + +export function knownKinds(): string[] { + return ADAPTERS.map((adapter) => adapter.kind) +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts new file mode 100644 index 0000000..aa62f99 --- /dev/null +++ b/packages/cli/src/adapters/nuxt.ts @@ -0,0 +1,59 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +const CONFIG_FILES = ['js', 'ts', 'mjs', 'cjs', 'mts'].map( + (extension) => `nuxt.config.${extension}` +) + +/** The framework itself, then the Druxt packages of either naming scheme. */ +const FRAMEWORK = 'nuxt' +const DRUXT_PACKAGE = /^(druxt|druxt-.+|@druxt\/.+)$/ + +async function declared(dir: string): Promise> { + const manifest = await readJsonObject(join(dir, 'package.json')) + return { + ...stringMap(manifest, 'devDependencies'), + ...stringMap(manifest, 'dependencies'), + } +} + +export const nuxtAdapter: KindAdapter = { + kind: 'nuxt', + role: 'frontend', + + async detect(dir) { + if (CONFIG_FILES.some((file) => existsSync(join(dir, file)))) return true + return FRAMEWORK in (await declared(dir)) + }, + + async packages(dir) { + const ranges = await declared(dir) + const names = Object.keys(ranges) + .filter((name) => name === FRAMEWORK || DRUXT_PACKAGE.test(name)) + .sort((a, b) => + a === FRAMEWORK ? -1 : b === FRAMEWORK ? 1 : a.localeCompare(b) + ) + + const versions: PackageVersion[] = [] + for (const name of names) { + const installed = await readJsonObject( + join(dir, 'node_modules', name, 'package.json') + ) + versions.push({ + name, + range: ranges[name] ?? null, + installed: + typeof installed?.version === 'string' ? installed.version : null, + }) + } + return versions + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/read-json.ts b/packages/cli/src/adapters/read-json.ts new file mode 100644 index 0000000..11b6f00 --- /dev/null +++ b/packages/cli/src/adapters/read-json.ts @@ -0,0 +1,28 @@ +import { readFile } from 'node:fs/promises' +import { isRecord } from '../validate.js' + +/** A JSON file's object, or undefined when it is missing or not an object. */ +export async function readJsonObject( + file: string +): Promise | undefined> { + try { + const parsed: unknown = JSON.parse(await readFile(file, 'utf8')) + return isRecord(parsed) ? parsed : undefined + } catch { + return undefined + } +} + +/** The string values of one key of an object, such as `dependencies`. */ +export function stringMap( + object: Record | undefined, + key: string +): Record { + const value = object?.[key] + if (!isRecord(value)) return {} + return Object.fromEntries( + Object.entries(value).filter( + (entry): entry is [string, string] => typeof entry[1] === 'string' + ) + ) +} diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts new file mode 100644 index 0000000..f4e9ecc --- /dev/null +++ b/packages/cli/src/args.ts @@ -0,0 +1,33 @@ +import type { ArgsDef } from 'citty' +import { DrxError } from './errors.js' + +/** + * Fails on an option the command does not define. citty accepts any flag + * and hands it to the command, so a mistyped one would otherwise be ignored. + */ +export function assertKnownOptions( + rawArgs: string[], + definitions: ArgsDef, + command: string +): void { + const known = new Set() + for (const [name, definition] of Object.entries(definitions)) { + if (definition.type === 'positional') continue + known.add(name) + if (definition.type === 'boolean') known.add(`no-${name}`) + const alias = 'alias' in definition ? definition.alias : undefined + for (const short of [alias ?? []].flat()) known.add(short) + } + + for (const argument of rawArgs) { + if (argument === '--') return + if (!argument.startsWith('-') || argument === '-') continue + const name = argument.replace(/^--?/, '').split('=')[0] ?? '' + if (!known.has(name)) { + throw new DrxError( + 'usage', + `Unknown option ${argument.split('=')[0]}. Run "drx ${command} --help" for the options.` + ) + } + } +} diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts new file mode 100644 index 0000000..a566d17 --- /dev/null +++ b/packages/cli/src/bin.ts @@ -0,0 +1,4 @@ +#!/usr/bin/env node +import { runCli } from './cli.js' + +process.exitCode = await runCli(process.argv.slice(2)) diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts new file mode 100644 index 0000000..44f075e --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,97 @@ +import { stripVTControlCharacters } from 'node:util' +import { defineCommand, renderUsage, runCommand, type CommandDef } from 'citty' +import { infoCommand } from './commands/info.js' +import { initCommand } from './commands/init.js' +import { defaultContext, type CliContext, type TextStream } from './context.js' +import { DrxError } from './errors.js' +import { cliVersion } from './package-root.js' + +function mainCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'drx', + version: cliVersion(), + description: 'The Druxt command-line tool', + }, + subCommands: { + init: initCommand(context), + info: infoCommand(context), + }, + }) +} + +/** citty colours its output whatever it writes to. A pipe gets plain text. */ +function plain(stream: TextStream, text: string): string { + return stream.isTTY ? text : stripVTControlCharacters(text) +} + +/** The usage of the command the arguments name, or of `drx` itself. */ +async function usage( + main: CommandDef, + subCommands: Record, + argv: string[] +): Promise { + const name = argv.find((argument) => !argument.startsWith('-')) + const command = name ? subCommands[name] : undefined + return command ? renderUsage(command, main) : renderUsage(main) +} + +/** The code and message to report for anything a command throws. */ +function describe(error: unknown): { code: string; message: string } { + if (error instanceof DrxError) { + return { code: error.code, message: error.message } + } + // citty's own error for a bad argument or command. The class is not + // exported, so it is recognised by name. + if (error instanceof Error && error.name === 'CLIError') { + return { + code: 'usage', + message: `${stripVTControlCharacters(error.message)}. Run "drx --help" for the commands and "drx --help" for their options.`, + } + } + return { + code: 'unexpected', + message: + error instanceof Error ? (error.stack ?? error.message) : String(error), + } +} + +/** + * Runs the CLI with the given arguments and returns the exit code. It never + * exits the process or throws, so a caller decides what to do with the code. + */ +export async function runCli( + argv: string[], + overrides: Partial = {} +): Promise { + const context = { ...defaultContext(), ...overrides } + const main = mainCommand(context) + const subCommands = main.subCommands as Record + const { stdout, stderr } = context + + try { + if (argv.includes('--help') || argv.includes('-h')) { + stdout.write(`${plain(stdout, await usage(main, subCommands, argv))}\n`) + return 0 + } + if (argv.length === 1 && ['--version', '-v'].includes(argv[0] ?? '')) { + stdout.write(`${cliVersion()}\n`) + return 0 + } + if (argv.length === 0) { + stderr.write(`${plain(stderr, await renderUsage(main))}\n`) + return 1 + } + await runCommand(main, { rawArgs: argv }) + return 0 + } catch (error) { + const failure = describe(error) + if (argv.includes('--json')) { + stdout.write( + `${JSON.stringify({ ok: false, error: failure }, null, 2)}\n` + ) + } + stderr.write(`Error: ${failure.message}\n`) + return 1 + } +} diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts new file mode 100644 index 0000000..8cf8775 --- /dev/null +++ b/packages/cli/src/commands/info.ts @@ -0,0 +1,133 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { adapterFor, type PackageVersion } from '../adapters/index.js' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { columns, createOutput } from '../output.js' +import { cliVersion } from '../package-root.js' +import type { Part } from '../parts.js' +import { + CONFIG_FILE, + findProjectRoot, + loadProjectConfig, + type ProjectConfig, +} from '../project.js' + +interface PartReport extends Part { + /** False when the part's directory is not there. */ + exists: boolean + /** True when the adapter for its kind recognises the directory. */ + detected: boolean + packages: PackageVersion[] +} + +interface InfoReport { + cli: { name: string; version: string } + node: string + project: + | (Omit & { + root: string + parts: PartReport[] + }) + | null +} + +async function reportPart(root: string, part: Part): Promise { + const dir = join(root, part.path) + const adapter = adapterFor(part.kind) + const exists = existsSync(dir) + const detected = exists && adapter ? await adapter.detect(dir) : false + return { + ...part, + exists, + detected, + packages: detected && adapter ? await adapter.packages(dir) : [], + } +} + +function partLines(part: PartReport): string[] { + const heading = `${part.role} ${part.kind} ${part.path}/` + if (!adapterFor(part.kind)) { + return [heading, ` This version has no adapter for the ${part.kind} kind.`] + } + if (!part.exists) return [heading, ' The directory does not exist.'] + if (!part.detected) { + return [heading, ` The directory does not look like a ${part.kind} part.`] + } + if (part.packages.length === 0) { + return [heading, ' No packages to report.'] + } + const rows = part.packages.map((entry) => [ + entry.name, + entry.range ?? '', + entry.installed ? `installed ${entry.installed}` : 'not installed', + ]) + return [heading, ...columns(rows, ' ')] +} + +function text(report: InfoReport, cwd: string): string { + const lines = columns([ + ['drx', report.cli.version], + ['Node', report.node], + ]) + lines.push('') + const project = report.project + if (!project) { + lines.push( + `Not inside a Druxt project: no ${CONFIG_FILE} in ${cwd} or above it.` + ) + return lines.join('\n') + } + lines.push( + ...columns([ + ['Project', project.root], + ['Layout', project.layout], + ['Line', project.line], + ['Starter', project.starter], + ['Source', project.source], + ]) + ) + for (const part of project.parts) { + lines.push('', ...partLines(part)) + } + return lines.join('\n') +} + +const args = { + json: { + type: 'boolean', + description: 'Print the report as JSON on stdout', + }, +} satisfies ArgsDef + +export function infoCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'info', + description: + 'Print the versions of the CLI, Node and the packages of each part of the project', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'info') + const output = createOutput(context, parsed.json === true) + + const report: InfoReport = { + cli: { name: '@druxt/cli', version: cliVersion() }, + node: context.nodeVersion, + project: null, + } + const root = findProjectRoot(context.cwd) + if (root) { + const config = await loadProjectConfig(root) + const parts: PartReport[] = [] + for (const part of config.parts) { + parts.push(await reportPart(root, part)) + } + report.project = { root, ...config, parts } + } + output.result(report, text(report, context.cwd)) + }, + }) +} diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts new file mode 100644 index 0000000..f23fb2e --- /dev/null +++ b/packages/cli/src/commands/init.ts @@ -0,0 +1,382 @@ +import { existsSync, readdirSync, statSync } from 'node:fs' +import { isAbsolute, join, relative, resolve } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + assertLayoutAvailable, + AVAILABLE_LAYOUTS, + isLayout, + LAYOUTS, + type Layout, +} from '../layouts.js' +import { createOutput, type Output } from '../output.js' +import { writeProjectConfig, type ProjectConfig } from '../project.js' +import type { StarterEntry } from '../registry/entry.js' +import { + defaultStarter, + openRegistry, + type Registry, +} from '../registry/registry.js' +import { + assertSourceAvailable, + DEFAULT_SOURCE, + resolveSource, +} from '../sources.js' +import { loadUserConfig, resolveRegistryUrl } from '../user-config.js' + +/** A starter not maintained for this long gets a warning. */ +const STALE_AFTER_DAYS = 365 + +const args = { + dir: { + type: 'positional', + required: false, + description: 'The directory to create the site in', + }, + starter: { + type: 'string', + valueHint: 'name', + description: + 'The starter to create the site from (default: the default of the registry)', + }, + layout: { + type: 'enum', + options: [...LAYOUTS], + description: `How the parts of the site are put together (available: ${AVAILABLE_LAYOUTS.join(', ')})`, + }, + registry: { + type: 'string', + valueHint: 'url', + description: + 'A starter registry: a URL, or a name from the user configuration', + }, + source: { + type: 'string', + valueHint: 'name', + description: `Where the Druxt packages come from (default: ${DEFAULT_SOURCE})`, + }, + install: { + type: 'boolean', + description: 'Install the dependencies of the site after creating it', + negativeDescription: 'Do not install the dependencies of the site', + }, + force: { + type: 'boolean', + description: 'Write into a directory that exists and is not empty', + }, + yes: { + type: 'boolean', + alias: 'y', + description: 'Accept the default for everything not given, and ask nothing', + }, + json: { + type: 'boolean', + description: 'Print the result as JSON on stdout', + }, +} satisfies ArgsDef + +interface InitOptions { + dir?: string + starter?: string + layout?: Layout + registry?: string + source?: string + install?: boolean + force: boolean + yes: boolean +} + +/** A string option's value, or an error when it was given with none. */ +function valueOf(name: string, value: unknown): string | undefined { + if (value === undefined) return undefined + if (typeof value !== 'string' || value.trim() === '') { + throw new DrxError('usage', `--${name} needs a value.`) + } + return value +} + +async function chooseStarter( + registry: Registry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + if (options.starter) return registry.entry(options.starter) + + const names = await registry.names() + if (canAsk && names.length > 1) { + const chosen = await context.prompter.select({ + message: 'Which starter?', + choices: names.map((name) => ({ value: name, label: name })), + }) + return registry.entry(chosen) + } + + const entry = await defaultStarter(registry) + if (!entry) { + throw new DrxError( + 'unknown-starter', + `The registry marks no starter as the default. Pass --starter with one of: ${names.join(', ')}.` + ) + } + return entry +} + +async function chooseLayout( + entry: StarterEntry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + const own = entry.druxt.layout + let layout = options.layout + if (!layout && canAsk) { + layout = await context.prompter.select({ + message: 'Which layout?', + choices: LAYOUTS.map((value) => ({ + value, + label: value, + ...(AVAILABLE_LAYOUTS.includes(value) + ? {} + : { hint: 'not available yet' }), + })), + initial: own, + }) + } + layout ??= own + assertLayoutAvailable(layout) + if (layout !== own) { + throw new DrxError( + 'not-available', + `The ${entry.name} starter has the ${own} layout and cannot be created as ${layout}.` + ) + } + return layout +} + +/** The directory to create, checked against what is already there. */ +function targetDirectory(cwd: string, dir: string, force: boolean): string { + const target = resolve(cwd, dir) + if (!existsSync(target)) return target + if (!statSync(target).isDirectory()) { + throw new DrxError( + 'directory-not-empty', + `${target} is a file, not a directory.` + ) + } + if (!force && readdirSync(target).length > 0) { + throw new DrxError( + 'directory-not-empty', + `${target} exists and is not empty. Choose another directory, or pass --force to write into it.` + ) + } + return target +} + +/** True when `running` is the version `needed` names, or one inside it. */ +function nodeSatisfies(running: string, needed: string): boolean { + const version = needed.replace(/^v/, '') + return running === version || running.startsWith(`${version}.`) +} + +function warnAboutStarter( + entry: StarterEntry, + target: string, + context: CliContext, + output: Output +): void { + const { requires, maintained, parts } = entry.druxt + if (!nodeSatisfies(context.nodeVersion, requires.node)) { + output.warn( + `The ${entry.name} starter needs Node ${requires.node} and this is Node ${context.nodeVersion}. Switch before you install or run the site.` + ) + } + const age = context.now().getTime() - new Date(maintained).getTime() + if (age > STALE_AFTER_DAYS * 24 * 60 * 60 * 1000) { + output.warn( + `The ${entry.name} starter was last maintained on ${maintained} and may no longer work.` + ) + } + for (const part of parts) { + if (!existsSync(join(target, part.path))) { + output.warn( + `The starter has no ${part.path}/ directory, which its registry entry names as the ${part.role} part.` + ) + } + } +} + +async function runInit( + options: InitOptions, + context: CliContext, + output: Output +): Promise { + const canAsk = context.interactive && !options.yes + if (!options.dir && !canAsk && !options.yes) { + throw new DrxError( + 'usage', + 'No directory was given and there is no terminal to ask on. Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.' + ) + } + + // Everything that can fail without the network is checked before it is used. + const userConfig = await loadUserConfig(context.env) + const source = resolveSource(options.source ?? DEFAULT_SOURCE, userConfig) + assertSourceAvailable(source) + if (options.layout) assertLayoutAvailable(options.layout) + const registryUrl = options.registry + ? resolveRegistryUrl(options.registry, userConfig) + : undefined + + const registry = await openRegistry({ + ...(registryUrl ? { url: registryUrl } : {}), + defaultUrl: context.defaultRegistry, + bundledDir: context.bundledRegistryDir, + fetch: context.fetch, + ...(context.env.GIGET_AUTH ? { auth: context.env.GIGET_AUTH } : {}), + }) + if (registry.origin === 'bundled') { + output.note(`${registry.fallbackReason}`) + output.note('Reading starters from the copy bundled with this version.') + } else { + output.note(`Reading starters from ${registry.location}.`) + } + + const entry = await chooseStarter(registry, options, context, canAsk) + const layout = await chooseLayout(entry, options, context, canAsk) + + const defaultDir = entry.defaultDir ?? entry.name + const dir = + options.dir ?? + (canAsk + ? await context.prompter.text({ + message: 'Where should the site be created?', + initial: defaultDir, + }) + : defaultDir) + const target = targetDirectory(context.cwd, dir, options.force) + + const install = + options.install ?? + (canAsk + ? await context.prompter.confirm({ + message: 'Install its dependencies now?', + initial: false, + }) + : false) + + output.note(`Fetching the ${entry.name} starter from ${entry.tar}.`) + try { + await context.download(`starter:${entry.name}`, { + // The entry is already read and checked, so giget is handed it as it + // is and looks nothing up. + providers: { + starter: () => ({ + name: entry.name, + tar: entry.tar, + ...(entry.subdir ? { subdir: entry.subdir } : {}), + ...(entry.headers ? { headers: entry.headers } : {}), + }), + }, + registry: false, + dir: target, + // The directory was checked above, with --force taken into account. + force: true, + silent: true, + }) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'download', + `Could not fetch the ${entry.name} starter: ${detail}` + ) + } + + const config: ProjectConfig = { + layout, + line: entry.druxt.line, + starter: entry.name, + source: source.name, + parts: entry.druxt.parts, + } + await writeProjectConfig(target, config) + warnAboutStarter(entry, target, context, output) + + if (install) { + output.note('Installing dependencies.') + try { + await context.install(target) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'install', + `The site was created in ${target}, but installing its dependencies failed: ${detail}` + ) + } + } + + const fromCwd = relative(context.cwd, target) + const inside = fromCwd !== '' && !fromCwd.startsWith('..') + const next = [ + `cd ${inside && !isAbsolute(fromCwd) ? fromCwd : target}`, + ...(entry.druxt.steps ?? []), + ] + const { requires } = entry.druxt + + output.result( + { + ok: true, + directory: target, + registry: { origin: registry.origin, location: registry.location }, + ...config, + installed: install, + requires, + next, + }, + [ + `Created a Druxt site in ${target} from the ${entry.name} starter.`, + '', + 'It needs:', + ` Node ${requires.node}`, + ...requires.tools.map((tool) => ` ${tool}`), + '', + 'Next:', + ...next.map((step) => ` ${step}`), + ].join('\n') + ) +} + +export function initCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'init', + description: 'Create a Druxt site from a starter', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'init') + const options: InitOptions = { + force: parsed.force === true, + yes: parsed.yes === true, + } + const dir = valueOf('dir', parsed.dir) + const starter = valueOf('starter', parsed.starter) + const registry = valueOf('registry', parsed.registry) + const source = valueOf('source', parsed.source) + if (dir) options.dir = dir + if (starter) options.starter = starter + if (registry) options.registry = registry + if (source) options.source = source + if (isLayout(parsed.layout)) options.layout = parsed.layout + if (typeof parsed.install === 'boolean') options.install = parsed.install + + await runInit( + options, + context, + createOutput(context, parsed.json === true) + ) + }, + }) +} diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts new file mode 100644 index 0000000..b4458d8 --- /dev/null +++ b/packages/cli/src/context.ts @@ -0,0 +1,74 @@ +import { downloadTemplate } from 'giget' +import { installDependencies } from './install.js' +import { bundledRegistryDir } from './package-root.js' +import { terminalPrompter } from './prompts.js' +import { DEFAULT_REGISTRY } from './registry/registry.js' + +/** The part of a stream the CLI writes to. */ +export interface TextStream { + write(chunk: string): unknown + isTTY?: boolean +} + +export interface Choice { + value: T + label: string + hint?: string +} + +/** The questions a command may ask a person at the terminal. */ +export interface Prompter { + text(question: { message: string; initial?: string }): Promise + select(question: { + message: string + choices: Choice[] + initial?: T + }): Promise + confirm(question: { message: string; initial: boolean }): Promise +} + +/** + * Everything a command takes from the process it runs in. The tests pass + * their own, so no command reads `process` directly. + */ +export interface CliContext { + cwd: string + env: Record + /** The result of a command: its text, or its JSON with `--json`. */ + stdout: TextStream + /** Progress, warnings, errors and prompts. */ + stderr: TextStream + /** True when a person is at the terminal to answer a prompt. */ + interactive: boolean + /** The running Node version, without the leading `v`. */ + nodeVersion: string + now: () => Date + fetch: typeof fetch + prompter: Prompter + /** The registry used when `--registry` is not given. */ + defaultRegistry: string + /** The copy of the registry used when the default cannot be read. */ + bundledRegistryDir: string + /** Fetches and unpacks a template. giget's `downloadTemplate`. */ + download: typeof downloadTemplate + /** Installs the dependencies of the site in a directory. */ + install: (dir: string) => Promise +} + +export function defaultContext(): CliContext { + return { + cwd: process.cwd(), + env: process.env, + stdout: process.stdout, + stderr: process.stderr, + interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY), + nodeVersion: process.versions.node, + now: () => new Date(), + fetch: globalThis.fetch, + prompter: terminalPrompter(), + defaultRegistry: DEFAULT_REGISTRY, + bundledRegistryDir: bundledRegistryDir(), + download: downloadTemplate, + install: (dir) => installDependencies(dir), + } +} diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..ef3e6ee --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,27 @@ +/** What went wrong, for a caller reading `--json` output. */ +export type DrxErrorCode = + | 'usage' + | 'not-available' + | 'registry' + | 'invalid-entry' + | 'unknown-starter' + | 'unknown-source' + | 'directory-not-empty' + | 'config' + | 'download' + | 'install' + | 'cancelled' + +/** + * A failure the user can act on. Its message is printed as it is, with no + * stack trace, and the process exits non-zero. + */ +export class DrxError extends Error { + readonly code: DrxErrorCode + + constructor(code: DrxErrorCode, message: string) { + super(message) + this.name = 'DrxError' + this.code = code + } +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 0000000..90930bb --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,11 @@ +export { runCli } from './cli.js' +export type { CliContext, Prompter } from './context.js' +export { DrxError, type DrxErrorCode } from './errors.js' +export type { KindAdapter, PackageVersion } from './adapters/index.js' +export type { Layout } from './layouts.js' +export type { Part, Role } from './parts.js' +export type { ProjectConfig } from './project.js' +export type { StarterDetails, StarterEntry } from './registry/entry.js' +export { DEFAULT_REGISTRY } from './registry/registry.js' +export type { Source, SourceDefinition } from './sources.js' +export type { UserConfig } from './user-config.js' diff --git a/packages/cli/src/install.ts b/packages/cli/src/install.ts new file mode 100644 index 0000000..221ab27 --- /dev/null +++ b/packages/cli/src/install.ts @@ -0,0 +1,54 @@ +import { spawn } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' + +const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const +type Manager = (typeof MANAGERS)[number] + +/** + * The package manager a directory declares in the `packageManager` field of + * its package.json, or npm when it declares none. Undefined when there is no + * package.json to install from. + */ +export async function packageManagerOf( + dir: string +): Promise { + let manifest: { packageManager?: unknown } + try { + manifest = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) + } catch { + return undefined + } + const declared = String(manifest.packageManager ?? '').split('@')[0] + return MANAGERS.find((manager) => manager === declared) ?? 'npm' +} + +/** + * Runs the install of the directory's package manager. Its output goes to + * stderr, so the stdout of the CLI stays the result of the command. + */ +export async function installDependencies( + dir: string, + env: NodeJS.ProcessEnv = process.env +): Promise { + const manager = await packageManagerOf(dir) + if (!manager) { + throw new Error(`${dir} has no package.json to install from`) + } + await new Promise((resolve, reject) => { + const child = spawn(manager, ['install'], { + cwd: dir, + env, + stdio: ['ignore', process.stderr, process.stderr], + shell: process.platform === 'win32', + }) + child.on('error', (error) => + reject(new Error(`${manager} install could not start: ${error.message}`)) + ) + child.on('close', (code) => + code === 0 + ? resolve() + : reject(new Error(`${manager} install exited with code ${code}`)) + ) + }) +} diff --git a/packages/cli/src/layouts.ts b/packages/cli/src/layouts.ts new file mode 100644 index 0000000..ce61241 --- /dev/null +++ b/packages/cli/src/layouts.ts @@ -0,0 +1,24 @@ +import { DrxError } from './errors.js' + +/** + * How the parts of a site are put together: one repository, a repository per + * part, or a parent repository with each part as a submodule. + */ +export const LAYOUTS = ['monorepo', 'split', 'workspace'] as const +export type Layout = (typeof LAYOUTS)[number] + +/** The layouts `init` can create. */ +export const AVAILABLE_LAYOUTS: readonly Layout[] = ['monorepo'] + +export function isLayout(value: unknown): value is Layout { + return LAYOUTS.includes(value as Layout) +} + +export function assertLayoutAvailable(layout: Layout): void { + if (!AVAILABLE_LAYOUTS.includes(layout)) { + throw new DrxError( + 'not-available', + `The ${layout} layout is not available yet. Use --layout ${AVAILABLE_LAYOUTS.join(' or ')}.` + ) + } +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts new file mode 100644 index 0000000..0fb5a58 --- /dev/null +++ b/packages/cli/src/output.ts @@ -0,0 +1,46 @@ +import type { CliContext } from './context.js' + +/** + * Where a command writes. The result goes to stdout: text, or JSON with + * `--json`. Everything said along the way goes to stderr, so stdout can be + * piped or parsed whichever form it takes. + */ +export interface Output { + readonly json: boolean + /** Progress, on stderr. */ + note(message: string): void + /** Something the user should know that does not stop the command. */ + warn(message: string): void + /** The result, on stdout. `text` is used unless `--json` was given. */ + result(data: unknown, text: string): void +} + +export function createOutput(context: CliContext, json: boolean): Output { + return { + json, + note: (message) => context.stderr.write(`${message}\n`), + warn: (message) => context.stderr.write(`Warning: ${message}\n`), + result: (data, text) => + context.stdout.write( + json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n` + ), + } +} + +/** Lines of cells, with every column padded to its widest cell. */ +export function columns(rows: string[][], indent = ''): string[] { + const widths: number[] = [] + for (const row of rows) { + for (const [index, cell] of row.entries()) { + widths[index] = Math.max(widths[index] ?? 0, cell.length) + } + } + return rows.map( + (row) => + indent + + row + .map((cell, index) => cell.padEnd(widths[index] ?? 0)) + .join(' ') + .trimEnd() + ) +} diff --git a/packages/cli/src/package-root.ts b/packages/cli/src/package-root.ts new file mode 100644 index 0000000..d845098 --- /dev/null +++ b/packages/cli/src/package-root.ts @@ -0,0 +1,39 @@ +import { existsSync, readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * The directory of this package, found from this file. The sources sit in + * src/ and the build in dist/, at different depths, so the nearest + * package.json is the fixed point. + */ +export function packageRoot(): string { + let dir = dirname(fileURLToPath(import.meta.url)) + while (!existsSync(join(dir, 'package.json'))) { + const parent = dirname(dir) + if (parent === dir) { + throw new Error('No package.json found above the CLI sources.') + } + dir = parent + } + return dir +} + +export function cliVersion(): string { + const manifest = JSON.parse( + readFileSync(join(packageRoot(), 'package.json'), 'utf8') + ) as { version: string } + return manifest.version +} + +/** + * The registry files that ship with the package. The build copies them into + * the package. In a checkout that has not been built they are read from the + * repository root. + */ +export function bundledRegistryDir(): string { + const root = packageRoot() + const packaged = join(root, 'starters') + if (existsSync(join(packaged, 'index.json'))) return packaged + return join(root, '..', '..', 'starters') +} diff --git a/packages/cli/src/parts.ts b/packages/cli/src/parts.ts new file mode 100644 index 0000000..881c2bf --- /dev/null +++ b/packages/cli/src/parts.ts @@ -0,0 +1,50 @@ +import { isNonEmptyString, isRecord } from './validate.js' + +export const ROLES = ['frontend', 'backend'] as const +export type Role = (typeof ROLES)[number] + +/** + * One side of a site. The role says what it is for and the kind says what it + * is built with. The kind is a plain string, so a new one needs an adapter + * and no change to this type. + */ +export interface Part { + role: Role + kind: string + /** Relative to the project root, with forward slashes. */ + path: string +} + +/** True for a path that stays inside the directory it is resolved against. */ +function isInsidePath(value: unknown): value is string { + if (!isNonEmptyString(value)) return false + if (value.startsWith('/') || /^[a-z]:/i.test(value)) return false + return !value.split(/[\\/]/).includes('..') +} + +/** + * The first problem with a list of parts, as "