From 7ff9c55f34f95f981cea0b92a7fc36e9e1a32d69 Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:59:52 -0800 Subject: [PATCH 1/6] feat(cli): add @cutils/cli, a type-first declarative CLI builder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The command spec is a plain record literal: command() normalizes options into a flat dispatch record and run() parses argv, generates --help/ --version, and returns an exit code. A mapped type (OptsFromOptions) carries the options literal into the handler's opts parameter, so parse rules, types, and help all come from one static schema — no runtime reflection. Subset discipline per the minicli rulebook: every lookup walks Object.entries() (dynamic record reads are SC1090; writes are fine), the handler crosses an (opts: unknown, args: string[]) => void boundary via a single upcast in command() (a generic-typed local would hold a dynamic slot), and the schema seam is a structural StandardValidator — the official StandardSchemaV1 type's computed "~standard" key poisons Object.entries lowering. Verified on scriptc 0.4.7 / darwin-arm64: gate.ts compiles statically (340/340, 100%) with zero dynamic slots, 37 node --test cases pass, and test/elf.test.sh drives the full matrix (flags, help, version, unknown command + suggestion, missing arg, bad number, schema rejection) through a compiled ELF. Binary size, measured not claimed: argv-only baseline 130,016 B vs one-command @cutils/cli demo 456,088 B (+326,072 B for the whole library) — recorded in packages/cli/AGENTS.md. Adds the package to the fixed version group and records the release intent. --- .changeset/cli-initial-release.md | 5 + packages/cli/AGENTS.md | 80 ++++ packages/cli/README.md | 112 ++++++ packages/cli/gate.ts | 131 +++++++ packages/cli/package.json | 51 +++ packages/cli/src/index.ts | 585 ++++++++++++++++++++++++++++ packages/cli/test/coverage.test.mjs | 23 ++ packages/cli/test/elf-app.ts | 57 +++ packages/cli/test/elf.test.sh | 75 ++++ packages/cli/test/errors.test.js | 112 ++++++ packages/cli/test/help.test.js | 128 ++++++ packages/cli/test/helpers.js | 16 + packages/cli/test/parse.test.js | 130 +++++++ packages/cli/test/schema.test.js | 142 +++++++ packages/cli/tsconfig.json | 17 + pnpm-lock.yaml | 9 + pnpm-workspace.yaml | 2 +- 17 files changed, 1674 insertions(+), 1 deletion(-) create mode 100644 .changeset/cli-initial-release.md create mode 100644 packages/cli/AGENTS.md create mode 100644 packages/cli/README.md create mode 100644 packages/cli/gate.ts create mode 100644 packages/cli/package.json create mode 100644 packages/cli/src/index.ts create mode 100644 packages/cli/test/coverage.test.mjs create mode 100644 packages/cli/test/elf-app.ts create mode 100755 packages/cli/test/elf.test.sh create mode 100644 packages/cli/test/errors.test.js create mode 100644 packages/cli/test/help.test.js create mode 100644 packages/cli/test/helpers.js create mode 100644 packages/cli/test/parse.test.js create mode 100644 packages/cli/test/schema.test.js create mode 100644 packages/cli/tsconfig.json diff --git a/.changeset/cli-initial-release.md b/.changeset/cli-initial-release.md new file mode 100644 index 0000000..796167b --- /dev/null +++ b/.changeset/cli-initial-release.md @@ -0,0 +1,5 @@ +--- +"@cutils/cli": minor +--- + +Initial release: type-first declarative CLI builder (`command`/`run`) — typed options, generated help/version, error suggestions, Standard-Schema seam; compiles statically into the app ELF. diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md new file mode 100644 index 0000000..6afc2d1 --- /dev/null +++ b/packages/cli/AGENTS.md @@ -0,0 +1,80 @@ +# @cutils/cli AGENTS.md + +Type-first declarative CLI builder in the scriptc subset — plain records + +functions, no classes, zero deps. Design source: +`.agents/plans/2026-11-07-cutils-cli.md` and the `minicli` prototype writeup +(`~/Downloads/scriptc-cli-compat-roadmap-and-design.md` Part 2). Same subset +rules as the root AGENTS.md, plus what authoring this package verified +empirically under the pinned scriptc (0.4.7): + +## Verified-OK constructs (probed by gate.ts at 100%) + +- **Generic functions over record literals**: `command>` lowers fully — the generic only feeds the + type-level `OptsFromOptions` mapped type; nothing generic survives + into runtime values. +- **Function values inside records**: `CommandDef.handler` and + `StandardValidator.validate` members lower fine (the cache "function + members degrade instantiation" rule does not apply to this shape — + the records are produced/consumed inside one program, never class + fields). +- **`Object.entries` + dynamic record WRITES**: every lookup walks + `Object.entries()` with an indexed loop (`findLong`/`findShort`/ + `valueOf`/command dispatch); `values[name] = v` writes are legal. + Dynamic record READS `obj[key]` remain SC1090 — never index a record. +- **`instanceof Promise`** narrows validator results; async validators are + rejected with a clean error. +- **`process.exit`** lowers (elf-app exits with `run`'s return code). +- **`Number.isNaN`, `Number()`, `String(unknown)`** all lower — the last + two land in the _dynamic tier_ (still static-compiled, runtime-checked). + +## Rules specific to this package + +- **One dynamic-slot trap survived**: `const h = spec.handler` holds a + value declared `(opts: OptsFromOptions, ...) => void` — a generic + mapped type has no static lowering → SC6104 dynamic slot. Fix is the + upcast in `command()`: `spec.handler as (opts: unknown, args: string[]) +=> void` stores the boundary-typed function directly (also saves a + wrapper closure). If you touch `command()`'s return path, re-run + `scriptc coverage gate.ts --explain-dynamic` — zero `dynamic slots` + lines is the bar (dynamic TIER statements are expected and fine). +- **`OptionSpec.default` is `unknown`**, not `boolean | string | number`: + multi-type unions in record members are subset-fragile. `command()` + runtime-checks the default against `type` at construction (`E_BAD_OPTION`). +- **The schema seam is structural, not StandardSchemaV1**: the official + type's computed `"~standard"` key poisons `Object.entries` lowering. + `StandardValidator`/`StandardResult` are hand-rolled structural twins — + users pass `mySchema["~standard"]`. Keep it that way. +- **`opts` keys are always present**: absent flag → `default` else the + type's zero value (`false`/`0`/`""`). Documented because it differs + from commander (`undefined`). "Was it passed" = sentinel default or + schema. +- **`run` never exits**: returns the code; `process.exit(run({...}))` is + the consumer idiom. Keeps `node --test` tests in-process. +- **`-h` yields to a declared `short: "h"`** — check `findShort` before + printing command help. +- **Help/errors go through `console.log`/`console.error`** — no + `process.stdout` writes or patching (patching is a subset ban). + +## Binary size (measured 2026-11-07, scriptc 0.4.7, darwin-arm64) + +`scriptc build` default flags: + +| program | bytes | +| -------------------------------------- | -------- | +| argv-only baseline (hand-rolled `if`s) | 130,016 | +| one-command @cutils/cli demo (`greet`) | 456,088 | +| **library overhead** | +326,072 | + +Reproduce: `test/size` is not shipped; rebuild the two programs described +in git history (`feat(cutils-cli)` commit message) or any equivalent +argv-only baseline vs `test/elf-app.ts`. No perf/size claims in the +README until a bench cell exists. + +## Commands + +- `pnpm build` / `pnpm test` — tsc + `node --test test/*.test.js` + `bash test/elf.test.sh` +- `scriptc coverage gate.ts` must report `compile statically (100%)` (via `scripts/scriptc-gate.sh`) +- `bash test/elf.test.sh` — builds `test/elf-app.ts`, runs the full matrix + (flags, `--help`, ` --help`, `--version`, unknown command + + suggestion, missing arg, bad number, schema rejection) diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..cf05338 --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,112 @@ +# @cutils/cli + +Type-first, declarative CLI builder authored inside the [scriptc](https://github.com/vercel-labs/scriptc) compilable subset — the command spec is a plain record literal, a mapped type carries the options into your handler, and `scriptc build` lowers the whole thing into the app's single static ELF. Zero dependencies; runs under Node unchanged. + +```ts +import { command, run } from "@cutils/cli"; + +process.exit( + run({ + name: "demo", + version: "1.0.0", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase output" }, + times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + }, + handler: (opts, args) => { + // opts: { upper: boolean; times: number } — fully inferred + const who = opts.upper ? args[0].toUpperCase() : args[0]; + for (let i = 0; i < opts.times; i++) console.log(`hello ${who}`); + }, + }), + }, + }), +); +``` + +- **The literal IS the schema.** Parse rules, `opts` types, `--help` tables, and error messages all come from the same `command()` spec — no runtime reflection (which scriptc cannot lower anyway). +- **`opts` is fully inferred.** The options literal flows through a mapped type: `{ type: "boolean" }` → `boolean`, `"number"` → `number`, `"string"` → `string`. Every declared key is always present. +- **Help, version, and errors are generated.** `--help`/`-h` at program and command level, `--version`, unknown-command suggestions, and labelled errors for missing arguments, unknown options, and bad values. +- **Standard Schema hook.** Any validator shaped like `schema["~standard"]` can guard an option value or the whole `{ opts, args }` input — sync only (async validators are rejected with a clear error). +- **Exits by return code.** `run` prints and returns a number; it never calls `process.exit` itself, so it stays unit-testable under plain `node --test`. + +## Surface + +```ts +declare function run(prog: ProgramSpec, argv?: string[]): number; +declare function command>( + description: string, + spec: CommandSpec, +): CommandDef; +``` + +`run(prog)` reads `process.argv.slice(2)`; pass `argv` explicitly as a test seam or to embed a sub-CLI. + +```ts +interface ProgramSpec { + name: string; + version?: string; + description?: string; + commands: Record; +} + +interface CommandSpec { + args?: string[]; // required positionals, in order + options?: O; // record of OptionSpec + schema?: StandardValidator; // validates { opts, args } + handler: (opts: OptsFromOptions, args: string[]) => void; +} + +interface OptionSpec { + type: "boolean" | "string" | "number"; + short?: string; // one character + default?: unknown; // must match `type`; checked in command() + description?: string; + schema?: StandardValidator; // validates the parsed option value +} +``` + +### Parsing rules + +| Input | Result | +| ----------------------------- | --------------------------------------------- | +| `--upper` | boolean `true` | +| `--times 3`, `--times=3` | number `3`; non-numeric → error | +| `-u`, `-t 3`, `-t3`, `-ut3` | short flags; boolean shorts cluster | +| `--greeting hi`, `-g hi` | string option | +| `--upper=false` / `=0` / `=1` | explicit boolean value | +| `--` | end of options; rest are positionals | +| `-h` | command help unless `h` is a declared `short` | + +Option values may appear anywhere before `--`. Declared positionals are all required; extra positionals are an `unexpected argument` error. + +### Defaults and `opts` presence + +Every declared option key exists in `opts` with its declared type. When the flag is absent: the `default` if one was declared, else the type's zero value (`false`, `0`, `""`). There is no `undefined` member to check — use a sentinel `default` or a `schema` if "was it passed" matters. + +### Standard Schema seam + +`schema` accepts any object with `validate(value)` returning `{ value }` or `{ issues: [{ message }] }` — the shape `mySchema["~standard"]` has (pass that member, not the schema itself). Option schemas receive the parsed option value; command schemas receive `{ opts, args }`. Results are synchronous — a `Promise` return is an error, not a wait. + +## Divergences from commander + +| commander | @cutils/cli | Why | +| ----------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------- | +| `.option()` / `.argument()` chaining | one `command()` literal | declarative spec = the static schema; no mutation | +| `opts` untyped (`OptionValues`) | `opts` inferred from the literal via mapped type | the literal is the type | +| absent option is `undefined` | zero value or declared `default` | no `\| undefined` unions in the subset | +| variadic args, `[optional]` positionals | required positionals only | v0 scope; variadic is a v1 item | +| `process.exit` inside the framework | `run` returns the code; caller exits | testable under `node --test`, no hidden exits | +| async/`.action()` promise handlers | sync handlers only | `void \| Promise` unions add dynamic slots | +| zod etc. via `.parse` wrappers | `schema:` Standard-Validator hook | async validators rejected; heavy schema libs stay | +| | | Node-mode under scriptc's island limits | +| automatic `-V` / help option registration | `-h`/`--help`/`--version` only, `-h` yields to `short: "h"` | small fixed set; user shorts win | +| subcommand trees | flat command map | v2 item | + +## Notes + +- No perf claims yet — binary size vs a hand-rolled argv baseline is measured and recorded in `packages/cli/AGENTS.md`. +- Requires Node >= 22 at dev/build time; the compiled ELF has no Node dependency. diff --git a/packages/cli/gate.ts b/packages/cli/gate.ts new file mode 100644 index 0000000..18e70db --- /dev/null +++ b/packages/cli/gate.ts @@ -0,0 +1,131 @@ +// scriptc coverage gate — exercises the full @cutils/cli public surface. +// scripts/scriptc-gate.sh requires `compile statically (100%)` here. +// +// Constructs this gate probes (each was suspect under older scriptc pins; +// all must stay at 100% under the pinned release): +// - generic function command> with a +// mapped-type handler parameter (OptsFromOptions) +// - function values inside record literals (handler, schema.validate) +// - Object.entries over Record/CommandDef for all +// lookups (dynamic record reads are SC1090) +// - instanceof Promise narrowing on a validator result +// - Number.isNaN, startsWith-free substring compares, process.argv slice + +import { command, run } from "./src/index.ts"; +import type { + CommandDef, + OptionSpec, + ParsedInput, + ProgramSpec, + StandardResult, + StandardValidator, + ValidationIssue, +} from "./src/index.ts"; + +// A hand-rolled Standard-Schema-shaped sync validator. +const noBigTimes: StandardValidator = { + validate: (value: unknown): StandardResult => { + if (typeof value === "number" && value > 10) { + const issues: ValidationIssue[] = [{ message: "times too large" }]; + return { issues: issues }; + } + return { value: value }; + }, +}; + +const asyncValidator: StandardValidator = { + validate: (value: unknown): Promise => { + return Promise.resolve({ value: value }); + }, +}; + +// OptionSpec and ParsedInput are part of the public surface too. +const optSpec: OptionSpec = { type: "string", short: "x" }; +const parsed: ParsedInput = { opts: { x: "y" }, args: ["y"] }; + +const prog: ProgramSpec = { + name: "demo", + version: "1.0.0", + description: "gate demo", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase" }, + times: { + type: "number", + short: "t", + default: 1, + description: "repeat", + schema: noBigTimes, + }, + greeting: { type: "string", description: "greeting word" }, + }, + schema: { + validate: (value: unknown): StandardResult => { + return { value: value }; + }, + }, + handler: (opts, args) => { + // opts is { upper: boolean; times: number; greeting: string } — + // the mapped type, proven by the typed uses below. + const shout: boolean = opts.upper; + const n: number = opts.times; + const g: string = opts.greeting; + let who = args[0]; + if (shout) { + who = who.toUpperCase(); + } + for (let i = 0; i < n; i++) { + console.log(g + " " + who); + } + }, + }), + add: command("add numbers", { + args: ["a", "b"], + handler: (_opts, args) => { + console.log(String(Number(args[0]) + Number(args[1]))); + }, + }), + slow: command("async schema command", { + schema: asyncValidator, + handler: (_opts, _args) => { + console.log("unreachable"); + }, + }), + }, +}; + +// Full validation matrix through the public API. +let code = 0; +code += run(prog, ["--help"]); +code += run(prog, ["--version"]); +code += run(prog, ["greet", "--help"]); +code += run(prog, ["greet", "-u", "world"]); +code += run(prog, ["greet", "--times=2", "--greeting", "hi", "world"]); +code += run(prog, ["greet", "--", "-strange"]); +code += run(prog, ["add", "1.5", "2.5"]); +code += run(prog, ["greet"]); // missing required argument +code += run(prog, ["greet", "a", "b"]); // unexpected extra +code += run(prog, ["greet", "--times", "abc", "x"]); // bad number +code += run(prog, ["greet", "--bogus", "x"]); // unknown option +code += run(prog, ["gret", "x"]); // unknown command + suggestion +code += run(prog, ["greet", "--times", "99", "x"]); // schema rejection +code += run(prog, ["slow"]); // async validator rejection + +// The CommandDef record is public: callers may compose specs by hand. +const raw: CommandDef = { + description: "raw", + args: [], + options: {}, + schema: null, + handler: (_opts: unknown, _args: string[]): void => { + console.log("raw"); + }, +}; +const p2: ProgramSpec = { name: "p2", commands: { raw: raw } }; +code += run(p2, ["raw"]); + +if (code > 100 || optSpec.short === "zzz" || parsed.args.length === 99) { + throw new Error("gate: unreachable"); +} diff --git a/packages/cli/package.json b/packages/cli/package.json new file mode 100644 index 0000000..0014ed9 --- /dev/null +++ b/packages/cli/package.json @@ -0,0 +1,51 @@ +{ + "name": "@cutils/cli", + "version": "0.5.0", + "description": "Type-first declarative CLI builder in the scriptc compilable subset — commands, typed options, generated help, compiles into the app's single static ELF", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/sigilco/cutils.git", + "directory": "packages/cli" + }, + "files": [ + "dist", + "src" + ], + "type": "module", + "main": "./dist/esm/index.js", + "types": "./dist/esm/index.d.ts", + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "npm run build && node --test test/*.test.js test/*.test.mjs && bash test/elf.test.sh" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^5.9.0" + }, + "engines": { + "node": ">=22" + }, + "author": "Joaquin Terrasa & contributors", + "keywords": [ + "cli", + "argv", + "commander", + "argparse", + "scriptc", + "native" + ], + "homepage": "https://github.com/sigilco/cutils/tree/main/packages/cli#readme", + "bugs": { + "url": "https://github.com/sigilco/cutils/issues" + }, + "sideEffects": false +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 0000000..f2c4dc6 --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,585 @@ +// @cutils/cli — type-first, declarative CLI builder in the scriptc +// compilable subset. The command spec is a plain record literal; a mapped +// type carries the options literal into the handler's `opts` parameter, so +// parse + validate + help all come from one static schema — no runtime +// reflection anywhere (reflection has no static lowering). +// +// Subset notes (see AGENTS.md for the full rulebook): +// - No dynamic record READS (obj[key] is SC1090). All lookups walk +// Object.entries() with indexed loops. Dynamic record WRITES (the +// `values[name] = v` below) are fine. +// - `| null` unions only; absent optional record members read as +// `undefined` and are tested with `=== undefined` (the cache pattern). +// - No classes, no `?.`/`??`, no spread, no shorthand methods. +// - The handler crosses a dispatch boundary typed +// `(opts: unknown, args: string[]) => void`; the precise `opts` shape +// lives only in the user-facing command() generic. +// - The Standard Schema seam is a structural StandardValidator interface, +// NOT the official StandardSchemaV1 type — its computed "~standard" key +// poisons Object.entries lowering. Users pass `schema["~standard"]`. + +// ---------------------------------------------------------------- public types + +// Structural Standard-Schema seam. `issues` absent/null = success. +export interface ValidationIssue { + message: string; +} + +export interface StandardResult { + value?: unknown; + issues?: ValidationIssue[] | null; +} + +export interface StandardValidator { + validate(value: unknown): StandardResult | Promise; +} + +export type OptionType = "boolean" | "string" | "number"; + +// User-facing per-option spec. `default` is `unknown` at the type level +// (multi-type unions in record members are subset-fragile); command() +// checks at construction that a provided default matches `type`. +export interface OptionSpec { + type: OptionType; + short?: string; // single character; "" / omitted = no short flag + default?: unknown; // must match `type`; checked in command() + description?: string; + schema?: StandardValidator; // validates the parsed option value +} + +// Mapped type: the options literal drives the handler's `opts` shape. +// Every declared key is present at runtime — boolean defaults to false, +// number to 0, string to "" — so `opts` members are never optional. +export type OptsFromOptions = { + [K in keyof O]: O[K] extends { type: "boolean" } + ? boolean + : O[K] extends { type: "number" } + ? number + : O[K] extends { type: "string" } + ? string + : unknown; +}; + +export interface CommandSpec> { + args?: string[]; // required positional argument names, in order + options?: O; + schema?: StandardValidator; // validates { opts, args } before the handler + handler: (opts: OptsFromOptions, args: string[]) => void; +} + +// Normalized internal option shape: concrete fields, no optional members, +// so the parse loop never branches on member presence. +export interface OptionDef { + type: string; // "boolean" | "string" | "number" + short: string; // "" = none + hasDefault: boolean; + defaultValue: unknown; + description: string; // "" = none + schema: StandardValidator | null; +} + +export interface CommandDef { + description: string; + args: string[]; + options: Record; + schema: StandardValidator | null; + handler: (opts: unknown, args: string[]) => void; +} + +export interface ProgramSpec { + name: string; + version?: string; + description?: string; + commands: Record; +} + +// What a command-level schema receives. +export interface ParsedInput { + opts: Record; + args: string[]; +} + +// ---------------------------------------------------------------- command() + +export function command>( + description: string, + spec: CommandSpec, +): CommandDef { + const options: Record = {}; + const specOpts: Record = + spec.options === undefined ? {} : (spec.options as Record); + const entries = Object.entries(specOpts); + for (let i = 0; i < entries.length; i++) { + const name = entries[i][0]; + const s = entries[i][1]; + const hasDefault = s.default !== undefined; + const def: OptionDef = { + type: s.type, + short: s.short === undefined ? "" : s.short, + hasDefault: hasDefault, + defaultValue: hasDefault ? s.default : "", + description: s.description === undefined ? "" : s.description, + schema: s.schema === undefined ? null : s.schema, + }; + if (def.short.length > 1) { + throw new Error("E_BAD_OPTION: --" + name + " short must be a single character"); + } + if (def.hasDefault) { + const dv = def.defaultValue; + const ok = + (def.type === "boolean" && typeof dv === "boolean") || + (def.type === "string" && typeof dv === "string") || + (def.type === "number" && typeof dv === "number"); + if (!ok) { + throw new Error("E_BAD_OPTION: default for --" + name + " does not match type " + def.type); + } + } + options[name] = def; + } + // Upcast the user handler to the dispatch boundary type. A plain + // `const h = spec.handler` would hold a value declared with the generic + // OptsFromOptions type — scriptc keeps those as checked-dynamic slots. + const h = spec.handler as (opts: unknown, args: string[]) => void; + return { + description: description, + args: spec.args === undefined ? [] : spec.args, + options: options, + schema: spec.schema === undefined ? null : spec.schema, + handler: h, + }; +} + +// ---------------------------------------------------------------- run() + +// Returns the process exit code; prints help to stdout and errors to +// stderr. Typical entry point: `process.exit(run({...}))` — run() itself +// never exits, so it stays unit-testable under plain Node. +export function run(prog: ProgramSpec, argv?: string[]): number { + const args = argv === undefined ? process.argv.slice(2) : argv; + if (args.length === 0) { + printProgramHelp(prog); + return 0; + } + const first = args[0]; + if (first === "--help" || first === "-h") { + printProgramHelp(prog); + return 0; + } + if (first === "--version") { + if (prog.version === undefined) { + console.log(prog.name); + } else { + console.log(prog.name + " " + prog.version); + } + return 0; + } + if (first.charAt(0) === "-") { + return fail("unknown option '" + first + "' — run '" + prog.name + " --help'"); + } + const cmds = Object.entries(prog.commands); + let cmd: CommandDef | null = null; + for (let i = 0; i < cmds.length; i++) { + if (cmds[i][0] === first) { + cmd = cmds[i][1]; + break; + } + } + if (cmd === null) { + const names: string[] = []; + for (let i = 0; i < cmds.length; i++) { + names.push(cmds[i][0]); + } + const sug = suggest(first, names); + if (sug === "") { + return fail("unknown command '" + first + "'"); + } + return fail("unknown command '" + first + "' — did you mean '" + sug + "'?"); + } + return runCommand(prog, first, cmd, args.slice(1)); +} + +// ---------------------------------------------------------------- parsing + +function fail(msg: string): number { + console.error("error: " + msg); + return 1; +} + +function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: string[]): number { + const optionEntries = Object.entries(cmd.options); + const values: Record = {}; + // Seed every declared key: explicit default, else the type's zero value. + for (let i = 0; i < optionEntries.length; i++) { + const name = optionEntries[i][0]; + const def = optionEntries[i][1]; + if (def.hasDefault) { + values[name] = def.defaultValue; + } else if (def.type === "boolean") { + values[name] = false; + } else if (def.type === "number") { + values[name] = 0; + } else { + values[name] = ""; + } + } + + const positionals: string[] = []; + let endOpts = false; + let i = 0; + while (i < args.length) { + const tok = args[i]; + if (endOpts) { + positionals.push(tok); + i = i + 1; + continue; + } + if (tok === "--") { + endOpts = true; + i = i + 1; + continue; + } + if (tok === "--help") { + printCommandHelp(prog, cmdName, cmd); + return 0; + } + if (tok.length > 2 && tok.substring(0, 2) === "--") { + // --name or --name=value + let body = tok.substring(2); + let attached = ""; + let hasAttached = false; + const eq = body.indexOf("="); + if (eq >= 0) { + attached = body.substring(eq + 1); + body = body.substring(0, eq); + hasAttached = true; + } + const k = findLong(optionEntries, body); + if (k < 0) { + return fail("unknown option '--" + body + "'"); + } + const def = optionEntries[k][1]; + if (def.type === "boolean") { + if (!hasAttached) { + values[body] = true; + } else if (attached === "true" || attached === "1") { + values[body] = true; + } else if (attached === "false" || attached === "0") { + values[body] = false; + } else { + return fail("--" + body + ": expected a boolean, got '" + attached + "'"); + } + } else { + let raw = ""; + if (hasAttached) { + raw = attached; + } else { + if (i + 1 >= args.length) { + return fail("--" + body + " requires a value"); + } + i = i + 1; + raw = args[i]; + } + const err = setValue(values, def, body, raw, "--" + body); + if (err !== "") { + return fail(err); + } + } + i = i + 1; + continue; + } + if (tok.length > 1 && tok.charAt(0) === "-") { + // Short cluster: -u, -t 3, -t3, -ut3 (boolean shorts may cluster; + // a value-taking short consumes the rest of the token or next arg). + let j = 1; + while (j < tok.length) { + const c = tok.charAt(j); + const k = findShort(optionEntries, c); + if (k < 0) { + if (c === "h" && j === 1 && tok.length === 2) { + printCommandHelp(prog, cmdName, cmd); + return 0; + } + return fail("unknown option '-" + c + "'"); + } + const name = optionEntries[k][0]; + const def = optionEntries[k][1]; + if (def.type === "boolean") { + values[name] = true; + j = j + 1; + continue; + } + let raw = ""; + if (j + 1 < tok.length) { + raw = tok.substring(j + 1); + if (raw.charAt(0) === "=") { + raw = raw.substring(1); + } + } else { + if (i + 1 >= args.length) { + return fail("-" + c + " requires a value"); + } + i = i + 1; + raw = args[i]; + } + const err = setValue(values, def, name, raw, "-" + c); + if (err !== "") { + return fail(err); + } + j = tok.length; + } + i = i + 1; + continue; + } + positionals.push(tok); + i = i + 1; + } + + const required = cmd.args.length; + if (positionals.length < required) { + return fail("missing required argument '" + cmd.args[positionals.length] + "'"); + } + if (positionals.length > required) { + return fail("unexpected argument '" + positionals[required] + "'"); + } + + // Standard-Schema seam: per-option validators, then the command-level + // validator over { opts, args }. Async validators are rejected cleanly — + // instanceof Promise narrowing lowers fine. + for (let e = 0; e < optionEntries.length; e++) { + const name = optionEntries[e][0]; + const def = optionEntries[e][1]; + if (def.schema !== null) { + const err = runValidator(def.schema, valueOf(values, name), "--" + name); + if (err !== "") { + return fail(err); + } + } + } + if (cmd.schema !== null) { + const input: ParsedInput = { opts: values, args: positionals }; + const err = runValidator(cmd.schema, input, cmdName); + if (err !== "") { + return fail(err); + } + } + + cmd.handler(values, positionals); + return 0; +} + +// values[name] would be a dynamic record read (SC1090); walk entries. +function valueOf(rec: Record, key: string): unknown { + const entries = Object.entries(rec); + for (let i = 0; i < entries.length; i++) { + if (entries[i][0] === key) { + return entries[i][1]; + } + } + return null; +} + +function findLong(entries: [string, OptionDef][], name: string): number { + for (let i = 0; i < entries.length; i++) { + if (entries[i][0] === name) { + return i; + } + } + return -1; +} + +function findShort(entries: [string, OptionDef][], c: string): number { + for (let i = 0; i < entries.length; i++) { + if (entries[i][1].short === c) { + return i; + } + } + return -1; +} + +function setValue( + values: Record, + def: OptionDef, + name: string, + raw: string, + label: string, +): string { + if (def.type === "number") { + const n = Number(raw); + if (raw === "" || Number.isNaN(n)) { + return label + ": expected a number, got '" + raw + "'"; + } + values[name] = n; + return ""; + } + if (def.type === "string") { + values[name] = raw; + return ""; + } + return label + ": boolean option '" + name + "' takes no value"; +} + +function runValidator(v: StandardValidator, value: unknown, label: string): string { + const r = v.validate(value); + if (r instanceof Promise) { + return label + ": async validators are not supported (schema returned a Promise)"; + } + const issues = r.issues; + if (issues === undefined || issues === null || issues.length === 0) { + return ""; + } + let msg = label + ": validation failed"; + for (let i = 0; i < issues.length; i++) { + msg = msg + "; " + issues[i].message; + } + return msg; +} + +// ---------------------------------------------------------------- help + +function pad(s: string, w: number): string { + let out = s; + while (out.length < w) { + out = out + " "; + } + return out; +} + +function printProgramHelp(prog: ProgramSpec): void { + let head = prog.name; + if (prog.version !== undefined) { + head = head + " " + prog.version; + } + if (prog.description !== undefined && prog.description !== "") { + head = head + " — " + prog.description; + } + console.log(head); + console.log(""); + console.log("Usage: " + prog.name + " [options]"); + const cmds = Object.entries(prog.commands); + if (cmds.length > 0) { + console.log(""); + console.log("Commands:"); + let w = 0; + for (let i = 0; i < cmds.length; i++) { + if (cmds[i][0].length > w) { + w = cmds[i][0].length; + } + } + for (let i = 0; i < cmds.length; i++) { + console.log(" " + pad(cmds[i][0], w) + " " + cmds[i][1].description); + } + } + console.log(""); + console.log("Options:"); + console.log(" -h, --help show help"); + console.log(" --version show version"); +} + +function printCommandHelp(prog: ProgramSpec, cmdName: string, cmd: CommandDef): void { + console.log(prog.name + " " + cmdName + " — " + cmd.description); + console.log(""); + const optionEntries = Object.entries(cmd.options); + let usage = "Usage: " + prog.name + " " + cmdName; + for (let i = 0; i < cmd.args.length; i++) { + usage = usage + " <" + cmd.args[i] + ">"; + } + if (optionEntries.length > 0) { + usage = usage + " [options]"; + } + console.log(usage); + if (cmd.args.length > 0) { + console.log(""); + console.log("Arguments:"); + for (let i = 0; i < cmd.args.length; i++) { + console.log(" <" + cmd.args[i] + ">"); + } + } + console.log(""); + console.log("Options:"); + // Build [label, description] rows, then pad labels to the widest. + const labels: string[] = []; + const descs: string[] = []; + for (let i = 0; i < optionEntries.length; i++) { + const name = optionEntries[i][0]; + const def = optionEntries[i][1]; + let label = ""; + if (def.short !== "") { + label = "-" + def.short + ", --" + name; + } else { + label = " --" + name; + } + if (def.type === "number") { + label = label + " "; + } else if (def.type === "string") { + label = label + " "; + } + let desc = def.description; + if (def.hasDefault) { + desc = desc + " (default: " + String(def.defaultValue) + ")"; + } + labels.push(label); + descs.push(desc); + } + labels.push("-h, --help"); + descs.push("show help"); + let w = 0; + for (let i = 0; i < labels.length; i++) { + if (labels[i].length > w) { + w = labels[i].length; + } + } + for (let i = 0; i < labels.length; i++) { + console.log(" " + pad(labels[i], w) + " " + descs[i]); + } +} + +// ---------------------------------------------------------------- suggestions + +function suggest(input: string, names: string[]): string { + let best = ""; + let bestDist = 3; // only distances <= 2 or a prefix match qualify + for (let i = 0; i < names.length; i++) { + const n = names[i]; + const prefix = n.substring(0, input.length) === input || input.substring(0, n.length) === n; + const d = editDistance(input, n); + if ((d <= 2 || prefix) && d < bestDist) { + best = n; + bestDist = d; + } + } + return best; +} + +function editDistance(a: string, b: string): number { + const m = a.length; + const n = b.length; + if (m === 0) { + return n; + } + if (n === 0) { + return m; + } + let prev: number[] = []; + for (let j = 0; j <= n; j++) { + prev.push(j); + } + for (let i = 1; i <= m; i++) { + const cur: number[] = [i]; + for (let j = 1; j <= n; j++) { + const cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1; + const del = prev[j] + 1; + const ins = cur[j - 1] + 1; + const sub = prev[j - 1] + cost; + let min = del; + if (ins < min) { + min = ins; + } + if (sub < min) { + min = sub; + } + cur.push(min); + } + prev = cur; + } + return prev[n]; +} diff --git a/packages/cli/test/coverage.test.mjs b/packages/cli/test/coverage.test.mjs new file mode 100644 index 0000000..03e1df3 --- /dev/null +++ b/packages/cli/test/coverage.test.mjs @@ -0,0 +1,23 @@ +// Subset gate: `scriptc coverage gate.ts` must report 100% static. +// Uses the workspace-root .bin/scriptc (scriptc is a root devDependency); +// falls back to PATH. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { existsSync } from "node:fs"; +import path from "node:path"; + +const pkgDir = path.dirname(fileURLToPath(import.meta.url)) + "/.."; +const rootBin = path.resolve(pkgDir, "../../node_modules/.bin/scriptc"); +const scriptc = existsSync(rootBin) ? rootBin : "scriptc"; + +test("gate.ts compiles statically (100%)", () => { + const out = execFileSync(scriptc, ["coverage", "gate.ts"], { + cwd: pkgDir, + encoding: "utf8", + }); + const line = out.split("\n").find((l) => l.includes("compile statically")); + assert.ok(line, `no coverage line in output:\n${out}`); + assert.match(line, /\(100%\)/); +}); diff --git a/packages/cli/test/elf-app.ts b/packages/cli/test/elf-app.ts new file mode 100644 index 0000000..eb1b493 --- /dev/null +++ b/packages/cli/test/elf-app.ts @@ -0,0 +1,57 @@ +// ELF smoke app for @cutils/cli — compiled with `scriptc build` by +// test/elf.test.sh. A two-command demo CLI: `greet` exercises boolean/ +// number/string options + short flags + a schema; `add` exercises two +// positionals. test/elf.test.sh drives the full validation matrix. + +import { command, run } from "../src/index.ts"; + +const prog = { + name: "demo", + version: "1.0.0", + description: "elf smoke demo", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase output" }, + times: { + type: "number", + short: "t", + default: 1, + description: "repeat n times", + schema: { + validate: (value: unknown) => { + if (typeof value === "number" && value > 10) { + return { issues: [{ message: "times must be <= 10" }] }; + } + return { value: value }; + }, + }, + }, + greeting: { type: "string", short: "g", description: "greeting word" }, + }, + handler: (opts, args) => { + let who = args[0]; + let word = opts.greeting; + if (word === "") { + word = "hello"; + } + if (opts.upper) { + who = who.toUpperCase(); + word = word.toUpperCase(); + } + for (let i = 0; i < opts.times; i++) { + console.log(word + " " + who); + } + }, + }), + add: command("add two numbers", { + args: ["a", "b"], + handler: (opts, args) => { + console.log(String(Number(args[0]) + Number(args[1]))); + }, + }), + }, +}; + +process.exit(run(prog)); diff --git a/packages/cli/test/elf.test.sh b/packages/cli/test/elf.test.sh new file mode 100755 index 0000000..fb6a79d --- /dev/null +++ b/packages/cli/test/elf.test.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Build test/elf-app.ts to a native ELF (scriptc build) and run the full +# CLI validation matrix through it: flags, help, version, and every error +# path. Requires `pnpm install` at the workspace root (scriptc is a root +# devDependency). +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +T="$(mktemp -d)" +trap 'rm -rf "$T"' EXIT + +fail() { + echo "elf-cli-smoke FAIL: $*" >&2 + exit 1 +} + +# Prefer the workspace-root binary; fall back to PATH. +BIN="scriptc" +if [ -x ../../node_modules/.bin/scriptc ]; then + BIN="../../node_modules/.bin/scriptc" +fi +"$BIN" build test/elf-app.ts -o "$T/cli-elf" >/dev/null || fail "scriptc build" +echo "build OK" + +# expect +expect() { + local want_code="$1" want_out="$2" + shift 2 + local out code + set +e + out="$("$T/cli-elf" "$@" 2>"$T/err")" + code=$? + set -e + [ "$code" = "$want_code" ] || fail "argv [$*]: exit $code, want $want_code (out: $out, err: $(cat "$T/err"))" + case "$out" in + *"$want_out"*) ;; + *) fail "argv [$*]: stdout missing '$want_out' (got: $out)" ;; + esac +} + +# expect_err +expect_err() { + local want_code="$1" want_err="$2" + shift 2 + local out code + set +e + out="$("$T/cli-elf" "$@" 2>"$T/err")" + code=$? + set -e + [ "$code" = "$want_code" ] || fail "argv [$*]: exit $code, want $want_code" + case "$(cat "$T/err")" in + *"$want_err"*) ;; + *) fail "argv [$*]: stderr missing '$want_err' (got: $(cat "$T/err"))" ;; + esac +} + +expect 0 "hello world" greet world +expect 0 "HELLO WORLD" greet -u world +expect 0 "hi there" greet --greeting hi --times 2 there +expect 0 "4" add 1.5 2.5 +expect 0 "Usage: demo " --help +expect 0 "Usage: demo " +expect 0 "demo 1.0.0" --version +expect 0 "-u, --upper" greet --help +expect 0 "(default: 1)" greet --help +expect_err 1 "missing required argument 'name'" greet +expect_err 1 "expected a number, got 'abc'" greet --times abc x +expect_err 1 "unknown option '--bogus'" greet --bogus x +expect_err 1 "did you mean 'greet'?" gret x +expect_err 1 "unexpected argument" greet a b +expect_err 1 "times must be <= 10" greet --times 99 x + +echo "elf-cli-smoke OK" diff --git a/packages/cli/test/errors.test.js b/packages/cli/test/errors.test.js new file mode 100644 index 0000000..96fbef9 --- /dev/null +++ b/packages/cli/test/errors.test.js @@ -0,0 +1,112 @@ +// Error-path tests for @cutils/cli — every failure is "error: ..." on +// stderr + exit code 1; nothing throws. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { command, run } from "../dist/esm/index.js"; +import { capture } from "./helpers.js"; + +function prog() { + return { + name: "demo", + version: "1.0.0", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u" }, + times: { type: "number", short: "t", default: 1 }, + }, + handler: () => {}, + }), + add: command("add numbers", { + args: ["a", "b"], + handler: () => {}, + }), + }, + }; +} + +test("missing required argument names the missing arg", () => { + const r = capture(() => run(prog(), ["greet"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /error: missing required argument 'name'/); +}); + +test("missing second positional names it", () => { + const r = capture(() => run(prog(), ["add", "1"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /missing required argument 'b'/); +}); + +test("extra positional is an unexpected-argument error", () => { + const r = capture(() => run(prog(), ["greet", "a", "b"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /error: unexpected argument 'b'/); +}); + +test("non-numeric option value errors with the option label", () => { + for (const argv of [ + ["greet", "--times", "abc", "x"], + ["greet", "--times=abc", "x"], + ["greet", "-t", "abc", "x"], + ["greet", "-tabc", "x"], + ]) { + const r = capture(() => run(prog(), argv)); + assert.equal(r.code, 1, JSON.stringify(argv)); + assert.match(r.err.join("\n"), /expected a number, got 'abc'/); + } +}); + +test("missing option value errors", () => { + for (const argv of [ + ["greet", "x", "--times"], + ["greet", "x", "-t"], + ]) { + const r = capture(() => run(prog(), argv)); + assert.equal(r.code, 1, JSON.stringify(argv)); + assert.match(r.err.join("\n"), /requires a value/); + } +}); + +test("unknown long option", () => { + const r = capture(() => run(prog(), ["greet", "--bogus", "x"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /error: unknown option '--bogus'/); +}); + +test("unknown short option", () => { + const r = capture(() => run(prog(), ["greet", "-z", "x"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /error: unknown option '-z'/); +}); + +test("boolean option rejects a non-boolean attached value", () => { + const r = capture(() => run(prog(), ["greet", "--upper=maybe", "x"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /expected a boolean, got 'maybe'/); +}); + +test("unknown command suggests on edit distance <= 2", () => { + const r = capture(() => run(prog(), ["gret", "x"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /unknown command 'gret' — did you mean 'greet'\?/); +}); + +test("unknown command suggests on prefix", () => { + const r = capture(() => run(prog(), ["gre", "x"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /did you mean 'greet'\?/); +}); + +test("far-away command name gets no suggestion", () => { + const r = capture(() => run(prog(), ["xyzzy"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /unknown command 'xyzzy'/); + assert.doesNotMatch(r.err.join("\n"), /did you mean/); +}); + +test("top-level unknown option", () => { + const r = capture(() => run(prog(), ["--bogus"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /unknown option '--bogus'/); +}); diff --git a/packages/cli/test/help.test.js b/packages/cli/test/help.test.js new file mode 100644 index 0000000..62c8db7 --- /dev/null +++ b/packages/cli/test/help.test.js @@ -0,0 +1,128 @@ +// Help and version output tests for @cutils/cli. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { command, run } from "../dist/esm/index.js"; +import { capture } from "./helpers.js"; + +function prog() { + return { + name: "demo", + version: "1.0.0", + description: "a demo program", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase output" }, + times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + }, + handler: () => {}, + }), + add: command("add numbers", { + args: ["a", "b"], + handler: () => {}, + }), + }, + }; +} + +test("no args prints program help", () => { + const r = capture(() => run(prog(), [])); + assert.equal(r.code, 0); + const out = r.out.join("\n"); + assert.match(out, /demo 1\.0\.0 — a demo program/); + assert.match(out, /Usage: demo \[options\]/); + assert.match(out, /Commands:/); + assert.match(out, /greet +greet someone/); + assert.match(out, /add +add numbers/); + assert.match(out, /--version +show version/); +}); + +test("--help and -h print program help", () => { + for (const flag of ["--help", "-h"]) { + const r = capture(() => run(prog(), [flag])); + assert.equal(r.code, 0); + assert.match(r.out.join("\n"), /Usage: demo /); + } +}); + +test("--version prints name and version", () => { + const r = capture(() => run(prog(), ["--version"])); + assert.equal(r.code, 0); + assert.deepEqual(r.out, ["demo 1.0.0"]); +}); + +test("--version without a version prints just the name", () => { + const p = prog(); + delete p.version; + const r = capture(() => run(p, ["--version"])); + assert.equal(r.code, 0); + assert.deepEqual(r.out, ["demo"]); +}); + +test(" --help prints usage, args, options table", () => { + const r = capture(() => run(prog(), ["greet", "--help"])); + assert.equal(r.code, 0); + const out = r.out.join("\n"); + assert.match(out, /demo greet — greet someone/); + assert.match(out, /Usage: demo greet \[options\]/); + assert.match(out, /Arguments:/); + assert.match(out, //); + assert.match(out, /-u, --upper +uppercase output/); + assert.match(out, /-t, --times +repeat n times \(default: 1\)/); + assert.match(out, /-h, --help +show help/); +}); + +test(" -h prints command help when h is unclaimed", () => { + const r = capture(() => run(prog(), ["greet", "-h"])); + assert.equal(r.code, 0); + assert.match(r.out.join("\n"), /Usage: demo greet/); +}); + +test("-h resolves to a user-declared short option first", () => { + let seen; + const p = { + name: "demo", + commands: { + c: command("c", { + options: { host: { type: "string", short: "h" } }, + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "-h", "example.com"])); + assert.equal(r.code, 0); + assert.equal(seen.host, "example.com"); +}); + +test("command without options still prints an options table with help", () => { + const r = capture(() => run(prog(), ["add", "--help"])); + assert.equal(r.code, 0); + const out = r.out.join("\n"); + assert.match(out, /Usage: demo add /); + assert.doesNotMatch(out, /\[options\]/); + assert.match(out, /-h, --help +show help/); +}); + +test("command help works mid-argv (flags before it still parse)", () => { + // --help is checked during the parse, after `--` it is positional. + const r = capture(() => + run( + { + name: "d", + commands: { + c: command("c", { + args: ["x"], + handler: (opts, args) => { + assert.deepEqual(args, ["--help"]); + }, + }), + }, + }, + ["c", "--", "--help"], + ), + ); + assert.equal(r.code, 0); +}); diff --git a/packages/cli/test/helpers.js b/packages/cli/test/helpers.js new file mode 100644 index 0000000..a5cb862 --- /dev/null +++ b/packages/cli/test/helpers.js @@ -0,0 +1,16 @@ +// Shared capture helper for @cutils/cli tests: run() writes help to +// console.log and errors to console.error, so tests collect both. +export function capture(fn) { + const out = []; + const err = []; + const ol = console.log; + const oe = console.error; + console.log = (m) => out.push(String(m)); + console.error = (m) => err.push(String(m)); + try { + return { code: fn(), out, err }; + } finally { + console.log = ol; + console.error = oe; + } +} diff --git a/packages/cli/test/parse.test.js b/packages/cli/test/parse.test.js new file mode 100644 index 0000000..65b1a94 --- /dev/null +++ b/packages/cli/test/parse.test.js @@ -0,0 +1,130 @@ +// Option/positional parsing tests for @cutils/cli — runs on the tsc build. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { command, run } from "../dist/esm/index.js"; +import { capture } from "./helpers.js"; + +function prog(handler) { + return { + name: "demo", + version: "1.0.0", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase" }, + times: { type: "number", short: "t", default: 1, description: "repeat" }, + greeting: { type: "string", short: "g", description: "greeting word" }, + }, + handler, + }), + }, + }; +} + +test("long boolean flag and defaults", () => { + let seen; + const p = prog((opts, args) => { + seen = { opts, args }; + }); + const r = capture(() => run(p, ["greet", "--upper", "world"])); + assert.equal(r.code, 0); + assert.deepEqual(seen.opts, { upper: true, times: 1, greeting: "" }); + assert.deepEqual(seen.args, ["world"]); +}); + +test("boolean stays false and number zero-defaults without flags", () => { + let seen; + const p = prog((opts) => { + seen = opts; + }); + const r = capture(() => run(p, ["greet", "world"])); + assert.equal(r.code, 0); + assert.deepEqual(seen, { upper: false, times: 1, greeting: "" }); +}); + +test("--opt value and --opt=value", () => { + const got = []; + const p = prog((opts) => got.push(opts)); + capture(() => run(p, ["greet", "--times", "3", "world"])); + capture(() => run(p, ["greet", "--times=4", "world"])); + assert.equal(got[0].times, 3); + assert.equal(got[1].times, 4); +}); + +test("string option long and short forms", () => { + const got = []; + const p = prog((opts) => got.push(opts)); + capture(() => run(p, ["greet", "--greeting", "hi", "world"])); + capture(() => run(p, ["greet", "--greeting=yo", "world"])); + capture(() => run(p, ["greet", "-g", "hey", "world"])); + capture(() => run(p, ["greet", "-ghey", "world"])); + assert.equal(got[0].greeting, "hi"); + assert.equal(got[1].greeting, "yo"); + assert.equal(got[2].greeting, "hey"); + assert.equal(got[3].greeting, "hey"); +}); + +test("short flags: -u, -t 3, -t3, clustered -ut3", () => { + const got = []; + const p = prog((opts) => got.push(opts)); + capture(() => run(p, ["greet", "-u", "world"])); + capture(() => run(p, ["greet", "-t", "2", "world"])); + capture(() => run(p, ["greet", "-t3", "world"])); + capture(() => run(p, ["greet", "-ut3", "world"])); + assert.deepEqual(got[0], { upper: true, times: 1, greeting: "" }); + assert.deepEqual(got[1], { upper: false, times: 2, greeting: "" }); + assert.deepEqual(got[2], { upper: false, times: 3, greeting: "" }); + assert.deepEqual(got[3], { upper: true, times: 3, greeting: "" }); +}); + +test("--flag=false parses boolean attached values", () => { + const got = []; + const p = prog((opts) => got.push(opts)); + capture(() => run(p, ["greet", "--upper=false", "world"])); + capture(() => run(p, ["greet", "--upper=1", "world"])); + capture(() => run(p, ["greet", "--upper=0", "world"])); + assert.equal(got[0].upper, false); + assert.equal(got[1].upper, true); + assert.equal(got[2].upper, false); +}); + +test("-- ends option parsing; later tokens are positional", () => { + let seen; + const p = prog((opts, args) => { + seen = { opts, args }; + }); + const r = capture(() => run(p, ["greet", "--", "-u"])); + assert.equal(r.code, 0); + assert.equal(seen.opts.upper, false); + assert.deepEqual(seen.args, ["-u"]); +}); + +test("options may follow positionals", () => { + let seen; + const p = prog((opts) => { + seen = opts; + }); + const r = capture(() => run(p, ["greet", "world", "-u"])); + assert.equal(r.code, 0); + assert.equal(seen.upper, true); +}); + +test("negative numbers as option values", () => { + let seen; + const p = prog((opts) => { + seen = opts; + }); + const r = capture(() => run(p, ["greet", "--times=-2", "world"])); + assert.equal(r.code, 0); + assert.equal(seen.times, -2); +}); + +test("float numbers parse", () => { + let seen; + const p = prog((opts) => { + seen = opts; + }); + capture(() => run(p, ["greet", "-t", "2.5", "world"])); + assert.equal(seen.times, 2.5); +}); diff --git a/packages/cli/test/schema.test.js b/packages/cli/test/schema.test.js new file mode 100644 index 0000000..bdd5e7f --- /dev/null +++ b/packages/cli/test/schema.test.js @@ -0,0 +1,142 @@ +// Standard-Schema seam tests: hand-rolled StandardValidator-shaped +// validators (the shape `schema["~standard"]` has) run before the handler, +// sync failures become errors, async validators are rejected cleanly. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { command, run } from "../dist/esm/index.js"; +import { capture } from "./helpers.js"; + +const range = (max) => ({ + validate: (value) => { + if (typeof value === "number" && value > max) { + return { issues: [{ message: `must be <= ${max}` }] }; + } + return { value }; + }, +}); + +test("option schema passes valid values through", () => { + let seen; + const p = { + name: "d", + commands: { + c: command("c", { + options: { times: { type: "number", schema: range(10) } }, + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "--times", "5"])); + assert.equal(r.code, 0); + assert.equal(seen.times, 5); +}); + +test("option schema rejects with its issue messages", () => { + const p = { + name: "d", + commands: { + c: command("c", { + options: { times: { type: "number", schema: range(10) } }, + handler: () => assert.fail("handler must not run"), + }), + }, + }; + const r = capture(() => run(p, ["c", "--times", "99"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /--times: validation failed; must be <= 10/); +}); + +test("command schema receives { opts, args } and runs before the handler", () => { + let input; + const p = { + name: "d", + commands: { + c: command("c", { + args: ["name"], + options: { upper: { type: "boolean", short: "u" } }, + schema: { + validate: (value) => { + input = value; + return { value }; + }, + }, + handler: (opts, args) => { + assert.deepEqual(args, input.args); + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "-u", "world"])); + assert.equal(r.code, 0); + assert.deepEqual(input.opts, { upper: true }); + assert.deepEqual(input.args, ["world"]); +}); + +test("command schema rejection stops the handler", () => { + const p = { + name: "d", + commands: { + c: command("c", { + args: ["name"], + schema: { + validate: (value) => { + if (value.args[0] === "root") { + return { issues: [{ message: "cannot greet root" }] }; + } + return { value }; + }, + }, + handler: () => assert.fail("handler must not run"), + }), + }, + }; + const r = capture(() => run(p, ["c", "root"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /c: validation failed; cannot greet root/); +}); + +test("async option validator is rejected cleanly", () => { + const p = { + name: "d", + commands: { + c: command("c", { + options: { + times: { + type: "number", + schema: { validate: (v) => Promise.resolve({ value: v }) }, + }, + }, + handler: () => assert.fail("handler must not run"), + }), + }, + }; + const r = capture(() => run(p, ["c", "--times", "1"])); + assert.equal(r.code, 1); + assert.match(r.err.join("\n"), /async validators are not supported/); +}); + +test("a real Standard-Schema-shaped validator object fits the interface", () => { + // What `zodSchema["~standard"]` looks like structurally. + const std = { + validate: (value) => + typeof value === "string" && value.length > 0 + ? { value } + : { issues: [{ message: "expected non-empty string" }] }, + }; + const p = { + name: "d", + commands: { + c: command("c", { + options: { greeting: { type: "string", schema: std } }, + handler: () => {}, + }), + }, + }; + const ok = capture(() => run(p, ["c", "--greeting", "hi"])); + const bad = capture(() => run(p, ["c"])); // "" zero value fails the schema + assert.equal(ok.code, 0); + assert.equal(bad.code, 1); + assert.match(bad.err.join("\n"), /expected non-empty string/); +}); diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json new file mode 100644 index 0000000..2cd5418 --- /dev/null +++ b/packages/cli/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "declarationMap": false, + "sourceMap": false, + "outDir": "dist/esm", + "rootDir": "src", + "rewriteRelativeImportExtensions": true, + "skipLibCheck": false, + "forceConsistentCasingInFileNames": true, + }, + "include": ["src/**/*.ts"], +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d18abab..b7f25aa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -251,6 +251,15 @@ importers: specifier: ^5.9.0 version: 5.9.3 + packages/cli: + devDependencies: + '@types/node': + specifier: ^24.0.0 + version: 24.19.2 + typescript: + specifier: ^5.9.0 + version: 5.9.3 + packages/ffi: devDependencies: '@types/node': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 81d39d2..dc9cddc 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,6 +18,6 @@ versioning: - "@cutils-example/todo-app-postgres" - "@cutils-example/todo-app-mongo" fixed: - - ["@cutils/sqlite", "@cutils/postgres", "@cutils/mongo", "@cutils/cache", "@cutils/ffi"] + - ["@cutils/sqlite", "@cutils/postgres", "@cutils/mongo", "@cutils/cache", "@cutils/ffi", "@cutils/cli"] changelog: storage: repository From 5f984c1b82da28fad185704bf0d6d90da9cfdf91 Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:59:52 -0800 Subject: [PATCH 2/6] docs(cli): document @cutils/cli Package page, docmd nav entry, and the README/packages/quickstart/ ARCHITECTURE tables. The package README carries the API reference and the commander divergence table; size numbers stay in the package AGENTS.md until a bench cell exists. --- ARCHITECTURE.md | 2 +- README.md | 1 + docs/cli.md | 61 ++++++++++++++++++++++++++++++++++++++++++ docs/docmd.config.json | 4 +++ docs/packages.md | 1 + docs/quickstart.md | 1 + 6 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 docs/cli.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8987502..6fbf240 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -4,7 +4,7 @@ cutils hosts the utility packages of the chttp/scriptc ecosystem. Two scopes, on ## Scopes -- **`@cutils/*`** — general-purpose utilities that own their own native dependency and ship it behind an FFI shim. `@cutils/ffi` names the shared scriptc format-7 span ABI (the same one `@cutils/sqlite` already ships). `@cutils/sqlite` is the first production consumer; `@cutils/postgres`/`@cutils/mongo` are wire drivers without FFI. The native library is vendored, the shim is fixed signatures, and the TypeScript wrapper is the only user-facing surface. +- **`@cutils/*`** — general-purpose utilities that own their own native dependency and ship it behind an FFI shim. `@cutils/ffi` names the shared scriptc format-7 span ABI (the same one `@cutils/sqlite` already ships). `@cutils/sqlite` is the first production consumer; `@cutils/postgres`/`@cutils/mongo` are wire drivers without FFI, and `@cutils/cache`/`@cutils/cli` are pure TypeScript with no native side at all. The native library is vendored, the shim is fixed signatures, and the TypeScript wrapper is the only user-facing surface. - **`@chttp/*`** — request-scoped utilities that are a web-server concern, pure TypeScript over the same subset, no C. Most live in the [chttp](https://github.com/sigilco/chttp) monorepo; only `@cutils/cache` still ships from here. ## The Standard-Schema seam diff --git a/README.md b/README.md index 37a79bc..c3d5e6b 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ | [`@cutils/postgres`](packages/postgres) | Postgres wire driver over `node:net` + `node:crypto` (SCRAM-SHA-256, txns, LISTEN/NOTIFY), no FFI | | [`@cutils/mongo`](packages/mongo) | MongoDB wire driver (OP_MSG + BSON, SCRAM-SHA-1/256, txns), no FFI | | [`@cutils/cache`](packages/cache) | LRU + TTL in-process cache with lru-cache parity semantics | +| [`@cutils/cli`](packages/cli) | Type-first declarative CLI builder: typed options, generated help/version, Standard-Schema seam | ## What it does diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..a15d67d --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,61 @@ +# @cutils/cli + +Type-first, declarative CLI builder in the scriptc-compilable subset — the same source runs under Node and lowers into a native ELF. Zero dependencies. + +## Quickstart + +::: tabs + +== tab Node + +```sh +pnpm add @cutils/cli +``` + +```ts +import { command, run } from "@cutils/cli"; + +process.exit( + run({ + name: "demo", + version: "1.0.0", + commands: { + greet: command("greet someone", { + args: ["name"], + options: { + upper: { type: "boolean", short: "u", description: "uppercase output" }, + times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + }, + handler: (opts, args) => { + // opts: { upper: boolean; times: number } — fully inferred + const who = opts.upper ? args[0].toUpperCase() : args[0]; + for (let i = 0; i < opts.times; i++) console.log(`hello ${who}`); + }, + }), + }, + }), +); +``` + +== tab Native ELF + +```sh +scriptc build src/main.ts -o demo +./demo greet -u -t2 world # hello WORLD, twice +./demo greet --help # generated usage + options table +``` + +::: + +## How it works + +The `command()` spec is a plain record literal. A mapped type (`OptsFromOptions`) carries the options literal into the handler's `opts` parameter, so parse rules, types, `--help` output, and error messages all come from one static schema — no runtime reflection anywhere. + +- `args` names required positionals, in order. Extra positionals are an `unexpected argument` error. +- `options` accepts `boolean`/`string`/`number` with `short` (one character), `default` (must match `type`), and `description`. Every declared key is always present in `opts` — the `default`, else the type's zero value (`false`/`0`/`""`). +- Parsing: `--opt`, `--opt=v`, `--opt v`, `-s`, `-s v`, `-sV`, clustered boolean shorts (`-ut3`), `--` end-of-options, `-h` (yields to a declared `short: "h"`). +- Generated: `--help`/`-h` at program and command level, `--version`, unknown-command suggestions (edit distance ≤ 2 or prefix), labelled errors for missing arguments, unknown options, and bad values. +- `schema` on an option or command accepts a Standard-Schema-shaped validator (`mySchema["~standard"]`); sync only — a `Promise` result is a clear error. +- `run` returns the exit code and never exits itself: `process.exit(run({...}))`, or pass `argv` as a test seam. + +See the [package README](https://github.com/sigilco/cutils/tree/main/packages/cli#readme) for the full surface and the commander divergence table. diff --git a/docs/docmd.config.json b/docs/docmd.config.json index 51b0068..5c18d0e 100644 --- a/docs/docmd.config.json +++ b/docs/docmd.config.json @@ -57,6 +57,10 @@ { "title": "@cutils/cache", "path": "/cache" + }, + { + "title": "@cutils/cli", + "path": "/cli" } ] } diff --git a/docs/packages.md b/docs/packages.md index f07171c..6babc50 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -7,6 +7,7 @@ | [`@cutils/postgres`](https://www.npmjs.com/package/@cutils/postgres) | cutils | Postgres wire driver over `node:net` + `node:crypto` (SCRAM-SHA-256, txns, LISTEN/NOTIFY), no FFI | | [`@cutils/mongo`](https://www.npmjs.com/package/@cutils/mongo) | cutils | MongoDB wire driver (OP_MSG + BSON, SCRAM-SHA-1/256, txns), no FFI | | [`@cutils/cache`](https://www.npmjs.com/package/@cutils/cache) | chttp | LRU + TTL in-process cache with lru-cache parity semantics | +| [`@cutils/cli`](https://www.npmjs.com/package/@cutils/cli) | cutils | Type-first declarative CLI builder: typed options, generated help/version, Standard-Schema seam | `@chttp/auth` and `@chttp/mcp` moved to the [chttp](https://github.com/sigilco/chttp) monorepo — new releases publish from there. diff --git a/docs/quickstart.md b/docs/quickstart.md index cae1973..c68000c 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -6,6 +6,7 @@ Each package installs from npm and works the same under Node and under `scriptc pnpm add @cutils/ffi # shared format-7 FFI spec + struct echo pnpm add @cutils/sqlite # embedded SQLite pnpm add @cutils/cache # LRU + TTL memory cache +pnpm add @cutils/cli # type-first CLI builder ``` ::: tabs From 0cdad08cc401868eff2ec2518d0444aaa4b8ae34 Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:46:55 -0800 Subject: [PATCH 3/6] fix(cli): accept readonly issue arrays in the Standard Schema seam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Standard Schema mandates `issues?: ReadonlyArray`; every compliant library (arktype, zod, valibot) returns a readonly array, which was not assignable to the mutable `ValidationIssue[]` the seam declared — so `schema["~standard"]` failed to typecheck against real validators. Verified end-to-end: an arktype `type("number>0")["~standard"] passed as an option schema validates under scriptc Node islands. --- packages/cli/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index f2c4dc6..06a2001 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -27,7 +27,7 @@ export interface ValidationIssue { export interface StandardResult { value?: unknown; - issues?: ValidationIssue[] | null; + issues?: readonly ValidationIssue[] | null; } export interface StandardValidator { From 51f9e893d81fd8e4529bf62f06b0488bec01109c Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:53:28 -0800 Subject: [PATCH 4/6] feat(cli): accept whole Standard Schema objects and infer opts from types.output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit schema now takes a bare validator, the "~standard" props object, or a whole schema object carrying "~standard" — pass an arktype Type or zod schema directly and command() unwraps to ~standard.validate (preferred when both paths exist; E_BAD_OPTION when neither does). Verified end-to-end under scriptc Node islands: arktype type("number>0") and type("'dev'|'prod'") validate natively with the library's own messages. OptsFromOptions reads the schema's declared types.output — Standard Schema's phantom type channel — before falling back to the primitive type, so schema libraries drive opts inference: literal unions come through as literal unions, unknown outputs fall back to the type-derived primitive. StandardResult.issues is readonly per the spec (previous commit) so real validators typecheck. --- docs/cli.md | 2 +- packages/cli/AGENTS.md | 11 +++- packages/cli/README.md | 15 +++-- packages/cli/src/index.ts | 106 ++++++++++++++++++++++++++----- packages/cli/test/schema.test.js | 72 ++++++++++++++++++++- 5 files changed, 179 insertions(+), 27 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index a15d67d..697f915 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -55,7 +55,7 @@ The `command()` spec is a plain record literal. A mapped type (`OptsFromOptions` - `options` accepts `boolean`/`string`/`number` with `short` (one character), `default` (must match `type`), and `description`. Every declared key is always present in `opts` — the `default`, else the type's zero value (`false`/`0`/`""`). - Parsing: `--opt`, `--opt=v`, `--opt v`, `-s`, `-s v`, `-sV`, clustered boolean shorts (`-ut3`), `--` end-of-options, `-h` (yields to a declared `short: "h"`). - Generated: `--help`/`-h` at program and command level, `--version`, unknown-command suggestions (edit distance ≤ 2 or prefix), labelled errors for missing arguments, unknown options, and bad values. -- `schema` on an option or command accepts a Standard-Schema-shaped validator (`mySchema["~standard"]`); sync only — a `Promise` result is a clear error. +- `schema` on an option or command accepts a bare validator, the `mySchema["~standard"]` props object, or a whole schema object carrying `"~standard"` (arktype `Type`, zod schema — unwrapped automatically, `"~standard".validate` preferred). When the schema declares `types.output`, `OptsFromOptions` uses it for `opts` — arktype literal unions infer as literal unions. Sync only — a `Promise` result is a clear error. - `run` returns the exit code and never exits itself: `process.exit(run({...}))`, or pass `argv` as a test seam. See the [package README](https://github.com/sigilco/cutils/tree/main/packages/cli#readme) for the full surface and the commander divergence table. diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 6afc2d1..3a6ea84 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -43,8 +43,15 @@ Record>` lowers fully — the generic only feeds the runtime-checks the default against `type` at construction (`E_BAD_OPTION`). - **The schema seam is structural, not StandardSchemaV1**: the official type's computed `"~standard"` key poisons `Object.entries` lowering. - `StandardValidator`/`StandardResult` are hand-rolled structural twins — - users pass `mySchema["~standard"]`. Keep it that way. + `StandardValidator`/`StandardResult`/`StandardSchemaInput` are + hand-rolled structural twins — `schema` accepts a bare validator, the + `"~standard"` props, or a whole schema object (arktype `Type`, zod); + `normalizeSchema` prefers `"~standard".validate` and throws + `E_BAD_OPTION` when neither path exists. `OptsFromOptions` reads the + schema's `types.output` (Standard Schema's phantom channel) before + falling back to the primitive `type` — verified 2026-11-08: arktype + `type("'dev'|'prod'")` infers `opts.env: "dev" | "prod"` and validates + under scriptc Node islands end-to-end. - **`opts` keys are always present**: absent flag → `default` else the type's zero value (`false`/`0`/`""`). Documented because it differs from commander (`undefined`). "Was it passed" = sentinel default or diff --git a/packages/cli/README.md b/packages/cli/README.md index cf05338..ad073ac 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -30,7 +30,7 @@ process.exit( - **The literal IS the schema.** Parse rules, `opts` types, `--help` tables, and error messages all come from the same `command()` spec — no runtime reflection (which scriptc cannot lower anyway). - **`opts` is fully inferred.** The options literal flows through a mapped type: `{ type: "boolean" }` → `boolean`, `"number"` → `number`, `"string"` → `string`. Every declared key is always present. - **Help, version, and errors are generated.** `--help`/`-h` at program and command level, `--version`, unknown-command suggestions, and labelled errors for missing arguments, unknown options, and bad values. -- **Standard Schema hook.** Any validator shaped like `schema["~standard"]` can guard an option value or the whole `{ opts, args }` input — sync only (async validators are rejected with a clear error). +- **Standard Schema hook.** Any validator shaped like `schema["~standard"]` — or a whole schema object carrying one, like an arktype `Type` or a zod schema — can guard an option value or the whole `{ opts, args }` input. When the schema declares `types.output`, that type flows into `opts` (arktype literal unions infer as literal unions). Sync only — async validators are rejected with a clear error. - **Exits by return code.** `run` prints and returns a number; it never calls `process.exit` itself, so it stays unit-testable under plain `node --test`. ## Surface @@ -56,7 +56,7 @@ interface ProgramSpec { interface CommandSpec { args?: string[]; // required positionals, in order options?: O; // record of OptionSpec - schema?: StandardValidator; // validates { opts, args } + schema?: StandardSchemaInput; // validates { opts, args } handler: (opts: OptsFromOptions, args: string[]) => void; } @@ -65,8 +65,13 @@ interface OptionSpec { short?: string; // one character default?: unknown; // must match `type`; checked in command() description?: string; - schema?: StandardValidator; // validates the parsed option value + schema?: StandardSchemaInput; // validates the parsed option value } + +// StandardSchemaInput accepts three shapes: a bare { validate(value) }, +// the "~standard" props object itself, or a whole schema object carrying +// "~standard" (arktype Type, zod schema). "~standard".validate wins when +// both paths exist; neither → E_BAD_OPTION at command() time. ``` ### Parsing rules @@ -89,7 +94,9 @@ Every declared option key exists in `opts` with its declared type. When the flag ### Standard Schema seam -`schema` accepts any object with `validate(value)` returning `{ value }` or `{ issues: [{ message }] }` — the shape `mySchema["~standard"]` has (pass that member, not the schema itself). Option schemas receive the parsed option value; command schemas receive `{ opts, args }`. Results are synchronous — a `Promise` return is an error, not a wait. +`schema` accepts three shapes: a bare `{ validate(value) }` returning `{ value }` or `{ issues: [{ message }] }`; the `mySchema["~standard"]` props object itself; or a whole schema object carrying `"~standard"` — pass `myArktype` or `myZodSchema` directly and the builder unwraps it. `"~standard".validate` wins when both paths exist; a schema with neither fails at `command()` time with `E_BAD_OPTION`. Option schemas receive the parsed option value; command schemas receive `{ opts, args }`. Results are synchronous — a `Promise` return is an error, not a wait. + +When the schema declares `types.output` (every Standard Schema library does — it is the spec's phantom type channel), `OptsFromOptions` uses it for `opts` instead of the primitive `type`: `type("'dev' | 'prod'")` gives `opts.env: "dev" | "prod"`. A schema output of `unknown` falls back to the `type`-derived primitive. ## Divergences from commander diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 06a2001..741d332 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -14,9 +14,11 @@ // - The handler crosses a dispatch boundary typed // `(opts: unknown, args: string[]) => void`; the precise `opts` shape // lives only in the user-facing command() generic. -// - The Standard Schema seam is a structural StandardValidator interface, -// NOT the official StandardSchemaV1 type — its computed "~standard" key -// poisons Object.entries lowering. Users pass `schema["~standard"]`. +// - The Standard Schema seam accepts a bare validator, the "~standard" +// props object, or a whole schema object (arktype Type, zod schema); +// command() unwraps to the callable validator. OptsFromOptions reads +// the schema's declared `types.output` so schema libraries drive `opts` +// inference through the spec's own type channel. // ---------------------------------------------------------------- public types @@ -34,6 +36,25 @@ export interface StandardValidator { validate(value: unknown): StandardResult | Promise; } +// The props object at schema["~standard"] — what Standard Schema consumers +// call. `types` is the spec's phantom in/out channel: libraries like arktype +// and zod populate it, and OptsFromOptions reads `output` back out so the +// schema's declared type flows into the handler's `opts`. +export interface StandardValidatorProps { + validate(value: unknown): StandardResult | Promise; + types?: { input?: unknown; output?: unknown }; +} + +// What OptionSpec.schema / CommandSpec.schema accept: a bare validator, the +// "~standard" props object, or a whole schema object carrying one (an +// arktype Type, a zod schema). All members optional so every shape fits; +// command() throws E_BAD_OPTION when neither validate path exists. +export interface StandardSchemaInput { + validate?(value: unknown): StandardResult | Promise; + "~standard"?: StandardValidatorProps; + types?: { input?: unknown; output?: unknown }; +} + export type OptionType = "boolean" | "string" | "number"; // User-facing per-option spec. `default` is `unknown` at the type level @@ -44,26 +65,58 @@ export interface OptionSpec { short?: string; // single character; "" / omitted = no short flag default?: unknown; // must match `type`; checked in command() description?: string; - schema?: StandardValidator; // validates the parsed option value + schema?: StandardSchemaInput; // validates the parsed option value +} + +// Sentinel for "the schema declares no output type" — an object shape no +// real schema output type is assignable to. +export interface NoSchemaOutput { + readonly "~cli/noSchemaOutput": true; } -// Mapped type: the options literal drives the handler's `opts` shape. -// Every declared key is present at runtime — boolean defaults to false, -// number to 0, string to "" — so `opts` members are never optional. +// The output type a schema declares through Standard Schema's `types` +// channel. Checks the whole-schema form first ("~standard".types.output), +// then the props form (types.output directly — what schema["~standard"] +// carries), then gives up. +export type SchemaOutput = S extends { "~standard": { types?: infer T } } + ? NonNullable extends { output: infer O } + ? O + : NoSchemaOutput + : S extends { types?: infer T } + ? NonNullable extends { output: infer O } + ? O + : NoSchemaOutput + : NoSchemaOutput; + +type PrimOption = O extends { type: "boolean" } + ? boolean + : O extends { type: "number" } + ? number + : string; + +// Mapped type: the options literal drives the handler's `opts` shape. A +// schema that declares `types.output` wins (arktype literal unions come +// through here); otherwise the primitive `type` decides. Every declared +// key is present at runtime — boolean defaults to false, number to 0, +// string to "" — so `opts` members are never optional. export type OptsFromOptions = { - [K in keyof O]: O[K] extends { type: "boolean" } - ? boolean - : O[K] extends { type: "number" } - ? number - : O[K] extends { type: "string" } - ? string - : unknown; + [K in keyof O]: O[K] extends { schema?: infer S } + ? [NonNullable] extends [never] + ? PrimOption + : SchemaOutput> extends infer T + ? [T] extends [NoSchemaOutput] + ? PrimOption + : [unknown] extends [T] + ? PrimOption + : T + : PrimOption + : PrimOption; }; export interface CommandSpec> { args?: string[]; // required positional argument names, in order options?: O; - schema?: StandardValidator; // validates { opts, args } before the handler + schema?: StandardSchemaInput; // validates { opts, args } before the handler handler: (opts: OptsFromOptions, args: string[]) => void; } @@ -119,7 +172,7 @@ export function command>( hasDefault: hasDefault, defaultValue: hasDefault ? s.default : "", description: s.description === undefined ? "" : s.description, - schema: s.schema === undefined ? null : s.schema, + schema: normalizeSchema(s.schema, "--" + name), }; if (def.short.length > 1) { throw new Error("E_BAD_OPTION: --" + name + " short must be a single character"); @@ -144,11 +197,30 @@ export function command>( description: description, args: spec.args === undefined ? [] : spec.args, options: options, - schema: spec.schema === undefined ? null : spec.schema, + schema: normalizeSchema(spec.schema, "command"), handler: h, }; } +// Unwrap a StandardSchemaInput to the callable validator: prefer the +// "~standard" props (the spec's consumption path — an arktype Type or zod +// schema carries no top-level validate), fall back to a bare validator. +// Throws at construction when neither exists so a schema-less "schema" +// can never silently pass. +function normalizeSchema(input: StandardSchemaInput | undefined, label: string): StandardValidator | null { + if (input === undefined) { + return null; + } + const std = input["~standard"]; + if (std !== undefined && std.validate !== undefined) { + return std; + } + if (input.validate !== undefined) { + return input as StandardValidator; + } + throw new Error("E_BAD_OPTION: " + label + " schema has neither ~standard.validate nor validate"); +} + // ---------------------------------------------------------------- run() // Returns the process exit code; prints help to stdout and errors to diff --git a/packages/cli/test/schema.test.js b/packages/cli/test/schema.test.js index bdd5e7f..480c793 100644 --- a/packages/cli/test/schema.test.js +++ b/packages/cli/test/schema.test.js @@ -1,6 +1,7 @@ -// Standard-Schema seam tests: hand-rolled StandardValidator-shaped -// validators (the shape `schema["~standard"]` has) run before the handler, -// sync failures become errors, async validators are rejected cleanly. +// Standard-Schema seam tests: bare validators, "~standard" props objects, +// and whole schema objects (the arktype Type / zod shape) all run before +// the handler; sync failures become errors, async validators are rejected +// cleanly, and a schema with no validate path fails at construction. import { test } from "node:test"; import assert from "node:assert/strict"; import { command, run } from "../dist/esm/index.js"; @@ -140,3 +141,68 @@ test("a real Standard-Schema-shaped validator object fits the interface", () => assert.equal(bad.code, 1); assert.match(bad.err.join("\n"), /expected non-empty string/); }); + +test("a whole schema object's ~standard props are unwrapped and called", () => { + // The arktype Type / zod schema shape: "~standard" carries validate + + // the phantom types channel, no top-level validate exists. + const whole = { + "~standard": { + validate: (value) => + value === "ok" ? { value } : { issues: [{ message: "must be ok" }] }, + types: { input: undefined, output: undefined }, + }, + }; + const p = { + name: "d", + commands: { + c: command("c", { + options: { mode: { type: "string", schema: whole } }, + handler: () => {}, + }), + }, + }; + const ok = capture(() => run(p, ["c", "--mode", "ok"])); + const bad = capture(() => run(p, ["c", "--mode", "no"])); + assert.equal(ok.code, 0); + assert.equal(bad.code, 1); + assert.match(bad.err.join("\n"), /--mode: validation failed; must be ok/); +}); + +test("~standard.validate wins over a top-level validate when both exist", () => { + const both = { + validate: () => ({ issues: [{ message: "top-level should not run" }] }), + "~standard": { + validate: (value) => ({ value }), + }, + }; + const p = { + name: "d", + commands: { + c: command("c", { + options: { x: { type: "string", schema: both } }, + handler: () => {}, + }), + }, + }; + const r = capture(() => run(p, ["c", "--x", "anything"])); + assert.equal(r.code, 0); +}); + +test("a schema with neither validate nor ~standard.validate throws E_BAD_OPTION", () => { + assert.throws( + () => + command("c", { + options: { x: { type: "string", schema: { types: {} } } }, + handler: () => {}, + }), + /E_BAD_OPTION: --x schema has neither ~standard\.validate nor validate/, + ); + assert.throws( + () => + command("c", { + schema: { "~standard": { types: {} } }, + handler: () => {}, + }), + /E_BAD_OPTION: command schema has neither ~standard\.validate nor validate/, + ); +}); From c216c6c60342b139e33da753447c67df82b1ef46 Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:53:44 -0800 Subject: [PATCH 5/6] style(cli): oxfmt the schema-input changes --- packages/cli/src/index.ts | 5 ++++- packages/cli/test/schema.test.js | 3 +-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 741d332..ed45327 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -207,7 +207,10 @@ export function command>( // schema carries no top-level validate), fall back to a bare validator. // Throws at construction when neither exists so a schema-less "schema" // can never silently pass. -function normalizeSchema(input: StandardSchemaInput | undefined, label: string): StandardValidator | null { +function normalizeSchema( + input: StandardSchemaInput | undefined, + label: string, +): StandardValidator | null { if (input === undefined) { return null; } diff --git a/packages/cli/test/schema.test.js b/packages/cli/test/schema.test.js index 480c793..13bb82a 100644 --- a/packages/cli/test/schema.test.js +++ b/packages/cli/test/schema.test.js @@ -147,8 +147,7 @@ test("a whole schema object's ~standard props are unwrapped and called", () => { // the phantom types channel, no top-level validate exists. const whole = { "~standard": { - validate: (value) => - value === "ok" ? { value } : { issues: [{ message: "must be ok" }] }, + validate: (value) => (value === "ok" ? { value } : { issues: [{ message: "must be ok" }] }), types: { input: undefined, output: undefined }, }, }; From 43ccdf84c57cc05e4e2670d5472583bd1cede235 Mon Sep 17 00:00:00 2001 From: Quino Terrasa <26749475+espetro@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:01:01 -0800 Subject: [PATCH 6/6] =?UTF-8?q?feat(cli):=20schema-first=20rewrite=20?= =?UTF-8?q?=E2=80=94=20drop=20`type`,=20delegate=20all=20semantics=20to=20?= =?UTF-8?q?Standard=20Schema?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The library now owns only the seam: argv tokenize -> flag-vs-value -> effective value -> validate() boundary -> dispatch. Every value semantic (coercion, bounds, literal unions, morphs) belongs to the schema; opts types derive entirely from Standard Schema's types.output phantom channel. - OptionSpec loses `type`; `flag` is the only parser-owned fact - options entries: OptionSpec | bare schema object | bare (v)=>result fn - SchemaInput = StandardSchemaInput | ValidateFn; async rejected cleanly - validators receive raw argv strings; returned value lands in opts - default runs through validate() at command() — morphs apply, schema issues become E_BAD_OPTION - builtins str()/num()/int()/bool() are Standard-Schema-shaped validators with types.output declared; num/int take {min,max} - metavar help hints (explicit > builtin > option name); flags show none - 50/50 node tests, gate.ts 451/451 static (100%), ELF matrix green --- .changeset/cli-initial-release.md | 2 +- docs/cli.md | 26 +- packages/cli/AGENTS.md | 77 +++-- packages/cli/README.md | 88 ++++-- packages/cli/gate.ts | 91 ++++-- packages/cli/src/index.ts | 497 +++++++++++++++++++++--------- packages/cli/test/elf-app.ts | 28 +- packages/cli/test/elf.test.sh | 2 +- packages/cli/test/errors.test.js | 6 +- packages/cli/test/help.test.js | 8 +- packages/cli/test/parse.test.js | 68 +++- packages/cli/test/schema.test.js | 164 ++++++++-- 12 files changed, 770 insertions(+), 287 deletions(-) diff --git a/.changeset/cli-initial-release.md b/.changeset/cli-initial-release.md index 796167b..40463ed 100644 --- a/.changeset/cli-initial-release.md +++ b/.changeset/cli-initial-release.md @@ -2,4 +2,4 @@ "@cutils/cli": minor --- -Initial release: type-first declarative CLI builder (`command`/`run`) — typed options, generated help/version, error suggestions, Standard-Schema seam; compiles statically into the app ELF. +Initial release: Standard-Schema-first declarative CLI builder (`command`/`run` + `str`/`num`/`int`/`bool` builtins) — `opts` types derive entirely from the schema's `types.output` channel; validators own all coercion and errors; compiles statically into the app ELF. diff --git a/docs/cli.md b/docs/cli.md index 697f915..f0579c2 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,6 +1,6 @@ # @cutils/cli -Type-first, declarative CLI builder in the scriptc-compilable subset — the same source runs under Node and lowers into a native ELF. Zero dependencies. +Declarative CLI builder in the scriptc-compilable subset — the same source runs under Node and lowers into a native ELF. Zero dependencies. It owns the seam only: argv → validated values → dispatch; all value semantics (coercion, constraints, morphs) belong to the [Standard Schema](https://standardschema.dev) you plug in. ## Quickstart @@ -13,7 +13,7 @@ pnpm add @cutils/cli ``` ```ts -import { command, run } from "@cutils/cli"; +import { bool, command, int, run, str } from "@cutils/cli"; process.exit( run({ @@ -23,13 +23,14 @@ process.exit( greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase output" }, - times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + upper: bool({ short: "u", description: "uppercase output" }), + times: int({ short: "t", default: 1, max: 10, description: "repeat n times" }), + greeting: str({ short: "g", description: "greeting word" }), }, handler: (opts, args) => { - // opts: { upper: boolean; times: number } — fully inferred + // opts: { upper: boolean; times: number; greeting: string } — fully inferred const who = opts.upper ? args[0].toUpperCase() : args[0]; - for (let i = 0; i < opts.times; i++) console.log(`hello ${who}`); + for (let i = 0; i < opts.times; i++) console.log(`${opts.greeting || "hello"} ${who}`); }, }), }, @@ -49,13 +50,16 @@ scriptc build src/main.ts -o demo ## How it works -The `command()` spec is a plain record literal. A mapped type (`OptsFromOptions`) carries the options literal into the handler's `opts` parameter, so parse rules, types, `--help` output, and error messages all come from one static schema — no runtime reflection anywhere. +The `command()` spec is a plain record literal. `OptsFromOptions` maps each options entry into the handler's `opts` parameter through Standard Schema's `types.output` channel — parse rules, types, `--help` output, and error messages all come from one static schema, no runtime reflection. - `args` names required positionals, in order. Extra positionals are an `unexpected argument` error. -- `options` accepts `boolean`/`string`/`number` with `short` (one character), `default` (must match `type`), and `description`. Every declared key is always present in `opts` — the `default`, else the type's zero value (`false`/`0`/`""`). -- Parsing: `--opt`, `--opt=v`, `--opt v`, `-s`, `-s v`, `-sV`, clustered boolean shorts (`-ut3`), `--` end-of-options, `-h` (yields to a declared `short: "h"`). -- Generated: `--help`/`-h` at program and command level, `--version`, unknown-command suggestions (edit distance ≤ 2 or prefix), labelled errors for missing arguments, unknown options, and bad values. -- `schema` on an option or command accepts a bare validator, the `mySchema["~standard"]` props object, or a whole schema object carrying `"~standard"` (arktype `Type`, zod schema — unwrapped automatically, `"~standard".validate` preferred). When the schema declares `types.output`, `OptsFromOptions` uses it for `opts` — arktype literal unions infer as literal unions. Sync only — a `Promise` result is a clear error. +- `options` entries are `OptionSpec`, a whole schema object, or a bare `(v) => result` function — discriminated by `~standard`/`validate` presence (or `typeof === "function"`). +- `OptionSpec` has no `type`: `flag` (consumes no value) is the only parse fact; `schema` adds validation + typing; `short`, `default` (validated through `validate()` at `command()`), `description`, `metavar` (help hint, defaults to the name). +- Validators receive the raw argv string; the returned `value` is what `opts` gets — morphs apply to explicit values and defaults. Absent options: `default`, else `false` for flags / `""` for value-options — a schema that rejects `""` is effectively required. +- `str()`/`num()`/`int()`/`bool()` builtins are zero-dep Standard-Schema-shaped validators with `types.output` declared — `num({min, max})` both infers `opts.x: number` and enforces bounds. +- Foreign schemas plug straight in: `schema: myZod`, `schema: myArktype`, `schema: mySchema["~standard"]`, or drop a whole schema object in as the option entry itself. Async validators are rejected cleanly. +- Parsing: `--opt`, `--opt=v`, `--opt v`, `-s`, `-s v`, `-sV`, clustered flag shorts (`-ut3`), `--flag=false`, `--` end-of-options, `-h` (yields to a declared `short: "h"`). +- Generated: `--help`/`-h` at program and command level, `--version`, unknown-command suggestions, labelled errors. - `run` returns the exit code and never exits itself: `process.exit(run({...}))`, or pass `argv` as a test seam. See the [package README](https://github.com/sigilco/cutils/tree/main/packages/cli#readme) for the full surface and the commander divergence table. diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 3a6ea84..4ae2c91 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1,23 +1,29 @@ # @cutils/cli AGENTS.md -Type-first declarative CLI builder in the scriptc subset — plain records + -functions, no classes, zero deps. Design source: -`.agents/plans/2026-11-07-cutils-cli.md` and the `minicli` prototype writeup -(`~/Downloads/scriptc-cli-compat-roadmap-and-design.md` Part 2). Same subset -rules as the root AGENTS.md, plus what authoring this package verified -empirically under the pinned scriptc (0.4.7): +Standard-Schema-first CLI builder in the scriptc subset — the library owns +only the seam (argv tokenize → flag-vs-value → `validate` boundary → +dispatch/help/errors); all value semantics live in whatever schema the +consumer brings. Plain records + functions, no classes, zero deps. Design +source: `.agents/plans/2026-11-08-cli-schema-first.md` (supersedes the +`type`-field design in `.agents/plans/2026-11-07-cutils-cli.md`). Same +subset rules as the root AGENTS.md, plus what authoring this package +verified empirically under the pinned scriptc (0.4.7): ## Verified-OK constructs (probed by gate.ts at 100%) - **Generic functions over record literals**: `command>` lowers fully — the generic only feeds the +Record>` lowers fully — the generic only feeds the type-level `OptsFromOptions` mapped type; nothing generic survives into runtime values. -- **Function values inside records**: `CommandDef.handler` and - `StandardValidator.validate` members lower fine (the cache "function - members degrade instantiation" rule does not apply to this shape — - the records are produced/consumed inside one program, never class - fields). +- **Union-typed options entries**: `OptionInput = OptionSpec | +StandardSchemaInput | ValidateFn` — declared in the generic param only, + erased; runtime discriminates via `isSchemaValue` (`typeof === +"function"` or `~standard`/`validate` member present). +- **Function values inside records** AND a **bare function as an options + entry** (`mark: (v) => ({value: v})`): both lower — the records are + produced/consumed inside one program, never class fields. +- **Validator closures capturing builtin params**: `num({min,max})` / + `int({min,max})` close over `lo`/`hi` — ordinary closures lower. - **`Object.entries` + dynamic record WRITES**: every lookup walks `Object.entries()` with an indexed loop (`findLong`/`findShort`/ `valueOf`/command dispatch); `values[name] = v` writes are legal. @@ -25,8 +31,9 @@ Record>` lowers fully — the generic only feeds the - **`instanceof Promise`** narrows validator results; async validators are rejected with a clean error. - **`process.exit`** lowers (elf-app exits with `run`'s return code). -- **`Number.isNaN`, `Number()`, `String(unknown)`** all lower — the last - two land in the _dynamic tier_ (still static-compiled, runtime-checked). +- **`Number.isNaN`, `Number.isInteger`, `Number()`, `String(unknown)`** all + lower — the last two land in the _dynamic tier_ (still static-compiled, + runtime-checked). ## Rules specific to this package @@ -38,24 +45,27 @@ Record>` lowers fully — the generic only feeds the wrapper closure). If you touch `command()`'s return path, re-run `scriptc coverage gate.ts --explain-dynamic` — zero `dynamic slots` lines is the bar (dynamic TIER statements are expected and fine). -- **`OptionSpec.default` is `unknown`**, not `boolean | string | number`: - multi-type unions in record members are subset-fragile. `command()` - runtime-checks the default against `type` at construction (`E_BAD_OPTION`). -- **The schema seam is structural, not StandardSchemaV1**: the official - type's computed `"~standard"` key poisons `Object.entries` lowering. - `StandardValidator`/`StandardResult`/`StandardSchemaInput` are - hand-rolled structural twins — `schema` accepts a bare validator, the - `"~standard"` props, or a whole schema object (arktype `Type`, zod); - `normalizeSchema` prefers `"~standard".validate` and throws - `E_BAD_OPTION` when neither path exists. `OptsFromOptions` reads the - schema's `types.output` (Standard Schema's phantom channel) before - falling back to the primitive `type` — verified 2026-11-08: arktype - `type("'dev'|'prod'")` infers `opts.env: "dev" | "prod"` and validates - under scriptc Node islands end-to-end. +- **`opts` typing is `types.output` only** — there is no `type` field to + fall back to. Priority in `OptsFromOptions`: bare-schema entry → + `SchemaOutput`; `{schema: S}` → `SchemaOutput` (no `types` → + `unknown`); `{flag: true}` → `boolean`; else `string`. +- **`TypedValidator` is the typed-validator contract**: `types?: {input?, +output: O}` — `output` must be a REQUIRED member, matching the Standard + Schema spec; `SchemaOutput`'s `{output: infer O}` pattern never matches + an optional one (this burned once — `output?: O` silently gave `unknown`). +- **`default` goes through `validate()`** at `command()` time — issues → + `E_BAD_OPTION` with the schema's message; a morph output is stored. + Schema-less defaults get a cheap typeof check (flag→boolean, else→string). +- **Values are raw strings until a validator says otherwise**: the parser + stores the argv string (or `true`/attached for flags); the end-of-parse + pass runs `validateValue` per option and stores the OUTPUT — morphs + apply. `num()`/`int()` do `Number()` inside their `validate`. +- **Schema-less flag attached values** (`--flag=false`): `true`/`1`→true, + `false`/`0`→false, else error — done in the validation pass, not the + parse loop. - **`opts` keys are always present**: absent flag → `default` else the - type's zero value (`false`/`0`/`""`). Documented because it differs - from commander (`undefined`). "Was it passed" = sentinel default or - schema. + zero value (`false`/`""`). A schema that rejects `""` makes its option + effectively required — document via `default`. - **`run` never exits**: returns the code; `process.exit(run({...}))` is the consumer idiom. Keeps `node --test` tests in-process. - **`-h` yields to a declared `short: "h"`** — check `findShort` before @@ -65,7 +75,8 @@ Record>` lowers fully — the generic only feeds the ## Binary size (measured 2026-11-07, scriptc 0.4.7, darwin-arm64) -`scriptc build` default flags: +`scriptc build` default flags (pre-schema-first surface; re-measure if +quoting): | program | bytes | | -------------------------------------- | -------- | @@ -84,4 +95,4 @@ README until a bench cell exists. - `scriptc coverage gate.ts` must report `compile statically (100%)` (via `scripts/scriptc-gate.sh`) - `bash test/elf.test.sh` — builds `test/elf-app.ts`, runs the full matrix (flags, `--help`, ` --help`, `--version`, unknown command + - suggestion, missing arg, bad number, schema rejection) + suggestion, missing arg, bad value, schema rejection, builtin bounds) diff --git a/packages/cli/README.md b/packages/cli/README.md index ad073ac..1ff7981 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -1,9 +1,11 @@ # @cutils/cli -Type-first, declarative CLI builder authored inside the [scriptc](https://github.com/vercel-labs/scriptc) compilable subset — the command spec is a plain record literal, a mapped type carries the options into your handler, and `scriptc build` lowers the whole thing into the app's single static ELF. Zero dependencies; runs under Node unchanged. +Declarative CLI builder authored inside the [scriptc](https://github.com/vercel-labs/scriptc) compilable subset — the command spec is a plain record literal, and `scriptc build` lowers the whole thing into the app's single static ELF. Zero dependencies; runs under Node unchanged. + +The library owns exactly one thing — the **seam**: argv tokenize → flag-vs-value → effective value → the [Standard Schema](https://standardschema.dev) `validate` boundary → `{opts, args}` → dispatch, help, errors, exit code. Every value semantic — coercion, constraints, literal unions, morphs — belongs to the schema you bring (zod, arktype, valibot, or a hand-rolled `{validate}`). `opts` typing derives entirely from Standard Schema's `types.output` phantom channel; an option without a schema is a raw string, which is just the truth about argv. ```ts -import { command, run } from "@cutils/cli"; +import { bool, command, int, run, str } from "@cutils/cli"; process.exit( run({ @@ -13,13 +15,14 @@ process.exit( greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase output" }, - times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + upper: bool({ short: "u", description: "uppercase output" }), + times: int({ short: "t", default: 1, max: 10, description: "repeat n times" }), + greeting: str({ short: "g", description: "greeting word" }), }, handler: (opts, args) => { - // opts: { upper: boolean; times: number } — fully inferred + // opts: { upper: boolean; times: number; greeting: string } — fully inferred const who = opts.upper ? args[0].toUpperCase() : args[0]; - for (let i = 0; i < opts.times; i++) console.log(`hello ${who}`); + for (let i = 0; i < opts.times; i++) console.log(`${opts.greeting || "hello"} ${who}`); }, }), }, @@ -27,20 +30,24 @@ process.exit( ); ``` -- **The literal IS the schema.** Parse rules, `opts` types, `--help` tables, and error messages all come from the same `command()` spec — no runtime reflection (which scriptc cannot lower anyway). -- **`opts` is fully inferred.** The options literal flows through a mapped type: `{ type: "boolean" }` → `boolean`, `"number"` → `number`, `"string"` → `string`. Every declared key is always present. -- **Help, version, and errors are generated.** `--help`/`-h` at program and command level, `--version`, unknown-command suggestions, and labelled errors for missing arguments, unknown options, and bad values. -- **Standard Schema hook.** Any validator shaped like `schema["~standard"]` — or a whole schema object carrying one, like an arktype `Type` or a zod schema — can guard an option value or the whole `{ opts, args }` input. When the schema declares `types.output`, that type flows into `opts` (arktype literal unions infer as literal unions). Sync only — async validators are rejected with a clear error. +- **No `type` field.** `flag` is the only parse fact the library owns; everything else is schema. `opts` types come 100% from `types.output` — bring arktype/zod and literal unions, branded types, morphs all flow through. +- **Schemas everywhere or nowhere.** `schema` is optional per option and accepts four shapes: a bare `{validate}`, a `(v) => result` function, the `mySchema["~standard"]` props object, or a whole schema object (an arktype `Type`, a zod schema). A bare schema object also works _as_ the option entry itself. +- **Validated output is what `opts` gets.** Validators receive the raw argv string and return the parsed value — morphs apply to explicit values _and_ to `default`s, which are run through `validate()` at `command()` time. +- **Zero-dep primitives built in.** `str()`, `num()`, `int()`, `bool()` are tiny Standard-Schema-shaped validators with the `types` phantom declared — `num({min:0, max:99})` infers `opts.x: number` and validates, no library required. - **Exits by return code.** `run` prints and returns a number; it never calls `process.exit` itself, so it stays unit-testable under plain `node --test`. ## Surface ```ts declare function run(prog: ProgramSpec, argv?: string[]): number; -declare function command>( +declare function command>( description: string, spec: CommandSpec, ): CommandDef; +declare function str(extra?: BuiltinOpts): OptionSpec & { schema: TypedValidator }; +declare function num(extra?: NumOpts): OptionSpec & { schema: TypedValidator }; +declare function int(extra?: NumOpts): OptionSpec & { schema: TypedValidator }; +declare function bool(extra?: BuiltinOpts): OptionSpec & { flag: true; schema: TypedValidator }; ``` `run(prog)` reads `process.argv.slice(2)`; pass `argv` explicitly as a test seam or to embed a sub-CLI. @@ -55,34 +62,35 @@ interface ProgramSpec { interface CommandSpec { args?: string[]; // required positionals, in order - options?: O; // record of OptionSpec - schema?: StandardSchemaInput; // validates { opts, args } + options?: O; // record of OptionSpec | schema | function + schema?: SchemaInput; // validates { opts, args } handler: (opts: OptsFromOptions, args: string[]) => void; } interface OptionSpec { - type: "boolean" | "string" | "number"; + schema?: SchemaInput; // absent = raw string passthrough + flag?: boolean; // consumes no value: --x / --x=false / -x short?: string; // one character - default?: unknown; // must match `type`; checked in command() + default?: unknown; // run through validate() in command() description?: string; - schema?: StandardSchemaInput; // validates the parsed option value + metavar?: string; // help hint: --name ; defaults to the name } -// StandardSchemaInput accepts three shapes: a bare { validate(value) }, -// the "~standard" props object itself, or a whole schema object carrying -// "~standard" (arktype Type, zod schema). "~standard".validate wins when -// both paths exist; neither → E_BAD_OPTION at command() time. +// SchemaInput = StandardSchemaInput | ValidateFn — a bare validator, the +// "~standard" props object, a whole schema object, or a (v) => result fn. +// OptsFromOptions reads types.output: bare schema → declared output; +// { schema } → declared output (or unknown); { flag } → boolean; else → string. ``` ### Parsing rules | Input | Result | | ----------------------------- | --------------------------------------------- | -| `--upper` | boolean `true` | -| `--times 3`, `--times=3` | number `3`; non-numeric → error | -| `-u`, `-t 3`, `-t3`, `-ut3` | short flags; boolean shorts cluster | +| `--upper` | flag `true` | +| `--upper=false` / `=0` / `=1` | flag value through the validator → `false` | +| `--times 3`, `--times=3` | raw `"3"` → validator's output (e.g. `3`) | +| `-u`, `-t 3`, `-t3`, `-ut3` | short flags; flag shorts cluster | | `--greeting hi`, `-g hi` | string option | -| `--upper=false` / `=0` / `=1` | explicit boolean value | | `--` | end of options; rest are positionals | | `-h` | command help unless `h` is a declared `short` | @@ -90,25 +98,45 @@ Option values may appear anywhere before `--`. Declared positionals are all requ ### Defaults and `opts` presence -Every declared option key exists in `opts` with its declared type. When the flag is absent: the `default` if one was declared, else the type's zero value (`false`, `0`, `""`). There is no `undefined` member to check — use a sentinel `default` or a `schema` if "was it passed" matters. +Every declared option key exists in `opts`. When the flag is absent: the `default` if one was declared (already validated and morphed at `command()` time), else `false` for flags / `""` for value-options. A schema on a value-option therefore sees `""` for absent input — a schema that rejects `""` makes its option effectively required; declare a `default` to keep it optional. Schema-less options check `default` cheaply (flag → boolean, else → string). + +### Custom validators -### Standard Schema seam +The seam is one interface: -`schema` accepts three shapes: a bare `{ validate(value) }` returning `{ value }` or `{ issues: [{ message }] }`; the `mySchema["~standard"]` props object itself; or a whole schema object carrying `"~standard"` — pass `myArktype` or `myZodSchema` directly and the builder unwraps it. `"~standard".validate` wins when both paths exist; a schema with neither fails at `command()` time with `E_BAD_OPTION`. Option schemas receive the parsed option value; command schemas receive `{ opts, args }`. Results are synchronous — a `Promise` return is an error, not a wait. +```ts +interface CliValidator { // i.e. StandardValidator + validate(value: unknown): StandardResult | Promise; + types?: { input?: I; output?: O }; // phantom — never read at runtime +} +``` + +Declare `types.output` on a hand-rolled validator and `opts` picks it up — no library needed: + +```ts +const port: TypedValidator = { + validate: (v) => { + const n = Number(v); + return Number.isNaN(n) ? { issues: [{ message: `expected a number` }] } : { value: n }; + }, + types: { output: 0 }, +}; +options: { port: { schema: port } } // opts.port: number +``` -When the schema declares `types.output` (every Standard Schema library does — it is the spec's phantom type channel), `OptsFromOptions` uses it for `opts` instead of the primitive `type`: `type("'dev' | 'prod'")` gives `opts.env: "dev" | "prod"`. A schema output of `unknown` falls back to the `type`-derived primitive. +Async validators are rejected with a clear error — `Promise` results are never awaited. ## Divergences from commander | commander | @cutils/cli | Why | | ----------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------- | | `.option()` / `.argument()` chaining | one `command()` literal | declarative spec = the static schema; no mutation | -| `opts` untyped (`OptionValues`) | `opts` inferred from the literal via mapped type | the literal is the type | +| `opts` untyped (`OptionValues`) | `opts` inferred from schemas via `types.output` | the schema carries the type | | absent option is `undefined` | zero value or declared `default` | no `\| undefined` unions in the subset | | variadic args, `[optional]` positionals | required positionals only | v0 scope; variadic is a v1 item | | `process.exit` inside the framework | `run` returns the code; caller exits | testable under `node --test`, no hidden exits | | async/`.action()` promise handlers | sync handlers only | `void \| Promise` unions add dynamic slots | -| zod etc. via `.parse` wrappers | `schema:` Standard-Validator hook | async validators rejected; heavy schema libs stay | +| zod etc. via `.parse` wrappers | `schema:` Standard-Schema seam | async validators rejected; heavy schema libs stay | | | | Node-mode under scriptc's island limits | | automatic `-V` / help option registration | `-h`/`--help`/`--version` only, `-h` yields to `short: "h"` | small fixed set; user shorts win | | subcommand trees | flat command map | v2 item | diff --git a/packages/cli/gate.ts b/packages/cli/gate.ts index 18e70db..a2c63a3 100644 --- a/packages/cli/gate.ts +++ b/packages/cli/gate.ts @@ -3,15 +3,21 @@ // // Constructs this gate probes (each was suspect under older scriptc pins; // all must stay at 100% under the pinned release): -// - generic function command> with a -// mapped-type handler parameter (OptsFromOptions) -// - function values inside record literals (handler, schema.validate) +// - generic function command> with a +// mapped-type handler parameter (OptsFromOptions over schema outputs) +// - function values inside record literals (handler, schema.validate) and +// a bare-function options entry (ValidateFn union arm) +// - builtin factories num()/int()/bool()/str() — validator closures +// capturing bound params (min/max) +// - a bare whole-schema object as an options entry (isSchemaValue +// discrimination: "~standard" member present) // - Object.entries over Record/CommandDef for all // lookups (dynamic record reads are SC1090) // - instanceof Promise narrowing on a validator result -// - Number.isNaN, startsWith-free substring compares, process.argv slice +// - Number.isNaN, Number.isInteger, startsWith-free substring compares, +// process.argv slice, typeof checks on unknown values -import { command, run } from "./src/index.ts"; +import { bool, command, int, num, run, str } from "./src/index.ts"; import type { CommandDef, OptionSpec, @@ -19,18 +25,26 @@ import type { ProgramSpec, StandardResult, StandardValidator, + TypedValidator, ValidationIssue, } from "./src/index.ts"; -// A hand-rolled Standard-Schema-shaped sync validator. -const noBigTimes: StandardValidator = { +// A hand-rolled validator carrying the phantom types.output channel — +// morphs the raw argv string into a number. +const noBigTimes: TypedValidator = { validate: (value: unknown): StandardResult => { - if (typeof value === "number" && value > 10) { + const n = Number(value); + if (Number.isNaN(n)) { + const bad: ValidationIssue[] = [{ message: "not a number" }]; + return { issues: bad }; + } + if (n > 10) { const issues: ValidationIssue[] = [{ message: "times too large" }]; return { issues: issues }; } - return { value: value }; + return { value: n }; }, + types: { output: 0 }, }; const asyncValidator: StandardValidator = { @@ -39,8 +53,23 @@ const asyncValidator: StandardValidator = { }, }; +// A whole schema object in the "~standard" carrier shape — used as a bare +// options entry (no OptionSpec wrapper). +const onlyOk = { + "~standard": { + validate: (value: unknown): StandardResult => { + if (value === "ok") { + return { value: value }; + } + const issues: ValidationIssue[] = [{ message: "must be ok" }]; + return { issues: issues }; + }, + types: { input: "", output: "" as "ok" }, + }, +}; + // OptionSpec and ParsedInput are part of the public surface too. -const optSpec: OptionSpec = { type: "string", short: "x" }; +const optSpec: OptionSpec = { flag: true, short: "x" }; const parsed: ParsedInput = { opts: { x: "y" }, args: ["y"] }; const prog: ProgramSpec = { @@ -51,15 +80,14 @@ const prog: ProgramSpec = { greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase" }, - times: { - type: "number", - short: "t", - default: 1, - description: "repeat", - schema: noBigTimes, + upper: bool({ short: "u", description: "uppercase" }), + times: { short: "t", default: 1, description: "repeat", schema: noBigTimes }, + greeting: str({ short: "g", description: "greeting word" }), + count: num({ default: 0, min: 0, max: 99 }), + level: int({ default: 1, min: 1, max: 5 }), + mark: (value: unknown): StandardResult => { + return { value: String(value) + "!" }; }, - greeting: { type: "string", description: "greeting word" }, }, schema: { validate: (value: unknown): StandardResult => { @@ -67,11 +95,18 @@ const prog: ProgramSpec = { }, }, handler: (opts, args) => { - // opts is { upper: boolean; times: number; greeting: string } — - // the mapped type, proven by the typed uses below. + // opts is { upper: boolean; times: number; greeting: string; + // count: number; level: number; mode: "ok"; mark: unknown } — + // every member's type comes from its schema's types.output. const shout: boolean = opts.upper; const n: number = opts.times; const g: string = opts.greeting; + const c: number = opts.count; + const lv: number = opts.level; + const u: unknown = opts.mark; + void c; + void lv; + void u; let who = args[0]; if (shout) { who = who.toUpperCase(); @@ -81,6 +116,15 @@ const prog: ProgramSpec = { } }, }), + check: command("check a bare schema entry", { + options: { + mode: onlyOk, // bare whole-schema object — the option IS the schema + }, + handler: (opts, _args) => { + const m: "ok" = opts.mode; + console.log("mode " + m); + }, + }), add: command("add numbers", { args: ["a", "b"], handler: (_opts, args) => { @@ -102,15 +146,20 @@ code += run(prog, ["--help"]); code += run(prog, ["--version"]); code += run(prog, ["greet", "--help"]); code += run(prog, ["greet", "-u", "world"]); +code += run(prog, ["greet", "--upper=false", "world"]); code += run(prog, ["greet", "--times=2", "--greeting", "hi", "world"]); +code += run(prog, ["check", "--mode", "ok"]); // bare-schema entry, required +code += run(prog, ["check"]); // bare-schema absent → "must be ok" error +code += run(prog, ["check", "--mode", "no"]); // bare-schema rejection code += run(prog, ["greet", "--", "-strange"]); code += run(prog, ["add", "1.5", "2.5"]); code += run(prog, ["greet"]); // missing required argument code += run(prog, ["greet", "a", "b"]); // unexpected extra -code += run(prog, ["greet", "--times", "abc", "x"]); // bad number +code += run(prog, ["greet", "--times", "abc", "x"]); // bad number (validator) code += run(prog, ["greet", "--bogus", "x"]); // unknown option code += run(prog, ["gret", "x"]); // unknown command + suggestion code += run(prog, ["greet", "--times", "99", "x"]); // schema rejection +code += run(prog, ["greet", "--count", "200", "x"]); // builtin bound rejection code += run(prog, ["slow"]); // async validator rejection // The CommandDef record is public: callers may compose specs by hand. diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index ed45327..321725e 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,24 +1,26 @@ -// @cutils/cli — type-first, declarative CLI builder in the scriptc -// compilable subset. The command spec is a plain record literal; a mapped -// type carries the options literal into the handler's `opts` parameter, so -// parse + validate + help all come from one static schema — no runtime -// reflection anywhere (reflection has no static lowering). +// @cutils/cli — declarative CLI builder in the scriptc compilable subset. +// Single-responsibility: argv tokenize → flag-vs-value → effective value → +// the Standard Schema `validate` boundary → {opts, args} → dispatch. All +// value semantics (coercion, constraints, literal unions, morphs) belong to +// the schema — we transport raw argv strings, validators interpret them. +// `opts` typing derives entirely from Standard Schema's `types.output` +// phantom channel; no schema → the option is a string (the argv truth). // // Subset notes (see AGENTS.md for the full rulebook): // - No dynamic record READS (obj[key] is SC1090). All lookups walk // Object.entries() with indexed loops. Dynamic record WRITES (the // `values[name] = v` below) are fine. // - `| null` unions only; absent optional record members read as -// `undefined` and are tested with `=== undefined` (the cache pattern). +// `undefined` and are tested with `=== undefined`. // - No classes, no `?.`/`??`, no spread, no shorthand methods. // - The handler crosses a dispatch boundary typed // `(opts: unknown, args: string[]) => void`; the precise `opts` shape // lives only in the user-facing command() generic. // - The Standard Schema seam accepts a bare validator, the "~standard" -// props object, or a whole schema object (arktype Type, zod schema); -// command() unwraps to the callable validator. OptsFromOptions reads -// the schema's declared `types.output` so schema libraries drive `opts` -// inference through the spec's own type channel. +// props object, a whole schema object (arktype Type, zod schema), or a +// bare `(v) => result` function; command() unwraps to the callable +// validator. OptsFromOptions reads `types.output` so schema libraries +// drive `opts` inference through the spec's own type channel. // ---------------------------------------------------------------- public types @@ -32,40 +34,77 @@ export interface StandardResult { issues?: readonly ValidationIssue[] | null; } +// A bare validator object — the shape hand-rolled and foreign validators +// share. `types` is Standard Schema's phantom input/output channel: it is +// never read at runtime, but OptsFromOptions maps `output` into `opts`, so +// declaring it on a custom validator types the option with zero machinery. export interface StandardValidator { validate(value: unknown): StandardResult | Promise; + types?: { input?: unknown; output?: unknown }; } // The props object at schema["~standard"] — what Standard Schema consumers -// call. `types` is the spec's phantom in/out channel: libraries like arktype -// and zod populate it, and OptsFromOptions reads `output` back out so the -// schema's declared type flows into the handler's `opts`. +// call. export interface StandardValidatorProps { validate(value: unknown): StandardResult | Promise; types?: { input?: unknown; output?: unknown }; } +// A bare `(v) => result` function — the minimal validation boundary. It has +// no type channel, so the option's `opts` member is `unknown`. +export type ValidateFn = (value: unknown) => StandardResult | Promise; + // What OptionSpec.schema / CommandSpec.schema accept: a bare validator, the -// "~standard" props object, or a whole schema object carrying one (an -// arktype Type, a zod schema). All members optional so every shape fits; -// command() throws E_BAD_OPTION when neither validate path exists. +// "~standard" props object, a whole schema object carrying one (an arktype +// Type, a zod schema), or a bare function. All members optional so every +// object shape fits; command() throws E_BAD_OPTION when no validate path +// exists. export interface StandardSchemaInput { validate?(value: unknown): StandardResult | Promise; "~standard"?: StandardValidatorProps; types?: { input?: unknown; output?: unknown }; } -export type OptionType = "boolean" | "string" | "number"; +export type SchemaInput = StandardSchemaInput | ValidateFn; -// User-facing per-option spec. `default` is `unknown` at the type level -// (multi-type unions in record members are subset-fragile); command() -// checks at construction that a provided default matches `type`. +// User-facing per-option spec. There is no `type` field: flag-vs-value is +// the only parse fact the library needs (`flag`), and everything else — +// coercion, constraints, the `opts` type — comes from the schema. export interface OptionSpec { - type: OptionType; + schema?: SchemaInput; // absent = raw string passthrough (the argv truth) + flag?: boolean; // true = consumes no value; --x / --x=false / -x short?: string; // single character; "" / omitted = no short flag - default?: unknown; // must match `type`; checked in command() + default?: unknown; // the value opts receives when absent; run through validate() in command() description?: string; - schema?: StandardSchemaInput; // validates the parsed option value + metavar?: string; // help hint shown as `--name `; defaults to the option name +} + +// One options-record member: a spec, a whole schema object, or a bare +// validate function. command() discriminates: "~standard" or "validate" +// present (or the entry is a function) → schema; otherwise OptionSpec. +export type OptionInput = OptionSpec | StandardSchemaInput | ValidateFn; + +// A validator whose declared output type is visible to OptsFromOptions — +// the shape the builtins return. `types` stays phantom; only the declared +// type is annotated, no runtime `types` member is emitted. `output` is a +// REQUIRED member of the phantom (matching the Standard Schema spec) — +// SchemaOutput's `{output: infer O}` pattern never matches an optional one. +export interface TypedValidator { + validate(value: unknown): StandardResult; + types?: { input?: unknown; output: O }; +} + +// Shared extras every builtin factory accepts and merges. +export interface BuiltinOpts { + short?: string; + default?: unknown; + description?: string; + metavar?: string; +} + +export interface NumOpts extends BuiltinOpts { + min?: number; // inclusive lower bound + max?: number; // inclusive upper bound } // Sentinel for "the schema declares no output type" — an object shape no @@ -76,8 +115,7 @@ export interface NoSchemaOutput { // The output type a schema declares through Standard Schema's `types` // channel. Checks the whole-schema form first ("~standard".types.output), -// then the props form (types.output directly — what schema["~standard"] -// carries), then gives up. +// then the props/bare-validator form (types.output directly), then gives up. export type SchemaOutput = S extends { "~standard": { types?: infer T } } ? NonNullable extends { output: infer O } ? O @@ -88,46 +126,52 @@ export type SchemaOutput = S extends { "~standard": { types?: infer T } } : NoSchemaOutput : NoSchemaOutput; -type PrimOption = O extends { type: "boolean" } - ? boolean - : O extends { type: "number" } - ? number - : string; - -// Mapped type: the options literal drives the handler's `opts` shape. A -// schema that declares `types.output` wins (arktype literal unions come -// through here); otherwise the primitive `type` decides. Every declared -// key is present at runtime — boolean defaults to false, number to 0, -// string to "" — so `opts` members are never optional. -export type OptsFromOptions = { - [K in keyof O]: O[K] extends { schema?: infer S } - ? [NonNullable] extends [never] - ? PrimOption - : SchemaOutput> extends infer T - ? [T] extends [NoSchemaOutput] - ? PrimOption - : [unknown] extends [T] - ? PrimOption - : T - : PrimOption - : PrimOption; +type FlagOrString = O extends { flag: true } ? boolean : string; + +// Mapped type: the options literal drives the handler's `opts` shape, and +// the Standard Schema `types.output` channel is the ONLY type source: +// bare schema entry → its declared output +// { schema: S } → S's declared output; no output → unknown +// { flag: true } (bare) → boolean +// everything else → string — absent a schema, argv IS strings +// Every declared key is present at runtime — absent options take the +// default, else flag → false, else "" — so members are never optional. +export type OptsFromOptions> = { + [K in keyof O]: O[K] extends { "~standard": unknown } + ? SchemaOutput + : O[K] extends { validate: unknown } + ? SchemaOutput + : O[K] extends ValidateFn + ? unknown + : O[K] extends { schema?: infer S } + ? [NonNullable] extends [never] + ? FlagOrString + : SchemaOutput> extends infer T + ? [T] extends [NoSchemaOutput] + ? unknown + : [unknown] extends [T] + ? unknown + : T + : unknown + : FlagOrString; }; -export interface CommandSpec> { +export interface CommandSpec> { args?: string[]; // required positional argument names, in order options?: O; - schema?: StandardSchemaInput; // validates { opts, args } before the handler + schema?: SchemaInput; // validates { opts, args } before the handler handler: (opts: OptsFromOptions, args: string[]) => void; } // Normalized internal option shape: concrete fields, no optional members, // so the parse loop never branches on member presence. export interface OptionDef { - type: string; // "boolean" | "string" | "number" + flag: boolean; // consumes no value short: string; // "" = none hasDefault: boolean; defaultValue: unknown; description: string; // "" = none + metavar: string; // "" = fall back to the option name in help schema: StandardValidator | null; } @@ -152,39 +196,202 @@ export interface ParsedInput { args: string[]; } +// ---------------------------------------------------------------- builtins + +// Zero-dependency primitives as Standard-Schema-shaped validators. Each +// factory returns an OptionSpec carrying a TypedValidator, so `opts` +// inference works without any schema library installed. Extra OptionSpec +// fields in `extra` (and metavar overrides) merge over the defaults. + +export function str(extra?: BuiltinOpts): OptionSpec & { schema: TypedValidator } { + const v: TypedValidator = { + validate: (value: unknown): StandardResult => { + if (typeof value === "string") { + return { value: value }; + } + return { issues: [{ message: "expected a string" }] }; + }, + }; + const spec: OptionSpec = { schema: v, metavar: "str" }; + return mergeExtra(spec, extra) as OptionSpec & { schema: TypedValidator }; +} + +export function num(extra?: NumOpts): OptionSpec & { schema: TypedValidator } { + const lo = extra !== undefined && extra.min !== undefined ? extra.min : null; + const hi = extra !== undefined && extra.max !== undefined ? extra.max : null; + const v: TypedValidator = { + validate: (value: unknown): StandardResult => { + const n = typeof value === "number" ? value : Number(value); + if (Number.isNaN(n)) { + return { issues: [{ message: "expected a number, got '" + String(value) + "'" }] }; + } + if (lo !== null && n < lo) { + return { + issues: [{ message: "expected a number >= " + String(lo) + ", got " + String(n) }], + }; + } + if (hi !== null && n > hi) { + return { + issues: [{ message: "expected a number <= " + String(hi) + ", got " + String(n) }], + }; + } + return { value: n }; + }, + }; + const spec: OptionSpec = { schema: v, metavar: "n" }; + return mergeExtra(spec, extra) as OptionSpec & { schema: TypedValidator }; +} + +export function int(extra?: NumOpts): OptionSpec & { schema: TypedValidator } { + const lo = extra !== undefined && extra.min !== undefined ? extra.min : null; + const hi = extra !== undefined && extra.max !== undefined ? extra.max : null; + const v: TypedValidator = { + validate: (value: unknown): StandardResult => { + const n = typeof value === "number" ? value : Number(value); + if (Number.isNaN(n)) { + return { issues: [{ message: "expected a number, got '" + String(value) + "'" }] }; + } + if (!Number.isInteger(n)) { + return { issues: [{ message: "expected an integer, got " + String(n) }] }; + } + if (lo !== null && n < lo) { + return { + issues: [{ message: "expected an integer >= " + String(lo) + ", got " + String(n) }], + }; + } + if (hi !== null && n > hi) { + return { + issues: [{ message: "expected an integer <= " + String(hi) + ", got " + String(n) }], + }; + } + return { value: n }; + }, + }; + const spec: OptionSpec = { schema: v, metavar: "int" }; + return mergeExtra(spec, extra) as OptionSpec & { schema: TypedValidator }; +} + +export function bool( + extra?: BuiltinOpts, +): OptionSpec & { flag: true; schema: TypedValidator } { + const v: TypedValidator = { + validate: (value: unknown): StandardResult => { + if (value === true || value === "true" || value === "1") { + return { value: true }; + } + if (value === false || value === "false" || value === "0") { + return { value: false }; + } + return { issues: [{ message: "expected a boolean, got '" + String(value) + "'" }] }; + }, + }; + const spec: OptionSpec = { flag: true, schema: v }; + return mergeExtra(spec, extra) as OptionSpec & { flag: true; schema: TypedValidator }; +} + +function mergeExtra(spec: OptionSpec, extra?: BuiltinOpts): OptionSpec { + const out: OptionSpec = {}; + if (spec.schema !== undefined) { + out.schema = spec.schema; + } + if (spec.flag !== undefined) { + out.flag = spec.flag; + } + if (spec.metavar !== undefined) { + out.metavar = spec.metavar; + } + if (extra === undefined) { + return out; + } + if (extra.short !== undefined) { + out.short = extra.short; + } + if (extra.default !== undefined) { + out.default = extra.default; + } + if (extra.description !== undefined) { + out.description = extra.description; + } + if (extra.metavar !== undefined) { + out.metavar = extra.metavar; + } + return out; +} + // ---------------------------------------------------------------- command() -export function command>( +export function command>( description: string, spec: CommandSpec, ): CommandDef { const options: Record = {}; - const specOpts: Record = - spec.options === undefined ? {} : (spec.options as Record); + const specOpts: Record = + spec.options === undefined ? {} : (spec.options as Record); const entries = Object.entries(specOpts); for (let i = 0; i < entries.length; i++) { const name = entries[i][0]; - const s = entries[i][1]; - const hasDefault = s.default !== undefined; + const raw = entries[i][1]; + // Discriminate: a "~standard" or "validate" member (or a bare function) + // means the entry IS a schema; otherwise it is an OptionSpec literal. + let flag = false; + let short = ""; + let desc = ""; + let metavar = ""; + let hasDefault = false; + let defaultValue: unknown = ""; + let schemaInput: SchemaInput | undefined; + if (isSchemaValue(raw)) { + schemaInput = raw as SchemaInput; + } else { + const sp = raw as OptionSpec; + flag = sp.flag === true; + short = sp.short === undefined ? "" : sp.short; + desc = sp.description === undefined ? "" : sp.description; + metavar = sp.metavar === undefined ? "" : sp.metavar; + if (sp.schema !== undefined) { + schemaInput = sp.schema; + } + if (sp.default !== undefined) { + hasDefault = true; + defaultValue = sp.default; + } + } const def: OptionDef = { - type: s.type, - short: s.short === undefined ? "" : s.short, + flag: flag, + short: short, hasDefault: hasDefault, - defaultValue: hasDefault ? s.default : "", - description: s.description === undefined ? "" : s.description, - schema: normalizeSchema(s.schema, "--" + name), + defaultValue: defaultValue, + description: desc, + metavar: metavar, + schema: normalizeSchema(schemaInput, "--" + name), }; if (def.short.length > 1) { throw new Error("E_BAD_OPTION: --" + name + " short must be a single character"); } if (def.hasDefault) { - const dv = def.defaultValue; - const ok = - (def.type === "boolean" && typeof dv === "boolean") || - (def.type === "string" && typeof dv === "string") || - (def.type === "number" && typeof dv === "number"); - if (!ok) { - throw new Error("E_BAD_OPTION: default for --" + name + " does not match type " + def.type); + // The default goes through the schema: issues → E_BAD_OPTION with the + // validator's own message; a morph output becomes the stored default. + if (def.schema !== null) { + const oc = validateValue(def.schema, def.defaultValue, "--" + name); + if (oc.error !== "") { + throw new Error("E_BAD_OPTION: " + oc.error); + } + if (oc.hasOut) { + def.defaultValue = oc.out; + } + } else { + const ok = def.flag + ? typeof def.defaultValue === "boolean" + : typeof def.defaultValue === "string"; + if (!ok) { + throw new Error( + "E_BAD_OPTION: default for --" + + name + + (def.flag + ? " must be a boolean" + : " must be a string (declare a schema for other types)"), + ); + } } } options[name] = def; @@ -202,18 +409,30 @@ export function command>( }; } -// Unwrap a StandardSchemaInput to the callable validator: prefer the -// "~standard" props (the spec's consumption path — an arktype Type or zod -// schema carries no top-level validate), fall back to a bare validator. -// Throws at construction when neither exists so a schema-less "schema" -// can never silently pass. -function normalizeSchema( - input: StandardSchemaInput | undefined, - label: string, -): StandardValidator | null { +// An options entry is a schema when it carries "~standard" or "validate", +// or when it is a bare function. OptionSpec never has those members, so the +// discriminator cannot collide (a zod schema's `.description` is never +// reached — "~standard" wins). +function isSchemaValue(v: unknown): boolean { + if (typeof v === "function") { + return true; + } + const s = v as StandardSchemaInput; + return s["~standard"] !== undefined || s.validate !== undefined; +} + +// Unwrap a SchemaInput to the callable validator: a bare function first, +// then the "~standard" props (the spec's consumption path — an arktype Type +// or zod schema carries no top-level validate), then a bare validator. +// Throws at construction when no validate path exists so a schema-less +// "schema" can never silently pass. +function normalizeSchema(input: SchemaInput | undefined, label: string): StandardValidator | null { if (input === undefined) { return null; } + if (typeof input === "function") { + return { validate: input }; + } const std = input["~standard"]; if (std !== undefined && std.validate !== undefined) { return std; @@ -283,16 +502,15 @@ function fail(msg: string): number { function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: string[]): number { const optionEntries = Object.entries(cmd.options); const values: Record = {}; - // Seed every declared key: explicit default, else the type's zero value. + // Seed every declared key: validated default, else the zero value — + // false for flags, "" for value-options (a schema may then coerce it). for (let i = 0; i < optionEntries.length; i++) { const name = optionEntries[i][0]; const def = optionEntries[i][1]; if (def.hasDefault) { values[name] = def.defaultValue; - } else if (def.type === "boolean") { + } else if (def.flag) { values[name] = false; - } else if (def.type === "number") { - values[name] = 0; } else { values[name] = ""; } @@ -318,7 +536,8 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s return 0; } if (tok.length > 2 && tok.substring(0, 2) === "--") { - // --name or --name=value + // --name or --name=value. Attached values stay strings — the + // validator owns interpretation, including "false"/"0" on flags. let body = tok.substring(2); let attached = ""; let hasAttached = false; @@ -333,15 +552,11 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s return fail("unknown option '--" + body + "'"); } const def = optionEntries[k][1]; - if (def.type === "boolean") { + if (def.flag) { if (!hasAttached) { values[body] = true; - } else if (attached === "true" || attached === "1") { - values[body] = true; - } else if (attached === "false" || attached === "0") { - values[body] = false; } else { - return fail("--" + body + ": expected a boolean, got '" + attached + "'"); + values[body] = attached; } } else { let raw = ""; @@ -354,17 +569,14 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s i = i + 1; raw = args[i]; } - const err = setValue(values, def, body, raw, "--" + body); - if (err !== "") { - return fail(err); - } + values[body] = raw; } i = i + 1; continue; } if (tok.length > 1 && tok.charAt(0) === "-") { - // Short cluster: -u, -t 3, -t3, -ut3 (boolean shorts may cluster; - // a value-taking short consumes the rest of the token or next arg). + // Short cluster: -u, -t 3, -t3, -ut3 (flag shorts may cluster; a + // value-taking short consumes the rest of the token or next arg). let j = 1; while (j < tok.length) { const c = tok.charAt(j); @@ -378,7 +590,7 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s } const name = optionEntries[k][0]; const def = optionEntries[k][1]; - if (def.type === "boolean") { + if (def.flag) { values[name] = true; j = j + 1; continue; @@ -396,10 +608,7 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s i = i + 1; raw = args[i]; } - const err = setValue(values, def, name, raw, "-" + c); - if (err !== "") { - return fail(err); - } + values[name] = raw; j = tok.length; } i = i + 1; @@ -417,24 +626,37 @@ function runCommand(prog: ProgramSpec, cmdName: string, cmd: CommandDef, args: s return fail("unexpected argument '" + positionals[required] + "'"); } - // Standard-Schema seam: per-option validators, then the command-level - // validator over { opts, args }. Async validators are rejected cleanly — - // instanceof Promise narrowing lowers fine. + // The schema boundary: every option's effective value (explicit, default, + // or zero) passes its validator and the OUTPUT is stored — morphs apply. + // Schema-less flags coerce "true"/"1"/"false"/"0" attached forms here. + // Async validators are rejected cleanly — instanceof Promise lowers fine. for (let e = 0; e < optionEntries.length; e++) { const name = optionEntries[e][0]; const def = optionEntries[e][1]; + const v = valueOf(values, name); if (def.schema !== null) { - const err = runValidator(def.schema, valueOf(values, name), "--" + name); - if (err !== "") { - return fail(err); + const oc = validateValue(def.schema, v, "--" + name); + if (oc.error !== "") { + return fail(oc.error); + } + if (oc.hasOut) { + values[name] = oc.out; + } + } else if (def.flag && typeof v === "string") { + if (v === "true" || v === "1") { + values[name] = true; + } else if (v === "false" || v === "0") { + values[name] = false; + } else { + return fail("--" + name + ": expected a boolean, got '" + v + "'"); } } } if (cmd.schema !== null) { const input: ParsedInput = { opts: values, args: positionals }; - const err = runValidator(cmd.schema, input, cmdName); - if (err !== "") { - return fail(err); + const oc = validateValue(cmd.schema, input, cmdName); + if (oc.error !== "") { + return fail(oc.error); } } @@ -471,42 +693,39 @@ function findShort(entries: [string, OptionDef][], c: string): number { return -1; } -function setValue( - values: Record, - def: OptionDef, - name: string, - raw: string, - label: string, -): string { - if (def.type === "number") { - const n = Number(raw); - if (raw === "" || Number.isNaN(n)) { - return label + ": expected a number, got '" + raw + "'"; - } - values[name] = n; - return ""; - } - if (def.type === "string") { - values[name] = raw; - return ""; - } - return label + ": boolean option '" + name + "' takes no value"; +interface ValidateOutcome { + error: string; // "" = success + hasOut: boolean; // the validator returned a (possibly morphed) value + out: unknown; } -function runValidator(v: StandardValidator, value: unknown, label: string): string { +// Run one validator and normalize the result: issues join into one error +// string (validator-owned messages), a success `value` becomes `out` so +// callers can store morphed output. A Promise result is a clean error. +function validateValue(v: StandardValidator, value: unknown, label: string): ValidateOutcome { const r = v.validate(value); if (r instanceof Promise) { - return label + ": async validators are not supported (schema returned a Promise)"; + return { + error: label + ": async validators are not supported (schema returned a Promise)", + hasOut: false, + out: null, + }; } const issues = r.issues; - if (issues === undefined || issues === null || issues.length === 0) { - return ""; + if (issues !== undefined && issues !== null && issues.length > 0) { + let msg = label + ": "; + for (let i = 0; i < issues.length; i++) { + if (i > 0) { + msg = msg + "; "; + } + msg = msg + (issues[i].message === "" ? "validation failed" : issues[i].message); + } + return { error: msg, hasOut: false, out: null }; } - let msg = label + ": validation failed"; - for (let i = 0; i < issues.length; i++) { - msg = msg + "; " + issues[i].message; + if (r.value !== undefined) { + return { error: "", hasOut: true, out: r.value }; } - return msg; + return { error: "", hasOut: false, out: null }; } // ---------------------------------------------------------------- help @@ -583,10 +802,8 @@ function printCommandHelp(prog: ProgramSpec, cmdName: string, cmd: CommandDef): } else { label = " --" + name; } - if (def.type === "number") { - label = label + " "; - } else if (def.type === "string") { - label = label + " "; + if (!def.flag) { + label = label + " <" + (def.metavar !== "" ? def.metavar : name) + ">"; } let desc = def.description; if (def.hasDefault) { diff --git a/packages/cli/test/elf-app.ts b/packages/cli/test/elf-app.ts index eb1b493..c08e96a 100644 --- a/packages/cli/test/elf-app.ts +++ b/packages/cli/test/elf-app.ts @@ -1,9 +1,10 @@ // ELF smoke app for @cutils/cli — compiled with `scriptc build` by -// test/elf.test.sh. A two-command demo CLI: `greet` exercises boolean/ -// number/string options + short flags + a schema; `add` exercises two -// positionals. test/elf.test.sh drives the full validation matrix. +// test/elf.test.sh. A two-command demo CLI: `greet` exercises the bool/ +// num/str builtins (flag, bounded number, raw string) + short flags; +// `add` exercises two positionals. test/elf.test.sh drives the full +// validation matrix. -import { command, run } from "../src/index.ts"; +import { bool, command, int, run, str } from "../src/index.ts"; const prog = { name: "demo", @@ -13,22 +14,9 @@ const prog = { greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase output" }, - times: { - type: "number", - short: "t", - default: 1, - description: "repeat n times", - schema: { - validate: (value: unknown) => { - if (typeof value === "number" && value > 10) { - return { issues: [{ message: "times must be <= 10" }] }; - } - return { value: value }; - }, - }, - }, - greeting: { type: "string", short: "g", description: "greeting word" }, + upper: bool({ short: "u", description: "uppercase output" }), + times: int({ short: "t", default: 1, max: 10, description: "repeat n times" }), + greeting: str({ short: "g", description: "greeting word" }), }, handler: (opts, args) => { let who = args[0]; diff --git a/packages/cli/test/elf.test.sh b/packages/cli/test/elf.test.sh index fb6a79d..71f5c65 100755 --- a/packages/cli/test/elf.test.sh +++ b/packages/cli/test/elf.test.sh @@ -70,6 +70,6 @@ expect_err 1 "expected a number, got 'abc'" greet --times abc x expect_err 1 "unknown option '--bogus'" greet --bogus x expect_err 1 "did you mean 'greet'?" gret x expect_err 1 "unexpected argument" greet a b -expect_err 1 "times must be <= 10" greet --times 99 x +expect_err 1 "expected an integer <= 10, got 99" greet --times 99 x echo "elf-cli-smoke OK" diff --git a/packages/cli/test/errors.test.js b/packages/cli/test/errors.test.js index 96fbef9..0c8b3d7 100644 --- a/packages/cli/test/errors.test.js +++ b/packages/cli/test/errors.test.js @@ -2,7 +2,7 @@ // stderr + exit code 1; nothing throws. import { test } from "node:test"; import assert from "node:assert/strict"; -import { command, run } from "../dist/esm/index.js"; +import { bool, command, num, run } from "../dist/esm/index.js"; import { capture } from "./helpers.js"; function prog() { @@ -13,8 +13,8 @@ function prog() { greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u" }, - times: { type: "number", short: "t", default: 1 }, + upper: bool({ short: "u" }), + times: num({ short: "t", default: 1 }), }, handler: () => {}, }), diff --git a/packages/cli/test/help.test.js b/packages/cli/test/help.test.js index 62c8db7..9fac24d 100644 --- a/packages/cli/test/help.test.js +++ b/packages/cli/test/help.test.js @@ -1,7 +1,7 @@ // Help and version output tests for @cutils/cli. import { test } from "node:test"; import assert from "node:assert/strict"; -import { command, run } from "../dist/esm/index.js"; +import { bool, command, num, run, str } from "../dist/esm/index.js"; import { capture } from "./helpers.js"; function prog() { @@ -13,8 +13,8 @@ function prog() { greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase output" }, - times: { type: "number", short: "t", default: 1, description: "repeat n times" }, + upper: bool({ short: "u", description: "uppercase output" }), + times: num({ short: "t", default: 1, description: "repeat n times" }), }, handler: () => {}, }), @@ -85,7 +85,7 @@ test("-h resolves to a user-declared short option first", () => { name: "demo", commands: { c: command("c", { - options: { host: { type: "string", short: "h" } }, + options: { host: str({ short: "h" }) }, handler: (opts) => { seen = opts; }, diff --git a/packages/cli/test/parse.test.js b/packages/cli/test/parse.test.js index 65b1a94..560afea 100644 --- a/packages/cli/test/parse.test.js +++ b/packages/cli/test/parse.test.js @@ -1,7 +1,7 @@ // Option/positional parsing tests for @cutils/cli — runs on the tsc build. import { test } from "node:test"; import assert from "node:assert/strict"; -import { command, run } from "../dist/esm/index.js"; +import { bool, command, num, run, str } from "../dist/esm/index.js"; import { capture } from "./helpers.js"; function prog(handler) { @@ -12,9 +12,9 @@ function prog(handler) { greet: command("greet someone", { args: ["name"], options: { - upper: { type: "boolean", short: "u", description: "uppercase" }, - times: { type: "number", short: "t", default: 1, description: "repeat" }, - greeting: { type: "string", short: "g", description: "greeting word" }, + upper: bool({ short: "u", description: "uppercase" }), + times: num({ short: "t", default: 1, description: "repeat" }), + greeting: str({ short: "g", description: "greeting word" }), }, handler, }), @@ -52,6 +52,42 @@ test("--opt value and --opt=value", () => { assert.equal(got[1].times, 4); }); +test("schema output replaces the raw string (morph)", () => { + let seen; + const p = { + name: "d", + commands: { + c: command("c", { + options: { count: num() }, + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "--count", "007"])); + assert.equal(r.code, 0); + assert.equal(seen.count, 7); // "007" → 7 — the validator's output, not the raw string +}); + +test("schema-less option is a raw string passthrough", () => { + let seen; + const p = { + name: "d", + commands: { + c: command("c", { + options: { note: { description: "free text" } }, + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "--note", "007"])); + assert.equal(r.code, 0); + assert.equal(seen.note, "007"); // no schema → no coercion +}); + test("string option long and short forms", () => { const got = []; const p = prog((opts) => got.push(opts)); @@ -89,6 +125,30 @@ test("--flag=false parses boolean attached values", () => { assert.equal(got[2].upper, false); }); +test("schema-less flag coerces attached true/false/1/0, rejects the rest", () => { + const got = []; + const p = { + name: "d", + commands: { + c: command("c", { + options: { loud: { flag: true } }, + handler: (opts) => got.push(opts), + }), + }, + }; + capture(() => run(p, ["c", "--loud"])); + capture(() => run(p, ["c", "--loud=false"])); + capture(() => run(p, ["c", "--loud=0"])); + capture(() => run(p, ["c"])); + assert.equal(got[0].loud, true); + assert.equal(got[1].loud, false); + assert.equal(got[2].loud, false); + assert.equal(got[3].loud, false); + const bad = capture(() => run(p, ["c", "--loud=maybe"])); + assert.equal(bad.code, 1); + assert.match(bad.err.join("\n"), /expected a boolean, got 'maybe'/); +}); + test("-- ends option parsing; later tokens are positional", () => { let seen; const p = prog((opts, args) => { diff --git a/packages/cli/test/schema.test.js b/packages/cli/test/schema.test.js index 13bb82a..b37fa37 100644 --- a/packages/cli/test/schema.test.js +++ b/packages/cli/test/schema.test.js @@ -1,28 +1,34 @@ // Standard-Schema seam tests: bare validators, "~standard" props objects, -// and whole schema objects (the arktype Type / zod shape) all run before -// the handler; sync failures become errors, async validators are rejected -// cleanly, and a schema with no validate path fails at construction. +// whole schema objects (the arktype Type / zod shape), and bare functions +// all run before the handler; validators receive the RAW argv string and +// their output is what lands in `opts`; sync failures become errors, async +// validators are rejected cleanly, and a schema with no validate path +// fails at construction. import { test } from "node:test"; import assert from "node:assert/strict"; -import { command, run } from "../dist/esm/index.js"; +import { command, num, run } from "../dist/esm/index.js"; import { capture } from "./helpers.js"; const range = (max) => ({ validate: (value) => { - if (typeof value === "number" && value > max) { + const n = Number(value); + if (Number.isNaN(n)) { + return { issues: [{ message: `expected a number, got '${value}'` }] }; + } + if (n > max) { return { issues: [{ message: `must be <= ${max}` }] }; } - return { value }; + return { value: n }; }, }); -test("option schema passes valid values through", () => { +test("option schema receives the raw string and its output lands in opts", () => { let seen; const p = { name: "d", commands: { c: command("c", { - options: { times: { type: "number", schema: range(10) } }, + options: { times: { schema: range(10) } }, handler: (opts) => { seen = opts; }, @@ -31,7 +37,7 @@ test("option schema passes valid values through", () => { }; const r = capture(() => run(p, ["c", "--times", "5"])); assert.equal(r.code, 0); - assert.equal(seen.times, 5); + assert.equal(seen.times, 5); // morphed: the number, not the string "5" }); test("option schema rejects with its issue messages", () => { @@ -39,14 +45,55 @@ test("option schema rejects with its issue messages", () => { name: "d", commands: { c: command("c", { - options: { times: { type: "number", schema: range(10) } }, + options: { times: { schema: range(10) } }, handler: () => assert.fail("handler must not run"), }), }, }; const r = capture(() => run(p, ["c", "--times", "99"])); assert.equal(r.code, 1); - assert.match(r.err.join("\n"), /--times: validation failed; must be <= 10/); + assert.match(r.err.join("\n"), /--times: must be <= 10/); +}); + +test("a bare validate function is a schema entry too", () => { + let seen; + const p = { + name: "d", + commands: { + c: command("c", { + options: { + shout: (value) => ({ value: String(value).toUpperCase() }), + }, + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c", "--shout", "hi"])); + assert.equal(r.code, 0); + assert.equal(seen.shout, "HI"); +}); + +test("a bare schema object works as the whole option entry", () => { + const whole = { + "~standard": { + validate: (value) => (value === "ok" ? { value } : { issues: [{ message: "must be ok" }] }), + }, + }; + const p = { + name: "d", + commands: { + c: command("c", { + options: { mode: whole }, + handler: () => {}, + }), + }, + }; + assert.equal(capture(() => run(p, ["c", "--mode", "ok"])).code, 0); + const bad = capture(() => run(p, ["c", "--mode", "no"])); + assert.equal(bad.code, 1); + assert.match(bad.err.join("\n"), /--mode: must be ok/); }); test("command schema receives { opts, args } and runs before the handler", () => { @@ -56,7 +103,7 @@ test("command schema receives { opts, args } and runs before the handler", () => commands: { c: command("c", { args: ["name"], - options: { upper: { type: "boolean", short: "u" } }, + options: { upper: { flag: true, short: "u" } }, schema: { validate: (value) => { input = value; @@ -95,7 +142,26 @@ test("command schema rejection stops the handler", () => { }; const r = capture(() => run(p, ["c", "root"])); assert.equal(r.code, 1); - assert.match(r.err.join("\n"), /c: validation failed; cannot greet root/); + assert.match(r.err.join("\n"), /c: cannot greet root/); +}); + +test("command schema also accepts a bare function", () => { + let input; + const p = { + name: "d", + commands: { + c: command("c", { + schema: (value) => { + input = value; + return { value }; + }, + handler: () => {}, + }), + }, + }; + const r = capture(() => run(p, ["c"])); + assert.equal(r.code, 0); + assert.deepEqual(input.opts, {}); }); test("async option validator is rejected cleanly", () => { @@ -105,7 +171,6 @@ test("async option validator is rejected cleanly", () => { c: command("c", { options: { times: { - type: "number", schema: { validate: (v) => Promise.resolve({ value: v }) }, }, }, @@ -130,7 +195,7 @@ test("a real Standard-Schema-shaped validator object fits the interface", () => name: "d", commands: { c: command("c", { - options: { greeting: { type: "string", schema: std } }, + options: { greeting: { schema: std } }, handler: () => {}, }), }, @@ -155,16 +220,18 @@ test("a whole schema object's ~standard props are unwrapped and called", () => { name: "d", commands: { c: command("c", { - options: { mode: { type: "string", schema: whole } }, + options: { mode: { schema: whole, default: "ok" } }, handler: () => {}, }), }, }; const ok = capture(() => run(p, ["c", "--mode", "ok"])); const bad = capture(() => run(p, ["c", "--mode", "no"])); + const dflt = capture(() => run(p, ["c"])); // default "ok" validates assert.equal(ok.code, 0); assert.equal(bad.code, 1); - assert.match(bad.err.join("\n"), /--mode: validation failed; must be ok/); + assert.equal(dflt.code, 0); + assert.match(bad.err.join("\n"), /--mode: must be ok/); }); test("~standard.validate wins over a top-level validate when both exist", () => { @@ -178,7 +245,7 @@ test("~standard.validate wins over a top-level validate when both exist", () => name: "d", commands: { c: command("c", { - options: { x: { type: "string", schema: both } }, + options: { x: { schema: both, default: "y" } }, handler: () => {}, }), }, @@ -191,7 +258,7 @@ test("a schema with neither validate nor ~standard.validate throws E_BAD_OPTION" assert.throws( () => command("c", { - options: { x: { type: "string", schema: { types: {} } } }, + options: { x: { schema: { types: {} } } }, handler: () => {}, }), /E_BAD_OPTION: --x schema has neither ~standard\.validate nor validate/, @@ -205,3 +272,62 @@ test("a schema with neither validate nor ~standard.validate throws E_BAD_OPTION" /E_BAD_OPTION: command schema has neither ~standard\.validate nor validate/, ); }); + +test("defaults go through the schema: bad default fails at construction", () => { + assert.throws( + () => + command("c", { + options: { times: { schema: range(10), default: 99 } }, + handler: () => {}, + }), + /E_BAD_OPTION: --times: must be <= 10/, + ); +}); + +test("defaults go through the schema: morph output becomes the default", () => { + let seen; + const p = { + name: "d", + commands: { + c: command("c", { + options: { times: { schema: range(10), default: "7" } }, // string default morphs to 7 + handler: (opts) => { + seen = opts; + }, + }), + }, + }; + const r = capture(() => run(p, ["c"])); + assert.equal(r.code, 0); + assert.equal(seen.times, 7); +}); + +test("schema-less defaults must match the flag/string kind", () => { + assert.throws( + () => command("c", { options: { s: { default: 5 } }, handler: () => {} }), + /E_BAD_OPTION.*must be a string/, + ); + assert.throws( + () => command("c", { options: { f: { flag: true, default: "x" } }, handler: () => {} }), + /E_BAD_OPTION.*must be a boolean/, + ); +}); + +test("builtin bounds enforce min and max", () => { + const p = { + name: "d", + commands: { + c: command("c", { + options: { port: num({ default: 8080, min: 1, max: 65535 }) }, + handler: () => {}, + }), + }, + }; + assert.equal(capture(() => run(p, ["c", "--port", "80"])).code, 0); + const lo = capture(() => run(p, ["c", "--port", "0"])); + assert.equal(lo.code, 1); + assert.match(lo.err.join("\n"), /expected a number >= 1, got 0/); + const hi = capture(() => run(p, ["c", "--port", "99999"])); + assert.equal(hi.code, 1); + assert.match(hi.err.join("\n"), /expected a number <= 65535, got 99999/); +});