Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cli-initial-release.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cutils/cli": minor
---

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.
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
65 changes: 65 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# @cutils/cli

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

::: tabs

== tab Node

```sh
pnpm add @cutils/cli
```

```ts
import { bool, command, int, run, str } from "@cutils/cli";

process.exit(
run({
name: "demo",
version: "1.0.0",
commands: {
greet: command("greet someone", {
args: ["name"],
options: {
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; greeting: string } — fully inferred
const who = opts.upper ? args[0].toUpperCase() : args[0];
for (let i = 0; i < opts.times; i++) console.log(`${opts.greeting || "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. `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` 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.
4 changes: 4 additions & 0 deletions docs/docmd.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@
{
"title": "@cutils/cache",
"path": "/cache"
},
{
"title": "@cutils/cli",
"path": "/cli"
}
]
}
Expand Down
1 change: 1 addition & 0 deletions docs/packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
98 changes: 98 additions & 0 deletions packages/cli/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# @cutils/cli AGENTS.md

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<O extends
Record<string, OptionInput>>` lowers fully — the generic only feeds the
type-level `OptsFromOptions<O>` mapped type; nothing generic survives
into runtime values.
- **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.
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.isInteger`, `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<O>, ...) => 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).
- **`opts` typing is `types.output` only** — there is no `type` field to
fall back to. Priority in `OptsFromOptions`: bare-schema entry →
`SchemaOutput<O[K]>`; `{schema: S}` → `SchemaOutput<S>` (no `types` →
`unknown`); `{flag: true}` → `boolean`; else `string`.
- **`TypedValidator<O>` 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
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
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 (pre-schema-first surface; re-measure if
quoting):

| 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`, `<cmd> --help`, `--version`, unknown command +
suggestion, missing arg, bad value, schema rejection, builtin bounds)
Loading
Loading