CLIBuilder
Immutable CLI program builder.
Registers commands, handles root-level --help/--version, and dispatches to the matched command based on argv.
Two execution paths:
.execute(argv, options?)— testable, returnsRunResult.run(options?)— production entry, readsprocess.argv, exits processImport:
@kjanat/dreamcliExport kind: class
Declared in:
src/core/cli/index.tsSource link:
src/core/cli/index.ts:1124
Signatures
class CLIBuilder {}Members
Methods
version
Set the program version (shown by --version).
Declaring a version also reserves --version/-V on every registered command, so this rejects a command that already declares either spelling.
version(v: string, options?: { alias?: string; }): CLIBuilder;envPrefix
Namespace every relative env binding under one CLI-wide prefix.
With no argument the prefix is derived from the name passed to cli(): camelCase word boundaries and each run of characters outside [A-Za-z0-9] become _, the result is uppercased with leading and trailing separators dropped, and _ is appended (foo-bar and fooBar → FOO_BAR_). This is the rule a name-derived .env() follows, minus the trailing _. An explicit prefix is used verbatim. Either way it is fixed here, so a manifest-inferred name or an inherited invocation name (a symlink, an alias, npx) never changes the environment API.
Every .env() binding on every command then reads the prefixed name, an indexed family's count and templates included, unless declared with { absolute: true }. Precedence, coercion, and validation are unchanged; help, diagnostics, and sources name the concrete variable.
envPrefix(prefix?: string): CLIBuilder;builtins
Choose which built-in flags the root keeps.
--help/-h, --json, and --quiet/-q are root-owned by default and never reach a command handler. Setting one to 'off' releases every spelling it answers to: the root stops reading it out of argv, root help stops advertising it under Global options:, and a command may declare it as an ordinary flag. RunOptions.jsonMode and RunOptions.verbosity keep working either way, since only argv-driven activation is disabled.
version and completions are absent by design, since .version() and .completions() are opt-in and a CLI declines those by omission.
Call multiple times to set built-ins incrementally; the last mode given for a built-in wins. Turning one back 'on' re-checks every registered command for a collision. Call this before registering the commands that declare a released flag, since .command() rejects the flag while the root still owns the token.
builtins(config: BuiltinsConfig): CLIBuilder;description
Set the program description (shown in root help).
description(text: string): CLIBuilder;links
Make help headers clickable with OSC 8 hyperlinks.
The first line of root help can link the program name and version. Set .help({ commandHeader: true }) to show those links on command and topic help. The output policy uses TTY detection by default, with overrides such as options.help.hyperlinks. Usage lines and command listings stay plain.
URLs not provided here are derived from manifest metadata when .manifest() is active (works with both filesystem discovery and pre-loaded data):
- name → normalized
repositoryURL, falling back tohomepage - version → forge release tag (
{repo}/releases/tag/v{version}on GitHub,{repo}/-/releases/v{version}on GitLab)
links(links?: { name?: string | URL; version?: string | URL; }): CLIBuilder;help
Configure root-help rendering defaults.
Stored on the schema and merged under any runtime options.help (runtime wins). Call multiple times to set fields incrementally.
help(config: HelpConfig): CLIBuilder;config
Enable automatic config file discovery.
When enabled, .run() probes standard paths before dispatching, first match wins, no merging:
- Project scope — for
$CWDand each ancestor directory up to the filesystem root, nearest first:.{appName}.json,{appName}.config.json,.config/{appName}.json - User scope —
{dir}/{appName}/config.jsonfor each user config root ($XDG_CONFIG_HOME/~/.configon Unix, plus~/Library/Application Supporton macOS,%APPDATA%/%USERPROFILE%\\AppData\\Roamingon Windows) - System scope —
/etc/{appName}/config.jsonon Linux and macOS
The user can override the path via --config <path> or --config=<path>.
Loaded config feeds into the resolution chain (CLI → env → config → prompt → default) for flags that declare .config('dotted.path').
Has no effect in .execute() (which receives config via options.config directly).
config(appName: string, input?: readonly ConfigLoader[] | ConfigOptions): CLIBuilder;configLoader
Register a custom config format loader.
Adds a ConfigLoader incrementally — call multiple times to register multiple formats. Loaders registered later for the same extension override earlier ones.
Requires .config() to have been called first (sets the app name).
configLoader(loader: ConfigLoader): CLIBuilder;manifest
Enable manifest metadata from pre-loaded data.
Pass an already-imported manifest (package.json, deno.json, jsr.json) to skip filesystem discovery entirely — useful for bundled or installable CLIs where the version should be locked at build time. The data's version/description are merged into the CLI schema immediately, so this form works in both .run() and .execute() (the filesystem-free path). Explicit .version()/.description() calls still take precedence, and the data form does not infer the CLI name — inferName / { scope } are available only on the discovery (settings) form. For a pre-loaded manifest whose scoped name should drive the CLI name, set the name explicitly via cli(name) (or call inferCliName on the data yourself).
Detected by field shape: an object carrying at least one of name/version/description/bin/homepage/repository. An empty {} or a settings-shaped object falls through to the settings overload.
Enable automatic manifest metadata discovery.
When enabled, .run() walks up from cwd (or ManifestSettings.from) to find the nearest manifest among ManifestSettings.files and merges its version/description into the CLI schema. Explicit .version() / .description() calls always take precedence.
Files are parsed as JSON with a JSONC fallback — package.json, deno.json, jsr.json, and deno.jsonc all qualify, including files with // / block comments or trailing commas. A file that fails both parses is skipped (discovery keeps walking).
Has no effect in .execute() (filesystem-free) — use the data overload.
A discovered version lands at .run() time, past every build-time check, so the RESERVED_FLAG guard re-runs there. A registered command that spells --version or -V as a flag name, an alias, or a negated spelling then fails startup, writing the error and its suggestion to stderr (a JSON error envelope on stdout under --json) and exiting with the error's exit code instead of throwing.
manifest(data: PackageJsonData): CLIBuilder;
manifest(settings?: ManifestSettings): CLIBuilder;command
Register a command with the CLI program.
The command's schema joins CLISchema.commands; its handler and subcommand tree are compiled into the builder's execution graph.
command<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown>>(cmd: CommandBuilder<F, A, C>): CLIBuilder;default
Register a command as the default — dispatched when no subcommand is given.
The CLI root behaves like a hybrid command group: named subcommands dispatch normally, but empty argv or flags-only argv falls through to this command instead of showing root help.
The default command is the CLI's root surface: its flags and arguments are rendered inline in root help. By default it is not a named subcommand — it cannot be invoked by its own name (mycli mycmd does not route to it) and it is omitted from the root Commands: list (re-enable listing with .help({ showDefaultInCommands: true })). Only one default is allowed.
Pass { route: true } to also expose the command under its own name as a routable top-level command: mycli and mycli <name> then run the same command object, and it is listed in Commands: beside its siblings. This avoids duplicating the command just to keep both forms equivalent during a v3 migration.
default<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown>>(cmd: CommandBuilder<F, A, C>, options?: DefaultCommandOptions): CLIBuilder;plugin
Register a CLI plugin.
Plugins run in registration order. At each lifecycle stage, all hooks for the first plugin run before hooks for the second plugin, and so on.
plugin(definition: CLIPlugin): CLIBuilder;completions
Register built-in shell completion.
By default ({ as: 'command' }) this registers a completions subcommand that accepts a shell argument and writes the script to stdout. With { as: 'flag' } it instead exposes an eager --completions <shell> flag on the CLI root — no subcommand is registered, so a default command stays the lone root surface. The flag may be given without a value to auto-detect the shell from $SHELL / $PSModulePath.
In subcommand mode, call this after registering all other commands so the completion script includes the full command set: that path snapshots the schema (and completion options) at call time, so commands registered afterwards will not appear in that subcommand's generated script. In flag mode, generation runs at execution time from the final builder schema, so registration order does not matter.
completions(options?: CompletionRegistrationOptions): CLIBuilder;execute
Execute the CLI program against explicit argv.
This is the testable execution path — no process state is touched. Returns a structured RunResult with exit code and captured output.
execute(argv: readonly string[], options?: CLIExecuteOptions): Promise<RunResult>;inspect
Inspect routing and resolved inputs without rendering or running the command. Uses supplied inputs and callbacks. A match's execute() resumes the same invocation once.
inspect(argv: readonly string[], options?: CLIExecuteOptions): Promise<InspectResult>;run
Run the CLI program as a production entry point.
Reads argv from the runtime adapter, dispatches to the matched command, writes output to real streams, and exits the process.
This is the only place that touches process state (via the adapter). For testing, use .execute() instead — or provide a test adapter via options.adapter.
Defaults to createAdapter() when no adapter is provided, which auto-detects the runtime (Node.js, Bun) and creates the appropriate adapter.
run(options?: CLIRunOptions): Promise<never>;Examples
import { cli, command, flag, arg } from '@kjanat/dreamcli';
const deploy = command('deploy')
.arg('target', arg.string())
.flag('force', flag.boolean().alias('f'))
.action(({ args, flags, out }) => {
out.log(`Deploying ${args.target}...`);
});
cli('mycli')
.version('1.0.0')
.command(deploy)
.run();