CommandBuilder
Immutable command schema builder.
The type parameters F (flags), A (args), and C (context) are phantom types that accumulate builder types as .flag(), .arg(), .derive(), and .middleware() are chained. The .action() handler receives fully typed ActionParams<F, A, C>.
C defaults to Record<string, never>, making ctx property access a type error until derive or middleware extends it.
- Import:
@kjanat/dreamcli - Export kind: class
- Declared in:
src/core/schema/command.ts - Source link:
src/core/schema/command.ts:1390
Signatures
class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown>> {}Members
Constructors
constructor
Create a command builder from a pre-built schema descriptor.
constructor(schema: CommandSchema, handler?: ErasedActionHandler, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);Methods
helpTopic
Register --help=<name> for a flag group, including its advanced flags.
helpTopic(name: string, group: string): CommandBuilder<F, A, C>;constrain
Declare typed relationships between already-resolved flags and arguments. A bare name selects a flag when both kinds use the same name.
constrain(build: { (builder: ConstraintBuilder<Extract<keyof F, string>, Extract<keyof A, string>>): readonly CommandConstraint[]; }): CommandBuilder<F, A, C>;validate
Validate the resolved flags using Standard Schema. Pass { input: 'resolved' } to validate an object containing flags, arguments, and their provenance. The validator's output is discarded.
validate(validator: StandardSchemaV1, options?: CommandValidationOptions): CommandBuilder<F, A, C>;interactive
Register a command-level interactive resolver for schema-driven prompts.
The resolver is called after CLI/env/config resolution with partially resolved flag values. It returns a prompt schema for flags that need interactive input based on the current state.
For flags the resolver returns a PromptConfig, that config is used instead of any per-flag .prompt() config. For flags returned as falsy (or not mentioned), per-flag .prompt() configs are used as fallback.
Commands without .interactive() use per-flag prompt configs directly.
interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;derive
Register a command-scoped typed pre-action handler.
Derive runs after full resolution and before the action handler. It receives typed { args, flags, ctx, out, meta } and may either:
- return nothing (or
undefined) for validation-only behavior - return an object to merge additional properties into
ctx
Handlers may be async — the runtime awaits them before continuing.
Unlike middleware, derive cannot wrap downstream execution and does not use next(). Use middleware for timing, logging, retries, cleanup, or error-boundary patterns.
Adding derive drops the current handler (like .flag(), .arg(), and .middleware()) because the action handler's ctx type may change.
derive<Output extends Record<string, unknown> | undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;middleware
Register middleware to run before the action handler.
Middleware executes in registration order. Each middleware receives { args, flags, ctx, out, meta, next } and must call next(additions) to continue the chain. Context additions are merged and become typed downstream.
Adding middleware widens C via intersection and drops the current handler (like .flag() / .arg() — the handler's type signature changes when context changes).
middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;description
Set the command's description for help text.
Displayed below the usage line in --help output and next to the command name in parent command/group help listings.
description(text: string): CommandBuilder<F, A, C>;details
Add a longer explanation to this command's help.
Paragraphs wrap to the help width. Parent command listings use only .description(). A function receives the current help description theme.
details(text: HelpDescription): CommandBuilder<F, A, C>;alias
Add an alternative name for this command.
Aliases are accepted during dispatch alongside the primary name. Multiple aliases can be chained. Aliases are shown in help output.
alias(name: string): CommandBuilder<F, A, C>;hidden
Hide this command from help listings.
The command remains fully functional and dispatchable — it just won't appear in --help output or shell completions. Useful for internal/debug commands.
hidden(): CommandBuilder<F, A, C>;example
Add a usage example to help text.
Examples are rendered in the "Examples:" section of --help output. Call multiple times to add several examples. Each example shows a shell invocation, optionally with a description.
cmd may be a literal string or a function receiving the program ExampleMeta (name, version), resolved at render time. Use the function form to reference the invoked program name instead of hardcoding it, so examples stay truthful under symlinks, inheritName, and npx x vs a global install.
example(cmd: ExampleCommand, description?: string): CommandBuilder<F, A, C>;flag
Register a named flag on this command.
The flag name is added to the type-level F map. Duplicate flag names are prevented at the type level via the Exclude constraint.
The builder controls the flag's type, presence, aliases, env/config bindings, and description. See FlagBuilder for available modifiers.
flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof KnownFlags<F>>, builder: B): CommandBuilder<MergeFlags<F, Record<N, B>>, A, C>;flags
Register a record of flags, preserving each own string key and inferred value type.
Names and aliases must not collide with existing flags or other entries. Literal names are checked by the compiler. Generated names are checked at runtime, and their values include the registered flag value types. Adding flags clears any previously registered action, like .flag().
flags<R extends Record<string, FlagBuilder<FlagConfig>>>(record: R & { [K in keyof KnownFlags<R> & keyof KnownFlags<F> | Extract<keyof R, symbol>]: never }): CommandBuilder<MergeFlags<F, R>, A, C>;arg
Register a named positional argument on this command.
Args are ordered by registration — position on the CLI matches the order of .arg() calls. The arg name is added to the type-level A map. Duplicate arg names are prevented at the type level via the Exclude constraint.
The builder controls the arg's type, presence, env binding, and description. See ArgBuilder for available modifiers.
arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;command
Register a nested subcommand on this command.
The subcommand's builder is stored in _subcommands for the CLI layer's compileCommand() to traverse when building the execution graph. The subcommand's CommandSchema is also appended to schema.commands for help rendering and completion generation.
Does not change F, A, or C — subcommands are type-erased at the parent level (same semantics as CLIBuilder.command()). The handler is preserved.
command<F2 extends Record<string, FlagBuilder<FlagConfig>>, A2 extends Record<string, ArgBuilder<ArgConfig>>, C2 extends Record<string, unknown>>(sub: CommandBuilder<F2, A2, C2>): CommandBuilder<F, A, C>;action
Register the action handler for this command.
The handler receives fully typed { args, flags, ctx, out, meta } derived from the accumulated .flag(), .arg(), .derive(), and .middleware() definitions.
May be synchronous or async. Return values are ignored; command handlers communicate through out, thrown errors, and side effects.
action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;Examples
const deploy = command('deploy')
.description('Deploy to an environment')
.arg('target', arg.string().describe('Deploy target'))
.flag('force', flag.boolean().alias('f'))
.flag('region', flag.enum(['us', 'eu', 'ap']))
.action(async ({ args, flags, out }) => {
// args.target: string
// flags.force: boolean
// flags.region: 'us' | 'eu' | 'ap' | undefined
out.log(`Deploying ${args.target}...`);
});