From ca5c5d994f9fe1e97e944bf865190c6cb11d922c Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 03:53:08 +0100 Subject: [PATCH 01/21] Add a DreamCLI-native create command --- README.md | 12 + bin/dreamcli.mjs | 33 ++ deno.json | 4 +- docs/.vitepress/data/api-index.test.ts | 1 + docs/.vitepress/data/deno-doc.test.ts | 12 + package.json | 9 + skills/cli-creation/SKILL.md | 7 +- .../templates/multi-command.bun-test.ts.tpl | 20 - .../templates/multi-command.test.ts.tpl | 20 - .../assets/templates/multi-command.ts.tpl | 89 ----- .../templates/single-command.bun-test.ts.tpl | 29 -- .../templates/single-command.test.ts.tpl | 29 -- .../assets/templates/single-command.ts.tpl | 47 --- .../references/consumer-workflow.md | 7 +- .../cli-creation/references/runtime-notes.md | 6 +- skills/cli-creation/scripts/scaffold_cli.py | 368 ------------------ src/create.test.ts | 86 ++++ src/create.ts | 135 +++++++ src/create/templates.ts | 192 +++++++++ src/create/test-runner.ts | 85 ++++ tsconfig.json | 1 + tsdown.config.ts | 1 + 22 files changed, 579 insertions(+), 614 deletions(-) create mode 100755 bin/dreamcli.mjs delete mode 100644 skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl delete mode 100644 skills/cli-creation/assets/templates/multi-command.test.ts.tpl delete mode 100644 skills/cli-creation/assets/templates/multi-command.ts.tpl delete mode 100644 skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl delete mode 100644 skills/cli-creation/assets/templates/single-command.test.ts.tpl delete mode 100644 skills/cli-creation/assets/templates/single-command.ts.tpl delete mode 100755 skills/cli-creation/scripts/scaffold_cli.py create mode 100644 src/create.test.ts create mode 100644 src/create.ts create mode 100644 src/create/templates.ts create mode 100644 src/create/test-runner.ts diff --git a/README.md b/README.md index f213a9af..3dfdf84a 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,18 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli ## Quick start +Generate a starter CLI and a matching test in the current directory. + +```sh +npm exec --package=@kjanat/dreamcli -- dreamcli create mycli +bun ./mycli.ts --help +``` + +`dreamcli init` is an alias for `dreamcli create`. Use `--mode multi` for a +grouped CLI, `--out ` to place the files elsewhere, and `--no-test` +to skip the test. Use `--force` to replace existing starter files. To generate +the same files from code, import `scaffold` from `@kjanat/dreamcli/create`. + ### Single command ```ts diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs new file mode 100755 index 00000000..5d20a123 --- /dev/null +++ b/bin/dreamcli.mjs @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +/** DreamCLI's package executable. @module */ + +import { arg, cli, command, flag } from '@kjanat/dreamcli'; +import { scaffold } from '@kjanat/dreamcli/create'; +import { DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; + +const create = command('create') + .alias('init') + .description('Generate a DreamCLI starter') + .arg('name', arg.string().required().describe('Name of the CLI')) + .flag('mode', flag.enum(['single', 'multi']).default('single').describe('Starter layout')) + .flag('out', flag.string().default('.').describe('Output directory')) + .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) + .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) + .action(({ args, flags, out }) => { + const result = scaffold({ name: args.name, ...flags }); + if (out.jsonMode) { + out.json(result); + return; + } + out.log(`Created ${result.entry}`); + if (result.test !== undefined) { + out.log(`Created ${result.test} (${result.testRunner})`); + } + }); + +await cli('dreamcli') + .version(DREAMCLI_VERSION) + .description('Create a project with DreamCLI') + .command(create) + .run(); diff --git a/deno.json b/deno.json index 5689b1d9..70f40d56 100644 --- a/deno.json +++ b/deno.json @@ -6,7 +6,7 @@ "tasks": { "check": { "description": "Type-check source with Deno's checker (may conflict with @types/node)", - "command": "deno check src/index.ts src/completion.ts src/config.ts src/json-schema.ts src/prompt.ts src/runtime.ts src/schema.ts src/testkit.ts src/version.ts" + "command": "deno check src/index.ts src/completion.ts src/config.ts src/create.ts src/json-schema.ts src/prompt.ts src/runtime.ts src/schema.ts src/testkit.ts src/version.ts" }, "smoke": { "description": "Run Deno adapter smoke test against source via import map", @@ -42,6 +42,7 @@ "./version": "./src/version.ts", "./completion": "./src/completion.ts", "./config": "./src/config.ts", + "./create": "./src/create.ts", "./json-schema": "./src/json-schema.ts", "./prompt": "./src/prompt.ts" }, @@ -57,6 +58,7 @@ "@kjanat/dreamcli/package.json": ["./package.json"], "@kjanat/dreamcli/completion": ["./src/completion.ts"], "@kjanat/dreamcli/config": ["./src/config.ts"], + "@kjanat/dreamcli/create": ["./src/create.ts"], "@kjanat/dreamcli/json-schema": ["./src/json-schema.ts"], "@kjanat/dreamcli/prompt": ["./src/prompt.ts"] } diff --git a/docs/.vitepress/data/api-index.test.ts b/docs/.vitepress/data/api-index.test.ts index 56052823..107e04b7 100644 --- a/docs/.vitepress/data/api-index.test.ts +++ b/docs/.vitepress/data/api-index.test.ts @@ -17,6 +17,7 @@ describe('api-index', () => { '@kjanat/dreamcli', '@kjanat/dreamcli/completion', '@kjanat/dreamcli/config', + '@kjanat/dreamcli/create', '@kjanat/dreamcli/json-schema', '@kjanat/dreamcli/prompt', '@kjanat/dreamcli/runtime', diff --git a/docs/.vitepress/data/deno-doc.test.ts b/docs/.vitepress/data/deno-doc.test.ts index b694a578..1bffe001 100644 --- a/docs/.vitepress/data/deno-doc.test.ts +++ b/docs/.vitepress/data/deno-doc.test.ts @@ -169,6 +169,18 @@ describe('deno doc normalization', () => { exportIds: expect.arrayContaining(['@kjanat/dreamcli/config:discoverConfig']), missingExports: [], }, + { + entrypoint: '@kjanat/dreamcli/create', + subpath: './create', + sourcePath: 'src/create.ts', + hasDocumentation: true, + exportIds: expect.arrayContaining([ + '@kjanat/dreamcli/create:scaffold', + '@kjanat/dreamcli/create:ScaffoldOptions', + '@kjanat/dreamcli/create:ScaffoldResult', + ]), + missingExports: [], + }, { entrypoint: '@kjanat/dreamcli/json-schema', subpath: './json-schema', diff --git a/package.json b/package.json index 7f3a3047..3c0ffc6f 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "#dreamcli": "./src/index.ts", "#dreamcli/completion": "./src/completion.ts", "#dreamcli/config": "./src/config.ts", + "#dreamcli/create": "./src/create.ts", "#dreamcli/json-schema": "./src/json-schema.ts", "#dreamcli/prompt": "./src/prompt.ts", "#dreamcli/runtime": "./src/runtime.ts", @@ -57,6 +58,10 @@ "types": "./dist/config.d.mts", "default": "./dist/config.mjs" }, + "./create": { + "types": "./dist/create.d.mts", + "default": "./dist/create.mjs" + }, "./json-schema": { "types": "./dist/json-schema.d.mts", "default": "./dist/json-schema.mjs" @@ -80,7 +85,11 @@ "./package.json": "./package.json", "./schema": "./dreamcli.schema.json" }, + "bin": { + "dreamcli": "./bin/dreamcli.mjs" + }, "files": [ + "bin", "dist", "dreamcli.schema.json", "skills", diff --git a/skills/cli-creation/SKILL.md b/skills/cli-creation/SKILL.md index f2406a86..f1973ba3 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/cli-creation/SKILL.md @@ -26,11 +26,11 @@ both. - `single`: one root command (`cli(name).default(command)`). - `multi`: grouped command surface (`group('...').command(...)`). 2. Generate starter files: - - `python scripts/scaffold_cli.py --name mycli --mode single --out .` + - `bunx --package @kjanat/dreamcli dreamcli create mycli --mode single --out .` - Tests are generated by default; add `--no-test` only when explicitly requested. - Test template is auto-detected: Bun without Vitest uses `bun:test`; otherwise Vitest. 3. Run and validate generated files: - - Use the printed path from the scaffolder output, for example `bun ./mycli.ts --help`. + - Run the generated entrypoint, for example `bun ./mycli.ts --help`. - Run the generated test unless `--no-test` was used. 4. Extend behavior with references: - `references/pattern-cookbook.md` — copy-ready, type-checked snippets. @@ -189,8 +189,7 @@ Assert output including trailing newlines. ## Resource Map -- `scripts/scaffold_cli.py` — generate Bun-first starter files and tests. -- `assets/templates/*.tpl` — source templates used by the scaffolder. +- `dreamcli create` (alias `dreamcli init`) — generate Bun-first starter files and tests. - `references/pattern-cookbook.md` — snippets by topic; all type-checked. - `references/consumer-workflow.md` — end-to-end flow from request to validation. - `references/runtime-notes.md` — runtime and package-manager execution guidance. diff --git a/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl b/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl deleted file mode 100644 index 5f9b6a30..00000000 --- a/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl +++ /dev/null @@ -1,20 +0,0 @@ -import { partyStart } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'bun:test'; - -describe('party start command', () => { - it('applies sparkle middleware when --sparkle is set', async () => { - const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(partyStart, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Start the pony party'); - }); -}); diff --git a/skills/cli-creation/assets/templates/multi-command.test.ts.tpl b/skills/cli-creation/assets/templates/multi-command.test.ts.tpl deleted file mode 100644 index e53a4b66..00000000 --- a/skills/cli-creation/assets/templates/multi-command.test.ts.tpl +++ /dev/null @@ -1,20 +0,0 @@ -import { partyStart } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'vitest'; - -describe('party start command', () => { - it('applies sparkle middleware when --sparkle is set', async () => { - const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(partyStart, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Start the pony party'); - }); -}); diff --git a/skills/cli-creation/assets/templates/multi-command.ts.tpl b/skills/cli-creation/assets/templates/multi-command.ts.tpl deleted file mode 100644 index 50026d7c..00000000 --- a/skills/cli-creation/assets/templates/multi-command.ts.tpl +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bun -/** - * __CLI_NAME__ - multi-command DreamCLI starter (pony party edition). - * - * Bun: - * bun __CLI_NAME__.ts snack cupcake --count 3 - * bun __CLI_NAME__.ts story "rainbow heist" --mood legendary --sparkle - * bun __CLI_NAME__.ts party start --theme midnight - * bun __CLI_NAME__.ts --help - * - * npm/tsx: - * npx tsx __CLI_NAME__.ts party playlist --genre chaos - * - * Deno: - * deno run -A __CLI_NAME__.ts snack donut --count 2 - */ - -import { arg, cli, command, flag, group, middleware } from '@kjanat/dreamcli'; - -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message), - }); -}); - -const sparkleFlag = () => flag.boolean().alias('s').env('SPARKLE').describe('Add extra sparkle'); - -export const snack = command('snack') - .description('Serve snacks to the crew') - .arg('treat', arg.string().default('cupcake').describe('Snack to serve')) - .flag('count', flag.number().default(1).alias('c').describe('How many snacks')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { treat } = args; - const { count } = flags; - out.log(ctx.sparkle(`Serving ${count} ${treat}(s)!`)); - }); - -export const story = command('story') - .description('Tell a dramatic story') - .arg('topic', arg.string().default('the great cupcake rescue').describe('Story topic')) - .flag('mood', flag.enum(['calm', 'chaos', 'legendary']) - .prompt({ kind: 'select', message: 'Set the mood!' }) - .default('calm').describe('Story mood')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { topic } = args; - const { mood } = flags; - out.log(ctx.sparkle(`Story time: ${topic} (${mood})`)); - out.log(ctx.sparkle('Dramatic glitter intensifies')); - }); - -export const partyStart = command('start') - .description('Start the pony party') - .flag('theme', flag.enum(['rainbow', 'midnight', 'glitter']).default('rainbow').describe('Party theme')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(`Party started with ${flags.theme} theme!`)); - }); - -export const partyPlaylist = command('playlist') - .description('Pick a party playlist vibe') - .flag('genre', flag.enum(['pop', 'ballad', 'chaos']).default('pop').describe('Playlist genre')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(`Now playing: ${flags.genre}`)); - }); - -export const party = group('party') - .description('Party controls') - .command(partyStart) - .command(partyPlaylist); - -export const app = cli('__CLI_NAME__') - .version('0.1.0') - .description('Fun DreamCLI starter app') - .command(snack) - .command(story) - .command(party) - .completions(); - -if (import.meta.main) { - app.run(); -} diff --git a/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl b/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl deleted file mode 100644 index 6a2c3d28..00000000 --- a/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl +++ /dev/null @@ -1,29 +0,0 @@ -import { hello } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'bun:test'; - -describe('hello command', () => { - it('prints sparkly greeting when --sparkle is set', async () => { - const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']); - // out.status() writes to stderr so stdout stays pipe-clean. - expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']); - }); - - it('suppresses status output with --quiet', async () => { - const result = await runCommand(hello, ['Twilight', '--quiet']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Twilight!\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(hello, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); - }); -}); diff --git a/skills/cli-creation/assets/templates/single-command.test.ts.tpl b/skills/cli-creation/assets/templates/single-command.test.ts.tpl deleted file mode 100644 index bd48df6d..00000000 --- a/skills/cli-creation/assets/templates/single-command.test.ts.tpl +++ /dev/null @@ -1,29 +0,0 @@ -import { hello } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'vitest'; - -describe('hello command', () => { - it('prints sparkly greeting when --sparkle is set', async () => { - const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']); - // out.status() writes to stderr so stdout stays pipe-clean. - expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']); - }); - - it('suppresses status output with --quiet', async () => { - const result = await runCommand(hello, ['Twilight', '--quiet']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Twilight!\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(hello, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); - }); -}); diff --git a/skills/cli-creation/assets/templates/single-command.ts.tpl b/skills/cli-creation/assets/templates/single-command.ts.tpl deleted file mode 100644 index 634e8e5a..00000000 --- a/skills/cli-creation/assets/templates/single-command.ts.tpl +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env bun -/** - * __CLI_NAME__ - hello-world DreamCLI starter. - * - * Bun: - * bun __CLI_NAME__.ts - * bun __CLI_NAME__.ts Twilight --sparkle --times 2 - * bun __CLI_NAME__.ts --help - * - * npm/tsx: - * npx tsx __CLI_NAME__.ts Twilight --sparkle --times 2 - * - * Deno: - * deno run -A __CLI_NAME__.ts Twilight --sparkle --times 2 - */ - -import { arg, cli, command, flag, middleware } from '@kjanat/dreamcli'; - -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message), - }); -}); - -export const hello = command('hello') - .description('Say hello with optional sparkle') - .example(({ name }) => `${name} Twilight --sparkle --times 2`, 'Sparkly double greeting') - .arg('name', arg.string().default('World').describe('Who to greet')) - .flag('sparkle', flag.boolean().alias('s').env('SPARKLE').describe('Add sparkles')) - // Constraints are enforced at every source, so the action needs no clamping. - .flag('times', flag.number({ int: true, min: 0, max: 100 }).default(1).alias('n').describe('Repeat count')) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - for (let i = 0; i < flags.times; i++) { - out.log(ctx.sparkle(`Hello, ${args.name}!`)); - } - - // stderr, and silenced by --quiet: keeps stdout pipe-clean. - out.status(`Greeted ${args.name} ${flags.times} time(s)`); - }); - -export const app = cli('__CLI_NAME__').default(hello); - -if (import.meta.main) { - app.run(); -} diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/cli-creation/references/consumer-workflow.md index 3bd6c5c3..d5b74e2a 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/cli-creation/references/consumer-workflow.md @@ -7,7 +7,7 @@ template and ending with validated behavior. ## Inputs to confirm -- CLI name (`--name`). +- CLI name (positional argument). - Surface shape (`single` or `multi`). - Whether tests should be skipped (`--no-test`). - Runtime the user runs on (Bun, npm/tsx, Deno). @@ -19,7 +19,7 @@ template and ending with validated behavior. 1. Scaffold starter files. ```bash - python scripts/scaffold_cli.py --name mycli --mode single --out . + bunx --package @kjanat/dreamcli dreamcli create mycli --mode single --out . ``` The scaffolder detects the package manager and Vitest usage to choose either @@ -53,7 +53,8 @@ template and ending with validated behavior. ```bash bun ./mycli.ts --help bun ./mycli.ts --json | jq . # stdout must parse - bun test ./mycli.test.ts + bun test ./mycli.test.ts # for bun:test + bunx vitest run ./mycli.test.ts # for Vitest ``` ## Done criteria diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index 84ee1bab..aea34173 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -3,17 +3,15 @@ ## Bun-first commands - Run CLI entrypoint: `bun mycli.ts --help` -- Run tests: `bun test mycli.test.ts` +- Run tests: `bun test mycli.test.ts` for `bun:test`, or `bunx vitest run mycli.test.ts` for Vitest. -The scaffolder prints path-aware run commands; use those exact printed paths when `--out` is not `.`. +Use the generated paths printed by `dreamcli create` when `--out` points to another directory. The scaffolder auto-detects test style: - Bun project + no detected Vitest usage: generate `bun:test` template. - Otherwise: generate Vitest template. - Package manager detection checks lockfiles (including `pnpm-*.yaml/.yml`) and manifest `packageManager` entries in `package.json`, `package.json5`, and `package.yaml/.yml`. -If Vitest template is generated inside a Bun project, `bun test` still runs those tests in this workflow. - ## npm/Node alternative - Run CLI entrypoint: `npx tsx mycli.ts --help` diff --git a/skills/cli-creation/scripts/scaffold_cli.py b/skills/cli-creation/scripts/scaffold_cli.py deleted file mode 100755 index 2ef21422..00000000 --- a/skills/cli-creation/scripts/scaffold_cli.py +++ /dev/null @@ -1,368 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.13" -# dependencies = [] -# /// -""" -Generate DreamCLI starter files from bundled templates. -""" - -import argparse -import json -import re -import sys -from pathlib import Path - -MANIFEST_FILENAMES = ( - "package.json", - "package.json5", - "package.yaml", - "package.yml", -) - -LOCKFILE_TO_MANAGER = ( - ("bun.lock", "bun"), - ("bun.lockb", "bun"), - ("pnpm-lock.yaml", "pnpm"), - ("pnpm-lock.yml", "pnpm"), - ("pnpm-workspace.yaml", "pnpm"), - ("pnpm-workspace.yml", "pnpm"), - ("yarn.lock", "yarn"), - ("package-lock.json", "npm"), - ("npm-shrinkwrap.json", "npm"), -) - - -def normalize_name(raw: str) -> str: - name = raw.strip().lower() - name = re.sub(r"[^a-z0-9]+", "-", name) - name = name.strip("-") - name = re.sub(r"-{2,}", "-", name) - return name - - -def read_template(path: Path) -> str: - if not path.exists(): - raise FileNotFoundError(f"Template not found: {path}") - return path.read_text() - - -def render_template(template: str, replacements: dict[str, str]) -> str: - rendered = template - for key, value in replacements.items(): - rendered = rendered.replace(key, value) - if not rendered.endswith("\n"): - rendered += "\n" - return rendered - - -def write_file(path: Path, content: str, force: bool) -> None: - if path.exists() and not force: - raise FileExistsError( - f"Refusing to overwrite existing file: {path}. Use --force to overwrite." - ) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(content) - - -def iter_ancestors(path: Path): - current = path.resolve() - while True: - yield current - if current.parent == current: - break - current = current.parent - - -def lockfiles_for_directory(directory: Path) -> list[Path]: - lockfiles: list[Path] = [] - for lockfile, _ in LOCKFILE_TO_MANAGER: - candidate = directory / lockfile - if candidate.exists(): - lockfiles.append(candidate) - - pnpm_globs = ( - "pnpm-*.yaml", - "pnpm-*.yml", - ) - for pattern in pnpm_globs: - for candidate in sorted(directory.glob(pattern)): - if candidate not in lockfiles: - lockfiles.append(candidate) - return lockfiles - - -def manifests_for_directory(directory: Path) -> list[Path]: - manifests: list[Path] = [] - for filename in MANIFEST_FILENAMES: - candidate = directory / filename - if candidate.exists(): - manifests.append(candidate) - return manifests - - -def package_manager_from_lockfiles(directory: Path) -> str | None: - for candidate in lockfiles_for_directory(directory): - if candidate.name.startswith("pnpm-") and candidate.suffix in {".yaml", ".yml"}: - return "pnpm" - for lockfile, manager in LOCKFILE_TO_MANAGER: - if candidate.name == lockfile: - return manager - return None - - -def package_manager_from_manifest(manifest: dict) -> str | None: - raw_value = manifest.get("packageManager") - if not isinstance(raw_value, str) or not raw_value.strip(): - return None - manager = raw_value.split("@", 1)[0].strip().lower() - if manager in {"bun", "pnpm", "npm", "yarn"}: - return manager - return None - - -def read_text_file(path: Path) -> str | None: - try: - return path.read_text(errors="ignore") - except OSError: - return None - - -def package_manager_from_text(raw_text: str) -> str | None: - match = re.search( - r'(?mi)^[ \t]*["\']?packageManager["\']?[ \t]*:[ \t]*["\']?([^"\',\n\r#]+)', - raw_text, - ) - if match is None: - return None - - value = match.group(1).strip() - manager = value.split("@", 1)[0].strip().lower() - if manager in {"bun", "pnpm", "npm", "yarn"}: - return manager - return None - - -def manifest_text_uses_vitest(raw_text: str) -> bool: - return re.search(r"\bvitest\b", raw_text) is not None - - -def detect_package_manager_with_root(start: Path) -> tuple[str | None, Path | None]: - for directory in iter_ancestors(start): - for manifest_path in manifests_for_directory(directory): - if manifest_path.name == "package.json": - manifest = read_package_json(manifest_path) - if manifest is not None: - from_manifest = package_manager_from_manifest(manifest) - if from_manifest is not None: - return (from_manifest, directory) - - raw_text = read_text_file(manifest_path) - if raw_text is not None: - from_text = package_manager_from_text(raw_text) - if from_text is not None: - return (from_text, directory) - - from_lockfile = package_manager_from_lockfiles(directory) - if from_lockfile is not None: - return (from_lockfile, directory) - return (None, None) - - -def read_package_json(path: Path) -> dict | None: - try: - raw = path.read_text() - parsed = json.loads(raw) - except (OSError, json.JSONDecodeError): - return None - if isinstance(parsed, dict): - return parsed - return None - - -def manifest_uses_vitest(manifest: dict) -> bool: - dependency_fields = ( - "dependencies", - "devDependencies", - "peerDependencies", - "optionalDependencies", - ) - for field in dependency_fields: - deps = manifest.get(field) - if isinstance(deps, dict) and "vitest" in deps: - return True - - scripts = manifest.get("scripts") - if isinstance(scripts, dict): - for script in scripts.values(): - if isinstance(script, str) and "vitest" in script: - return True - - return False - - -def find_project_root(start: Path) -> Path | None: - for directory in iter_ancestors(start): - if package_manager_from_lockfiles(directory) is not None: - return directory - if manifests_for_directory(directory): - return directory - return None - - -def iter_to_ancestor(start: Path, ancestor: Path): - current = start.resolve() - target = ancestor.resolve() - while True: - yield current - if current == target: - break - if current.parent == current: - break - current = current.parent - - -def detect_vitest_usage_in_project(project_root: Path, manager_root: Path | None) -> bool: - stop_at = manager_root.resolve() if manager_root is not None else project_root.resolve() - for directory in iter_to_ancestor(project_root, stop_at): - for manifest_path in manifests_for_directory(directory): - if manifest_path.name == "package.json": - manifest = read_package_json(manifest_path) - if manifest and manifest_uses_vitest(manifest): - return True - - raw_text = read_text_file(manifest_path) - if raw_text is not None and manifest_text_uses_vitest(raw_text): - return True - - if (stop_at / "node_modules" / "vitest" / "package.json").exists(): - return True - - for lockfile in lockfiles_for_directory(stop_at): - try: - if "vitest" in lockfile.read_text(errors="ignore"): - return True - except OSError: - continue - - return False - - -def choose_test_template( - mode: str, package_manager: str | None, uses_vitest: bool -) -> tuple[str, str]: - if package_manager == "bun" and not uses_vitest: - return (f"{mode}-command.bun-test.ts.tpl", "bun:test") - return (f"{mode}-command.test.ts.tpl", "vitest") - - -def choose_test_command(package_manager: str | None, test_framework: str, test_path: str) -> str: - if test_framework == "bun:test": - return f"bun test {test_path}" - if package_manager == "bun": - return f"bun test {test_path}" - if package_manager == "pnpm": - return f"pnpm vitest run {test_path}" - if package_manager == "yarn": - return f"yarn vitest run {test_path}" - return f"npx vitest run {test_path}" - - -def format_run_path(path: Path, cwd: Path) -> str: - try: - relative = path.relative_to(cwd).as_posix() - if not relative.startswith((".", "..")): - return f"./{relative}" - return relative - except ValueError: - return path.as_posix() - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Scaffold Bun-first DreamCLI starter files from templates." - ) - parser.add_argument("--name", required=True, help="CLI name (e.g. mycli)") - parser.add_argument( - "--mode", - choices=["single", "multi"], - default="single", - help="Starter shape. single=one root command, multi=nested command groups.", - ) - parser.add_argument("--out", required=True, help="Output directory") - parser.add_argument( - "--no-test", - action="store_true", - help="Skip generating the starter test file.", - ) - parser.add_argument( - "--force", - action="store_true", - help="Overwrite existing files if present.", - ) - args = parser.parse_args() - - cli_name = normalize_name(args.name) - if not cli_name: - print("[ERROR] --name must include at least one letter or digit.") - return 1 - - output_dir = Path(args.out).resolve() - output_dir.mkdir(parents=True, exist_ok=True) - - skill_root = Path(__file__).resolve().parent.parent - templates_dir = skill_root / "assets" / "templates" - - entry_template_path = templates_dir / f"{args.mode}-command.ts.tpl" - test_template_path = templates_dir / f"{args.mode}-command.test.ts.tpl" - - entry_filename = f"{cli_name}.ts" - entry_path = output_dir / entry_filename - test_path = output_dir / f"{cli_name}.test.ts" - include_test = not args.no_test - project_root = find_project_root(output_dir) or find_project_root(Path.cwd()) or output_dir - package_manager, manager_root = detect_package_manager_with_root(project_root) - uses_vitest = detect_vitest_usage_in_project(project_root, manager_root) - test_framework = "none" - - replacements = { - "__CLI_NAME__": cli_name, - "__ENTRY_FILE__": f"./{entry_filename}", - } - - try: - entry_template = read_template(entry_template_path) - entry_content = render_template(entry_template, replacements) - write_file(entry_path, entry_content, args.force) - print(f"[OK] Wrote {entry_path}") - - if include_test: - test_template_name, test_framework = choose_test_template( - args.mode, package_manager, uses_vitest - ) - test_template_path = templates_dir / test_template_name - test_template = read_template(test_template_path) - test_content = render_template(test_template, replacements) - write_file(test_path, test_content, args.force) - print(f"[OK] Wrote {test_path}") - except (FileExistsError, FileNotFoundError) as error: - print(f"[ERROR] {error}") - return 1 - - print("\nNext steps:") - run_path = format_run_path(entry_path, Path.cwd()) - test_run_path = format_run_path(test_path, Path.cwd()) - print(f"1. Run: bun {run_path} --help") - if include_test: - test_command = choose_test_command(package_manager, test_framework, test_run_path) - print(f"2. Test: {test_command}") - if test_framework == "bun:test": - print(" Detected Bun without vitest; generated a bun:test starter test.") - else: - print("2. Re-run without --no-test to include a starter test file") - print("3. Adapt commands, flags, and prompts to the user request") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/src/create.test.ts b/src/create.test.ts new file mode 100644 index 00000000..2a5eb813 --- /dev/null +++ b/src/create.test.ts @@ -0,0 +1,86 @@ +/** Verify starter generation and destination safeguards. @module */ + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { scaffold } from './create.ts'; + +function withProject(test: (directory: string) => void): void { + const directory = mkdtempSync(join(tmpdir(), 'dreamcli-create-')); + try { + test(directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +describe('scaffold', () => { + it('creates a single-command starter under a nested destination in a Bun project', () => { + withProject((directory) => { + writeFileSync(join(directory, 'bun.lock'), '{}'); + const out = join(directory, 'src', 'cli'); + const result = scaffold({ name: ' My CLI! ', out }); + + expect(result).toEqual({ + name: 'my-cli', + entry: join(out, 'my-cli.ts'), + test: join(out, 'my-cli.test.ts'), + testRunner: 'bun:test', + }); + expect(readFileSync(result.entry, 'utf8')).toContain("cli('my-cli').default(hello)"); + expect(readFileSync(join(out, 'my-cli.test.ts'), 'utf8')).toContain("from 'bun:test'"); + }); + }); + + it('uses Vitest for a multi-command starter when declared in a Bun workspace', () => { + withProject((directory) => { + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ packageManager: 'bun@1.4.5', devDependencies: { vitest: '^5.0.0' } }), + ); + const result = scaffold({ name: 'my-cli', mode: 'multi', out: directory }); + + expect(result.testRunner).toBe('vitest'); + expect(readFileSync(result.entry, 'utf8')).toContain("group('party')"); + const test = readFileSync(join(directory, 'my-cli.test.ts'), 'utf8'); + expect(test).toContain("from 'vitest'"); + expect(test).toContain("import { partyStart } from './my-cli.ts'"); + }); + }); + + it('leaves the directory untouched when only the test file exists', () => { + withProject((directory) => { + const existing = join(directory, 'my-cli.test.ts'); + writeFileSync(existing, 'keep this'); + expect(() => scaffold({ name: 'my-cli', out: directory })).toThrow( + /--force|Refusing to overwrite/, + ); + expect(existsSync(join(directory, 'my-cli.ts'))).toBe(false); + expect(readFileSync(existing, 'utf8')).toBe('keep this'); + }); + }); + + it('replaces the entry with force and leaves the test alone when tests are disabled', () => { + withProject((directory) => { + const entry = join(directory, 'my-cli.ts'); + const test = join(directory, 'my-cli.test.ts'); + writeFileSync(entry, 'old entry'); + writeFileSync(test, 'keep this'); + const result = scaffold({ name: 'my-cli', out: directory, test: false, force: true }); + expect(result).toEqual({ name: 'my-cli', entry }); + expect(readFileSync(entry, 'utf8')).toContain("cli('my-cli')"); + expect(readFileSync(test, 'utf8')).toBe('keep this'); + }); + }); + + it('refuses to replace directories even with force', () => { + withProject((directory) => { + mkdirSync(join(directory, 'my-cli.test.ts')); + expect(() => scaffold({ name: 'my-cli', out: directory, force: true })).toThrow( + /regular file/, + ); + expect(existsSync(join(directory, 'my-cli.ts'))).toBe(false); + }); + }); +}); diff --git a/src/create.ts b/src/create.ts new file mode 100644 index 00000000..7de1336b --- /dev/null +++ b/src/create.ts @@ -0,0 +1,135 @@ +/** + * Generate DreamCLI starter files using the templates shipped with the package. + * + * @module @kjanat/dreamcli/create + */ + +import { + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; +import { CLIError } from './core/errors/index.ts'; +import { entryTemplates, testTemplates } from './create/templates.ts'; +import { detectTestRunner } from './create/test-runner.ts'; + +export interface ScaffoldOptions { + /** CLI name. Converted to a lowercase, hyphen-separated filename. */ + readonly name: string; + /** Starter layout. Defaults to a single root command. */ + readonly mode?: 'single' | 'multi'; + /** Output directory. Defaults to the current working directory. */ + readonly out?: string; + /** Generate a test file. Defaults to true. */ + readonly test?: boolean; + /** Replace existing starter files. Defaults to false. */ + readonly force?: boolean; +} + +export interface ScaffoldResult { + /** Normalized CLI name. */ + readonly name: string; + /** Absolute path to the generated entrypoint. */ + readonly entry: string; + /** Absolute path to the generated test, when enabled. */ + readonly test?: string; + /** Import specifier for the generated test runner, when tests are enabled. */ + readonly testRunner?: 'bun:test' | 'vitest'; +} + +function renderTemplate(template: string, name: string): string { + return template.replaceAll('__CLI_NAME__', name).replaceAll('__ENTRY_FILE__', `./${name}.ts`); +} + +function existingFile(path: string): CLIError { + return new CLIError(`Refusing to overwrite existing file: ${path}`, { + code: 'SCAFFOLD_FILE_EXISTS', + suggest: 'Use --force to replace the existing starter file.', + }); +} + +/** Generate starter files in an existing project or a new directory. */ +export function scaffold(options: ScaffoldOptions): ScaffoldResult { + const name = options.name + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + if (name === '' || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) { + throw new CLIError('Choose a CLI name that can be used as a filename.', { + code: 'SCAFFOLD_INVALID_NAME', + suggest: 'Use a name with at least one letter or digit, such as my-cli.', + }); + } + + const directory = resolve(options.out ?? '.'); + const mode = options.mode ?? 'single'; + const entry = join(directory, `${name}.ts`); + const test = options.test === false ? undefined : join(directory, `${name}.test.ts`); + const testRunner = test === undefined ? undefined : detectTestRunner(directory); + const files: { path: string; content: string; mode?: number }[] = [ + { path: entry, content: renderTemplate(entryTemplates[mode], name) }, + ]; + if (test !== undefined && testRunner !== undefined) { + files.push({ + path: test, + content: renderTemplate(testTemplates[mode], name).replace('__TEST_RUNNER__', testRunner), + }); + } + + for (const file of files) { + const { path } = file; + const existing = lstatSync(path, { throwIfNoEntry: false }); + if (!existing) continue; + if (!existing.isFile()) { + throw new CLIError(`Cannot replace a path that is not a regular file: ${path}`, { + code: 'SCAFFOLD_NOT_A_FILE', + }); + } + if (!options.force) throw existingFile(path); + file.mode = existing.mode & 0o777; + } + + mkdirSync(directory, { recursive: true }); + // Stage every file before publishing any output. + const staging = mkdtempSync(join(directory, '.dreamcli-')); + const created: string[] = []; + try { + const staged = files.map(({ path, content, mode }, index) => { + const source = join(staging, String(index)); + writeFileSync(source, content, mode === undefined ? undefined : { mode }); + return { path, source }; + }); + + for (const { path, source } of staged) { + if (options.force) { + renameSync(source, path); + continue; + } + // A hard link publishes the complete file and fails if another writer won the race. + try { + linkSync(source, path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(path); + throw error; + } + created.push(path); + } + } catch (error) { + for (const path of created) rmSync(path, { force: true }); + throw error; + } finally { + rmSync(staging, { recursive: true, force: true }); + } + + return { + name, + entry, + ...(test !== undefined && { test }), + ...(testRunner !== undefined && { testRunner }), + }; +} diff --git a/src/create/templates.ts b/src/create/templates.ts new file mode 100644 index 00000000..70a67765 --- /dev/null +++ b/src/create/templates.ts @@ -0,0 +1,192 @@ +/** Starter source and test templates for DreamCLI projects. @module */ + +export const entryTemplates = { + single: `#!/usr/bin/env bun +// __CLI_NAME__ - hello-world DreamCLI starter. +// +// Bun: +// bun __CLI_NAME__.ts +// bun __CLI_NAME__.ts Twilight --sparkle --times 2 +// bun __CLI_NAME__.ts --help +// +// npm/tsx: +// npx tsx __CLI_NAME__.ts Twilight --sparkle --times 2 +// +// Deno: +// deno run -A __CLI_NAME__.ts Twilight --sparkle --times 2 + +import { arg, cli, command, flag, middleware } from '@kjanat/dreamcli'; + +const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { + const sparkleEnabled = flags.sparkle === true; + return next({ + sparkle: (message: string) => (sparkleEnabled ? \`✨ \${message} ✨\` : message), + }); +}); + +export const hello = command('hello') + .description('Say hello with optional sparkle') + .example(({ name }) => \`\${name} Twilight --sparkle --times 2\`, 'Sparkly double greeting') + .arg('name', arg.string().default('World').describe('Who to greet')) + .flag('sparkle', flag.boolean().alias('s').env('SPARKLE').describe('Add sparkles')) + // Constraints are enforced at every source, so the action needs no clamping. + .flag('times', flag.number({ int: true, min: 0, max: 100 }).default(1).alias('n').describe('Repeat count')) + .middleware(sparkle) + .action(({ args, flags, ctx, out }) => { + for (let i = 0; i < flags.times; i++) { + out.log(ctx.sparkle(\`Hello, \${args.name}!\`)); + } + + // stderr, and silenced by --quiet: keeps stdout pipe-clean. + out.status(\`Greeted \${args.name} \${flags.times} time(s)\`); + }); + +export const app = cli('__CLI_NAME__').default(hello); + +if (import.meta.main) { + app.run(); +} +`, + multi: `#!/usr/bin/env bun +// __CLI_NAME__ - multi-command DreamCLI starter (pony party edition). +// +// Bun: +// bun __CLI_NAME__.ts snack cupcake --count 3 +// bun __CLI_NAME__.ts story "rainbow heist" --mood legendary --sparkle +// bun __CLI_NAME__.ts party start --theme midnight +// bun __CLI_NAME__.ts --help +// +// npm/tsx: +// npx tsx __CLI_NAME__.ts party playlist --genre chaos +// +// Deno: +// deno run -A __CLI_NAME__.ts snack donut --count 2 + +import { arg, cli, command, flag, group, middleware } from '@kjanat/dreamcli'; + +const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { + const sparkleEnabled = flags.sparkle === true; + return next({ + sparkle: (message: string) => (sparkleEnabled ? \`✨ \${message} ✨\` : message), + }); +}); + +const sparkleFlag = () => flag.boolean().alias('s').env('SPARKLE').describe('Add extra sparkle'); + +export const snack = command('snack') + .description('Serve snacks to the crew') + .arg('treat', arg.string().default('cupcake').describe('Snack to serve')) + .flag('count', flag.number().default(1).alias('c').describe('How many snacks')) + .flag('sparkle', sparkleFlag()) + .middleware(sparkle) + .action(({ args, flags, ctx, out }) => { + const { treat } = args; + const { count } = flags; + out.log(ctx.sparkle(\`Serving \${count} \${treat}(s)!\`)); + }); + +export const story = command('story') + .description('Tell a dramatic story') + .arg('topic', arg.string().default('the great cupcake rescue').describe('Story topic')) + .flag('mood', flag.enum(['calm', 'chaos', 'legendary']) + .prompt({ kind: 'select', message: 'Set the mood!' }) + .default('calm').describe('Story mood')) + .flag('sparkle', sparkleFlag()) + .middleware(sparkle) + .action(({ args, flags, ctx, out }) => { + const { topic } = args; + const { mood } = flags; + out.log(ctx.sparkle(\`Story time: \${topic} (\${mood})\`)); + out.log(ctx.sparkle('Dramatic glitter intensifies')); + }); + +export const partyStart = command('start') + .description('Start the pony party') + .flag('theme', flag.enum(['rainbow', 'midnight', 'glitter']).default('rainbow').describe('Party theme')) + .flag('sparkle', sparkleFlag()) + .middleware(sparkle) + .action(({ flags, ctx, out }) => { + out.log(ctx.sparkle(\`Party started with \${flags.theme} theme!\`)); + }); + +export const partyPlaylist = command('playlist') + .description('Pick a party playlist vibe') + .flag('genre', flag.enum(['pop', 'ballad', 'chaos']).default('pop').describe('Playlist genre')) + .flag('sparkle', sparkleFlag()) + .middleware(sparkle) + .action(({ flags, ctx, out }) => { + out.log(ctx.sparkle(\`Now playing: \${flags.genre}\`)); + }); + +export const party = group('party') + .description('Party controls') + .command(partyStart) + .command(partyPlaylist); + +export const app = cli('__CLI_NAME__') + .version('0.1.0') + .description('Fun DreamCLI starter app') + .command(snack) + .command(story) + .command(party) + .completions(); + +if (import.meta.main) { + app.run(); +} +`, +}; + +export const testTemplates = { + single: `import { hello } from '__ENTRY_FILE__'; +import { runCommand } from '@kjanat/dreamcli/testkit'; +import { describe, expect, it } from '__TEST_RUNNER__'; + +describe('hello command', () => { + it('prints sparkly greeting when --sparkle is set', async () => { + const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\\n', '✨ Hello, Twilight! ✨\\n']); + // out.status() writes to stderr so stdout stays pipe-clean. + expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\\n']); + }); + + it('suppresses status output with --quiet', async () => { + const result = await runCommand(hello, ['Twilight', '--quiet']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toEqual(['Hello, Twilight!\\n']); + expect(result.stderr).toEqual([]); + }); + + it('renders help text', async () => { + const result = await runCommand(hello, ['--help']); + + expect(result.exitCode).toBe(0); + expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); + }); +}); +`, + multi: `import { partyStart } from '__ENTRY_FILE__'; +import { runCommand } from '@kjanat/dreamcli/testkit'; +import { describe, expect, it } from '__TEST_RUNNER__'; + +describe('party start command', () => { + it('applies sparkle middleware when --sparkle is set', async () => { + const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\\n']); + expect(result.stderr).toEqual([]); + }); + + it('renders help text', async () => { + const result = await runCommand(partyStart, ['--help']); + + expect(result.exitCode).toBe(0); + expect(result.stdout.join('')).toContain('Start the pony party'); + }); +}); +`, +}; diff --git a/src/create/test-runner.ts b/src/create/test-runner.ts new file mode 100644 index 00000000..84e7ade8 --- /dev/null +++ b/src/create/test-runner.ts @@ -0,0 +1,85 @@ +/** Select the starter test template for the destination project. @module */ + +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { cwd } from 'node:process'; + +const manifests = ['package.json', 'package.json5', 'package.yaml', 'package.yml']; +const lockfiles = [ + 'bun.lock', + 'bun.lockb', + 'pnpm-lock.yaml', + 'pnpm-lock.yml', + 'pnpm-workspace.yaml', + 'pnpm-workspace.yml', + 'yarn.lock', + 'package-lock.json', + 'npm-shrinkwrap.json', +]; + +function readOptional(path: string): string { + try { + return readFileSync(path, 'utf8'); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR' || code === 'EACCES') + return ''; + throw error; + } +} + +function projectLocks(directory: string): string[] { + if (!existsSync(directory)) return []; + const names = readdirSync(directory, { withFileTypes: true }); + return [ + ...lockfiles.filter((name) => + names.some((entry) => !entry.isDirectory() && entry.name === name), + ), + ...names + .filter( + (entry) => + !entry.isDirectory() && + /^pnpm-.*\.ya?ml$/.test(entry.name) && + !lockfiles.includes(entry.name), + ) + .map((entry) => entry.name) + .sort(), + ]; +} + +function detectProject(start: string): 'bun:test' | 'vitest' | undefined { + let hasProject = false; + let hasVitest = false; + for (let directory = start; ; directory = dirname(directory)) { + const manifestPaths = manifests.map((name) => join(directory, name)).filter(existsSync); + const locks = projectLocks(directory); + const contents = manifestPaths.map(readOptional); + hasProject ||= contents.length > 0 || locks.length > 0; + hasVitest ||= + contents.some((content) => /\bvitest\b/.test(content)) || + existsSync(join(directory, 'node_modules', 'vitest', 'package.json')); + + const declared = contents + .map( + (content) => + /(?:^|[,{\n])\s*["']?packageManager["']?\s*:\s*["']?(bun|npm|pnpm|yarn)(?=[@\s"',}#]|$)/.exec( + content, + )?.[1], + ) + .find((manager) => manager !== undefined); + const lock = locks[0]; + if (declared !== undefined || lock !== undefined) { + const isBun = declared === undefined ? lock?.startsWith('bun.') : declared === 'bun'; + if (!isBun) return 'vitest'; + hasVitest ||= locks.some((filename) => + /\bvitest\b/.test(readOptional(join(directory, filename))), + ); + return hasVitest ? 'vitest' : 'bun:test'; + } + if (dirname(directory) === directory) return hasProject ? 'vitest' : undefined; + } +} + +export function detectTestRunner(directory: string): 'bun:test' | 'vitest' { + return detectProject(directory) ?? detectProject(cwd()) ?? 'vitest'; +} diff --git a/tsconfig.json b/tsconfig.json index 8b7d87e7..8e9f154c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -31,6 +31,7 @@ "@kjanat/dreamcli/package.json": ["./package.json"], "@kjanat/dreamcli/completion": ["./src/completion.ts"], "@kjanat/dreamcli/config": ["./src/config.ts"], + "@kjanat/dreamcli/create": ["./src/create.ts"], "@kjanat/dreamcli/json-schema": ["./src/json-schema.ts"], "@kjanat/dreamcli/prompt": ["./src/prompt.ts"], "@kjanat/dreamcli/version": ["./src/version.ts"] diff --git a/tsdown.config.ts b/tsdown.config.ts index afd5baae..dc43b1db 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -11,6 +11,7 @@ export const entries = { index: 'src/index.ts', completion: 'src/completion.ts', config: 'src/config.ts', + create: 'src/create.ts', 'json-schema': 'src/json-schema.ts', prompt: 'src/prompt.ts', runtime: 'src/runtime.ts', From bc3fd8b0503e10c07af10380ec913753b1388d7b Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:01:31 -0500 Subject: [PATCH 02/21] Generate a runnable project with dreamcli create --- README.md | 11 +- bin/dreamcli.mjs | 10 +- .../cli-creation/references/runtime-notes.md | 2 +- src/create.test.ts | 41 +++- src/create.ts | 53 ++++- src/create/templates.ts | 203 +++--------------- src/create/test-runner.ts | 11 +- 7 files changed, 132 insertions(+), 199 deletions(-) diff --git a/README.md b/README.md index 3dfdf84a..cd3ed091 100644 --- a/README.md +++ b/README.md @@ -61,16 +61,19 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli ## Quick start -Generate a starter CLI and a matching test in the current directory. +Create a runnable TypeScript CLI project in a new directory. ```sh npm exec --package=@kjanat/dreamcli -- dreamcli create mycli -bun ./mycli.ts --help +cd mycli +npm install +npm start -- --help +npm test ``` `dreamcli init` is an alias for `dreamcli create`. Use `--mode multi` for a -grouped CLI, `--out ` to place the files elsewhere, and `--no-test` -to skip the test. Use `--force` to replace existing starter files. To generate +grouped CLI, `--out ` to add just the starter files to an existing project, and `--no-test` +to skip the test. Use `--force` to replace existing starter files, never the project manifest. To generate the same files from code, import `scaffold` from `@kjanat/dreamcli/create`. ### Single command diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 5d20a123..04f49615 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -11,7 +11,10 @@ const create = command('create') .description('Generate a DreamCLI starter') .arg('name', arg.string().required().describe('Name of the CLI')) .flag('mode', flag.enum(['single', 'multi']).default('single').describe('Starter layout')) - .flag('out', flag.string().default('.').describe('Output directory')) + .flag( + 'out', + flag.string().describe('Write files into this directory instead of creating a project'), + ) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) .action(({ args, flags, out }) => { @@ -21,8 +24,9 @@ const create = command('create') return; } out.log(`Created ${result.entry}`); - if (result.test !== undefined) { - out.log(`Created ${result.test} (${result.testRunner})`); + if (result.test !== undefined) out.log(`Created ${result.test}`); + if (flags.out === undefined) { + out.log(`cd ${result.name} && npm install && npm start -- --help`); } }); diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index aea34173..54361d2c 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -14,7 +14,7 @@ The scaffolder auto-detects test style: ## npm/Node alternative -- Run CLI entrypoint: `npx tsx mycli.ts --help` +- Run CLI entrypoint in an ESM package (`"type": "module"`): `node mycli.ts --help` - Run tests: `npx vitest run mycli.test.ts` ## Deno alternative diff --git a/src/create.test.ts b/src/create.test.ts index 2a5eb813..b4285e5f 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -1,5 +1,6 @@ /** Verify starter generation and destination safeguards. @module */ +import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -16,6 +17,42 @@ function withProject(test: (directory: string) => void): void { } describe('scaffold', () => { + it('creates a runnable npm project by default without touching an existing directory', () => { + withProject((directory) => { + const run = (options: { name: string; test?: boolean; force?: boolean }) => + execFileSync( + process.execPath, + [ + '-e', + `import { scaffold } from ${JSON.stringify(new URL('./create.ts', import.meta.url).href)}; scaffold(${JSON.stringify(options)});`, + ], + { cwd: directory, stdio: 'pipe' }, + ); + + run({ name: 'My CLI' }); + const packageFile = join(directory, 'my-cli', 'package.json'); + const manifest = readFileSync(packageFile, 'utf8'); + expect(JSON.parse(manifest)).toMatchObject({ + name: 'my-cli', + type: 'module', + scripts: { start: 'node ./my-cli.ts', test: 'vitest run' }, + dependencies: { '@kjanat/dreamcli': expect.any(String) }, + devDependencies: { vitest: expect.any(String) }, + }); + expect(existsSync(join(directory, 'my-cli', 'my-cli.test.ts'))).toBe(true); + expect(() => run({ name: 'my-cli', force: true })).toThrow(/already exists/); + expect(readFileSync(packageFile, 'utf8')).toBe(manifest); + + run({ name: 'no-test', test: false }); + const withoutTests = JSON.parse( + readFileSync(join(directory, 'no-test', 'package.json'), 'utf8'), + ); + expect(withoutTests.scripts).toEqual({ start: 'node ./no-test.ts' }); + expect(withoutTests.devDependencies).toBeUndefined(); + expect(existsSync(join(directory, 'no-test', 'no-test.test.ts'))).toBe(false); + }); + }); + it('creates a single-command starter under a nested destination in a Bun project', () => { withProject((directory) => { writeFileSync(join(directory, 'bun.lock'), '{}'); @@ -42,10 +79,10 @@ describe('scaffold', () => { const result = scaffold({ name: 'my-cli', mode: 'multi', out: directory }); expect(result.testRunner).toBe('vitest'); - expect(readFileSync(result.entry, 'utf8')).toContain("group('party')"); + expect(readFileSync(result.entry, 'utf8')).toContain("group('greet')"); const test = readFileSync(join(directory, 'my-cli.test.ts'), 'utf8'); expect(test).toContain("from 'vitest'"); - expect(test).toContain("import { partyStart } from './my-cli.ts'"); + expect(test).toContain("import { hello } from './my-cli.ts'"); }); }); diff --git a/src/create.ts b/src/create.ts index 7de1336b..3b2909a5 100644 --- a/src/create.ts +++ b/src/create.ts @@ -15,15 +15,16 @@ import { } from 'node:fs'; import { join, resolve } from 'node:path'; import { CLIError } from './core/errors/index.ts'; -import { entryTemplates, testTemplates } from './create/templates.ts'; +import { entryTemplates, testTemplate } from './create/templates.ts'; import { detectTestRunner } from './create/test-runner.ts'; +import { DREAMCLI_VERSION } from './version.ts'; export interface ScaffoldOptions { /** CLI name. Converted to a lowercase, hyphen-separated filename. */ readonly name: string; /** Starter layout. Defaults to a single root command. */ readonly mode?: 'single' | 'multi'; - /** Output directory. Defaults to the current working directory. */ + /** Write starter files into this directory instead of creating a named project. */ readonly out?: string; /** Generate a test file. Defaults to true. */ readonly test?: boolean; @@ -53,34 +54,66 @@ function existingFile(path: string): CLIError { }); } -/** Generate starter files in an existing project or a new directory. */ +/** Create a named npm project or add starter files to an explicit output directory. */ export function scaffold(options: ScaffoldOptions): ScaffoldResult { const name = options.name .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, ''); - if (name === '' || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) { + if (name === '' || name.length > 214 || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) { throw new CLIError('Choose a CLI name that can be used as a filename.', { code: 'SCAFFOLD_INVALID_NAME', - suggest: 'Use a name with at least one letter or digit, such as my-cli.', + suggest: 'Use 1 to 214 letters, digits, or hyphens, such as my-cli.', }); } - const directory = resolve(options.out ?? '.'); + const project = options.out === undefined; + const directory = resolve(options.out ?? name); const mode = options.mode ?? 'single'; const entry = join(directory, `${name}.ts`); const test = options.test === false ? undefined : join(directory, `${name}.test.ts`); - const testRunner = test === undefined ? undefined : detectTestRunner(directory); + const testRunner = + test === undefined ? undefined : project ? 'vitest' : detectTestRunner(directory); const files: { path: string; content: string; mode?: number }[] = [ { path: entry, content: renderTemplate(entryTemplates[mode], name) }, ]; if (test !== undefined && testRunner !== undefined) { files.push({ path: test, - content: renderTemplate(testTemplates[mode], name).replace('__TEST_RUNNER__', testRunner), + content: renderTemplate(testTemplate, name).replace('__TEST_RUNNER__', testRunner), }); } + if (project) { + const manifest = { + name, + private: true, + type: 'module', + scripts: { + start: `node ./${name}.ts`, + ...(test !== undefined && { test: 'vitest run' }), + }, + engines: { node: '>=22.22.2' }, + dependencies: { + '@kjanat/dreamcli': DREAMCLI_VERSION === 'dev' ? 'latest' : DREAMCLI_VERSION, + }, + ...(test !== undefined && { devDependencies: { vitest: '^5.1.2' } }), + }; + files.push({ + path: join(directory, 'package.json'), + content: `${JSON.stringify(manifest, null, 2)}\n`, + }); + try { + mkdirSync(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + throw new CLIError(`Project directory already exists: ${directory}`, { + code: 'SCAFFOLD_PROJECT_EXISTS', + suggest: 'Use --out to add starter files to an existing project.', + }); + } + } + for (const file of files) { const { path } = file; const existing = lstatSync(path, { throwIfNoEntry: false }); @@ -94,7 +127,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { file.mode = existing.mode & 0o777; } - mkdirSync(directory, { recursive: true }); + if (!project) mkdirSync(directory, { recursive: true }); // Stage every file before publishing any output. const staging = mkdtempSync(join(directory, '.dreamcli-')); const created: string[] = []; @@ -106,7 +139,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { }); for (const { path, source } of staged) { - if (options.force) { + if (options.force && !project) { renameSync(source, path); continue; } diff --git a/src/create/templates.ts b/src/create/templates.ts index 70a67765..f0524b0b 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -1,192 +1,41 @@ -/** Starter source and test templates for DreamCLI projects. @module */ +/** Source and test templates for the two starter layouts. @module */ -export const entryTemplates = { - single: `#!/usr/bin/env bun -// __CLI_NAME__ - hello-world DreamCLI starter. -// -// Bun: -// bun __CLI_NAME__.ts -// bun __CLI_NAME__.ts Twilight --sparkle --times 2 -// bun __CLI_NAME__.ts --help -// -// npm/tsx: -// npx tsx __CLI_NAME__.ts Twilight --sparkle --times 2 -// -// Deno: -// deno run -A __CLI_NAME__.ts Twilight --sparkle --times 2 - -import { arg, cli, command, flag, middleware } from '@kjanat/dreamcli'; - -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? \`✨ \${message} ✨\` : message), - }); -}); - -export const hello = command('hello') - .description('Say hello with optional sparkle') - .example(({ name }) => \`\${name} Twilight --sparkle --times 2\`, 'Sparkly double greeting') +const hello = `export const hello = command('hello') + .description('Say hello') .arg('name', arg.string().default('World').describe('Who to greet')) - .flag('sparkle', flag.boolean().alias('s').env('SPARKLE').describe('Add sparkles')) - // Constraints are enforced at every source, so the action needs no clamping. - .flag('times', flag.number({ int: true, min: 0, max: 100 }).default(1).alias('n').describe('Repeat count')) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - for (let i = 0; i < flags.times; i++) { - out.log(ctx.sparkle(\`Hello, \${args.name}!\`)); - } - - // stderr, and silenced by --quiet: keeps stdout pipe-clean. - out.status(\`Greeted \${args.name} \${flags.times} time(s)\`); + .action(({ args, out }) => { + out.log(\`Hello, \${args.name}!\`); }); +`; -export const app = cli('__CLI_NAME__').default(hello); - -if (import.meta.main) { - app.run(); +const run = `if (import.meta.main) { + await app.run(); } -`, - multi: `#!/usr/bin/env bun -// __CLI_NAME__ - multi-command DreamCLI starter (pony party edition). -// -// Bun: -// bun __CLI_NAME__.ts snack cupcake --count 3 -// bun __CLI_NAME__.ts story "rainbow heist" --mood legendary --sparkle -// bun __CLI_NAME__.ts party start --theme midnight -// bun __CLI_NAME__.ts --help -// -// npm/tsx: -// npx tsx __CLI_NAME__.ts party playlist --genre chaos -// -// Deno: -// deno run -A __CLI_NAME__.ts snack donut --count 2 - -import { arg, cli, command, flag, group, middleware } from '@kjanat/dreamcli'; +`; -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? \`✨ \${message} ✨\` : message), - }); -}); - -const sparkleFlag = () => flag.boolean().alias('s').env('SPARKLE').describe('Add extra sparkle'); - -export const snack = command('snack') - .description('Serve snacks to the crew') - .arg('treat', arg.string().default('cupcake').describe('Snack to serve')) - .flag('count', flag.number().default(1).alias('c').describe('How many snacks')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { treat } = args; - const { count } = flags; - out.log(ctx.sparkle(\`Serving \${count} \${treat}(s)!\`)); - }); - -export const story = command('story') - .description('Tell a dramatic story') - .arg('topic', arg.string().default('the great cupcake rescue').describe('Story topic')) - .flag('mood', flag.enum(['calm', 'chaos', 'legendary']) - .prompt({ kind: 'select', message: 'Set the mood!' }) - .default('calm').describe('Story mood')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { topic } = args; - const { mood } = flags; - out.log(ctx.sparkle(\`Story time: \${topic} (\${mood})\`)); - out.log(ctx.sparkle('Dramatic glitter intensifies')); - }); - -export const partyStart = command('start') - .description('Start the pony party') - .flag('theme', flag.enum(['rainbow', 'midnight', 'glitter']).default('rainbow').describe('Party theme')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(\`Party started with \${flags.theme} theme!\`)); - }); +export const entryTemplates = { + single: `import { arg, cli, command } from '@kjanat/dreamcli'; -export const partyPlaylist = command('playlist') - .description('Pick a party playlist vibe') - .flag('genre', flag.enum(['pop', 'ballad', 'chaos']).default('pop').describe('Playlist genre')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(\`Now playing: \${flags.genre}\`)); - }); +${hello} +export const app = cli('__CLI_NAME__').default(hello); -export const party = group('party') - .description('Party controls') - .command(partyStart) - .command(partyPlaylist); +${run}`, + multi: `import { arg, cli, command, group } from '@kjanat/dreamcli'; -export const app = cli('__CLI_NAME__') - .version('0.1.0') - .description('Fun DreamCLI starter app') - .command(snack) - .command(story) - .command(party) - .completions(); +${hello} +export const app = cli('__CLI_NAME__').command(group('greet').command(hello)); -if (import.meta.main) { - app.run(); -} -`, +${run}`, }; -export const testTemplates = { - single: `import { hello } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from '__TEST_RUNNER__'; - -describe('hello command', () => { - it('prints sparkly greeting when --sparkle is set', async () => { - const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\\n', '✨ Hello, Twilight! ✨\\n']); - // out.status() writes to stderr so stdout stays pipe-clean. - expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\\n']); - }); - - it('suppresses status output with --quiet', async () => { - const result = await runCommand(hello, ['Twilight', '--quiet']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Twilight!\\n']); - expect(result.stderr).toEqual([]); - }); +export const testTemplate = `import { runCommand } from '@kjanat/dreamcli/testkit'; +import { expect, it } from '__TEST_RUNNER__'; +import { hello } from '__ENTRY_FILE__'; - it('renders help text', async () => { - const result = await runCommand(hello, ['--help']); +it('greets the name passed on the command line', async () => { + const result = await runCommand(hello, ['Ada']); - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); - }); + expect(result.exitCode).toBe(0); + expect(result.stdout).toEqual(['Hello, Ada!\\n']); }); -`, - multi: `import { partyStart } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from '__TEST_RUNNER__'; - -describe('party start command', () => { - it('applies sparkle middleware when --sparkle is set', async () => { - const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(partyStart, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Start the pony party'); - }); -}); -`, -}; +`; diff --git a/src/create/test-runner.ts b/src/create/test-runner.ts index 84e7ade8..8b2f017e 100644 --- a/src/create/test-runner.ts +++ b/src/create/test-runner.ts @@ -1,5 +1,6 @@ /** Select the starter test template for the destination project. @module */ +import type { Dirent } from 'node:fs'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { cwd } from 'node:process'; @@ -29,8 +30,14 @@ function readOptional(path: string): string { } function projectLocks(directory: string): string[] { - if (!existsSync(directory)) return []; - const names = readdirSync(directory, { withFileTypes: true }); + let names: Dirent[]; + try { + names = readdirSync(directory, { withFileTypes: true }); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EACCES' || code === 'EPERM') return []; + throw error; + } return [ ...lockfiles.filter((name) => names.some((entry) => !entry.isDirectory() && entry.name === name), From 4841e38b806b8a98ec7e41988156c0218187fa8a Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:05:39 -0500 Subject: [PATCH 03/21] Scaffold into the selected folder and record the generator in Git --- README.md | 14 ++++++++--- bin/dreamcli.mjs | 39 ++++++++++++++++++++++++------ bin/git.mjs | 33 +++++++++++++++++++++++++ src/create.test.ts | 13 +++++++++- src/create.ts | 19 +++++++++------ src/create/git.test.ts | 55 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 154 insertions(+), 19 deletions(-) create mode 100644 bin/git.mjs create mode 100644 src/create/git.test.ts diff --git a/README.md b/README.md index cd3ed091..502a7c0a 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli ## Quick start -Create a runnable TypeScript CLI project in a new directory. +Create a runnable TypeScript CLI project in a new or empty directory. ```sh npm exec --package=@kjanat/dreamcli -- dreamcli create mycli @@ -73,8 +73,16 @@ npm test `dreamcli init` is an alias for `dreamcli create`. Use `--mode multi` for a grouped CLI, `--out ` to add just the starter files to an existing project, and `--no-test` -to skip the test. Use `--force` to replace existing starter files, never the project manifest. To generate -the same files from code, import `scaffold` from `@kjanat/dreamcli/create`. +to skip the test. Use `--force` with `--out` to replace existing starter files. + +Pass a relative or absolute path, or use `.` for the current directory. The package name defaults to +the last component of the path, normalized to lowercase with hyphens. For a standalone project, +DreamCLI initializes Git and records the generator version in the first commit. Use `--no-git` to +skip this. Existing Git repositories are left alone, and missing Git or commit identity does not +prevent project creation. + +To generate the files from code without running Git, import `scaffold` from +`@kjanat/dreamcli/create`. ### Single command diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 04f49615..5d486e08 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -2,32 +2,57 @@ /** DreamCLI's package executable. @module */ +import { basename, resolve } from 'node:path'; import { arg, cli, command, flag } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; -import { DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; +import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; +import { initGit } from './git.mjs'; const create = command('create') .alias('init') .description('Generate a DreamCLI starter') - .arg('name', arg.string().required().describe('Name of the CLI')) + .arg( + 'directory', + arg.string().default('.').describe('Project directory (or CLI name with --out)'), + ) .flag('mode', flag.enum(['single', 'multi']).default('single').describe('Starter layout')) .flag( 'out', flag.string().describe('Write files into this directory instead of creating a project'), ) + .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) .action(({ args, flags, out }) => { - const result = scaffold({ name: args.name, ...flags }); + const { git: useGit, ...options } = flags; + const directory = resolve(args.directory); + const project = options.out === undefined; + const name = project ? basename(directory) : args.directory; + const result = scaffold({ name, directory, ...options }); + const git = + project && useGit + ? initGit( + directory, + [ + basename(result.entry), + 'package.json', + '.gitignore', + ...(result.test ? [basename(result.test)] : []), + ], + DREAMCLI_VERSION, + DREAMCLI_REVISION, + ) + : undefined; if (out.jsonMode) { - out.json(result); + out.json({ ...result, ...(git && { git }) }); return; } out.log(`Created ${result.entry}`); if (result.test !== undefined) out.log(`Created ${result.test}`); - if (flags.out === undefined) { - out.log(`cd ${result.name} && npm install && npm start -- --help`); - } + if (git?.commit) out.log(`Initial Git commit: ${git.commit.slice(0, 12)}`); + if (git?.skipped) out.status('Git skipped: the project is inside an existing repository.'); + if (git?.error) out.warn(`Initial Git commit was not created: ${git.error}`); + if (project) out.log(`In ${directory}, run npm install, then npm start -- --help.`); }); await cli('dreamcli') diff --git a/bin/git.mjs b/bin/git.mjs new file mode 100644 index 00000000..82134969 --- /dev/null +++ b/bin/git.mjs @@ -0,0 +1,33 @@ +/** Initialize a standalone starter without touching a surrounding repository. @module */ + +import { spawnSync } from 'node:child_process'; +import { env } from 'node:process'; + +export function initGit(cwd, files, version, revision) { + const options = { cwd, encoding: 'utf8', env: { ...env, LC_ALL: 'C' } }; + const run = (...args) => spawnSync('git', args, options); + const local = run('rev-parse', '--local-env-vars'); + if (local.status !== 0) return failure(local); + for (const key of local.stdout.trim().split(/\s+/)) delete options.env[key]; + + const repository = run('rev-parse', '--git-dir'); + if (repository.status === 0) return { skipped: 'existing-repository' }; + if (!repository.stderr?.includes('not a git repository')) return failure(repository); + + const message = ['-m', `Initialize with dreamcli create ${version}`]; + if (revision !== 'dev') message.push('-m', `DreamCLI-Revision: ${revision}`); + for (const args of [ + ['init', '--template='], + ['add', '--', ...files], + ['commit', ...message, '--', ...files], + ]) { + const result = run(...args); + if (result.status !== 0) return failure(result); + } + const head = run('rev-parse', 'HEAD'); + return head.status === 0 ? { commit: head.stdout.trim() } : failure(head); +} + +function failure(result) { + return { error: result.stderr?.trim() || result.error?.message || 'Git exited unsuccessfully.' }; +} diff --git a/src/create.test.ts b/src/create.test.ts index b4285e5f..122f7620 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -40,7 +40,7 @@ describe('scaffold', () => { devDependencies: { vitest: expect.any(String) }, }); expect(existsSync(join(directory, 'my-cli', 'my-cli.test.ts'))).toBe(true); - expect(() => run({ name: 'my-cli', force: true })).toThrow(/already exists/); + expect(() => run({ name: 'my-cli', force: true })).toThrow(/not empty/); expect(readFileSync(packageFile, 'utf8')).toBe(manifest); run({ name: 'no-test', test: false }); @@ -53,6 +53,17 @@ describe('scaffold', () => { }); }); + it('uses an explicit project directory and keeps its existing parents', () => { + withProject((directory) => { + const target = join(directory, 'nested', 'My CLI'); + mkdirSync(target, { recursive: true }); + const result = scaffold({ name: 'My CLI', directory: target, test: false }); + expect(result.entry).toBe(join(target, 'my-cli.ts')); + expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe('node_modules/\n'); + expect(JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).name).toBe('my-cli'); + }); + }); + it('creates a single-command starter under a nested destination in a Bun project', () => { withProject((directory) => { writeFileSync(join(directory, 'bun.lock'), '{}'); diff --git a/src/create.ts b/src/create.ts index 3b2909a5..2db58859 100644 --- a/src/create.ts +++ b/src/create.ts @@ -9,6 +9,7 @@ import { lstatSync, mkdirSync, mkdtempSync, + readdirSync, renameSync, rmSync, writeFileSync, @@ -22,6 +23,8 @@ import { DREAMCLI_VERSION } from './version.ts'; export interface ScaffoldOptions { /** CLI name. Converted to a lowercase, hyphen-separated filename. */ readonly name: string; + /** Exact project directory. Defaults to a directory named after the CLI. */ + readonly directory?: string; /** Starter layout. Defaults to a single root command. */ readonly mode?: 'single' | 'multi'; /** Write starter files into this directory instead of creating a named project. */ @@ -68,7 +71,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } const project = options.out === undefined; - const directory = resolve(options.out ?? name); + const directory = resolve(options.out ?? options.directory ?? name); const mode = options.mode ?? 'single'; const entry = join(directory, `${name}.ts`); const test = options.test === false ? undefined : join(directory, `${name}.test.ts`); @@ -103,13 +106,13 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { path: join(directory, 'package.json'), content: `${JSON.stringify(manifest, null, 2)}\n`, }); - try { - mkdirSync(directory); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - throw new CLIError(`Project directory already exists: ${directory}`, { + files.push({ path: join(directory, '.gitignore'), content: 'node_modules/\n' }); + const existing = lstatSync(directory, { throwIfNoEntry: false }); + if (existing && (!existing.isDirectory() || readdirSync(directory).length > 0)) { + throw new CLIError(`Project directory is not empty or not a directory: ${directory}`, { code: 'SCAFFOLD_PROJECT_EXISTS', - suggest: 'Use --out to add starter files to an existing project.', + suggest: + 'Choose an empty directory or use --out to add starter files to an existing project.', }); } } @@ -127,7 +130,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { file.mode = existing.mode & 0o777; } - if (!project) mkdirSync(directory, { recursive: true }); + mkdirSync(directory, { recursive: true }); // Stage every file before publishing any output. const staging = mkdtempSync(join(directory, '.dreamcli-')); const created: string[] = []; diff --git a/src/create/git.test.ts b/src/create/git.test.ts new file mode 100644 index 00000000..153cf654 --- /dev/null +++ b/src/create/git.test.ts @@ -0,0 +1,55 @@ +/** Verify creation of the initial Git commit. @module */ + +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect, it } from 'vitest'; + +it.skipIf(spawnSync('git', ['--version']).status !== 0)( + 'commits only the starter files with generator provenance and skips an existing repository', + () => { + const root = mkdtempSync(join(tmpdir(), 'dreamcli-git-')); + try { + const config = join(root, 'gitconfig'); + writeFileSync(config, '[user]\n\tname = DreamCLI Test\n\temail = dreamcli@example.invalid\n'); + const env = { ...process.env, GIT_CONFIG_GLOBAL: config, GIT_CONFIG_NOSYSTEM: '1' }; + const git = (cwd: string, ...args: string[]) => + execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim(); + const init = (cwd: string, extraEnv = {}) => + JSON.parse( + execFileSync( + process.execPath, + [ + '-e', + `import { initGit } from ${JSON.stringify(new URL('../../bin/git.mjs', import.meta.url).href)}; console.log(JSON.stringify(initGit(process.cwd(), ['starter.ts'], '5.7.0', 'abc1234')));`, + ], + { cwd, env: { ...env, ...extraEnv }, encoding: 'utf8' }, + ), + ); + + const unrelated = join(root, 'unrelated'); + mkdirSync(unrelated); + git(unrelated, 'init'); + const project = join(root, 'project'); + mkdirSync(project); + writeFileSync(join(project, 'starter.ts'), 'export {};\n'); + writeFileSync(join(project, 'untracked.txt'), 'leave untracked\n'); + const result = init(project, { GIT_DIR: join(unrelated, '.git') }); + expect(result).toEqual({ commit: git(project, 'rev-parse', 'HEAD') }); + expect(git(project, 'log', '-1', '--format=%B')).toBe( + 'Initialize with dreamcli create 5.7.0\n\nDreamCLI-Revision: abc1234', + ); + expect(git(project, 'ls-tree', '--name-only', 'HEAD')).toBe('starter.ts'); + expect(git(unrelated, 'rev-list', '--all', '--count')).toBe('0'); + + const nested = join(project, 'nested'); + mkdirSync(nested); + expect(init(nested)).toEqual({ skipped: 'existing-repository' }); + expect(existsSync(join(nested, '.git'))).toBe(false); + expect(git(project, 'rev-list', '--count', 'HEAD')).toBe('1'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, +); From a43fbd364c398f2c6202004c64055172580c0c15 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:13:54 -0500 Subject: [PATCH 04/21] Require a project destination and prompt in interactive terminals --- README.md | 9 +++-- bin/dreamcli.mjs | 87 ++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 502a7c0a..e1287b31 100644 --- a/README.md +++ b/README.md @@ -75,8 +75,13 @@ npm test grouped CLI, `--out ` to add just the starter files to an existing project, and `--no-test` to skip the test. Use `--force` with `--out` to replace existing starter files. -Pass a relative or absolute path, or use `.` for the current directory. The package name defaults to -the last component of the path, normalized to lowercase with hyphens. For a standalone project, +Pass a relative or absolute path, or explicitly use `.` for the current directory. +In a terminal, omitting the path prompts for one. The wizard asks for unset project options and +shows the full path for confirmation before writing. The package name defaults to the last +component of the path, normalized to lowercase with hyphens. Override it with `--name`. +Use `--yes` to skip the wizard. Scripts, CI, and JSON mode never prompt and must supply a path. + +For a standalone project, DreamCLI initializes Git and records the generator version in the first commit. Use `--no-git` to skip this. Existing Git repositories are left alone, and missing Git or commit identity does not prevent project creation. diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 5d486e08..d443c7a2 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,18 +3,19 @@ /** DreamCLI's package executable. @module */ import { basename, resolve } from 'node:path'; -import { arg, cli, command, flag } from '@kjanat/dreamcli'; +import { env, stderr, stdin } from 'node:process'; +import { arg, CLIError, cli, command, flag, wasExplicit } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; +import { prompt } from '@kjanat/dreamcli/prompt'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; import { initGit } from './git.mjs'; const create = command('create') .alias('init') .description('Generate a DreamCLI starter') - .arg( - 'directory', - arg.string().default('.').describe('Project directory (or CLI name with --out)'), - ) + .arg('directory', arg.string().optional().describe('Project directory (or CLI name with --out)')) + .flag('name', flag.string().describe('Override the project name')) + .flag('yes', flag.boolean().alias('y').describe('Use defaults without prompting')) .flag('mode', flag.enum(['single', 'multi']).default('single').describe('Starter layout')) .flag( 'out', @@ -23,12 +24,78 @@ const create = command('create') .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) - .action(({ args, flags, out }) => { - const { git: useGit, ...options } = flags; - const directory = resolve(args.directory); + .action(async ({ args, flags, sources, out, ask }) => { + const { git: defaultGit, name: explicitName, yes, ...options } = flags; const project = options.out === undefined; - const name = project ? basename(directory) : args.directory; - const result = scaffold({ name, directory, ...options }); + const inCI = env.CI && env.CI !== 'false' && env.CI !== '0'; + const interactive = + project && !yes && !inCI && !out.jsonMode && out.isTTY && stdin.isTTY && stderr.isTTY; + + let target = args.directory; + if (!target && interactive) { + target = await ask( + prompt.input({ + message: 'Project directory', + placeholder: 'e.g. ./my-cli', + }), + ); + } + if (!target) { + throw new CLIError( + project ? 'Provide a project directory.' : 'Provide a CLI name with --out.', + { + code: 'SCAFFOLD_DIRECTORY_REQUIRED', + exitCode: 2, + suggest: project + ? 'For example: dreamcli create ./my-cli' + : 'For example: dreamcli create my-cli --out .', + }, + ); + } + + const directory = resolve(target); + let name = explicitName ?? (project ? basename(directory) : target); + let { mode, test } = options; + let useGit = defaultGit; + if (interactive) { + if (explicitName === undefined) { + name = await ask( + prompt.input({ + message: 'Project name', + ...(name ? { default: name } : {}), + }), + ); + } + if (!wasExplicit(sources.flags.mode)) { + mode = await ask( + prompt.select({ + message: 'Starter layout', + choices: [ + { value: 'single', label: 'Single command' }, + { value: 'multi', label: 'Grouped commands' }, + ], + }), + ); + } + if (!wasExplicit(sources.flags.test)) { + test = await ask(prompt.confirm({ message: 'Generate a starter test?', default: test })); + } + if (!wasExplicit(sources.flags.git)) { + useGit = await ask( + prompt.confirm({ message: 'Create the initial Git commit?', default: useGit }), + ); + } + if ( + !(await ask( + prompt.confirm({ message: `Create the project in ${directory}?`, default: false }), + )) + ) { + out.status('Cancelled. No files written.'); + return; + } + } + + const result = scaffold({ ...options, name, directory, mode, test }); const git = project && useGit ? initGit( From e27a57e6fb8cdf7283a3fa30f09006a2e08f1cff Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:17:49 -0500 Subject: [PATCH 05/21] Use the derived defaults throughout the create wizard --- README.md | 3 ++- bin/dreamcli.mjs | 26 ++++++++++++++++---------- src/create.ts | 16 +++++++++++++--- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index e1287b31..e7883b49 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,8 @@ to skip the test. Use `--force` with `--out` to replace existing starter files. Pass a relative or absolute path, or explicitly use `.` for the current directory. In a terminal, omitting the path prompts for one. The wizard asks for unset project options and -shows the full path for confirmation before writing. The package name defaults to the last +shows the full path for confirmation before writing. Press Enter to keep each suggested option. +When writing to the current directory, explicitly confirm with `y`. The package name defaults to the last component of the path, normalized to lowercase with hyphens. Override it with `--name`. Use `--yes` to skip the wizard. Scripts, CI, and JSON mode never prompt and must supply a path. diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index d443c7a2..8b09498b 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,9 +3,9 @@ /** DreamCLI's package executable. @module */ import { basename, resolve } from 'node:path'; -import { env, stderr, stdin } from 'node:process'; +import { cwd, env, stderr, stdin } from 'node:process'; import { arg, CLIError, cli, command, flag, wasExplicit } from '@kjanat/dreamcli'; -import { scaffold } from '@kjanat/dreamcli/create'; +import { normalizeProjectName, scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; import { initGit } from './git.mjs'; @@ -59,21 +59,24 @@ const create = command('create') let useGit = defaultGit; if (interactive) { if (explicitName === undefined) { + const suggested = normalizeProjectName(name); name = await ask( prompt.input({ message: 'Project name', - ...(name ? { default: name } : {}), + ...(suggested !== undefined && { default: suggested }), + validate: (value) => + normalizeProjectName(value) !== undefined || + 'Use a valid project name, such as my-cli.', }), ); } if (!wasExplicit(sources.flags.mode)) { mode = await ask( - prompt.select({ - message: 'Starter layout', - choices: [ - { value: 'single', label: 'Single command' }, - { value: 'multi', label: 'Grouped commands' }, - ], + prompt.input({ + message: 'Starter layout (single or multi)', + default: mode, + validate: (value) => + value === 'single' || value === 'multi' || 'Enter single or multi.', }), ); } @@ -87,7 +90,10 @@ const create = command('create') } if ( !(await ask( - prompt.confirm({ message: `Create the project in ${directory}?`, default: false }), + prompt.confirm({ + message: `Create the project in ${directory}?`, + default: directory !== cwd(), + }), )) ) { out.status('Cancelled. No files written.'); diff --git a/src/create.ts b/src/create.ts index 2db58859..4501088a 100644 --- a/src/create.ts +++ b/src/create.ts @@ -57,13 +57,23 @@ function existingFile(path: string): CLIError { }); } -/** Create a named npm project or add starter files to an explicit output directory. */ -export function scaffold(options: ScaffoldOptions): ScaffoldResult { - const name = options.name +/** Normalize a project name for use as a package name and filename. */ +export function normalizeProjectName(input: string): string | undefined { + const name = input .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, ''); if (name === '' || name.length > 214 || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) { + return undefined; + } + + return name; +} + +/** Create a named npm project or add starter files to an explicit output directory. */ +export function scaffold(options: ScaffoldOptions): ScaffoldResult { + const name = normalizeProjectName(options.name); + if (name === undefined) { throw new CLIError('Choose a CLI name that can be used as a filename.', { code: 'SCAFFOLD_INVALID_NAME', suggest: 'Use 1 to 214 letters, digits, or hyphens, such as my-cli.', From d5b3d2a19a8b0f1a6b1404120ef67d2687275110 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:23:22 -0500 Subject: [PATCH 06/21] Scaffold a standard TypeScript CLI project without a wizard --- README.md | 40 ++++++---- bin/dreamcli.mjs | 79 +++---------------- skills/cli-creation/SKILL.md | 17 ++-- .../references/consumer-workflow.md | 2 +- .../cli-creation/references/runtime-notes.md | 3 + src/create.test.ts | 27 ++++--- src/create.ts | 66 ++++++++++++---- src/create/templates.ts | 30 ++++--- 8 files changed, 124 insertions(+), 140 deletions(-) diff --git a/README.md b/README.md index e7883b49..35d691d3 100644 --- a/README.md +++ b/README.md @@ -61,34 +61,40 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli ## Quick start -Create a runnable TypeScript CLI project in a new or empty directory. +Create a TypeScript CLI project in a new or empty directory: ```sh npm exec --package=@kjanat/dreamcli -- dreamcli create mycli cd mycli npm install -npm start -- --help +npm start -- hello Ada npm test +npm run typecheck ``` -`dreamcli init` is an alias for `dreamcli create`. Use `--mode multi` for a -grouped CLI, `--out ` to add just the starter files to an existing project, and `--no-test` -to skip the test. Use `--force` with `--out` to replace existing starter files. +```text +mycli/ +├── .gitignore +├── package.json +├── tsconfig.json +└── src/ + ├── cli.ts + └── commands/ + ├── hello.ts + └── hello.test.ts +``` -Pass a relative or absolute path, or explicitly use `.` for the current directory. -In a terminal, omitting the path prompts for one. The wizard asks for unset project options and -shows the full path for confirmation before writing. Press Enter to keep each suggested option. -When writing to the current directory, explicitly confirm with `y`. The package name defaults to the last -component of the path, normalized to lowercase with hyphens. Override it with `--name`. -Use `--yes` to skip the wizard. Scripts, CI, and JSON mode never prompt and must supply a path. +`dreamcli init` is an alias. In a terminal, an omitted path prompts for a directory. +Non-interactive runs require a path. Use `.` explicitly to create in an empty current +directory, where the CLI asks for confirmation unless you pass `--yes`. -For a standalone project, -DreamCLI initializes Git and records the generator version in the first commit. Use `--no-git` to -skip this. Existing Git repositories are left alone, and missing Git or commit identity does not -prevent project creation. +The package name comes from the directory; `--name` overrides it. A new Git repository +gets an initial commit with the generator version. Use `--no-git` or `--no-test` to skip +those steps. Existing repositories are left alone. -To generate the files from code without running Git, import `scaffold` from -`@kjanat/dreamcli/create`. +Use `dreamcli create mycli --out .` to add just the starter files to an existing +project. Use `--force` with `--out` to replace those files. The programmatic +`scaffold()` from `@kjanat/dreamcli/create` generates files without running Git. ### Single command diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 8b09498b..fede407c 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -2,10 +2,10 @@ /** DreamCLI's package executable. @module */ -import { basename, resolve } from 'node:path'; +import { basename, relative, resolve, sep } from 'node:path'; import { cwd, env, stderr, stdin } from 'node:process'; -import { arg, CLIError, cli, command, flag, wasExplicit } from '@kjanat/dreamcli'; -import { normalizeProjectName, scaffold } from '@kjanat/dreamcli/create'; +import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; +import { scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; import { initGit } from './git.mjs'; @@ -16,7 +16,6 @@ const create = command('create') .arg('directory', arg.string().optional().describe('Project directory (or CLI name with --out)')) .flag('name', flag.string().describe('Override the project name')) .flag('yes', flag.boolean().alias('y').describe('Use defaults without prompting')) - .flag('mode', flag.enum(['single', 'multi']).default('single').describe('Starter layout')) .flag( 'out', flag.string().describe('Write files into this directory instead of creating a project'), @@ -24,8 +23,8 @@ const create = command('create') .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) - .action(async ({ args, flags, sources, out, ask }) => { - const { git: defaultGit, name: explicitName, yes, ...options } = flags; + .action(async ({ args, flags, out, ask }) => { + const { git: useGit, name: explicitName, yes, ...options } = flags; const project = options.out === undefined; const inCI = env.CI && env.CI !== 'false' && env.CI !== '0'; const interactive = @@ -35,8 +34,7 @@ const create = command('create') if (!target && interactive) { target = await ask( prompt.input({ - message: 'Project directory', - placeholder: 'e.g. ./my-cli', + message: 'Directory', }), ); } @@ -54,64 +52,17 @@ const create = command('create') } const directory = resolve(target); - let name = explicitName ?? (project ? basename(directory) : target); - let { mode, test } = options; - let useGit = defaultGit; - if (interactive) { - if (explicitName === undefined) { - const suggested = normalizeProjectName(name); - name = await ask( - prompt.input({ - message: 'Project name', - ...(suggested !== undefined && { default: suggested }), - validate: (value) => - normalizeProjectName(value) !== undefined || - 'Use a valid project name, such as my-cli.', - }), - ); - } - if (!wasExplicit(sources.flags.mode)) { - mode = await ask( - prompt.input({ - message: 'Starter layout (single or multi)', - default: mode, - validate: (value) => - value === 'single' || value === 'multi' || 'Enter single or multi.', - }), - ); - } - if (!wasExplicit(sources.flags.test)) { - test = await ask(prompt.confirm({ message: 'Generate a starter test?', default: test })); - } - if (!wasExplicit(sources.flags.git)) { - useGit = await ask( - prompt.confirm({ message: 'Create the initial Git commit?', default: useGit }), - ); - } - if ( - !(await ask( - prompt.confirm({ - message: `Create the project in ${directory}?`, - default: directory !== cwd(), - }), - )) - ) { - out.status('Cancelled. No files written.'); - return; - } + const name = explicitName ?? (project ? basename(directory) : target); + if (interactive && relative(cwd(), directory) === '') { + if (!(await ask(prompt.confirm({ message: 'Create here?', default: false })))) return; } - const result = scaffold({ ...options, name, directory, mode, test }); + const result = scaffold({ ...options, name, directory }); const git = project && useGit ? initGit( directory, - [ - basename(result.entry), - 'package.json', - '.gitignore', - ...(result.test ? [basename(result.test)] : []), - ], + result.files.map((path) => relative(directory, path).split(sep).join('/')), DREAMCLI_VERSION, DREAMCLI_REVISION, ) @@ -120,12 +71,8 @@ const create = command('create') out.json({ ...result, ...(git && { git }) }); return; } - out.log(`Created ${result.entry}`); - if (result.test !== undefined) out.log(`Created ${result.test}`); - if (git?.commit) out.log(`Initial Git commit: ${git.commit.slice(0, 12)}`); - if (git?.skipped) out.status('Git skipped: the project is inside an existing repository.'); - if (git?.error) out.warn(`Initial Git commit was not created: ${git.error}`); - if (project) out.log(`In ${directory}, run npm install, then npm start -- --help.`); + out.log(project ? `Created ${target}` : `Created ${relative(cwd(), result.entry)}`); + if (git?.error) out.warn(`Git: ${git.error}`); }); await cli('dreamcli') diff --git a/skills/cli-creation/SKILL.md b/skills/cli-creation/SKILL.md index f1973ba3..33052263 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/cli-creation/SKILL.md @@ -22,15 +22,13 @@ both. ## Quick Start -1. Choose a starter mode: - - `single`: one root command (`cli(name).default(command)`). - - `multi`: grouped command surface (`group('...').command(...)`). -2. Generate starter files: - - `bunx --package @kjanat/dreamcli dreamcli create mycli --mode single --out .` - - Tests are generated by default; add `--no-test` only when explicitly requested. - - Test template is auto-detected: Bun without Vitest uses `bun:test`; otherwise Vitest. +1. Create a project: `bunx --package @kjanat/dreamcli dreamcli create mycli`. +2. To add starter files to an existing project instead, use + `bunx --package @kjanat/dreamcli dreamcli create mycli --out .`. + Tests are generated by default. For existing projects, Bun without Vitest uses + `bun:test`; otherwise the generated test uses Vitest. 3. Run and validate generated files: - - Run the generated entrypoint, for example `bun ./mycli.ts --help`. + - Run the generated entrypoint, for example `bun ./src/cli.ts --help` in a new project. - Run the generated test unless `--no-test` was used. 4. Extend behavior with references: - `references/pattern-cookbook.md` — copy-ready, type-checked snippets. @@ -93,8 +91,7 @@ Paths are relative to the dreamcli repository root. ## Workflow Decision Tree -- Simple one-command utility → `--mode single`. -- Nested command groups (git/gh style) → `--mode multi`. +- Start with the generated command. Add new commands under `src/commands/` and register them in `src/cli.ts`. - Tests wanted from the start → do nothing, they are scaffolded by default. - Tests explicitly unwanted → add `--no-test`. - npm/tsx or Deno instructions → keep generated code unchanged and give the diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/cli-creation/references/consumer-workflow.md index d5b74e2a..f1593e9d 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/cli-creation/references/consumer-workflow.md @@ -19,7 +19,7 @@ template and ending with validated behavior. 1. Scaffold starter files. ```bash - bunx --package @kjanat/dreamcli dreamcli create mycli --mode single --out . + bunx --package @kjanat/dreamcli dreamcli create mycli --out . ``` The scaffolder detects the package manager and Vitest usage to choose either diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index 54361d2c..63ce1ba1 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -1,5 +1,8 @@ # Runtime Notes +In a new project, run the CLI with `npm start -- hello Ada` or `bun src/cli.ts hello Ada`. +Run the Vitest suite with `npm test`. The commands below are for files added with `--out`. + ## Bun-first commands - Run CLI entrypoint: `bun mycli.ts --help` diff --git a/src/create.test.ts b/src/create.test.ts index 122f7620..39773262 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -35,11 +35,11 @@ describe('scaffold', () => { expect(JSON.parse(manifest)).toMatchObject({ name: 'my-cli', type: 'module', - scripts: { start: 'node ./my-cli.ts', test: 'vitest run' }, + scripts: { start: 'node src/cli.ts', typecheck: 'tsc --noEmit', test: 'vitest run' }, dependencies: { '@kjanat/dreamcli': expect.any(String) }, devDependencies: { vitest: expect.any(String) }, }); - expect(existsSync(join(directory, 'my-cli', 'my-cli.test.ts'))).toBe(true); + expect(existsSync(join(directory, 'my-cli', 'src/commands/hello.test.ts'))).toBe(true); expect(() => run({ name: 'my-cli', force: true })).toThrow(/not empty/); expect(readFileSync(packageFile, 'utf8')).toBe(manifest); @@ -47,9 +47,9 @@ describe('scaffold', () => { const withoutTests = JSON.parse( readFileSync(join(directory, 'no-test', 'package.json'), 'utf8'), ); - expect(withoutTests.scripts).toEqual({ start: 'node ./no-test.ts' }); - expect(withoutTests.devDependencies).toBeUndefined(); - expect(existsSync(join(directory, 'no-test', 'no-test.test.ts'))).toBe(false); + expect(withoutTests.scripts).toEqual({ start: 'node src/cli.ts', typecheck: 'tsc --noEmit' }); + expect(withoutTests.devDependencies.vitest).toBeUndefined(); + expect(existsSync(join(directory, 'no-test', 'src/commands/hello.test.ts'))).toBe(false); }); }); @@ -58,13 +58,13 @@ describe('scaffold', () => { const target = join(directory, 'nested', 'My CLI'); mkdirSync(target, { recursive: true }); const result = scaffold({ name: 'My CLI', directory: target, test: false }); - expect(result.entry).toBe(join(target, 'my-cli.ts')); - expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe('node_modules/\n'); + expect(result.entry).toBe(join(target, 'src/cli.ts')); + expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe('node_modules/\ncoverage/\n'); expect(JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).name).toBe('my-cli'); }); }); - it('creates a single-command starter under a nested destination in a Bun project', () => { + it('adds starter files under a nested destination in a Bun project', () => { withProject((directory) => { writeFileSync(join(directory, 'bun.lock'), '{}'); const out = join(directory, 'src', 'cli'); @@ -74,23 +74,24 @@ describe('scaffold', () => { name: 'my-cli', entry: join(out, 'my-cli.ts'), test: join(out, 'my-cli.test.ts'), + files: [join(out, 'my-cli.ts'), join(out, 'my-cli.test.ts')], testRunner: 'bun:test', }); - expect(readFileSync(result.entry, 'utf8')).toContain("cli('my-cli').default(hello)"); + expect(readFileSync(result.entry, 'utf8')).toContain("cli('my-cli').command(hello)"); expect(readFileSync(join(out, 'my-cli.test.ts'), 'utf8')).toContain("from 'bun:test'"); }); }); - it('uses Vitest for a multi-command starter when declared in a Bun workspace', () => { + it('uses Vitest for starter files when declared in a Bun workspace', () => { withProject((directory) => { writeFileSync( join(directory, 'package.json'), JSON.stringify({ packageManager: 'bun@1.4.5', devDependencies: { vitest: '^5.0.0' } }), ); - const result = scaffold({ name: 'my-cli', mode: 'multi', out: directory }); + const result = scaffold({ name: 'my-cli', out: directory }); expect(result.testRunner).toBe('vitest'); - expect(readFileSync(result.entry, 'utf8')).toContain("group('greet')"); + expect(readFileSync(result.entry, 'utf8')).toContain("command('hello')"); const test = readFileSync(join(directory, 'my-cli.test.ts'), 'utf8'); expect(test).toContain("from 'vitest'"); expect(test).toContain("import { hello } from './my-cli.ts'"); @@ -116,7 +117,7 @@ describe('scaffold', () => { writeFileSync(entry, 'old entry'); writeFileSync(test, 'keep this'); const result = scaffold({ name: 'my-cli', out: directory, test: false, force: true }); - expect(result).toEqual({ name: 'my-cli', entry }); + expect(result).toEqual({ name: 'my-cli', entry, files: [entry] }); expect(readFileSync(entry, 'utf8')).toContain("cli('my-cli')"); expect(readFileSync(test, 'utf8')).toBe('keep this'); }); diff --git a/src/create.ts b/src/create.ts index 4501088a..9c38bb9b 100644 --- a/src/create.ts +++ b/src/create.ts @@ -14,9 +14,14 @@ import { rmSync, writeFileSync, } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { CLIError } from './core/errors/index.ts'; -import { entryTemplates, testTemplate } from './create/templates.ts'; +import { + cliTemplate, + commandTemplate, + standaloneTemplate, + testTemplate, +} from './create/templates.ts'; import { detectTestRunner } from './create/test-runner.ts'; import { DREAMCLI_VERSION } from './version.ts'; @@ -25,8 +30,6 @@ export interface ScaffoldOptions { readonly name: string; /** Exact project directory. Defaults to a directory named after the CLI. */ readonly directory?: string; - /** Starter layout. Defaults to a single root command. */ - readonly mode?: 'single' | 'multi'; /** Write starter files into this directory instead of creating a named project. */ readonly out?: string; /** Generate a test file. Defaults to true. */ @@ -40,16 +43,14 @@ export interface ScaffoldResult { readonly name: string; /** Absolute path to the generated entrypoint. */ readonly entry: string; + /** Absolute paths to all generated files. */ + readonly files: readonly string[]; /** Absolute path to the generated test, when enabled. */ readonly test?: string; /** Import specifier for the generated test runner, when tests are enabled. */ readonly testRunner?: 'bun:test' | 'vitest'; } -function renderTemplate(template: string, name: string): string { - return template.replaceAll('__CLI_NAME__', name).replaceAll('__ENTRY_FILE__', `./${name}.ts`); -} - function existingFile(path: string): CLIError { return new CLIError(`Refusing to overwrite existing file: ${path}`, { code: 'SCAFFOLD_FILE_EXISTS', @@ -58,7 +59,7 @@ function existingFile(path: string): CLIError { } /** Normalize a project name for use as a package name and filename. */ -export function normalizeProjectName(input: string): string | undefined { +function normalizeProjectName(input: string): string | undefined { const name = input .toLowerCase() .replace(/[^a-z0-9]+/g, '-') @@ -82,41 +83,70 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { const project = options.out === undefined; const directory = resolve(options.out ?? options.directory ?? name); - const mode = options.mode ?? 'single'; - const entry = join(directory, `${name}.ts`); - const test = options.test === false ? undefined : join(directory, `${name}.test.ts`); + const entry = join(directory, project ? 'src/cli.ts' : `${name}.ts`); + const test = + options.test === false + ? undefined + : join(directory, project ? 'src/commands/hello.test.ts' : `${name}.test.ts`); const testRunner = test === undefined ? undefined : project ? 'vitest' : detectTestRunner(directory); const files: { path: string; content: string; mode?: number }[] = [ - { path: entry, content: renderTemplate(entryTemplates[mode], name) }, + { + path: entry, + content: (project ? cliTemplate : standaloneTemplate).replace('__CLI_NAME__', name), + }, ]; + if (project) + files.push({ path: join(directory, 'src/commands/hello.ts'), content: commandTemplate }); if (test !== undefined && testRunner !== undefined) { files.push({ path: test, - content: renderTemplate(testTemplate, name).replace('__TEST_RUNNER__', testRunner), + content: testTemplate + .replace('__COMMAND_FILE__', project ? './hello.ts' : `./${name}.ts`) + .replace('__TEST_RUNNER__', testRunner), }); } if (project) { const manifest = { name, + version: '0.1.0', private: true, type: 'module', scripts: { - start: `node ./${name}.ts`, + start: 'node src/cli.ts', + typecheck: 'tsc --noEmit', ...(test !== undefined && { test: 'vitest run' }), }, engines: { node: '>=22.22.2' }, dependencies: { '@kjanat/dreamcli': DREAMCLI_VERSION === 'dev' ? 'latest' : DREAMCLI_VERSION, }, - ...(test !== undefined && { devDependencies: { vitest: '^5.1.2' } }), + devDependencies: { + '@types/node': '^22.0.0', + typescript: '^6.0.3', + ...(test !== undefined && { vitest: '^5.1.2' }), + }, }; files.push({ path: join(directory, 'package.json'), content: `${JSON.stringify(manifest, null, 2)}\n`, }); - files.push({ path: join(directory, '.gitignore'), content: 'node_modules/\n' }); + const tsconfig = { + compilerOptions: { + target: 'ES2022', + module: 'NodeNext', + strict: true, + noEmit: true, + allowImportingTsExtensions: true, + types: ['node'], + }, + include: ['src'], + }; + files.push( + { path: join(directory, 'tsconfig.json'), content: `${JSON.stringify(tsconfig, null, 2)}\n` }, + { path: join(directory, '.gitignore'), content: 'node_modules/\ncoverage/\n' }, + ); const existing = lstatSync(directory, { throwIfNoEntry: false }); if (existing && (!existing.isDirectory() || readdirSync(directory).length > 0)) { throw new CLIError(`Project directory is not empty or not a directory: ${directory}`, { @@ -152,6 +182,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { }); for (const { path, source } of staged) { + mkdirSync(dirname(path), { recursive: true }); if (options.force && !project) { renameSync(source, path); continue; @@ -175,6 +206,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { return { name, entry, + files: files.map(({ path }) => path), ...(test !== undefined && { test }), ...(testRunner !== undefined && { testRunner }), }; diff --git a/src/create/templates.ts b/src/create/templates.ts index f0524b0b..f32d45ca 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -1,4 +1,4 @@ -/** Source and test templates for the two starter layouts. @module */ +/** Templates for a DreamCLI project and for adding starter files to an existing project. @module */ const hello = `export const hello = command('hello') .description('Say hello') @@ -8,29 +8,27 @@ const hello = `export const hello = command('hello') }); `; -const run = `if (import.meta.main) { - await app.run(); -} -`; +export const commandTemplate = `import { arg, command } from '@kjanat/dreamcli'; -export const entryTemplates = { - single: `import { arg, cli, command } from '@kjanat/dreamcli'; +${hello}`; -${hello} -export const app = cli('__CLI_NAME__').default(hello); +export const cliTemplate = `import { cli } from '@kjanat/dreamcli'; +import { hello } from './commands/hello.ts'; + +await cli('__CLI_NAME__').command(hello).run(); +`; -${run}`, - multi: `import { arg, cli, command, group } from '@kjanat/dreamcli'; +export const standaloneTemplate = `import { arg, cli, command } from '@kjanat/dreamcli'; ${hello} -export const app = cli('__CLI_NAME__').command(group('greet').command(hello)); - -${run}`, -}; +if (import.meta.main) { + await cli('__CLI_NAME__').command(hello).run(); +} +`; export const testTemplate = `import { runCommand } from '@kjanat/dreamcli/testkit'; import { expect, it } from '__TEST_RUNNER__'; -import { hello } from '__ENTRY_FILE__'; +import { hello } from '__COMMAND_FILE__'; it('greets the name passed on the command line', async () => { const result = await runCommand(hello, ['Ada']); From e6c19c12215b1ba8611edc63c2b2cf6483d0a6aa Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sat, 28 Nov 2026 13:50:47 -0500 Subject: [PATCH 07/21] Use the correct subprocess runtime in scaffold tests --- src/create.test.ts | 2 +- src/create/git.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/create.test.ts b/src/create.test.ts index 39773262..c22f6a95 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -23,7 +23,7 @@ describe('scaffold', () => { execFileSync( process.execPath, [ - '-e', + ...(typeof Deno === 'undefined' ? ['-e'] : ['eval', '--ext=mjs']), `import { scaffold } from ${JSON.stringify(new URL('./create.ts', import.meta.url).href)}; scaffold(${JSON.stringify(options)});`, ], { cwd: directory, stdio: 'pipe' }, diff --git a/src/create/git.test.ts b/src/create/git.test.ts index 153cf654..15180ba3 100644 --- a/src/create/git.test.ts +++ b/src/create/git.test.ts @@ -19,7 +19,7 @@ it.skipIf(spawnSync('git', ['--version']).status !== 0)( const init = (cwd: string, extraEnv = {}) => JSON.parse( execFileSync( - process.execPath, + typeof Deno === 'undefined' ? process.execPath : 'node', [ '-e', `import { initGit } from ${JSON.stringify(new URL('../../bin/git.mjs', import.meta.url).href)}; console.log(JSON.stringify(initGit(process.cwd(), ['starter.ts'], '5.7.0', 'abc1234')));`, From b9d128f5dab551b98032a10a2eea844e46f540ab Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 07:21:52 -0500 Subject: [PATCH 08/21] Use manifest links and roll back failed scaffolds --- bin/dreamcli.mjs | 3 +- src/create.test.ts | 47 ++++++++++++++++++++++++++++ src/create.ts | 76 +++++++++++++++++++++++++++++++--------------- 3 files changed, 101 insertions(+), 25 deletions(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index fede407c..cb3ae002 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -76,7 +76,8 @@ const create = command('create') }); await cli('dreamcli') - .version(DREAMCLI_VERSION) + .manifest({ from: import.meta, files: ['package.json'] }) + .links() .description('Create a project with DreamCLI') .command(create) .run(); diff --git a/src/create.test.ts b/src/create.test.ts index c22f6a95..70844d41 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -64,6 +64,53 @@ describe('scaffold', () => { }); }); + it.skipIf(typeof Deno !== 'undefined' || typeof Bun !== 'undefined')( + 'cleans up staging and partial publication failures without deleting existing directories', + () => { + withProject((directory) => { + const target = join(directory, 'project'); + mkdirSync(target); + execFileSync( + process.execPath, + [ + '-e', + ` + import assert from 'node:assert/strict'; + import fs from 'node:fs'; + import { syncBuiltinESMExports } from 'node:module'; + import { dirname, join } from 'node:path'; + + const link = fs.linkSync; + let calls = 0; + fs.linkSync = (...args) => { + if (++calls === 2) throw new Error('publication failed'); + return link(...args); + }; + const mkdtemp = fs.mkdtempSync; + fs.mkdtempSync = (prefix) => { + if (prefix.includes('stage-failure')) throw new Error('staging failed'); + return mkdtemp(prefix); + }; + syncBuiltinESMExports(); + const { scaffold } = await import(${JSON.stringify(new URL('./create.ts', import.meta.url).href)}); + const options = { name: 'project', directory: process.argv[1] }; + assert.throws(() => scaffold(options), /publication failed/); + assert.deepEqual(fs.readdirSync(options.directory), []); + scaffold(options); + + const newParent = join(dirname(options.directory), 'stage-failure'); + assert.throws(() => scaffold({ ...options, directory: join(newParent, 'project') }), /staging failed/); + assert.equal(fs.existsSync(newParent), false); + `, + target, + ], + { stdio: 'pipe' }, + ); + expect(existsSync(join(target, 'src/commands/hello.test.ts'))).toBe(true); + }); + }, + ); + it('adds starter files under a nested destination in a Bun project', () => { withProject((directory) => { writeFileSync(join(directory, 'bun.lock'), '{}'); diff --git a/src/create.ts b/src/create.ts index 9c38bb9b..ab7087ad 100644 --- a/src/create.ts +++ b/src/create.ts @@ -11,7 +11,9 @@ import { mkdtempSync, readdirSync, renameSync, + rmdirSync, rmSync, + statSync, writeFileSync, } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; @@ -71,6 +73,19 @@ function normalizeProjectName(input: string): string | undefined { return name; } +function makeDirectory(path: string, created: string[]): void { + try { + mkdirSync(path); + created.push(path); + } catch (error) { + const { code } = error as NodeJS.ErrnoException; + if (code === 'EEXIST' && statSync(path, { throwIfNoEntry: false })?.isDirectory()) return; + if (code !== 'ENOENT' || dirname(path) === path) throw error; + makeDirectory(dirname(path), created); + makeDirectory(path, created); + } +} + /** Create a named npm project or add starter files to an explicit output directory. */ export function scaffold(options: ScaffoldOptions): ScaffoldResult { const name = normalizeProjectName(options.name); @@ -170,37 +185,50 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { file.mode = existing.mode & 0o777; } - mkdirSync(directory, { recursive: true }); - // Stage every file before publishing any output. - const staging = mkdtempSync(join(directory, '.dreamcli-')); const created: string[] = []; + const directories: string[] = []; try { - const staged = files.map(({ path, content, mode }, index) => { - const source = join(staging, String(index)); - writeFileSync(source, content, mode === undefined ? undefined : { mode }); - return { path, source }; - }); + makeDirectory(directory, directories); + // Stage every file before publishing any output. + const staging = mkdtempSync(join(directory, '.dreamcli-')); + try { + const staged = files.map(({ path, content, mode }, index) => { + const source = join(staging, String(index)); + writeFileSync(source, content, mode === undefined ? undefined : { mode }); + return { path, source }; + }); - for (const { path, source } of staged) { - mkdirSync(dirname(path), { recursive: true }); - if (options.force && !project) { - renameSync(source, path); - continue; - } - // A hard link publishes the complete file and fails if another writer won the race. - try { - linkSync(source, path); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(path); - throw error; + for (const { path, source } of staged) { + makeDirectory(dirname(path), directories); + if (options.force && !project) { + renameSync(source, path); + continue; + } + // A hard link publishes the complete file and fails if another writer won the race. + try { + linkSync(source, path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(path); + throw error; + } + created.push(path); } - created.push(path); + } finally { + rmSync(staging, { recursive: true, force: true }); } } catch (error) { - for (const path of created) rmSync(path, { force: true }); + try { + for (const path of created) rmSync(path, { force: true }); + } finally { + for (const path of directories.reverse()) { + try { + rmdirSync(path); + } catch { + // Leave directories that another writer populated intact. + } + } + } throw error; - } finally { - rmSync(staging, { recursive: true, force: true }); } return { From bee3f78845289e884a030faef863f8aec5bc1912 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 07:44:48 -0500 Subject: [PATCH 09/21] Protect scaffold rollback and run standalone starters across supported Node versions --- docs/.vitepress/data/api-index.test.ts | 2 +- docs/reference/main.md | 9 +- skills/cli-creation/SKILL.md | 7 +- .../references/consumer-workflow.md | 8 +- .../cli-creation/references/runtime-notes.md | 22 ++- src/core/cli/cli-manifest.test.ts | 7 + src/core/cli/index.ts | 22 +-- src/create.test.ts | 77 +++++----- src/create.ts | 97 +------------ src/create/git.test.ts | 9 +- src/create/publish.ts | 131 ++++++++++++++++++ src/create/templates.ts | 4 +- src/runtime/main-module.ts | 27 ++++ tests/fixtures/scaffold-publication.mjs | 39 ++++++ 14 files changed, 285 insertions(+), 176 deletions(-) create mode 100644 src/create/publish.ts create mode 100644 src/runtime/main-module.ts create mode 100644 tests/fixtures/scaffold-publication.mjs diff --git a/docs/.vitepress/data/api-index.test.ts b/docs/.vitepress/data/api-index.test.ts index 107e04b7..55bf3247 100644 --- a/docs/.vitepress/data/api-index.test.ts +++ b/docs/.vitepress/data/api-index.test.ts @@ -41,7 +41,7 @@ describe('api-index', () => { expect(root?.kindGroups.find((group) => group.kind === 'function')?.symbols).toContainEqual({ name: 'isMainModule', kind: 'function', - sourcePath: 'src/core/cli/index.ts', + sourcePath: 'src/runtime/main-module.ts', }); expect(root?.kindGroups.find((group) => group.kind === 'interface')?.symbols).toContainEqual({ name: 'CLIOptions', diff --git a/docs/reference/main.md b/docs/reference/main.md index 5dc0365d..409ea4b5 100644 --- a/docs/reference/main.md +++ b/docs/reference/main.md @@ -161,8 +161,7 @@ cli('mycli').manifest(denoCfg).command(deploy).run(); ### `isMainModule(meta)` -Node, Bun, and Deno expose the conventional entrypoint guard directly. Use it when the runtime's -ambient types are available: +Use the native entrypoint guard when both the runtime and its ambient types support it: ```ts twoslash import { cli, command } from '@kjanat/dreamcli'; @@ -175,9 +174,9 @@ if (import.meta.main) { } ``` -`isMainModule(import.meta)` is the compatibility form for projects whose ambient `ImportMeta` -interface omits `main`. It performs the same check without direct property access or global -augmentation, keeping cross-runtime JSR packages type-checkable and publishable: +Use `isMainModule(import.meta)` across the full supported Node range or when the ambient +`ImportMeta` interface omits `main`. On Node versions without the native guard, the helper +compares the module filename with the entry script: ```ts twoslash import { diff --git a/skills/cli-creation/SKILL.md b/skills/cli-creation/SKILL.md index 33052263..2d66fd85 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/cli-creation/SKILL.md @@ -22,9 +22,10 @@ both. ## Quick Start -1. Create a project: `bunx --package @kjanat/dreamcli dreamcli create mycli`. +1. Create a project: `bunx --bun --package @kjanat/dreamcli dreamcli create mycli`. + Enter the project and install its dependencies with `cd mycli && bun install`. 2. To add starter files to an existing project instead, use - `bunx --package @kjanat/dreamcli dreamcli create mycli --out .`. + `bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out .`. Tests are generated by default. For existing projects, Bun without Vitest uses `bun:test`; otherwise the generated test uses Vitest. 3. Run and validate generated files: @@ -186,7 +187,7 @@ Assert output including trailing newlines. ## Resource Map -- `dreamcli create` (alias `dreamcli init`) — generate Bun-first starter files and tests. +- `dreamcli create` (alias `dreamcli init`) — create a TypeScript CLI project or add starter files to an existing project. - `references/pattern-cookbook.md` — snippets by topic; all type-checked. - `references/consumer-workflow.md` — end-to-end flow from request to validation. - `references/runtime-notes.md` — runtime and package-manager execution guidance. diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/cli-creation/references/consumer-workflow.md index f1593e9d..a92e6478 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/cli-creation/references/consumer-workflow.md @@ -2,7 +2,7 @@ ## Goal -Build a consumer-facing CLI app with DreamCLI 3.x, starting from a working +Build a consumer-facing CLI app with DreamCLI, starting from a working template and ending with validated behavior. ## Inputs to confirm @@ -10,7 +10,7 @@ template and ending with validated behavior. - CLI name (positional argument). - Surface shape (`single` or `multi`). - Whether tests should be skipped (`--no-test`). -- Runtime the user runs on (Bun, npm/tsx, Deno). +- Runtime the user runs on (Bun, Node, Deno). - Whether the CLI needs machine-readable output, config files, or prompts — each adds declarations to the schema rather than code to the action. @@ -19,7 +19,7 @@ template and ending with validated behavior. 1. Scaffold starter files. ```bash - bunx --package @kjanat/dreamcli dreamcli create mycli --out . + bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out . ``` The scaffolder detects the package manager and Vitest usage to choose either @@ -54,7 +54,7 @@ template and ending with validated behavior. bun ./mycli.ts --help bun ./mycli.ts --json | jq . # stdout must parse bun test ./mycli.test.ts # for bun:test - bunx vitest run ./mycli.test.ts # for Vitest + bunx --bun vitest run ./mycli.test.ts # for Vitest ``` ## Done criteria diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index 63ce1ba1..20f17d1e 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -1,14 +1,24 @@ # Runtime Notes -In a new project, run the CLI with `npm start -- hello Ada` or `bun src/cli.ts hello Ada`. -Run the Vitest suite with `npm test`. The commands below are for files added with `--out`. +After `dreamcli create mycli`, enter the generated project and install its dependencies: -## Bun-first commands +```sh +cd mycli +npm install +npm start -- hello Ada +npm test +npm run typecheck +``` -- Run CLI entrypoint: `bun mycli.ts --help` -- Run tests: `bun test mycli.test.ts` for `bun:test`, or `bunx vitest run mycli.test.ts` for Vitest. +With Bun, use `bun install`, `bun src/cli.ts hello Ada`, and `bunx --bun vitest run` in that directory. + +## Files added with `--out` + +For `dreamcli create mycli --out tools`, run `bun tools/mycli.ts --help`. +Run `bun test tools/mycli.test.ts` for `bun:test`, or `bunx --bun vitest run tools/mycli.test.ts` for Vitest. +With `--json`, the result contains absolute paths in `entry` and `test`; `--no-test` omits the latter. +The examples below use `--out .`. -Use the generated paths printed by `dreamcli create` when `--out` points to another directory. The scaffolder auto-detects test style: - Bun project + no detected Vitest usage: generate `bun:test` template. diff --git a/src/core/cli/cli-manifest.test.ts b/src/core/cli/cli-manifest.test.ts index ccdf8d2e..1fd7c332 100644 --- a/src/core/cli/cli-manifest.test.ts +++ b/src/core/cli/cli-manifest.test.ts @@ -785,6 +785,13 @@ describe('isMainModule', () => { expect(isMainModule(import.meta)).toBe(false); }); + it('recognizes the Node entry script when the runtime omits import.meta.main', () => { + const meta = { ...import.meta, filename: process.argv[1] }; + Reflect.deleteProperty(meta, 'main'); + expect(isMainModule(meta as ImportMeta)).toBe(true); + expect(isMainModule({ ...meta, filename: '/different/module.ts' } as ImportMeta)).toBe(false); + }); + it('is true when import.meta.main is set', () => { const meta: ImportMeta = { ...import.meta, main: true }; expect(isMainModule(meta)).toBe(true); diff --git a/src/core/cli/index.ts b/src/core/cli/index.ts index 7355c0fb..9a7640b3 100644 --- a/src/core/cli/index.ts +++ b/src/core/cli/index.ts @@ -53,6 +53,7 @@ import { acceptsArgv } from '#internals/core/schema/stdin.ts'; import type { RuntimeAdapter } from '#internals/runtime/adapter.ts'; import { exitAfterFlush } from '#internals/runtime/adapter.ts'; import { createAdapter } from '#internals/runtime/auto.ts'; +import { isMainModule } from '#internals/runtime/main-module.ts'; import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts'; import type { Builtins, BuiltinsConfig, BuiltinsDraft } from './builtins.ts'; import { normalizeBuiltins } from './builtins.ts'; @@ -2618,27 +2619,6 @@ function cli( }); } -/** - * Report whether the calling module is the process entrypoint, cross-runtime. - * - * Node, Bun, and Deno set `import.meta.main` on the module invoked directly; - * projects with the runtime's ambient types can read that property directly. - * This helper is a compatibility form for projects whose `tsconfig.json` `lib` - * override drops those `ImportMeta` extras: passing `import.meta` whole avoids - * a direct `.main` access without requiring global augmentation. - * - * @param meta - The calling module's `import.meta`. - * @returns `true` when the module was run as the entrypoint. - * - * @example - * ```ts - * if (isMainModule(import.meta)) cli('mycli').command(deploy).run(); - * ``` - */ -function isMainModule(meta: ImportMeta): boolean { - return meta.main === true; -} - // --- Exports export type { BuiltinMode, BuiltinName, Builtins, BuiltinsConfig } from './builtins.ts'; diff --git a/src/create.test.ts b/src/create.test.ts index 70844d41..4280fcd0 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -1,9 +1,18 @@ /** Verify starter generation and destination safeguards. @module */ import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { scaffold } from './create.ts'; @@ -65,48 +74,34 @@ describe('scaffold', () => { }); it.skipIf(typeof Deno !== 'undefined' || typeof Bun !== 'undefined')( - 'cleans up staging and partial publication failures without deleting existing directories', + 'rolls back partial writes, rejects concurrent replacement and permits a retry', () => { - withProject((directory) => { - const target = join(directory, 'project'); - mkdirSync(target); - execFileSync( - process.execPath, - [ - '-e', - ` - import assert from 'node:assert/strict'; - import fs from 'node:fs'; - import { syncBuiltinESMExports } from 'node:module'; - import { dirname, join } from 'node:path'; - - const link = fs.linkSync; - let calls = 0; - fs.linkSync = (...args) => { - if (++calls === 2) throw new Error('publication failed'); - return link(...args); - }; - const mkdtemp = fs.mkdtempSync; - fs.mkdtempSync = (prefix) => { - if (prefix.includes('stage-failure')) throw new Error('staging failed'); - return mkdtemp(prefix); - }; - syncBuiltinESMExports(); - const { scaffold } = await import(${JSON.stringify(new URL('./create.ts', import.meta.url).href)}); - const options = { name: 'project', directory: process.argv[1] }; - assert.throws(() => scaffold(options), /publication failed/); - assert.deepEqual(fs.readdirSync(options.directory), []); - scaffold(options); - - const newParent = join(dirname(options.directory), 'stage-failure'); - assert.throws(() => scaffold({ ...options, directory: join(newParent, 'project') }), /staging failed/); - assert.equal(fs.existsSync(newParent), false); - `, - target, - ], - { stdio: 'pipe' }, + withProject((out) => { + const fixture = fileURLToPath( + new URL('../tests/fixtures/scaffold-publication.mjs', import.meta.url), ); - expect(existsSync(join(target, 'src/commands/hello.test.ts'))).toBe(true); + const run = (scenario: string, target = out) => + execFileSync(process.execPath, [fixture, scenario, target], { stdio: 'pipe' }); + + const nested = join(out, 'nested', 'target'); + expect(() => run('stage', nested)).toThrow(/staging failed/); + expect(readdirSync(out)).toEqual([]); + + expect(() => run('project')).toThrow(/Error: project publication failed/); + expect(readdirSync(out)).toEqual([]); + + expect(() => run('create')).toThrow(/Error: second file failed/); + expect(readdirSync(out)).toEqual([]); + + const entry = join(out, 'demo.ts'); + writeFileSync(entry, 'original'); + expect(() => run('replace')).toThrow(/Error: second file failed/); + expect(readdirSync(out)).toEqual(['demo.ts']); + expect(readFileSync(entry, 'utf8')).toBe('original'); + + const result = scaffold({ name: 'demo', out, force: true }); + expect(result.files).toEqual([entry, join(out, 'demo.test.ts')]); + expect(readdirSync(out).sort()).toEqual(['demo.test.ts', 'demo.ts']); }); }, ); diff --git a/src/create.ts b/src/create.ts index ab7087ad..43adcc9b 100644 --- a/src/create.ts +++ b/src/create.ts @@ -4,20 +4,10 @@ * @module @kjanat/dreamcli/create */ -import { - linkSync, - lstatSync, - mkdirSync, - mkdtempSync, - readdirSync, - renameSync, - rmdirSync, - rmSync, - statSync, - writeFileSync, -} from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; +import { lstatSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; import { CLIError } from './core/errors/index.ts'; +import { publishFiles } from './create/publish.ts'; import { cliTemplate, commandTemplate, @@ -53,13 +43,6 @@ export interface ScaffoldResult { readonly testRunner?: 'bun:test' | 'vitest'; } -function existingFile(path: string): CLIError { - return new CLIError(`Refusing to overwrite existing file: ${path}`, { - code: 'SCAFFOLD_FILE_EXISTS', - suggest: 'Use --force to replace the existing starter file.', - }); -} - /** Normalize a project name for use as a package name and filename. */ function normalizeProjectName(input: string): string | undefined { const name = input @@ -73,19 +56,6 @@ function normalizeProjectName(input: string): string | undefined { return name; } -function makeDirectory(path: string, created: string[]): void { - try { - mkdirSync(path); - created.push(path); - } catch (error) { - const { code } = error as NodeJS.ErrnoException; - if (code === 'EEXIST' && statSync(path, { throwIfNoEntry: false })?.isDirectory()) return; - if (code !== 'ENOENT' || dirname(path) === path) throw error; - makeDirectory(dirname(path), created); - makeDirectory(path, created); - } -} - /** Create a named npm project or add starter files to an explicit output directory. */ export function scaffold(options: ScaffoldOptions): ScaffoldResult { const name = normalizeProjectName(options.name); @@ -105,7 +75,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { : join(directory, project ? 'src/commands/hello.test.ts' : `${name}.test.ts`); const testRunner = test === undefined ? undefined : project ? 'vitest' : detectTestRunner(directory); - const files: { path: string; content: string; mode?: number }[] = [ + const files: { path: string; content: string }[] = [ { path: entry, content: (project ? cliTemplate : standaloneTemplate).replace('__CLI_NAME__', name), @@ -172,64 +142,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } } - for (const file of files) { - const { path } = file; - const existing = lstatSync(path, { throwIfNoEntry: false }); - if (!existing) continue; - if (!existing.isFile()) { - throw new CLIError(`Cannot replace a path that is not a regular file: ${path}`, { - code: 'SCAFFOLD_NOT_A_FILE', - }); - } - if (!options.force) throw existingFile(path); - file.mode = existing.mode & 0o777; - } - - const created: string[] = []; - const directories: string[] = []; - try { - makeDirectory(directory, directories); - // Stage every file before publishing any output. - const staging = mkdtempSync(join(directory, '.dreamcli-')); - try { - const staged = files.map(({ path, content, mode }, index) => { - const source = join(staging, String(index)); - writeFileSync(source, content, mode === undefined ? undefined : { mode }); - return { path, source }; - }); - - for (const { path, source } of staged) { - makeDirectory(dirname(path), directories); - if (options.force && !project) { - renameSync(source, path); - continue; - } - // A hard link publishes the complete file and fails if another writer won the race. - try { - linkSync(source, path); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(path); - throw error; - } - created.push(path); - } - } finally { - rmSync(staging, { recursive: true, force: true }); - } - } catch (error) { - try { - for (const path of created) rmSync(path, { force: true }); - } finally { - for (const path of directories.reverse()) { - try { - rmdirSync(path); - } catch { - // Leave directories that another writer populated intact. - } - } - } - throw error; - } + publishFiles(files, !project && options.force === true); return { name, diff --git a/src/create/git.test.ts b/src/create/git.test.ts index 15180ba3..e0c1b084 100644 --- a/src/create/git.test.ts +++ b/src/create/git.test.ts @@ -13,7 +13,14 @@ it.skipIf(spawnSync('git', ['--version']).status !== 0)( try { const config = join(root, 'gitconfig'); writeFileSync(config, '[user]\n\tname = DreamCLI Test\n\temail = dreamcli@example.invalid\n'); - const env = { ...process.env, GIT_CONFIG_GLOBAL: config, GIT_CONFIG_NOSYSTEM: '1' }; + const inherited = Object.entries(process.env).filter( + ([key]) => !key.toUpperCase().startsWith('GIT_'), + ); + const env = { + ...Object.fromEntries(inherited), + GIT_CONFIG_GLOBAL: config, + GIT_CONFIG_NOSYSTEM: '1', + }; const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim(); const init = (cwd: string, extraEnv = {}) => diff --git a/src/create/publish.ts b/src/create/publish.ts new file mode 100644 index 00000000..a66da5ea --- /dev/null +++ b/src/create/publish.ts @@ -0,0 +1,131 @@ +/** Stage and publish scaffold files while holding exclusive locks on their destinations. @module */ + +import { + chmodSync, + linkSync, + lstatSync, + mkdirSync, + renameSync, + rmdirSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join } from 'node:path'; +import { CLIError } from '../core/errors/index.ts'; + +function makeDirectory(path: string, created: string[]): void { + try { + mkdirSync(path); + created.push(path); + } catch (error) { + const { code } = error as NodeJS.ErrnoException; + if (code === 'EEXIST' && statSync(path, { throwIfNoEntry: false })?.isDirectory()) return; + if (code !== 'ENOENT' || dirname(path) === path) throw error; + makeDirectory(dirname(path), created); + makeDirectory(path, created); + } +} + +interface StagedFile { + path: string; + lock: string; + backup?: string; + published?: boolean; +} + +function lockFile(path: string): StagedFile { + const lock = `${path}.dreamcli-lock`; + try { + mkdirSync(lock, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + throw new CLIError(`Scaffold destination is locked: ${path}`, { + code: 'SCAFFOLD_BUSY', + suggest: `Retry after the other scaffold finishes. If it was interrupted, inspect ${lock} before removing it.`, + }); + } + return { path, lock }; +} + +function stage(file: StagedFile, content: string, force: boolean): void { + const existing = lstatSync(file.path, { throwIfNoEntry: false }); + if (existing && !existing.isFile()) { + throw new CLIError(`Cannot replace a path that is not a regular file: ${file.path}`, { + code: 'SCAFFOLD_NOT_A_FILE', + }); + } + if (existing && !force) throw existingFile(file.path); + const source = join(file.lock, 'new'); + writeFileSync(source, content); + if (existing) { + chmodSync(source, existing.mode & 0o777); + file.backup = join(file.lock, 'original'); + linkSync(file.path, file.backup); + } +} + +function publish(file: StagedFile): void { + const source = join(file.lock, 'new'); + if (file.backup) renameSync(source, file.path); + else { + try { + linkSync(source, file.path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(file.path); + throw error; + } + } + file.published = true; +} + +/** Acquire every destination before publishing. Retain its backup if a restore itself fails. */ +export function publishFiles( + files: readonly { path: string; content: string }[], + force: boolean, +): void { + const directories: string[] = []; + const staged: StagedFile[] = []; + const errors: unknown[] = []; + try { + for (const { path, content } of files) { + makeDirectory(dirname(path), directories); + const file = lockFile(path); + staged.push(file); + stage(file, content, force); + } + for (const file of staged) publish(file); + } catch (error) { + errors.push(error); + } + const rollback = errors.length > 0; + for (const file of staged.reverse()) { + try { + if (rollback && file.published) { + if (file.backup) renameSync(file.backup, file.path); + else rmSync(file.path); + } + rmSync(file.lock, { recursive: true }); + } catch (error) { + errors.push(error); + } + } + if (rollback) { + for (const path of directories.reverse()) { + try { + rmdirSync(path); + } catch { + // A concurrent writer may have populated this directory. + } + } + } + if (errors.length === 1) throw errors[0]; + if (errors.length > 1) throw new AggregateError(errors, 'Could not clean up scaffold files.'); +} + +function existingFile(path: string): CLIError { + return new CLIError(`Refusing to overwrite existing file: ${path}`, { + code: 'SCAFFOLD_FILE_EXISTS', + suggest: 'Use --force to replace the existing starter file.', + }); +} diff --git a/src/create/templates.ts b/src/create/templates.ts index f32d45ca..3c7159d5 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -18,10 +18,10 @@ import { hello } from './commands/hello.ts'; await cli('__CLI_NAME__').command(hello).run(); `; -export const standaloneTemplate = `import { arg, cli, command } from '@kjanat/dreamcli'; +export const standaloneTemplate = `import { arg, cli, command, isMainModule } from '@kjanat/dreamcli'; ${hello} -if (import.meta.main) { +if (isMainModule(import.meta)) { await cli('__CLI_NAME__').command(hello).run(); } `; diff --git a/src/runtime/main-module.ts b/src/runtime/main-module.ts new file mode 100644 index 00000000..20d4e07d --- /dev/null +++ b/src/runtime/main-module.ts @@ -0,0 +1,27 @@ +/** Detect direct module execution across supported runtimes. @module */ + +/** + * Report whether the calling module is the process entrypoint, cross-runtime. + * + * Uses the runtime's native `import.meta.main` when available. On older Node + * releases, compare the module filename with the resolved entry script. + * + * @param meta - The calling module's `import.meta`. + * @returns `true` when the module was run as the entrypoint. + * + * @example + * ```ts + * if (isMainModule(import.meta)) cli('mycli').command(deploy).run(); + * ``` + */ +export function isMainModule(meta: ImportMeta): boolean { + if (typeof meta.main === 'boolean') return meta.main; + const entry = globalThis.process?.argv[1]; + if (!entry || !meta.filename) return false; + if (entry === meta.filename) return true; + try { + return globalThis.process.getBuiltinModule('fs').realpathSync(entry) === meta.filename; + } catch { + return false; + } +} diff --git a/tests/fixtures/scaffold-publication.mjs b/tests/fixtures/scaffold-publication.mjs new file mode 100644 index 00000000..9025fdde --- /dev/null +++ b/tests/fixtures/scaffold-publication.mjs @@ -0,0 +1,39 @@ +/** Run a scaffold with a deterministic filesystem failure in an isolated Node process. @module */ + +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import { syncBuiltinESMExports } from 'node:module'; +import { basename } from 'node:path'; +import { scaffold } from '../../src/create.ts'; + +const [scenario, target] = process.argv.slice(2); +const options = { name: 'demo', out: target, force: scenario === 'replace' }; + +if (scenario === 'contender') { + // A successful overwrite or any other error fails the parent's race assertion. + try { + scaffold({ ...options, force: true }); + } catch (error) { + if (error.code === 'SCAFFOLD_BUSY') process.exit(0); + throw error; + } + throw new Error('A concurrent scaffold replaced a locked file'); +} + +const link = fs.linkSync; +fs.linkSync = (source, destination) => { + if (scenario === 'project' && basename(destination) === 'hello.ts') + throw new Error('project publication failed'); + if (basename(destination) === 'demo.test.ts') { + execFileSync(process.execPath, [import.meta.filename, 'contender', target]); + throw new Error('second file failed'); + } + return link(source, destination); +}; +if (scenario === 'stage') { + fs.writeFileSync = () => { + throw new Error('staging failed'); + }; +} +syncBuiltinESMExports(); +scaffold(scenario === 'project' ? { name: 'demo', directory: target } : options); From 2342c1d08178930f3cf4834cad26dc82e137e5c8 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 07:45:46 -0500 Subject: [PATCH 10/21] Document dependency installation for existing projects --- skills/cli-creation/SKILL.md | 5 +++-- skills/cli-creation/references/consumer-workflow.md | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/skills/cli-creation/SKILL.md b/skills/cli-creation/SKILL.md index 2d66fd85..fc7aee4d 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/cli-creation/SKILL.md @@ -24,10 +24,11 @@ both. 1. Create a project: `bunx --bun --package @kjanat/dreamcli dreamcli create mycli`. Enter the project and install its dependencies with `cd mycli && bun install`. -2. To add starter files to an existing project instead, use +2. To add starter files to an existing project, install DreamCLI there with + `bun add @kjanat/dreamcli` and run `bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out .`. Tests are generated by default. For existing projects, Bun without Vitest uses - `bun:test`; otherwise the generated test uses Vitest. + `bun:test`; otherwise the generated test uses Vitest. Add it with `bun add -d vitest` if needed. 3. Run and validate generated files: - Run the generated entrypoint, for example `bun ./src/cli.ts --help` in a new project. - Run the generated test unless `--no-test` was used. diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/cli-creation/references/consumer-workflow.md index a92e6478..2f7f80de 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/cli-creation/references/consumer-workflow.md @@ -16,14 +16,16 @@ template and ending with validated behavior. ## Implementation flow -1. Scaffold starter files. +1. Install DreamCLI in the existing project and scaffold starter files. ```bash + bun add @kjanat/dreamcli bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out . ``` The scaffolder detects the package manager and Vitest usage to choose either - a `bun:test` or Vitest starter test template. + a `bun:test` or Vitest starter test template. If the test imports `vitest` + and the project does not already declare it, run `bun add -d vitest`. 2. Shape the command surface. From 53b34f727a125983800dba61f31b9405121496a8 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 21:26:13 -0500 Subject: [PATCH 11/21] Clarify how DreamCLI chooses the starter test runner --- skills/cli-creation/SKILL.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/skills/cli-creation/SKILL.md b/skills/cli-creation/SKILL.md index fc7aee4d..a9aaae06 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/cli-creation/SKILL.md @@ -27,8 +27,10 @@ both. 2. To add starter files to an existing project, install DreamCLI there with `bun add @kjanat/dreamcli` and run `bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out .`. - Tests are generated by default. For existing projects, Bun without Vitest uses - `bun:test`; otherwise the generated test uses Vitest. Add it with `bun add -d vitest` if needed. + Tests are generated by default. DreamCLI uses `bun:test` only if the project’s + `packageManager` (or its lockfile if none is declared) identifies Bun and no + Vitest usage is detected. The runtime running DreamCLI does not affect this. + Otherwise, install Vitest as a dev dependency if it isn’t already available. 3. Run and validate generated files: - Run the generated entrypoint, for example `bun ./src/cli.ts --help` in a new project. - Run the generated test unless `--no-test` was used. From 53c32ac20dc534b7347140f1185fefb846e2cdd0 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 21:40:50 -0500 Subject: [PATCH 12/21] Greet Satan in the starter examples --- README.md | 2 +- skills/cli-creation/references/runtime-notes.md | 4 ++-- src/create/templates.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 35d691d3..0afa61ea 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Create a TypeScript CLI project in a new or empty directory: npm exec --package=@kjanat/dreamcli -- dreamcli create mycli cd mycli npm install -npm start -- hello Ada +npm start -- hello Satan npm test npm run typecheck ``` diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index 20f17d1e..99771932 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -5,12 +5,12 @@ After `dreamcli create mycli`, enter the generated project and install its depen ```sh cd mycli npm install -npm start -- hello Ada +npm start -- hello Satan npm test npm run typecheck ``` -With Bun, use `bun install`, `bun src/cli.ts hello Ada`, and `bunx --bun vitest run` in that directory. +With Bun, use `bun install`, `bun src/cli.ts hello Satan`, and `bunx --bun vitest run` in that directory. ## Files added with `--out` diff --git a/src/create/templates.ts b/src/create/templates.ts index 3c7159d5..6aceb575 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -31,9 +31,9 @@ import { expect, it } from '__TEST_RUNNER__'; import { hello } from '__COMMAND_FILE__'; it('greets the name passed on the command line', async () => { - const result = await runCommand(hello, ['Ada']); + const result = await runCommand(hello, ['Satan']); expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Ada!\\n']); + expect(result.stdout).toEqual(['Hello, Satan!\\n']); }); `; From 74e330b9a2b27f177999f4182f74cf30d115fa38 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 21:42:46 -0500 Subject: [PATCH 13/21] =?UTF-8?q?Use=20Jalape=C3=B1o=20in=20the=20starter?= =?UTF-8?q?=20greeting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- skills/cli-creation/references/runtime-notes.md | 4 ++-- src/create/templates.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0afa61ea..8e47b555 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Create a TypeScript CLI project in a new or empty directory: npm exec --package=@kjanat/dreamcli -- dreamcli create mycli cd mycli npm install -npm start -- hello Satan +npm start -- hello Jalapeño npm test npm run typecheck ``` diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/cli-creation/references/runtime-notes.md index 99771932..3ec0bf8c 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/cli-creation/references/runtime-notes.md @@ -5,12 +5,12 @@ After `dreamcli create mycli`, enter the generated project and install its depen ```sh cd mycli npm install -npm start -- hello Satan +npm start -- hello Jalapeño npm test npm run typecheck ``` -With Bun, use `bun install`, `bun src/cli.ts hello Satan`, and `bunx --bun vitest run` in that directory. +With Bun, use `bun install`, `bun src/cli.ts hello Jalapeño`, and `bunx --bun vitest run` in that directory. ## Files added with `--out` diff --git a/src/create/templates.ts b/src/create/templates.ts index 6aceb575..edf69fc8 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -31,9 +31,9 @@ import { expect, it } from '__TEST_RUNNER__'; import { hello } from '__COMMAND_FILE__'; it('greets the name passed on the command line', async () => { - const result = await runCommand(hello, ['Satan']); + const result = await runCommand(hello, ['Jalapeño']); expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Satan!\\n']); + expect(result.stdout).toEqual(['Hello, Jalapeño!\\n']); }); `; From eb3a1c8e76ea0a995eeaa1344331ea46ea5d9297 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 21:53:23 -0500 Subject: [PATCH 14/21] Guide interactive project creation and fix standalone starters --- README.md | 3 ++- bin/dreamcli.mjs | 47 ++++++++++++++++++++++++++-------- src/core/prompt/prompt.test.ts | 7 +++++ src/core/prompt/terminal.ts | 5 ++-- src/create.test.ts | 44 +++++++++++++++++++++---------- src/create.ts | 10 +++++++- src/create/templates.ts | 29 ++++++++++++++++++--- 7 files changed, 115 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 8e47b555..26149abe 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,8 @@ mycli/ └── hello.test.ts ``` -`dreamcli init` is an alias. In a terminal, an omitted path prompts for a directory. +In a terminal, `npx @kjanat/dreamcli` asks where to create the project and prints the commands +to install dependencies and run the starter. `dreamcli init` is an alias for `dreamcli create`. Non-interactive runs require a path. Use `.` explicitly to create in an empty current directory, where the CLI asks for confirmation unless you pass `--yes`. diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index cb3ae002..cc608ff7 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,13 +3,37 @@ /** DreamCLI's package executable. @module */ import { basename, relative, resolve, sep } from 'node:path'; -import { cwd, env, stderr, stdin } from 'node:process'; +import { argv, cwd, env, platform, stderr, stdin, stdout, versions } from 'node:process'; import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; import { initGit } from './git.mjs'; +const inCI = env.CI && env.CI !== 'false' && env.CI !== '0'; +const terminal = !inCI && stdin.isTTY && stdout.isTTY && stderr.isTTY; + +function nextSteps(directory, test) { + const commands = []; + const path = relative(cwd(), directory); + if (path) { + if (platform === 'win32') { + // PowerShell recognizes typographic single quotes as delimiters too. + commands.push(`Set-Location -LiteralPath '${directory.replace(/['‘’‚‛]/gu, "'$&")}'`); + } else { + commands.push(`cd './${path.replaceAll("'", "'\\''")}'`); + } + } + if (versions.bun) { + commands.push('bun install', 'bun src/cli.ts hello Jalapeño'); + if (test) commands.push('bunx --bun vitest run'); + } else { + commands.push('npm install', 'npm start -- hello Jalapeño'); + if (test) commands.push('npm test'); + } + return commands.join('\n'); +} + const create = command('create') .alias('init') .description('Generate a DreamCLI starter') @@ -22,19 +46,20 @@ const create = command('create') ) .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) - .flag('force', flag.boolean().default(false).describe('Replace existing starter files')) + .flag( + 'force', + flag.boolean().default(false).describe('Replace existing starter files when using --out'), + ) .action(async ({ args, flags, out, ask }) => { const { git: useGit, name: explicitName, yes, ...options } = flags; const project = options.out === undefined; - const inCI = env.CI && env.CI !== 'false' && env.CI !== '0'; - const interactive = - project && !yes && !inCI && !out.jsonMode && out.isTTY && stdin.isTTY && stderr.isTTY; + const interactive = project && !yes && !out.jsonMode && terminal; let target = args.directory; if (!target && interactive) { target = await ask( prompt.input({ - message: 'Directory', + message: 'Where should I create your CLI?', }), ); } @@ -73,11 +98,13 @@ const create = command('create') } out.log(project ? `Created ${target}` : `Created ${relative(cwd(), result.entry)}`); if (git?.error) out.warn(`Git: ${git.error}`); + if (project) out.status(`\n${nextSteps(directory, result.test)}`); }); -await cli('dreamcli') +const app = cli('dreamcli') .manifest({ from: import.meta, files: ['package.json'] }) .links() - .description('Create a project with DreamCLI') - .command(create) - .run(); + .description('Create a project with DreamCLI'); + +if (terminal && argv.length === 2) await app.default(create).run(); +else await app.command(create).run(); diff --git a/src/core/prompt/prompt.test.ts b/src/core/prompt/prompt.test.ts index 91f06fc2..626d4230 100644 --- a/src/core/prompt/prompt.test.ts +++ b/src/core/prompt/prompt.test.ts @@ -265,6 +265,13 @@ describe('createTerminalPrompter', () => { expect(lines[0]).toContain('Name:'); }); + it('keeps a question mark as the input prompt delimiter', async () => { + const { write, lines } = captureWrite(); + const prompter = createTerminalPrompter(mockRead(['tools']), write); + await prompter.promptOne({ kind: 'input', message: 'Where should I create your CLI?' }); + expect(lines[0]).toBe('Where should I create your CLI? '); + }); + it('shows placeholder when set', async () => { const { write, lines } = captureWrite(); const prompter = createTerminalPrompter(mockRead(['test']), write); diff --git a/src/core/prompt/terminal.ts b/src/core/prompt/terminal.ts index 542ac272..a75c24d2 100644 --- a/src/core/prompt/terminal.ts +++ b/src/core/prompt/terminal.ts @@ -196,10 +196,11 @@ async function promptInput( if (config.kind === 'input' && config.placeholder !== undefined) hints.push(config.placeholder); if (config.kind === 'input' && config.default !== undefined && !config.sensitive) hints.push(`default: ${config.default}`); - const hint = hints.length > 0 ? ` (${hints.join(', ')})` : ''; + const label = hints.length > 0 ? `${config.message} (${hints.join(', ')})` : config.message; + const suffix = /[?:]$/.test(label) ? ' ' : ': '; while (retries < MAX_RETRIES) { - write(`${config.message}${hint}: `); + write(label + suffix); const line = await read(); if (line === null) return { answered: false }; diff --git a/src/create.test.ts b/src/create.test.ts index 4280fcd0..70d0d997 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -14,6 +14,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; +import type { ScaffoldOptions } from './create.ts'; import { scaffold } from './create.ts'; function withProject(test: (directory: string) => void): void { @@ -25,20 +26,21 @@ function withProject(test: (directory: string) => void): void { } } +function runScaffold(cwd: string, options: ScaffoldOptions) { + return execFileSync( + process.execPath, + [ + ...(typeof Deno === 'undefined' ? ['-e'] : ['eval', '--ext=mjs']), + `import { scaffold } from ${JSON.stringify(new URL('./create.ts', import.meta.url).href)}; scaffold(${JSON.stringify(options)});`, + ], + { cwd, stdio: 'pipe' }, + ); +} + describe('scaffold', () => { it('creates a runnable npm project by default without touching an existing directory', () => { withProject((directory) => { - const run = (options: { name: string; test?: boolean; force?: boolean }) => - execFileSync( - process.execPath, - [ - ...(typeof Deno === 'undefined' ? ['-e'] : ['eval', '--ext=mjs']), - `import { scaffold } from ${JSON.stringify(new URL('./create.ts', import.meta.url).href)}; scaffold(${JSON.stringify(options)});`, - ], - { cwd: directory, stdio: 'pipe' }, - ); - - run({ name: 'My CLI' }); + runScaffold(directory, { name: 'My CLI' }); const packageFile = join(directory, 'my-cli', 'package.json'); const manifest = readFileSync(packageFile, 'utf8'); expect(JSON.parse(manifest)).toMatchObject({ @@ -49,10 +51,10 @@ describe('scaffold', () => { devDependencies: { vitest: expect.any(String) }, }); expect(existsSync(join(directory, 'my-cli', 'src/commands/hello.test.ts'))).toBe(true); - expect(() => run({ name: 'my-cli', force: true })).toThrow(/not empty/); + expect(() => runScaffold(directory, { name: 'my-cli', force: true })).toThrow(/not empty/); expect(readFileSync(packageFile, 'utf8')).toBe(manifest); - run({ name: 'no-test', test: false }); + runScaffold(directory, { name: 'no-test', test: false }); const withoutTests = JSON.parse( readFileSync(join(directory, 'no-test', 'package.json'), 'utf8'), ); @@ -62,6 +64,22 @@ describe('scaffold', () => { }); }); + it('rejects a blank destination before resolving it to the working directory', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + writeFileSync(entry, 'keep this file'); + for (const target of ['', ' ']) { + for (const destination of [{ out: target }, { directory: target }]) { + expect(() => runScaffold(cwd, { name: 'demo', ...destination, force: true })).toThrow( + /Provide a non-empty destination directory/, + ); + } + } + expect(readFileSync(entry, 'utf8')).toBe('keep this file'); + expect(readdirSync(cwd)).toEqual(['demo.ts']); + }); + }); + it('uses an explicit project directory and keeps its existing parents', () => { withProject((directory) => { const target = join(directory, 'nested', 'My CLI'); diff --git a/src/create.ts b/src/create.ts index 43adcc9b..a3be8527 100644 --- a/src/create.ts +++ b/src/create.ts @@ -67,7 +67,15 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } const project = options.out === undefined; - const directory = resolve(options.out ?? options.directory ?? name); + const target = options.out ?? options.directory ?? name; + if (target.trim() === '') { + throw new CLIError('Provide a non-empty destination directory.', { + code: 'SCAFFOLD_EMPTY_DIRECTORY', + exitCode: 2, + suggest: 'Use . to select the current directory explicitly.', + }); + } + const directory = resolve(target); const entry = join(directory, project ? 'src/cli.ts' : `${name}.ts`); const test = options.test === false diff --git a/src/create/templates.ts b/src/create/templates.ts index edf69fc8..def8d6ce 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -4,7 +4,9 @@ const hello = `export const hello = command('hello') .description('Say hello') .arg('name', arg.string().default('World').describe('Who to greet')) .action(({ args, out }) => { - out.log(\`Hello, \${args.name}!\`); + const message = \`Hello, \${args.name}!\`; + if (out.jsonMode) out.json({ message }); + else out.log(message); }); `; @@ -18,10 +20,23 @@ import { hello } from './commands/hello.ts'; await cli('__CLI_NAME__').command(hello).run(); `; -export const standaloneTemplate = `import { arg, cli, command, isMainModule } from '@kjanat/dreamcli'; +export const standaloneTemplate = `import { realpathSync } from 'node:fs'; +import { argv } from 'node:process'; +import { arg, cli, command } from '@kjanat/dreamcli'; ${hello} -if (isMainModule(import.meta)) { +// Node 24.0 and 24.1 predate import.meta.main. +function isNodeEntry(): boolean { + const entry = argv[1]; + if (!entry) return false; + try { + return realpathSync(entry) === import.meta.filename; + } catch { + return false; + } +} + +if (import.meta.main ?? isNodeEntry()) { await cli('__CLI_NAME__').command(hello).run(); } `; @@ -36,4 +51,12 @@ it('greets the name passed on the command line', async () => { expect(result.exitCode).toBe(0); expect(result.stdout).toEqual(['Hello, Jalapeño!\\n']); }); + +it('writes a JSON greeting to stdout with --json', async () => { + const result = await runCommand(hello, ['Jalapeño', '--json']); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout.join(''))).toEqual({ message: 'Hello, Jalapeño!' }); + expect(result.stderr).toEqual([]); +}); `; From 44ce90b5689f88a31dee1a3c31d9dad53140d56b Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 21:55:35 -0500 Subject: [PATCH 15/21] Test scaffold rollback with real filesystem conflicts --- src/create.test.ts | 82 +++++++++++++++---------- tests/fixtures/scaffold-publication.mjs | 39 ------------ 2 files changed, 49 insertions(+), 72 deletions(-) delete mode 100644 tests/fixtures/scaffold-publication.mjs diff --git a/src/create.test.ts b/src/create.test.ts index 70d0d997..5740fad9 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -12,8 +12,8 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; +import { publishFiles } from './create/publish.ts'; import type { ScaffoldOptions } from './create.ts'; import { scaffold } from './create.ts'; @@ -91,38 +91,54 @@ describe('scaffold', () => { }); }); - it.skipIf(typeof Deno !== 'undefined' || typeof Bun !== 'undefined')( - 'rolls back partial writes, rejects concurrent replacement and permits a retry', - () => { - withProject((out) => { - const fixture = fileURLToPath( - new URL('../tests/fixtures/scaffold-publication.mjs', import.meta.url), - ); - const run = (scenario: string, target = out) => - execFileSync(process.execPath, [fixture, scenario, target], { stdio: 'pipe' }); - - const nested = join(out, 'nested', 'target'); - expect(() => run('stage', nested)).toThrow(/staging failed/); - expect(readdirSync(out)).toEqual([]); - - expect(() => run('project')).toThrow(/Error: project publication failed/); - expect(readdirSync(out)).toEqual([]); - - expect(() => run('create')).toThrow(/Error: second file failed/); - expect(readdirSync(out)).toEqual([]); - - const entry = join(out, 'demo.ts'); - writeFileSync(entry, 'original'); - expect(() => run('replace')).toThrow(/Error: second file failed/); - expect(readdirSync(out)).toEqual(['demo.ts']); - expect(readFileSync(entry, 'utf8')).toBe('original'); - - const result = scaffold({ name: 'demo', out, force: true }); - expect(result.files).toEqual([entry, join(out, 'demo.test.ts')]); - expect(readdirSync(out).sort()).toEqual(['demo.test.ts', 'demo.ts']); - }); - }, - ); + it('leaves another publisher’s entry intact when a forced scaffold cannot acquire its lock', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + const lock = `${entry}.dreamcli-lock`; + mkdirSync(lock); + writeFileSync(entry, 'first publisher'); + const options = { name: 'demo', out: cwd, force: true }; + expect(() => runScaffold(cwd, options)).toThrow(/destination is locked/); + expect(readFileSync(entry, 'utf8')).toBe('first publisher'); + expect(existsSync(join(cwd, 'demo.test.ts'))).toBe(false); + expect(existsSync(lock)).toBe(true); + + rmSync(lock, { recursive: true }); + expect(scaffold(options).files).toEqual([entry, join(cwd, 'demo.test.ts')]); + }); + }); + + it('restores replaced files and removes new files when publication fails after staging', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + writeFileSync(entry, 'original'); + // Staging the child creates its parent. Publishing a file at that same path must fail. + const paths = [entry, join(cwd, 'new.ts'), join(cwd, 'parent'), join(cwd, 'parent/child.ts')]; + const files = paths.map((path) => ({ path, content: 'replacement' })); + expect(() => publishFiles(files, true)).toThrow(/Refusing to overwrite existing file/); + expect(readdirSync(cwd)).toEqual(['demo.ts']); + expect(readFileSync(entry, 'utf8')).toBe('original'); + publishFiles(files.slice(0, 2), true); + expect(readFileSync(entry, 'utf8')).toBe('replacement'); + }); + }); + + it('cleans up newly created directories when staging is interrupted', () => { + withProject((cwd) => { + const occupied = join(cwd, 'occupied'); + mkdirSync(occupied); + expect(() => + publishFiles( + [ + { path: join(cwd, 'nested/deeper/entry.ts'), content: 'new' }, + { path: occupied, content: 'cannot replace a directory' }, + ], + true, + ), + ).toThrow(/regular file/); + expect(readdirSync(cwd)).toEqual(['occupied']); + }); + }); it('adds starter files under a nested destination in a Bun project', () => { withProject((directory) => { diff --git a/tests/fixtures/scaffold-publication.mjs b/tests/fixtures/scaffold-publication.mjs deleted file mode 100644 index 9025fdde..00000000 --- a/tests/fixtures/scaffold-publication.mjs +++ /dev/null @@ -1,39 +0,0 @@ -/** Run a scaffold with a deterministic filesystem failure in an isolated Node process. @module */ - -import { execFileSync } from 'node:child_process'; -import fs from 'node:fs'; -import { syncBuiltinESMExports } from 'node:module'; -import { basename } from 'node:path'; -import { scaffold } from '../../src/create.ts'; - -const [scenario, target] = process.argv.slice(2); -const options = { name: 'demo', out: target, force: scenario === 'replace' }; - -if (scenario === 'contender') { - // A successful overwrite or any other error fails the parent's race assertion. - try { - scaffold({ ...options, force: true }); - } catch (error) { - if (error.code === 'SCAFFOLD_BUSY') process.exit(0); - throw error; - } - throw new Error('A concurrent scaffold replaced a locked file'); -} - -const link = fs.linkSync; -fs.linkSync = (source, destination) => { - if (scenario === 'project' && basename(destination) === 'hello.ts') - throw new Error('project publication failed'); - if (basename(destination) === 'demo.test.ts') { - execFileSync(process.execPath, [import.meta.filename, 'contender', target]); - throw new Error('second file failed'); - } - return link(source, destination); -}; -if (scenario === 'stage') { - fs.writeFileSync = () => { - throw new Error('staging failed'); - }; -} -syncBuiltinESMExports(); -scaffold(scenario === 'project' ? { name: 'demo', directory: target } : options); From 107a36154f4b5d614524f10292e90aa6ac144fbe Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 22:08:34 -0500 Subject: [PATCH 16/21] =?UTF-8?q?Use=20DreamCLI=E2=80=99s=20runtime=20adap?= =?UTF-8?q?ter=20in=20the=20create=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/dreamcli.mjs | 27 +++++++++++++++------------ bin/git.mjs | 3 +-- src/create/git.test.ts | 2 +- src/create/templates.ts | 10 +++++----- src/create/test-runner.ts | 5 ++--- src/runtime/adapter.ts | 7 +++++++ src/runtime/deno.test.ts | 9 +++++++++ src/runtime/deno.ts | 3 +++ src/runtime/node.ts | 2 ++ src/runtime/runtime.test.ts | 10 ++++++++++ 10 files changed, 55 insertions(+), 23 deletions(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index cc608ff7..2c2f591f 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,28 +3,30 @@ /** DreamCLI's package executable. @module */ import { basename, relative, resolve, sep } from 'node:path'; -import { argv, cwd, env, platform, stderr, stdin, stdout, versions } from 'node:process'; import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; +import { createAdapter, detectRuntime } from '@kjanat/dreamcli/runtime'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; import { initGit } from './git.mjs'; -const inCI = env.CI && env.CI !== 'false' && env.CI !== '0'; -const terminal = !inCI && stdin.isTTY && stdout.isTTY && stderr.isTTY; +const adapter = createAdapter(); +const ci = adapter.env.CI; +const inCI = ci && ci !== 'false' && ci !== '0'; +const terminal = !inCI && adapter.stdinIsTTY && adapter.isTTY && adapter.stderrIsTTY; function nextSteps(directory, test) { const commands = []; - const path = relative(cwd(), directory); + const path = relative(adapter.cwd, directory); if (path) { - if (platform === 'win32') { + if (sep === '\\') { // PowerShell recognizes typographic single quotes as delimiters too. commands.push(`Set-Location -LiteralPath '${directory.replace(/['‘’‚‛]/gu, "'$&")}'`); } else { commands.push(`cd './${path.replaceAll("'", "'\\''")}'`); } } - if (versions.bun) { + if (detectRuntime() === 'bun') { commands.push('bun install', 'bun src/cli.ts hello Jalapeño'); if (test) commands.push('bunx --bun vitest run'); } else { @@ -42,7 +44,7 @@ const create = command('create') .flag('yes', flag.boolean().alias('y').describe('Use defaults without prompting')) .flag( 'out', - flag.string().describe('Write files into this directory instead of creating a project'), + flag.path().describe('Write files into this directory instead of creating a project'), ) .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) @@ -76,9 +78,9 @@ const create = command('create') ); } - const directory = resolve(target); + const directory = resolve(adapter.cwd, target); const name = explicitName ?? (project ? basename(directory) : target); - if (interactive && relative(cwd(), directory) === '') { + if (interactive && relative(adapter.cwd, directory) === '') { if (!(await ask(prompt.confirm({ message: 'Create here?', default: false })))) return; } @@ -90,13 +92,14 @@ const create = command('create') result.files.map((path) => relative(directory, path).split(sep).join('/')), DREAMCLI_VERSION, DREAMCLI_REVISION, + adapter.env, ) : undefined; if (out.jsonMode) { out.json({ ...result, ...(git && { git }) }); return; } - out.log(project ? `Created ${target}` : `Created ${relative(cwd(), result.entry)}`); + out.log(project ? `Created ${target}` : `Created ${relative(adapter.cwd, result.entry)}`); if (git?.error) out.warn(`Git: ${git.error}`); if (project) out.status(`\n${nextSteps(directory, result.test)}`); }); @@ -106,5 +109,5 @@ const app = cli('dreamcli') .links() .description('Create a project with DreamCLI'); -if (terminal && argv.length === 2) await app.default(create).run(); -else await app.command(create).run(); +const program = terminal && adapter.argv.length === 2 ? app.default(create) : app.command(create); +await program.run({ adapter }); diff --git a/bin/git.mjs b/bin/git.mjs index 82134969..454f6379 100644 --- a/bin/git.mjs +++ b/bin/git.mjs @@ -1,9 +1,8 @@ /** Initialize a standalone starter without touching a surrounding repository. @module */ import { spawnSync } from 'node:child_process'; -import { env } from 'node:process'; -export function initGit(cwd, files, version, revision) { +export function initGit(cwd, files, version, revision, env) { const options = { cwd, encoding: 'utf8', env: { ...env, LC_ALL: 'C' } }; const run = (...args) => spawnSync('git', args, options); const local = run('rev-parse', '--local-env-vars'); diff --git a/src/create/git.test.ts b/src/create/git.test.ts index e0c1b084..2e361626 100644 --- a/src/create/git.test.ts +++ b/src/create/git.test.ts @@ -29,7 +29,7 @@ it.skipIf(spawnSync('git', ['--version']).status !== 0)( typeof Deno === 'undefined' ? process.execPath : 'node', [ '-e', - `import { initGit } from ${JSON.stringify(new URL('../../bin/git.mjs', import.meta.url).href)}; console.log(JSON.stringify(initGit(process.cwd(), ['starter.ts'], '5.7.0', 'abc1234')));`, + `import { initGit } from ${JSON.stringify(new URL('../../bin/git.mjs', import.meta.url).href)}; console.log(JSON.stringify(initGit(process.cwd(), ['starter.ts'], '5.7.0', 'abc1234', process.env)));`, ], { cwd, env: { ...env, ...extraEnv }, encoding: 'utf8' }, ), diff --git a/src/create/templates.ts b/src/create/templates.ts index def8d6ce..1c167e57 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -21,13 +21,13 @@ await cli('__CLI_NAME__').command(hello).run(); `; export const standaloneTemplate = `import { realpathSync } from 'node:fs'; -import { argv } from 'node:process'; -import { arg, cli, command } from '@kjanat/dreamcli'; +import { arg, cli, command, isMainModule } from '@kjanat/dreamcli'; +import { createAdapter } from '@kjanat/dreamcli/runtime'; ${hello} -// Node 24.0 and 24.1 predate import.meta.main. +// DreamCLI 5.7.0 relies on import.meta.main, absent on early Node 24. function isNodeEntry(): boolean { - const entry = argv[1]; + const entry = createAdapter().argv[1]; if (!entry) return false; try { return realpathSync(entry) === import.meta.filename; @@ -36,7 +36,7 @@ function isNodeEntry(): boolean { } } -if (import.meta.main ?? isNodeEntry()) { +if (isMainModule(import.meta) || (import.meta.main === undefined && isNodeEntry())) { await cli('__CLI_NAME__').command(hello).run(); } `; diff --git a/src/create/test-runner.ts b/src/create/test-runner.ts index 8b2f017e..3c33b0ba 100644 --- a/src/create/test-runner.ts +++ b/src/create/test-runner.ts @@ -2,8 +2,7 @@ import type { Dirent } from 'node:fs'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; -import { cwd } from 'node:process'; +import { dirname, join, resolve } from 'node:path'; const manifests = ['package.json', 'package.json5', 'package.yaml', 'package.yml']; const lockfiles = [ @@ -88,5 +87,5 @@ function detectProject(start: string): 'bun:test' | 'vitest' | undefined { } export function detectTestRunner(directory: string): 'bun:test' | 'vitest' { - return detectProject(directory) ?? detectProject(cwd()) ?? 'vitest'; + return detectProject(directory) ?? detectProject(resolve('.')) ?? 'vitest'; } diff --git a/src/runtime/adapter.ts b/src/runtime/adapter.ts index b9a1c7a0..b1333b40 100644 --- a/src/runtime/adapter.ts +++ b/src/runtime/adapter.ts @@ -89,6 +89,9 @@ interface RuntimeAdapter { /** Whether stdin is connected to a TTY (used for prompt gating). */ readonly stdinIsTTY: boolean; + /** Whether prompts written to stderr are visible on a terminal. */ + readonly stderrIsTTY?: boolean; + /** Read current terminal dimensions for stdout, if available. */ readonly getTerminalSize: () => TerminalSize | undefined; @@ -245,6 +248,9 @@ interface TestAdapterOptions { /** TTY flag for stdin (defaults to `false`). */ readonly stdinIsTTY?: boolean; + /** Set the test adapter's stderr terminal state. Defaults to false. */ + readonly stderrIsTTY?: boolean; + /** Terminal dimensions returned by `getTerminalSize()`. */ readonly terminalSize?: TerminalSize; @@ -399,6 +405,7 @@ function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter { }, isTTY: options?.isTTY ?? false, stdinIsTTY, + stderrIsTTY: options?.stderrIsTTY ?? false, getTerminalSize: () => options?.terminalSize, onTerminalResize: (listener) => options?.onTerminalResize?.(listener), exit: diff --git a/src/runtime/deno.test.ts b/src/runtime/deno.test.ts index 20ec8b2f..30fff4fa 100644 --- a/src/runtime/deno.test.ts +++ b/src/runtime/deno.test.ts @@ -418,6 +418,15 @@ describe('createDenoAdapter', () => { expect(adapter.isTTY).toBe(false); }); + it('uses stderr.isTerminal for the prompt output stream when available', () => { + const adapter = createDenoAdapter( + mockDeno({ stderr: { isTerminal: () => true, writeSync: () => 0 } }), + ); + expect(adapter.isTTY).toBe(false); + expect(adapter.stderrIsTTY).toBe(true); + expect(createDenoAdapter(mockDeno()).stderrIsTTY).toBe(false); + }); + it('stdinIsTTY is true when stdin.isTerminal() returns true', () => { const ns = mockDeno({ stdin: { isTerminal: () => true, readable: mockReadableStream([]) }, diff --git a/src/runtime/deno.ts b/src/runtime/deno.ts index 33c5b9da..afae1ee6 100644 --- a/src/runtime/deno.ts +++ b/src/runtime/deno.ts @@ -101,6 +101,8 @@ interface DenoNamespace { /** Standard error — synchronous byte writer. */ readonly stderr: { + /** Whether stderr is connected to a terminal. */ + isTerminal?(): boolean; /** Write raw bytes to stderr synchronously. */ writeSync(p: Uint8Array): number; }; @@ -347,6 +349,7 @@ function createDenoAdapter(ns?: DenoNamespace): RuntimeAdapter { ...(input.readSecret !== undefined ? { readSecret: input.readSecret } : {}), readStdin: () => readDenoStdinAll(d, stdinIsTTY), isTTY: d.stdout.isTerminal(), + stderrIsTTY: d.stderr.isTerminal?.() ?? false, stdinIsTTY, getTerminalSize: () => readDenoTerminalSize(d), onTerminalResize: (listener) => onDenoTerminalResize(d, listener), diff --git a/src/runtime/node.ts b/src/runtime/node.ts index 1d8d3dbd..84b47fdd 100644 --- a/src/runtime/node.ts +++ b/src/runtime/node.ts @@ -77,6 +77,7 @@ interface NodeProcess { }; /** Standard error stream with write. */ readonly stderr: { + readonly isTTY?: boolean; on?(event: 'error', listener: (error: Error) => void): unknown; write(data: string, callback?: (error?: Error | null) => void): unknown; }; @@ -279,6 +280,7 @@ function createNodeAdapter(proc?: NodeProcess): RuntimeAdapter { ...(input.readSecret !== undefined ? { readSecret: input.readSecret } : {}), readStdin: () => readNodeStdinAll(p, stdinIsTTY), isTTY: p.stdout.isTTY === true, + stderrIsTTY: p.stderr.isTTY === true, stdinIsTTY, getTerminalSize: () => readNodeTerminalSize(p), onTerminalResize: (listener) => onNodeTerminalResize(p, listener), diff --git a/src/runtime/runtime.test.ts b/src/runtime/runtime.test.ts index 89f3f76a..7332622d 100644 --- a/src/runtime/runtime.test.ts +++ b/src/runtime/runtime.test.ts @@ -290,6 +290,16 @@ describe('createNodeAdapter', () => { expect(adapter.stdinIsTTY).toBe(true); }); + it('reports the prompt output terminal independently of stdout', () => { + const adapter = createNodeAdapter( + mockNodeProcess({ stderr: { isTTY: true, write: immediateWrite } }), + ); + expect(adapter.isTTY).toBe(false); + expect(adapter.stderrIsTTY).toBe(true); + expect(createTestAdapter({ isTTY: true }).stderrIsTTY).toBe(false); + expect(createTestAdapter({ stderrIsTTY: true }).stderrIsTTY).toBe(true); + }); + it('routes stdout writes to process.stdout.write', () => { const writeFn = vi.fn(); const mockProc = mockNodeProcess({ stdout: { isTTY: false, write: writeFn } }); From ae8b2f82dae56e3f183c0a6742c535565c942d6d Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 22:26:59 -0500 Subject: [PATCH 17/21] Use manifest links and terminal-aware styling in generated CLIs --- bin/dreamcli.mjs | 8 ++++++-- docs/guide/help.md | 5 ++--- src/core/output/index.ts | 2 +- src/core/output/output.test.ts | 8 ++++++++ src/core/schema/command.ts | 3 +-- src/create.test.ts | 4 +++- src/create/templates.ts | 16 +++++++++++++--- 7 files changed, 34 insertions(+), 12 deletions(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 2c2f591f..6b5ebdb3 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,6 +3,7 @@ /** DreamCLI's package executable. @module */ import { basename, relative, resolve, sep } from 'node:path'; +import { pathToFileURL } from 'node:url'; import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; @@ -99,14 +100,17 @@ const create = command('create') out.json({ ...result, ...(git && { git }) }); return; } - out.log(project ? `Created ${target}` : `Created ${relative(adapter.cwd, result.entry)}`); + const destination = project ? directory : result.entry; + const label = out.color.cyan(project ? target : relative(adapter.cwd, destination)); + out.log(`Created ${out.color.link(pathToFileURL(destination), label)}`); if (git?.error) out.warn(`Git: ${git.error}`); if (project) out.status(`\n${nextSteps(directory, result.test)}`); }); const app = cli('dreamcli') - .manifest({ from: import.meta, files: ['package.json'] }) + .manifest({ from: import.meta }) .links() + .help({ commandHeader: true }) .description('Create a project with DreamCLI'); const program = terminal && adapter.argv.length === 2 ? app.default(create) : app.command(create); diff --git a/docs/guide/help.md b/docs/guide/help.md index b0b29317..9d9e8012 100644 --- a/docs/guide/help.md +++ b/docs/guide/help.md @@ -199,9 +199,8 @@ The root-help header can wrap the program name and version in OSC 8 terminal hyperlinks (pointing at the repository and release tag). Explicit `--no-hyperlinks` / `--hyperlinks` flags take precedence, followed by `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, and finally TTY detection. When both -environment variables are set, `NO_HYPERLINKS` wins. The same resolved decision is exposed to handlers as -`out.isHyperlinkSupported`, so code rendering its own `out.color.link(...)` -output can gate on it and keep escapes out of piped or opted-out contexts. +environment variables are set, `NO_HYPERLINKS` wins. Handlers can format a link with `out.color.link(url, label)`. It follows +the same hyperlink policy and returns the label alone when links are disabled. Set `.help({ commandHeader: true })` to show that same program and version header in command help and help topics. The header uses the URLs from diff --git a/src/core/output/index.ts b/src/core/output/index.ts index 45b9f388..28e8270a 100644 --- a/src/core/output/index.ts +++ b/src/core/output/index.ts @@ -292,7 +292,7 @@ class OutputChannel implements Out { this.verbosity = this.policy.verbosity; this.isTTY = options.isTTY; this.terminalSize = options.terminalSize; - this.color = createColors(options.color); + this.color = createColors(options.color, options.isHyperlinkSupported); this.isHyperlinkSupported = options.isHyperlinkSupported; // Bind methods to the instance so they keep working when destructured diff --git a/src/core/output/output.test.ts b/src/core/output/output.test.ts index 578dfa7e..70ebd9d8 100644 --- a/src/core/output/output.test.ts +++ b/src/core/output/output.test.ts @@ -240,6 +240,14 @@ describe('isHyperlinkSupported', () => { expect(createOutput({ isTTY: false }).isHyperlinkSupported).toBe(false); }); + it.each([false, true])('applies the hyperlink policy to the palette with color=%s', (color) => { + const url = 'https://example.com/'; + const linked = createOutput({ color, isTTY: false, hyperlinks: true }); + const plain = createOutput({ color, isTTY: true, hyperlinks: false }); + expect(linked.color.link(url, 'docs')).toBe(`\x1b]8;;${url}\x1b\\docs\x1b]8;;\x1b\\`); + expect(plain.color.link(url, 'docs')).toBe('docs'); + }); + it('explicit hyperlinks option wins over isTTY', () => { expect(createOutput({ isTTY: false, hyperlinks: true }).isHyperlinkSupported).toBe(true); expect(createOutput({ isTTY: true, hyperlinks: false }).isHyperlinkSupported).toBe(false); diff --git a/src/core/schema/command.ts b/src/core/schema/command.ts index 9fbc1af6..c108f64b 100644 --- a/src/core/schema/command.ts +++ b/src/core/schema/command.ts @@ -255,8 +255,7 @@ interface Out { * * Honors explicit `--no-hyperlinks`/`--hyperlinks` argv flags first, then * `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, falling back to `isTTY`. - * Handlers rendering their own `out.color.link(...)` output can gate on - * this to keep OSC 8 escapes out of piped or opted-out contexts. + * `out.color.link(url, label)` applies this policy automatically. */ readonly isHyperlinkSupported: boolean; diff --git a/src/create.test.ts b/src/create.test.ts index 5740fad9..6c576902 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -153,7 +153,9 @@ describe('scaffold', () => { files: [join(out, 'my-cli.ts'), join(out, 'my-cli.test.ts')], testRunner: 'bun:test', }); - expect(readFileSync(result.entry, 'utf8')).toContain("cli('my-cli').command(hello)"); + const entry = readFileSync(result.entry, 'utf8'); + expect(entry).toContain("cli('my-cli')"); + expect(entry).toContain('.command(hello)'); expect(readFileSync(join(out, 'my-cli.test.ts'), 'utf8')).toContain("from 'bun:test'"); }); }); diff --git a/src/create/templates.ts b/src/create/templates.ts index 1c167e57..a8bc5afd 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -6,7 +6,7 @@ const hello = `export const hello = command('hello') .action(({ args, out }) => { const message = \`Hello, \${args.name}!\`; if (out.jsonMode) out.json({ message }); - else out.log(message); + else out.log(out.color.green(message)); }); `; @@ -17,7 +17,12 @@ ${hello}`; export const cliTemplate = `import { cli } from '@kjanat/dreamcli'; import { hello } from './commands/hello.ts'; -await cli('__CLI_NAME__').command(hello).run(); +await cli('__CLI_NAME__') + .manifest({ from: import.meta }) + .links() + .help({ commandHeader: true }) + .command(hello) + .run(); `; export const standaloneTemplate = `import { realpathSync } from 'node:fs'; @@ -37,7 +42,12 @@ function isNodeEntry(): boolean { } if (isMainModule(import.meta) || (import.meta.main === undefined && isNodeEntry())) { - await cli('__CLI_NAME__').command(hello).run(); + await cli('__CLI_NAME__') + .manifest({ from: import.meta }) + .links() + .help({ commandHeader: true }) + .command(hello) + .run(); } `; From 307de9294dfb9929641b3ccb482d60da20f9d922 Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 22:32:23 -0500 Subject: [PATCH 18/21] Keep starter tests runnable in paths containing URL delimiters or globs --- bin/dreamcli.mjs | 2 +- src/create.test.ts | 9 +++++++++ src/create.ts | 6 +++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 6b5ebdb3..c03b6a35 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -29,7 +29,7 @@ function nextSteps(directory, test) { } if (detectRuntime() === 'bun') { commands.push('bun install', 'bun src/cli.ts hello Jalapeño'); - if (test) commands.push('bunx --bun vitest run'); + if (test) commands.push('bun run test'); } else { commands.push('npm install', 'npm start -- hello Jalapeño'); if (test) commands.push('npm test'); diff --git a/src/create.test.ts b/src/create.test.ts index 6c576902..31e24dec 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -64,6 +64,15 @@ describe('scaffold', () => { }); }); + it('uses native imports for Vitest in a project under a hash-marked parent directory', () => { + withProject((cwd) => { + const directory = join(cwd, 'Peppers #5', 'cli'); + scaffold({ name: 'peppers', directory }); + const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')); + expect(manifest.scripts.test).toBe('vitest run --experimental.viteModuleRunner=false'); + }); + }); + it('rejects a blank destination before resolving it to the working directory', () => { withProject((cwd) => { const entry = join(cwd, 'demo.ts'); diff --git a/src/create.ts b/src/create.ts index a3be8527..23bde53a 100644 --- a/src/create.ts +++ b/src/create.ts @@ -101,6 +101,10 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } if (project) { + // Vite interprets these characters in module IDs. Native imports preserve the path. + const testScript = /[#?*]/.test(directory) + ? 'vitest run --experimental.viteModuleRunner=false' + : 'vitest run'; const manifest = { name, version: '0.1.0', @@ -109,7 +113,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { scripts: { start: 'node src/cli.ts', typecheck: 'tsc --noEmit', - ...(test !== undefined && { test: 'vitest run' }), + ...(test !== undefined && { test: testScript }), }, engines: { node: '>=22.22.2' }, dependencies: { From b818c74a1e391edf013fdd0a2e1707aa34cd439d Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Sun, 29 Nov 2026 22:33:49 -0500 Subject: [PATCH 19/21] =?UTF-8?q?Use=20the=20starter=E2=80=99s=20Node=20en?= =?UTF-8?q?try=20when=20Bun=20misreads=20a=20question=20mark=20in=20its=20?= =?UTF-8?q?path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/dreamcli.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index c03b6a35..08e1dfd6 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -28,7 +28,9 @@ function nextSteps(directory, test) { } } if (detectRuntime() === 'bun') { - commands.push('bun install', 'bun src/cli.ts hello Jalapeño'); + // Bun treats '?' in the absolute entry path as a query. The Node start script handles it. + const start = directory.includes('?') ? 'bun run start' : 'bun src/cli.ts'; + commands.push('bun install', `${start} hello Jalapeño`); if (test) commands.push('bun run test'); } else { commands.push('npm install', 'npm start -- hello Jalapeño'); From d906532b3f63a7ce852b889f8306edb90f489cbb Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Mon, 30 Nov 2026 04:26:46 -0500 Subject: [PATCH 20/21] Reject blank scaffold destinations and suppress hyperlinks in JSON mode --- bin/dreamcli.mjs | 6 ++++-- docs/guide/output.md | 2 +- src/core/output/index.ts | 8 +++----- src/core/output/output.test.ts | 9 +++++++++ src/core/schema/command.ts | 2 +- 5 files changed, 18 insertions(+), 9 deletions(-) diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 08e1dfd6..7339df91 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -61,14 +61,16 @@ const create = command('create') const interactive = project && !yes && !out.jsonMode && terminal; let target = args.directory; - if (!target && interactive) { + if (target === undefined && interactive) { target = await ask( prompt.input({ message: 'Where should I create your CLI?', + empty: 'accept', + trim: false, }), ); } - if (!target) { + if (!target?.trim()) { throw new CLIError( project ? 'Provide a project directory.' : 'Provide a CLI name with --out.', { diff --git a/docs/guide/output.md b/docs/guide/output.md index 21954f7b..1611c35b 100644 --- a/docs/guide/output.md +++ b/docs/guide/output.md @@ -327,7 +327,7 @@ if (!ctx.jsonMode && ctx.verbosity !== 'quiet') The returned `color` is the same gated palette the channel will expose as `out.color` (`ctx.color.isColorSupported` is the boolean form), and -`ctx.isHyperlinkSupported` uses the same precedence as the help header: explicit +`ctx.isHyperlinkSupported` is false in JSON mode. Otherwise it follows the help header: explicit `--no-hyperlinks` / `--hyperlinks` flags, then `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, and finally TTY detection. diff --git a/src/core/output/index.ts b/src/core/output/index.ts index 28e8270a..2c3f3d13 100644 --- a/src/core/output/index.ts +++ b/src/core/output/index.ts @@ -123,12 +123,12 @@ interface OutputOptions { /** * Resolved OSC 8 hyperlink support for `out.isHyperlinkSupported`. * - * When set, this wins over the `isTTY` fallback. Callers pass the + * JSON mode disables hyperlinks. Otherwise this overrides the `isTTY` fallback. Callers pass the * `NO_HYPERLINKS`/`FORCE_HYPERLINKS` (and `--no-hyperlinks`/`--hyperlinks`) * decision here via {@linkcode resolveHyperlinkOverride}, keeping `process` * access out of the output layer. * - * @defaultValue `isTTY` + * @defaultValue `!jsonMode && isTTY` */ readonly hyperlinks?: boolean; } @@ -215,9 +215,7 @@ function resolveOptions(options?: OutputOptions): ResolvedOutputOptions { // Explicit `color` wins; otherwise gate on TTY, JSON mode, and // environment support (NO_COLOR/FORCE_COLOR/--no-color/--color/CI). color: options?.color ?? (isTTY && !jsonMode && isColorSupported), - // Explicit `hyperlinks` (the caller-resolved env/argv override) wins; - // otherwise fall back to TTY. - isHyperlinkSupported: options?.hyperlinks ?? isTTY, + isHyperlinkSupported: !jsonMode && (options?.hyperlinks ?? isTTY), }; } diff --git a/src/core/output/output.test.ts b/src/core/output/output.test.ts index 70ebd9d8..02fb16b6 100644 --- a/src/core/output/output.test.ts +++ b/src/core/output/output.test.ts @@ -248,6 +248,15 @@ describe('isHyperlinkSupported', () => { expect(plain.color.link(url, 'docs')).toBe('docs'); }); + it('keeps JSON string values plain on a TTY, including when links are forced', () => { + for (const options of [{}, { hyperlinks: true }]) { + const [out, captured] = createCaptureOutput({ isTTY: true, jsonMode: true, ...options }); + out.json({ name: out.color.link('https://example.com/', 'Scotch Bonnet') }); + expect(out.isHyperlinkSupported).toBe(false); + expect(JSON.parse(captured.stdout.join(''))).toEqual({ name: 'Scotch Bonnet' }); + } + }); + it('explicit hyperlinks option wins over isTTY', () => { expect(createOutput({ isTTY: false, hyperlinks: true }).isHyperlinkSupported).toBe(true); expect(createOutput({ isTTY: true, hyperlinks: false }).isHyperlinkSupported).toBe(false); diff --git a/src/core/schema/command.ts b/src/core/schema/command.ts index c108f64b..b5ac19e1 100644 --- a/src/core/schema/command.ts +++ b/src/core/schema/command.ts @@ -253,7 +253,7 @@ interface Out { /** * Whether OSC 8 terminal hyperlinks should be emitted. * - * Honors explicit `--no-hyperlinks`/`--hyperlinks` argv flags first, then + * False in JSON mode. Otherwise honors explicit `--no-hyperlinks`/`--hyperlinks` flags, then * `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, falling back to `isTTY`. * `out.color.link(url, label)` applies this policy automatically. */ From 6a6e21e7549c2a923998d3452c26ff56f71ee80c Mon Sep 17 00:00:00 2001 From: Kaj Kowalski Date: Mon, 30 Nov 2026 07:11:50 -0500 Subject: [PATCH 21/21] Scaffold a buildable CLI with versioned docs and the DreamCLI skill --- AGENTS.md | 2 +- README.md | 148 +++++------------- bin/dreamcli.mjs | 23 ++- bin/git.mjs | 31 +++- bin/project.mjs | 20 +++ skills/cli-creation/agents/openai.yaml | 4 - skills/{cli-creation => dreamcli}/SKILL.md | 53 ++----- skills/dreamcli/agents/openai.yaml | 4 + .../references/consumer-workflow.md | 2 +- .../references/pattern-cookbook.md | 0 .../references/runtime-notes.md | 2 +- src/create.test.ts | 67 +++++++- src/create.ts | 53 ++----- src/create/guidance.ts | 63 ++++++++ src/create/project.ts | 127 +++++++++++++++ src/create/publish.ts | 6 +- src/create/templates.ts | 4 +- 17 files changed, 400 insertions(+), 209 deletions(-) create mode 100644 bin/project.mjs delete mode 100644 skills/cli-creation/agents/openai.yaml rename skills/{cli-creation => dreamcli}/SKILL.md (82%) create mode 100644 skills/dreamcli/agents/openai.yaml rename skills/{cli-creation => dreamcli}/references/consumer-workflow.md (97%) rename skills/{cli-creation => dreamcli}/references/pattern-cookbook.md (100%) rename skills/{cli-creation => dreamcli}/references/runtime-notes.md (94%) create mode 100644 src/create/guidance.ts create mode 100644 src/create/project.ts diff --git a/AGENTS.md b/AGENTS.md index d4b8c022..e9938fbc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ src/ docs/ # VitePress site. Prose in guide/ and concepts/ examples/ # runnable examples, gh/ and pwsh-demo/ workspaces scripts/ # build, release, package checks, gh-project -skills/cli-creation/ # published consumer skill +skills/dreamcli/ # published consumer skill ``` ## WHERE TO LOOK diff --git a/README.md b/README.md index 26149abe..8c85c5a9 100644 --- a/README.md +++ b/README.md @@ -64,38 +64,40 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli Create a TypeScript CLI project in a new or empty directory: ```sh -npm exec --package=@kjanat/dreamcli -- dreamcli create mycli +npx @kjanat/dreamcli create mycli cd mycli npm install npm start -- hello Jalapeño npm test npm run typecheck +npm run build +node dist/cli.mjs --help ``` -```text -mycli/ -├── .gitignore -├── package.json -├── tsconfig.json -└── src/ - ├── cli.ts - └── commands/ - ├── hello.ts - └── hello.test.ts -``` - -In a terminal, `npx @kjanat/dreamcli` asks where to create the project and prints the commands -to install dependencies and run the starter. `dreamcli init` is an alias for `dreamcli create`. -Non-interactive runs require a path. Use `.` explicitly to create in an empty current -directory, where the CLI asks for confirmation unless you pass `--yes`. - -The package name comes from the directory; `--name` overrides it. A new Git repository -gets an initial commit with the generator version. Use `--no-git` or `--no-test` to skip -those steps. Existing repositories are left alone. - -Use `dreamcli create mycli --out .` to add just the starter files to an existing -project. Use `--force` with `--out` to replace those files. The programmatic -`scaffold()` from `@kjanat/dreamcli/create` generates files without running Git. +Edit `src/commands/hello.ts` to change the greeting and register new commands in +`src/cli.ts`. The generated README covers development and packaging. GitHub +Actions checks types, tests, and the built executable. `npm pack` rebuilds it. +At creation, the generator looks up the latest tsdown release on npm and pins +it; offline it uses the version tested with DreamCLI. + +In a terminal, `npx @kjanat/dreamcli` prompts for the directory. `init` is an +alias for `create`. Supply a path in scripts. Use `--name` to override the +package name, `--no-test` to omit the starter test, or `--no-git` to skip Git +initialization. The manifest uses the configured Git author and infers a GitHub +repository from the owner and folder name. A new local repository gets that +`origin` and an initial commit. Review the inferred URL before pushing. + +Use `dreamcli create mycli --out .` to add a standalone entry and test to an +existing package. Both layouts add `AGENTS.md`, `CLAUDE.md`, and the bundled +[DreamCLI skill](skills/dreamcli/SKILL.md) under `.agents/skills/dreamcli/` +in the destination. Existing guidance is preserved even when `--force` replaces +the entry and test. The synchronous `scaffold()` API in `@kjanat/dreamcli/create` +accepts project metadata and a local skill directory without running Git or +fetching dependencies. + +[Framework guides](https://dreamcli.kjanat.dev/guide/getting-started) · +[JSR API reference](https://jsr.io/@kjanat/dreamcli/doc) · +[Markdown index](https://dreamcli.kjanat.dev/llms.txt) ### Single command @@ -138,96 +140,24 @@ cli('greet').default(greet).run(); DreamCLI migration progress demo -```ts -import { - cli, - command, - group, - flag, - arg, -} from '@kjanat/dreamcli'; - -const deploy = command('deploy') - .description('Deploy to an environment') - .arg('target', arg.string()) - .flag('force', flag.boolean().alias('f')) - .flag( - 'region', - flag.enum(['us', 'eu', 'ap']).env('DEPLOY_REGION'), - ) - .action(({ args, flags, out }) => { - out.log( - `Deploying ${args.target} to ${flags.region ?? 'default'}`, - ); - }); - -const login = command('login') - .description('Authenticate with the service') - .flag('token', flag.string().describe('Auth token')) - .action(({ flags, out }) => { - out.log( - flags.token - ? 'Authenticated via token' - : 'Authenticated interactively', - ); - }); - -// Nested command groups -const migrate = command('migrate') - .description('Run migrations') - .flag('steps', flag.number()) - .action(async ({ flags, meta, out }) => { - const steps = flags.steps ?? 3; - - out.log(`${meta.name} ${meta.version ?? ''}`.trim()); - out.log(`Command: ${meta.command}`); - - const spinner = out.spinner('Preparing migrations'); - await new Promise((resolve) => - setTimeout(resolve, 1000), - ); - spinner.succeed(`Ready to run ${steps} steps`); - - const progress = out.progress({ - label: 'Migrating', - total: steps, - }); - - for (let step = 1; step <= steps; step++) { - await new Promise((resolve) => - setTimeout(resolve, 700), - ); - progress.update(step); - } - - progress.done(`Migrated ${steps} steps`); - }); +Register named commands with `.command()`. Nest related commands with `group()`: -const seed = command('seed') - .description('Seed database') - .action(({ out }) => { - out.log('seeding'); - }); +```ts +import { cli, command, group } from '@kjanat/dreamcli'; +const migrate = command('migrate').action(({ out }) => + out.log('Migrating'), +); const db = group('db') .description('Database operations') - .command(migrate) - .command(seed); - -cli('mycli') - .version('1.0.0') - .description('My awesome tool') - .command(deploy) - .command(login) - .command(db) - .run(); - -// mycli deploy production --force -// mycli login --token abc123 -// mycli db migrate --steps 3 -// mycli db seed + .command(migrate); +await cli('mycli').command(db).run(); // mycli db migrate ``` +For flags, nested help, and progress reporting, see the +[walkthrough](https://dreamcli.kjanat.dev/guide/walkthrough) and +[runnable examples](https://github.com/kjanat/dreamcli/tree/master/examples). + ## Why dreamcli Most TypeScript CLI frameworks treat the type system like decoration. diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs index 7339df91..3547200e 100755 --- a/bin/dreamcli.mjs +++ b/bin/dreamcli.mjs @@ -3,13 +3,14 @@ /** DreamCLI's package executable. @module */ import { basename, relative, resolve, sep } from 'node:path'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; import { scaffold } from '@kjanat/dreamcli/create'; import { prompt } from '@kjanat/dreamcli/prompt'; import { createAdapter, detectRuntime } from '@kjanat/dreamcli/runtime'; import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; -import { initGit } from './git.mjs'; +import { initGit, projectIdentity } from './git.mjs'; +import { latestTsdown } from './project.mjs'; const adapter = createAdapter(); const ci = adapter.env.CI; @@ -89,7 +90,19 @@ const create = command('create') if (!(await ask(prompt.confirm({ message: 'Create here?', default: false })))) return; } - const result = scaffold({ ...options, name, directory }); + const metadata = project + ? { + ...projectIdentity(directory, adapter.env), + tsdownVersion: await latestTsdown(adapter.env), + } + : undefined; + const result = scaffold({ + ...options, + name, + directory, + metadata, + skillDirectory: fileURLToPath(new URL('../skills/dreamcli/', import.meta.url)), + }); const git = project && useGit ? initGit( @@ -98,6 +111,7 @@ const create = command('create') DREAMCLI_VERSION, DREAMCLI_REVISION, adapter.env, + metadata?.repository, ) : undefined; if (out.jsonMode) { @@ -108,6 +122,9 @@ const create = command('create') const label = out.color.cyan(project ? target : relative(adapter.cwd, destination)); out.log(`Created ${out.color.link(pathToFileURL(destination), label)}`); if (git?.error) out.warn(`Git: ${git.error}`); + if (project && !metadata?.tsdownVersion) { + out.status("Using DreamCLI's tested tsdown version because the npm lookup was unavailable."); + } if (project) out.status(`\n${nextSteps(directory, result.test)}`); }); diff --git a/bin/git.mjs b/bin/git.mjs index 454f6379..3661c17e 100644 --- a/bin/git.mjs +++ b/bin/git.mjs @@ -1,8 +1,36 @@ /** Initialize a standalone starter without touching a surrounding repository. @module */ import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { basename, dirname } from 'node:path'; -export function initGit(cwd, files, version, revision, env) { +export function projectIdentity(directory, env) { + let cwd = directory; + while (!existsSync(cwd) && dirname(cwd) !== cwd) cwd = dirname(cwd); + const config = (key) => { + const result = spawnSync('git', ['config', '--get', key], { cwd, env, encoding: 'utf8' }); + return result.status === 0 ? result.stdout.trim() : ''; + }; + const name = env.GIT_AUTHOR_NAME || config('user.name'); + const email = env.GIT_AUTHOR_EMAIL || config('user.email'); + const owner = + config('github.user') || + /^(?:\d+\+)?([\w-]+)@users\.noreply\.github\.com$/i.exec(email)?.[1] || + name.trim().replace(/\s+/g, '-'); + const folder = basename(directory) + .replace(/[^A-Za-z0-9_.-]+/g, '-') + .replace(/^-+|-+$/g, ''); + const repository = + /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(owner) && folder && !/^\.+$/.test(folder) + ? `https://github.com/${owner}/${folder}` + : undefined; + return { + ...((name || email) && { author: { ...(name && { name }), ...(email && { email }) } }), + ...(repository && { repository }), + }; +} + +export function initGit(cwd, files, version, revision, env, remote) { const options = { cwd, encoding: 'utf8', env: { ...env, LC_ALL: 'C' } }; const run = (...args) => spawnSync('git', args, options); const local = run('rev-parse', '--local-env-vars'); @@ -17,6 +45,7 @@ export function initGit(cwd, files, version, revision, env) { if (revision !== 'dev') message.push('-m', `DreamCLI-Revision: ${revision}`); for (const args of [ ['init', '--template='], + ...(remote ? [['remote', 'add', 'origin', `${remote}.git`]] : []), ['add', '--', ...files], ['commit', ...message, '--', ...files], ]) { diff --git a/bin/project.mjs b/bin/project.mjs new file mode 100644 index 00000000..13c80ac0 --- /dev/null +++ b/bin/project.mjs @@ -0,0 +1,20 @@ +/** Resolve the npm dist-tag at init time; offline scaffolds use the tested build version. @module */ + +export async function latestTsdown(env) { + if ((env.npm_config_offline ?? env.NPM_CONFIG_OFFLINE) === 'true') return undefined; + try { + const registry = + env.npm_config_registry || env.NPM_CONFIG_REGISTRY || 'https://registry.npmjs.org/'; + const response = await fetch(new URL('tsdown/latest', registry.replace(/\/?$/, '/')), { + signal: AbortSignal.timeout(8000), + headers: { Accept: 'application/json' }, + }); + if (!response.ok) return undefined; + const { version } = await response.json(); + return typeof version === 'string' && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version) + ? version + : undefined; + } catch { + return undefined; + } +} diff --git a/skills/cli-creation/agents/openai.yaml b/skills/cli-creation/agents/openai.yaml deleted file mode 100644 index 277eb701..00000000 --- a/skills/cli-creation/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "CLI Creation" - short_description: "Build typed DreamCLI consumer CLIs quickly" - default_prompt: "Use $cli-creation to scaffold a Bun-first DreamCLI CLI with tests." diff --git a/skills/cli-creation/SKILL.md b/skills/dreamcli/SKILL.md similarity index 82% rename from skills/cli-creation/SKILL.md rename to skills/dreamcli/SKILL.md index a9aaae06..58e3e793 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/dreamcli/SKILL.md @@ -1,9 +1,9 @@ --- -name: cli-creation +name: dreamcli description: Build consumer-facing DreamCLI CLIs from scratch with Bun-first workflows and typed patterns. Use when asked to scaffold or implement a new @kjanat/dreamcli command-line app, add commands/flags/args/prompts/output/testing, or create starter files/tests for DreamCLI users. --- -# CLI Creation +# DreamCLI ## Overview @@ -11,15 +11,6 @@ Create runnable DreamCLI starter CLIs and extend them with typed command patterns. This skill covers user-facing app code built **on** DreamCLI, not DreamCLI framework internals. -The baseline examples target DreamCLI 4.0. For argv transforms, check the installed -`CLIPluginHooks` type for `transformArgv` before generating code. - -Version 3 removed the DSL, made the default command the -root surface, and added a large typed-flag surface. Version 4 gave both -factories the same sources, so `.stdin()`, `.env()`, `.config()`, and -`.prompt()` are available on flags and positionals alike. Snippets below assume -both. - ## Quick Start 1. Create a project: `bunx --bun --package @kjanat/dreamcli dreamcli create mycli`. @@ -41,39 +32,27 @@ both. ## Looking Things Up -Prefer these over recalling API shapes from memory; they reflect the installed -or published version rather than training data. - -**The API, offline-ish, no repo needed.** If `deno` is on the system this works -regardless of whether the project installed from npm or JSR: +Use JSR's source-level API docs for the exact installed release. DreamCLI ships +the same release version on npm and JSR. From the consuming project after install: -```bash -deno doc jsr:@kjanat/dreamcli 2>/dev/null # root entry: builders, parsing, help, errors, every public type -deno doc jsr:@kjanat/dreamcli/completion 2>/dev/null # one subpath at a time; also /config, /json-schema, /prompt, /testkit, /runtime, /version, /schema -deno doc --json jsr:@kjanat/dreamcli 2>/dev/null # machine-readable, for scripted lookups -deno doc --filter=CLIBuilder jsr:@kjanat/dreamcli 2>/dev/null # one symbol +```sh +version=$(node -p "require('@kjanat/dreamcli/package.json').version") +deno doc --quiet --filter=command "jsr:@kjanat/dreamcli@$version" +deno doc --quiet --filter=runCommand "jsr:@kjanat/dreamcli@$version/testkit" ``` -`2>/dev/null` matters: deno writes download and type-check progress to stderr, -which otherwise swamps the documentation output. +Use `--json` for structured documentation, or omit `--filter` to list exports. +For a JSR-only project, use the exact version resolved in `deno.lock`. -Pin a version with `jsr:@kjanat/dreamcli@5.1.0` when the project is not on -latest. `--filter` takes a declaration name; it prints nothing for a name that -does not exist, which is itself a useful signal. +The website tracks current guides. Find a page in the index, then request its +authored Markdown using content negotiation or the direct raw URL: -**The docs site, as markdown.** Every page is authored markdown served under -`/raw/`, and any page URL returns markdown under content negotiation: - -```bash -curl -s https://dreamcli.kjanat.dev/llms.txt # index of every page, one line each -curl -s https://dreamcli.kjanat.dev/llms-full.txt # every page concatenated (~250 kB) -curl -s https://dreamcli.kjanat.dev/raw/guide/flags # one page, authored markdown -curl -sH 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +```sh +curl -fsSL https://dreamcli.kjanat.dev/llms.txt +curl -fsSL -H 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +curl -fsSL https://dreamcli.kjanat.dev/raw/guide/flags ``` -Start from `llms.txt` to find the right page, then fetch that page rather than -pulling `llms-full.txt` into context. - ## Grounding Sources Paths are relative to the dreamcli repository root. diff --git a/skills/dreamcli/agents/openai.yaml b/skills/dreamcli/agents/openai.yaml new file mode 100644 index 00000000..04ac3fde --- /dev/null +++ b/skills/dreamcli/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "DreamCLI" + short_description: "Build typed DreamCLI consumer CLIs quickly" + default_prompt: "Use $dreamcli to scaffold a Bun-first DreamCLI CLI with tests." diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/dreamcli/references/consumer-workflow.md similarity index 97% rename from skills/cli-creation/references/consumer-workflow.md rename to skills/dreamcli/references/consumer-workflow.md index 2f7f80de..dbe2ed31 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/dreamcli/references/consumer-workflow.md @@ -56,7 +56,7 @@ template and ending with validated behavior. bun ./mycli.ts --help bun ./mycli.ts --json | jq . # stdout must parse bun test ./mycli.test.ts # for bun:test - bunx --bun vitest run ./mycli.test.ts # for Vitest + bunx --bun vitest run ./mycli.test.ts # for a standalone Vitest file ``` ## Done criteria diff --git a/skills/cli-creation/references/pattern-cookbook.md b/skills/dreamcli/references/pattern-cookbook.md similarity index 100% rename from skills/cli-creation/references/pattern-cookbook.md rename to skills/dreamcli/references/pattern-cookbook.md diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/dreamcli/references/runtime-notes.md similarity index 94% rename from skills/cli-creation/references/runtime-notes.md rename to skills/dreamcli/references/runtime-notes.md index 3ec0bf8c..1d7e7a71 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/dreamcli/references/runtime-notes.md @@ -10,7 +10,7 @@ npm test npm run typecheck ``` -With Bun, use `bun install`, `bun src/cli.ts hello Jalapeño`, and `bunx --bun vitest run` in that directory. +With Bun, use `bun install`, `bun src/cli.ts hello Jalapeño`, and `bun run test` in that directory. Build the executable with `bun run build`. ## Files added with `--out` diff --git a/src/create.test.ts b/src/create.test.ts index 31e24dec..7d1c8fe2 100644 --- a/src/create.test.ts +++ b/src/create.test.ts @@ -12,6 +12,7 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { publishFiles } from './create/publish.ts'; import type { ScaffoldOptions } from './create.ts'; @@ -58,12 +59,54 @@ describe('scaffold', () => { const withoutTests = JSON.parse( readFileSync(join(directory, 'no-test', 'package.json'), 'utf8'), ); - expect(withoutTests.scripts).toEqual({ start: 'node src/cli.ts', typecheck: 'tsc --noEmit' }); + expect(withoutTests.scripts).toMatchObject({ + start: 'node src/cli.ts', + typecheck: 'tsc --noEmit', + build: 'tsdown', + }); + expect(withoutTests.scripts.test).toBeUndefined(); expect(withoutTests.devDependencies.vitest).toBeUndefined(); expect(existsSync(join(directory, 'no-test', 'src/commands/hello.test.ts'))).toBe(false); }); }); + it('writes build metadata, project guidance and the bundled skill together', () => { + withProject((directory) => { + const skillDirectory = fileURLToPath(new URL('../skills/dreamcli/', import.meta.url)); + const metadata = { + author: { name: 'Pepper Farmer', email: 'pepper@example.invalid' }, + repository: 'https://github.com/pepper-farmer/hot-sauce', + tsdownVersion: '1.2.3', + }; + const result = scaffold({ + directory, + name: 'hot-sauce', + metadata, + skillDirectory, + test: false, + }); + const read = (path: string) => readFileSync(join(directory, path), 'utf8'); + expect(JSON.parse(read('package.json'))).toMatchObject({ + author: metadata.author, + repository: { url: `git+${metadata.repository}.git` }, + bin: { 'hot-sauce': './dist/cli.mjs' }, + keywords: ['cli', 'dreamcli', 'ansispeck'], + devDependencies: { tsdown: '1.2.3' }, + scripts: { build: 'tsdown', prepack: 'npm run build' }, + }); + expect(read('CLAUDE.md')).toBe('@AGENTS.md\n'); + expect(read('AGENTS.md')).toContain('--filter=runCommand'); + expect(read('.github/workflows/ci.yml')).not.toContain('npm test'); + expect(read('README.md')).not.toContain('npm test'); + const skillPath = '.agents/skills/dreamcli/SKILL.md'; + expect(result.files).toContain(join(directory, skillPath)); + expect(read(skillPath)).toBe(readFileSync(join(skillDirectory, 'SKILL.md'), 'utf8')); + writeFileSync(join(directory, skillPath), 'custom'); + scaffold({ out: directory, name: 'other', force: true, skillDirectory }); + expect(read(skillPath)).toBe('custom'); + }); + }); + it('uses native imports for Vitest in a project under a hash-marked parent directory', () => { withProject((cwd) => { const directory = join(cwd, 'Peppers #5', 'cli'); @@ -95,7 +138,9 @@ describe('scaffold', () => { mkdirSync(target, { recursive: true }); const result = scaffold({ name: 'My CLI', directory: target, test: false }); expect(result.entry).toBe(join(target, 'src/cli.ts')); - expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe('node_modules/\ncoverage/\n'); + expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe( + 'node_modules/\ncoverage/\ndist/\n*.tgz\n', + ); expect(JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).name).toBe('my-cli'); }); }); @@ -113,7 +158,12 @@ describe('scaffold', () => { expect(existsSync(lock)).toBe(true); rmSync(lock, { recursive: true }); - expect(scaffold(options).files).toEqual([entry, join(cwd, 'demo.test.ts')]); + expect(scaffold(options).files).toEqual([ + entry, + join(cwd, 'demo.test.ts'), + join(cwd, 'CLAUDE.md'), + join(cwd, 'AGENTS.md'), + ]); }); }); @@ -159,7 +209,12 @@ describe('scaffold', () => { name: 'my-cli', entry: join(out, 'my-cli.ts'), test: join(out, 'my-cli.test.ts'), - files: [join(out, 'my-cli.ts'), join(out, 'my-cli.test.ts')], + files: [ + join(out, 'my-cli.ts'), + join(out, 'my-cli.test.ts'), + join(out, 'CLAUDE.md'), + join(out, 'AGENTS.md'), + ], testRunner: 'bun:test', }); const entry = readFileSync(result.entry, 'utf8'); @@ -203,7 +258,11 @@ describe('scaffold', () => { const test = join(directory, 'my-cli.test.ts'); writeFileSync(entry, 'old entry'); writeFileSync(test, 'keep this'); + for (const guide of ['CLAUDE.md', 'AGENTS.md']) + writeFileSync(join(directory, guide), 'team rules'); const result = scaffold({ name: 'my-cli', out: directory, test: false, force: true }); + for (const guide of ['CLAUDE.md', 'AGENTS.md']) + expect(readFileSync(join(directory, guide), 'utf8')).toBe('team rules'); expect(result).toEqual({ name: 'my-cli', entry, files: [entry] }); expect(readFileSync(entry, 'utf8')).toContain("cli('my-cli')"); expect(readFileSync(test, 'utf8')).toBe('keep this'); diff --git a/src/create.ts b/src/create.ts index 23bde53a..ade53ba6 100644 --- a/src/create.ts +++ b/src/create.ts @@ -7,6 +7,9 @@ import { lstatSync, readdirSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { CLIError } from './core/errors/index.ts'; +import { guidanceFiles } from './create/guidance.ts'; +import type { ProjectMetadata } from './create/project.ts'; +import { projectFiles } from './create/project.ts'; import { publishFiles } from './create/publish.ts'; import { cliTemplate, @@ -15,7 +18,6 @@ import { testTemplate, } from './create/templates.ts'; import { detectTestRunner } from './create/test-runner.ts'; -import { DREAMCLI_VERSION } from './version.ts'; export interface ScaffoldOptions { /** CLI name. Converted to a lowercase, hyphen-separated filename. */ @@ -28,6 +30,10 @@ export interface ScaffoldOptions { readonly test?: boolean; /** Replace existing starter files. Defaults to false. */ readonly force?: boolean; + /** Project author, repository and resolved bundler version for a new project. */ + readonly metadata?: ProjectMetadata; + /** Copy this local DreamCLI skill directory into the destination. */ + readonly skillDirectory?: string; } export interface ScaffoldResult { @@ -101,49 +107,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } if (project) { - // Vite interprets these characters in module IDs. Native imports preserve the path. - const testScript = /[#?*]/.test(directory) - ? 'vitest run --experimental.viteModuleRunner=false' - : 'vitest run'; - const manifest = { - name, - version: '0.1.0', - private: true, - type: 'module', - scripts: { - start: 'node src/cli.ts', - typecheck: 'tsc --noEmit', - ...(test !== undefined && { test: testScript }), - }, - engines: { node: '>=22.22.2' }, - dependencies: { - '@kjanat/dreamcli': DREAMCLI_VERSION === 'dev' ? 'latest' : DREAMCLI_VERSION, - }, - devDependencies: { - '@types/node': '^22.0.0', - typescript: '^6.0.3', - ...(test !== undefined && { vitest: '^5.1.2' }), - }, - }; - files.push({ - path: join(directory, 'package.json'), - content: `${JSON.stringify(manifest, null, 2)}\n`, - }); - const tsconfig = { - compilerOptions: { - target: 'ES2022', - module: 'NodeNext', - strict: true, - noEmit: true, - allowImportingTsExtensions: true, - types: ['node'], - }, - include: ['src'], - }; - files.push( - { path: join(directory, 'tsconfig.json'), content: `${JSON.stringify(tsconfig, null, 2)}\n` }, - { path: join(directory, '.gitignore'), content: 'node_modules/\ncoverage/\n' }, - ); + files.push(...projectFiles(directory, name, test !== undefined, options.metadata ?? {})); const existing = lstatSync(directory, { throwIfNoEntry: false }); if (existing && (!existing.isDirectory() || readdirSync(directory).length > 0)) { throw new CLIError(`Project directory is not empty or not a directory: ${directory}`, { @@ -154,6 +118,7 @@ export function scaffold(options: ScaffoldOptions): ScaffoldResult { } } + files.push(...guidanceFiles(directory, options.skillDirectory)); publishFiles(files, !project && options.force === true); return { diff --git a/src/create/guidance.ts b/src/create/guidance.ts new file mode 100644 index 00000000..e6fde732 --- /dev/null +++ b/src/create/guidance.ts @@ -0,0 +1,63 @@ +/** Agent instructions and the optional copy of the packaged DreamCLI skill. @module */ +import { lstatSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const instructions = `# Working with DreamCLI + +Use the JSR API reference for the version actually installed. DreamCLI releases +the same version on npm and JSR. From this project after installing dependencies: + +\`\`\`sh +version=$(node -p "require('@kjanat/dreamcli/package.json').version") +deno doc --quiet --filter=command "jsr:@kjanat/dreamcli@$version" +deno doc --quiet --filter=runCommand "jsr:@kjanat/dreamcli@$version/testkit" +\`\`\` + +Replace the filter with an exported symbol, omit it to list exports, or use +\`--json\` for structured API documentation. In a JSR-only project, use the exact +version in \`deno.lock\`. Browse the same version at +\`https://jsr.io/@kjanat/dreamcli@/doc\`. + +For usage examples, search the current guide index, then read one page as Markdown: + +\`\`\`sh +curl -fsSL https://dreamcli.kjanat.dev/llms.txt +curl -fsSL -H 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +curl -fsSL https://dreamcli.kjanat.dev/raw/guide/flags +\`\`\` +`; + +export function guidanceFiles(directory: string, skillDirectory?: string) { + const files: { path: string; content: string; preserveExisting: boolean }[] = []; + const existing = (path: string) => lstatSync(path, { throwIfNoEntry: false }); + function add(path: string, content: string) { + if (!existing(path)) files.push({ path, content, preserveExisting: true }); + } + const agents = join(directory, 'AGENTS.md'); + const skill = join(directory, '.agents', 'skills', 'dreamcli'); + const installSkill = + skillDirectory !== undefined && + ['.agents', '.agents/skills', '.agents/skills/dreamcli'].every((part) => { + const item = existing(join(directory, part)); + return item === undefined || item.isDirectory(); + }); + const guide = + instructions + + (installSkill + ? '\nUse the [DreamCLI skill](.agents/skills/dreamcli/SKILL.md) for command design and testing patterns.\n' + : ''); + add(join(directory, 'CLAUDE.md'), existing(agents) ? guide : '@AGENTS.md\n'); + add(agents, guide); + function copySkill(from: string, to: string) { + for (const entry of readdirSync(from, { withFileTypes: true })) { + const source = join(from, entry.name); + const target = join(to, entry.name); + if (entry.isDirectory()) { + const item = existing(target); + if (item === undefined || item.isDirectory()) copySkill(source, target); + } else if (entry.isFile()) add(target, readFileSync(source, 'utf8')); + } + } + if (installSkill && skillDirectory !== undefined) copySkill(skillDirectory, skill); + return files; +} diff --git a/src/create/project.ts b/src/create/project.ts new file mode 100644 index 00000000..a75b5324 --- /dev/null +++ b/src/create/project.ts @@ -0,0 +1,127 @@ +/** Package, executable build and user documentation for a new CLI project. @module */ +import { join } from 'node:path'; +import { DREAMCLI_VERSION } from '../version.ts'; + +export interface ProjectMetadata { + readonly author?: { readonly name?: string; readonly email?: string }; + readonly repository?: string; + readonly tsdownVersion?: string; +} + +export function projectFiles( + directory: string, + name: string, + test: boolean, + metadata: ProjectMetadata, +) { + // Vite interprets these characters in module IDs. Native imports preserve the path. + const testScript = /[#?*]/.test(directory) + ? 'vitest run --experimental.viteModuleRunner=false' + : 'vitest run'; + const manifest = { + name, + version: '0.1.0', + private: true, + type: 'module', + keywords: ['cli', 'dreamcli', 'ansispeck'], + ...(metadata.author && { author: metadata.author }), + ...(metadata.repository && { + repository: { type: 'git', url: `git+${metadata.repository}.git` }, + }), + bin: { [name]: './dist/cli.mjs' }, + files: ['dist'], + scripts: { + start: 'node src/cli.ts', + typecheck: 'tsc --noEmit', + build: 'tsdown', + prepack: 'npm run build', + ...(test && { test: testScript }), + }, + engines: { node: '>=22.22.2' }, + dependencies: { '@kjanat/dreamcli': DREAMCLI_VERSION === 'dev' ? 'latest' : DREAMCLI_VERSION }, + devDependencies: { + '@types/node': '^22.0.0', + tsdown: metadata.tsdownVersion ?? '0.23.7', + typescript: '^6.0.3', + ...(test && { vitest: '^5.1.2' }), + }, + }; + const tsconfig = { + compilerOptions: { + target: 'ES2022', + module: 'NodeNext', + strict: true, + noEmit: true, + allowImportingTsExtensions: true, + types: ['node'], + }, + include: ['src', 'tsdown.config.ts'], + }; + const build = `import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/cli.ts'], + platform: 'node', + format: 'esm', + fixedExtension: true, + dts: false, +}); +`; + const readme = `# ${name} + +A TypeScript CLI built with [DreamCLI](https://dreamcli.kjanat.dev/). + +## Run locally + +Use Node.js 24 LTS to develop and build the CLI. + +\`\`\`sh +npm install +npm start -- --help +npm start -- hello Jalapeño +\`\`\` + +Edit \`src/commands/hello.ts\` to change the greeting. Register additional +commands in \`src/cli.ts\`. Pass \`--json\` for machine-readable output. + +## Check and build + +\`\`\`sh +npm run typecheck +${test ? 'npm test\n' : ''}npm run build +node dist/cli.mjs --help +\`\`\` + +Commit your package lock after installing. GitHub Actions runs the checks on +pushes and pull requests. \`npm pack\` rebuilds the executable and produces +an installable tarball with the \`${name}\` command. + +See [AGENTS.md](./AGENTS.md) for version-matched framework documentation. +`; + const workflow = `name: CI +on: [push, pull_request] +permissions: + contents: read +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + package-manager-cache: false + - run: if [ -f package-lock.json ]; then npm ci; else npm install; fi + - run: npm run typecheck +${test ? ' - run: npm test\n' : ''} - run: npm run build + - run: node dist/cli.mjs --help +`; + return Object.entries({ + 'package.json': `${JSON.stringify(manifest, null, 2)}\n`, + 'tsconfig.json': `${JSON.stringify(tsconfig, null, 2)}\n`, + 'tsdown.config.ts': build, + '.gitignore': 'node_modules/\ncoverage/\ndist/\n*.tgz\n', + 'README.md': readme, + '.github/workflows/ci.yml': workflow, + }).map(([path, content]) => ({ path: join(directory, path), content })); +} diff --git a/src/create/publish.ts b/src/create/publish.ts index a66da5ea..1fe5444f 100644 --- a/src/create/publish.ts +++ b/src/create/publish.ts @@ -81,18 +81,18 @@ function publish(file: StagedFile): void { /** Acquire every destination before publishing. Retain its backup if a restore itself fails. */ export function publishFiles( - files: readonly { path: string; content: string }[], + files: readonly { path: string; content: string; preserveExisting?: boolean }[], force: boolean, ): void { const directories: string[] = []; const staged: StagedFile[] = []; const errors: unknown[] = []; try { - for (const { path, content } of files) { + for (const { path, content, preserveExisting } of files) { makeDirectory(dirname(path), directories); const file = lockFile(path); staged.push(file); - stage(file, content, force); + stage(file, content, force && !preserveExisting); } for (const file of staged) publish(file); } catch (error) { diff --git a/src/create/templates.ts b/src/create/templates.ts index a8bc5afd..60e1c76c 100644 --- a/src/create/templates.ts +++ b/src/create/templates.ts @@ -14,7 +14,9 @@ export const commandTemplate = `import { arg, command } from '@kjanat/dreamcli'; ${hello}`; -export const cliTemplate = `import { cli } from '@kjanat/dreamcli'; +export const cliTemplate = `#!/usr/bin/env node + +import { cli } from '@kjanat/dreamcli'; import { hello } from './commands/hello.ts'; await cli('__CLI_NAME__')