@kjanat/dreamcli 0.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +706 -0
- package/LICENSE +22 -0
- package/README.md +502 -0
- package/dist/core/cli/dispatch.d.mts +85 -0
- package/dist/core/cli/dispatch.mjs +1 -0
- package/dist/core/cli/index.d.mts +418 -0
- package/dist/core/cli/index.mjs +1 -0
- package/dist/core/cli/planner.d.mts +143 -0
- package/dist/core/cli/planner.mjs +1 -0
- package/dist/core/cli/plugin.d.mts +94 -0
- package/dist/core/cli/plugin.mjs +1 -0
- package/dist/core/cli/propagate.d.mts +39 -0
- package/dist/core/cli/propagate.mjs +1 -0
- package/dist/core/cli/root-help.d.mts +28 -0
- package/dist/core/cli/root-help.mjs +7 -0
- package/dist/core/cli/root-surface.d.mts +42 -0
- package/dist/core/cli/root-surface.mjs +1 -0
- package/dist/core/cli/runtime-preflight.d.mts +149 -0
- package/dist/core/cli/runtime-preflight.mjs +1 -0
- package/dist/core/completion/index.d.mts +46 -0
- package/dist/core/completion/index.mjs +1 -0
- package/dist/core/completion/shells/bash.d.mts +24 -0
- package/dist/core/completion/shells/bash.mjs +3 -0
- package/dist/core/completion/shells/fish.d.mts +20 -0
- package/dist/core/completion/shells/fish.mjs +2 -0
- package/dist/core/completion/shells/powershell.d.mts +14 -0
- package/dist/core/completion/shells/powershell.mjs +2 -0
- package/dist/core/completion/shells/shared.d.mts +139 -0
- package/dist/core/completion/shells/shared.mjs +1 -0
- package/dist/core/completion/shells/zsh.d.mts +24 -0
- package/dist/core/completion/shells/zsh.mjs +2 -0
- package/dist/core/config/index.d.mts +161 -0
- package/dist/core/config/index.mjs +1 -0
- package/dist/core/config/package-json.d.mts +68 -0
- package/dist/core/config/package-json.mjs +1 -0
- package/dist/core/errors/index.d.mts +126 -0
- package/dist/core/errors/index.mjs +1 -0
- package/dist/core/execution/index.d.mts +49 -0
- package/dist/core/execution/index.mjs +1 -0
- package/dist/core/help/index.d.mts +49 -0
- package/dist/core/help/index.mjs +8 -0
- package/dist/core/json-schema/index.d.mts +109 -0
- package/dist/core/json-schema/index.mjs +55 -0
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
- package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
- package/dist/core/output/activity.d.mts +194 -0
- package/dist/core/output/activity.mjs +1 -0
- package/dist/core/output/contracts.d.mts +88 -0
- package/dist/core/output/contracts.mjs +1 -0
- package/dist/core/output/display-value.d.mts +19 -0
- package/dist/core/output/display-value.mjs +1 -0
- package/dist/core/output/index.d.mts +280 -0
- package/dist/core/output/index.mjs +2 -0
- package/dist/core/output/renderers.d.mts +46 -0
- package/dist/core/output/renderers.mjs +1 -0
- package/dist/core/output/writer.d.mts +40 -0
- package/dist/core/output/writer.mjs +1 -0
- package/dist/core/parse/index.d.mts +79 -0
- package/dist/core/parse/index.mjs +1 -0
- package/dist/core/prompt/index.d.mts +205 -0
- package/dist/core/prompt/index.mjs +6 -0
- package/dist/core/resolve/args.d.mts +8 -0
- package/dist/core/resolve/args.mjs +1 -0
- package/dist/core/resolve/coerce.d.mts +22 -0
- package/dist/core/resolve/coerce.mjs +1 -0
- package/dist/core/resolve/config.d.mts +10 -0
- package/dist/core/resolve/config.mjs +1 -0
- package/dist/core/resolve/contracts.d.mts +112 -0
- package/dist/core/resolve/errors.d.mts +11 -0
- package/dist/core/resolve/errors.mjs +2 -0
- package/dist/core/resolve/flags.d.mts +10 -0
- package/dist/core/resolve/flags.mjs +1 -0
- package/dist/core/resolve/index.d.mts +42 -0
- package/dist/core/resolve/index.mjs +1 -0
- package/dist/core/resolve/property.d.mts +47 -0
- package/dist/core/resolve/property.mjs +1 -0
- package/dist/core/schema/activity.d.mts +169 -0
- package/dist/core/schema/arg.d.mts +559 -0
- package/dist/core/schema/arg.mjs +1 -0
- package/dist/core/schema/command.d.mts +960 -0
- package/dist/core/schema/command.mjs +1 -0
- package/dist/core/schema/flag.d.mts +491 -0
- package/dist/core/schema/flag.mjs +1 -0
- package/dist/core/schema/index.d.mts +8 -0
- package/dist/core/schema/middleware.d.mts +122 -0
- package/dist/core/schema/middleware.mjs +1 -0
- package/dist/core/schema/prompt.d.mts +117 -0
- package/dist/core/schema/run.d.mts +171 -0
- package/dist/core/schema-dsl/runtime.d.mts +144 -0
- package/dist/core/schema-dsl/runtime.mjs +2 -0
- package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
- package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
- package/dist/core/testkit/index.d.mts +54 -0
- package/dist/core/testkit/index.mjs +1 -0
- package/dist/index.d.mts +28 -0
- package/dist/index.mjs +1 -0
- package/dist/runtime/adapter.d.mts +212 -0
- package/dist/runtime/adapter.mjs +1 -0
- package/dist/runtime/auto.d.mts +26 -0
- package/dist/runtime/auto.mjs +1 -0
- package/dist/runtime/bun.d.mts +28 -0
- package/dist/runtime/bun.mjs +1 -0
- package/dist/runtime/deno.d.mts +76 -0
- package/dist/runtime/deno.mjs +2 -0
- package/dist/runtime/detect.d.mts +86 -0
- package/dist/runtime/detect.mjs +1 -0
- package/dist/runtime/index.d.mts +7 -0
- package/dist/runtime/node.d.mts +65 -0
- package/dist/runtime/node.mjs +2 -0
- package/dist/runtime/paths.d.mts +31 -0
- package/dist/runtime/paths.mjs +1 -0
- package/dist/runtime/support.d.mts +42 -0
- package/dist/runtime/support.mjs +1 -0
- package/dist/runtime.d.mts +7 -0
- package/dist/runtime.mjs +1 -0
- package/dist/testkit.d.mts +6 -0
- package/dist/testkit.mjs +1 -0
- package/dist/version.d.mts +16 -0
- package/dist/version.mjs +1 -0
- package/dreamcli.schema.json +338 -0
- package/examples/basic.ts +33 -0
- package/examples/gh/package.json +44 -0
- package/examples/gh/src/commands/auth.ts +66 -0
- package/examples/gh/src/commands/issue.ts +120 -0
- package/examples/gh/src/commands/pr.ts +125 -0
- package/examples/gh/src/data/issues.yaml +5 -0
- package/examples/gh/src/data/issues.yaml.d.ts +17 -0
- package/examples/gh/src/data/pull-requests.yaml +7 -0
- package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
- package/examples/gh/src/docs.ts +11 -0
- package/examples/gh/src/lib/auth.ts +37 -0
- package/examples/gh/src/lib/utils.ts +17 -0
- package/examples/gh/src/main.test.ts +307 -0
- package/examples/gh/src/main.ts +40 -0
- package/examples/interactive.ts +66 -0
- package/examples/json-mode.ts +91 -0
- package/examples/middleware.ts +71 -0
- package/examples/multi-command.ts +66 -0
- package/examples/spinner-progress.ts +49 -0
- package/examples/testing.ts +147 -0
- package/package.json +149 -2
- package/src/core/cli/dispatch.ts +286 -0
- package/src/core/cli/index.ts +978 -0
- package/src/core/cli/planner.ts +413 -0
- package/src/core/cli/plugin.ts +117 -0
- package/src/core/cli/propagate.ts +97 -0
- package/src/core/cli/root-help.ts +269 -0
- package/src/core/cli/root-surface.ts +74 -0
- package/src/core/cli/runtime-preflight.ts +409 -0
- package/src/core/completion/index.ts +88 -0
- package/src/core/completion/shells/bash.ts +459 -0
- package/src/core/completion/shells/fish.ts +259 -0
- package/src/core/completion/shells/powershell.ts +405 -0
- package/src/core/completion/shells/shared.ts +283 -0
- package/src/core/completion/shells/zsh.ts +381 -0
- package/src/core/config/index.ts +407 -0
- package/src/core/config/package-json.ts +220 -0
- package/src/core/errors/index.ts +193 -0
- package/src/core/execution/index.ts +270 -0
- package/src/core/help/index.ts +557 -0
- package/src/core/json-schema/index.ts +891 -0
- package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
- package/src/core/output/activity.ts +568 -0
- package/src/core/output/contracts.ts +194 -0
- package/src/core/output/display-value.ts +48 -0
- package/src/core/output/index.ts +669 -0
- package/src/core/output/renderers.ts +125 -0
- package/src/core/output/writer.ts +46 -0
- package/src/core/parse/index.ts +661 -0
- package/src/core/prompt/index.ts +583 -0
- package/src/core/resolve/args.ts +144 -0
- package/src/core/resolve/coerce.ts +432 -0
- package/src/core/resolve/config.ts +26 -0
- package/src/core/resolve/contracts.ts +135 -0
- package/src/core/resolve/errors.ts +227 -0
- package/src/core/resolve/flags.ts +205 -0
- package/src/core/resolve/index.ts +108 -0
- package/src/core/resolve/property.ts +99 -0
- package/src/core/schema/activity.ts +240 -0
- package/src/core/schema/arg.ts +719 -0
- package/src/core/schema/command.ts +1490 -0
- package/src/core/schema/flag.ts +756 -0
- package/src/core/schema/index.ts +91 -0
- package/src/core/schema/middleware.ts +171 -0
- package/src/core/schema/prompt.ts +156 -0
- package/src/core/schema/run.ts +195 -0
- package/src/core/schema-dsl/index.ts +109 -0
- package/src/core/schema-dsl/parse.ts +262 -0
- package/src/core/schema-dsl/runtime.ts +609 -0
- package/src/core/schema-dsl/to-json-schema.ts +102 -0
- package/src/core/testkit/index.ts +123 -0
- package/src/index.ts +170 -0
- package/src/runtime/adapter.ts +303 -0
- package/src/runtime/auto.ts +110 -0
- package/src/runtime/bun.ts +55 -0
- package/src/runtime/deno.ts +369 -0
- package/src/runtime/detect.ts +105 -0
- package/src/runtime/index.ts +21 -0
- package/src/runtime/node-builtins.d.ts +23 -0
- package/src/runtime/node.ts +300 -0
- package/src/runtime/paths.ts +62 -0
- package/src/runtime/support.ts +135 -0
- package/src/runtime.ts +31 -0
- package/src/testkit.ts +25 -0
- package/src/version.ts +20 -0
|
@@ -0,0 +1,1490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command schema builder with flag/arg composition and type accumulation.
|
|
3
|
+
*
|
|
4
|
+
* The {@linkcode command} factory returns an immutable {@linkcode CommandBuilder}
|
|
5
|
+
* whose generic parameters track accumulated flag and arg builder types. Chaining
|
|
6
|
+
* `.flag()` and `.arg()` calls produces progressively narrower types. The
|
|
7
|
+
* `.action()` handler receives fully typed `{ args, flags, ctx, out, meta }`.
|
|
8
|
+
*
|
|
9
|
+
* @module dreamcli/core/schema/command
|
|
10
|
+
*/
|
|
11
|
+
import { CLIError } from '#internals/core/errors/index.ts';
|
|
12
|
+
import type {
|
|
13
|
+
ProgressHandle,
|
|
14
|
+
ProgressOptions,
|
|
15
|
+
SpinnerHandle,
|
|
16
|
+
SpinnerOptions,
|
|
17
|
+
TableColumn,
|
|
18
|
+
TableOptions,
|
|
19
|
+
} from './activity.ts';
|
|
20
|
+
import type { ArgBuilder, ArgConfig, ArgSchema, InferArgs } from './arg.ts';
|
|
21
|
+
import type { FlagBuilder, FlagConfig, FlagSchema, InferFlags } from './flag.ts';
|
|
22
|
+
import type { ErasedMiddlewareHandler, Middleware } from './middleware.ts';
|
|
23
|
+
import type { PromptConfig } from './prompt.ts';
|
|
24
|
+
import type { RunOptions, RunResult } from './run.ts';
|
|
25
|
+
|
|
26
|
+
// --- Context type utilities
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Widen the context type when adding middleware.
|
|
30
|
+
*
|
|
31
|
+
* The default `C = Record<string, never>` uses an index signature where
|
|
32
|
+
* every key maps to `never` — making property access a type error until
|
|
33
|
+
* middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
|
|
34
|
+
* collapses all properties to `never` because `never & T = never`.
|
|
35
|
+
*
|
|
36
|
+
* This utility replaces `Record<string, never>` entirely on the first
|
|
37
|
+
* `.middleware()` call. Subsequent calls use plain intersection.
|
|
38
|
+
*/
|
|
39
|
+
type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> =
|
|
40
|
+
C extends Record<string, never> ? Output : C & Output;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Widen the context type when adding command-scoped derived context.
|
|
44
|
+
*
|
|
45
|
+
* Validation-only derive handlers return `undefined`, preserving `C`.
|
|
46
|
+
* Context-producing derive handlers return an object that merges into `C`
|
|
47
|
+
* using the same first-call replacement rules as middleware.
|
|
48
|
+
*/
|
|
49
|
+
type WidenDerivedContext<C extends Record<string, unknown>, Output> =
|
|
50
|
+
Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
|
|
51
|
+
|
|
52
|
+
// --- Type-level configuration (phantom state tracked through the chain)
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Compile-time state carried through the command builder chain.
|
|
56
|
+
*
|
|
57
|
+
* `F` accumulates named flag builders; `A` accumulates named arg builders.
|
|
58
|
+
* Both start empty (`{}`) and grow as `.flag()` / `.arg()` are called.
|
|
59
|
+
*/
|
|
60
|
+
interface CommandConfig {
|
|
61
|
+
/** Accumulated flag builders keyed by flag name. */
|
|
62
|
+
readonly flags: Record<string, FlagBuilder<FlagConfig>>;
|
|
63
|
+
/** Accumulated arg builders keyed by arg name. */
|
|
64
|
+
readonly args: Record<string, ArgBuilder<ArgConfig>>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// --- Interactive resolver types
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Parameters received by the interactive resolver function.
|
|
71
|
+
*
|
|
72
|
+
* `flags` contains partially resolved values — present for flags resolved
|
|
73
|
+
* via CLI, env, or config, `undefined` for unresolved flags. The resolver
|
|
74
|
+
* uses this to decide which prompts to show based on current state.
|
|
75
|
+
*/
|
|
76
|
+
interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
|
|
77
|
+
/** Partially resolved flag values (after CLI/env/config, before prompts). */
|
|
78
|
+
readonly flags: Readonly<Partial<InferFlags<F>>>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A record mapping flag names to prompt configs or falsy values.
|
|
83
|
+
*
|
|
84
|
+
* - `PromptConfig` — show this prompt for the flag
|
|
85
|
+
* - `false | undefined | null | 0 | ''` — skip prompting for this flag
|
|
86
|
+
*
|
|
87
|
+
* Only flag names that need prompting should have truthy values.
|
|
88
|
+
* Flags not mentioned are handled by their per-flag `.prompt()` config.
|
|
89
|
+
*/
|
|
90
|
+
type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Interactive resolver function for command-level prompt control.
|
|
94
|
+
*
|
|
95
|
+
* Called after CLI/env/config resolution but before per-flag prompts fire.
|
|
96
|
+
* Receives partially resolved values and returns a prompt schema for
|
|
97
|
+
* flags that should be prompted. Commands without `.interactive()` use
|
|
98
|
+
* per-flag prompt configs directly.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* import { command, flag } from '@kjanat/dreamcli';
|
|
103
|
+
*
|
|
104
|
+
* const deploy = command('deploy')
|
|
105
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
106
|
+
* .interactive(({ flags }) => ({
|
|
107
|
+
* region: !flags.region && {
|
|
108
|
+
* kind: 'select',
|
|
109
|
+
* message: 'Select region',
|
|
110
|
+
* },
|
|
111
|
+
* }))
|
|
112
|
+
* .action(({ flags, out }) => {
|
|
113
|
+
* out.log(`Deploying to ${flags.region}`);
|
|
114
|
+
* });
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (
|
|
118
|
+
params: InteractiveParams<F>,
|
|
119
|
+
) => InteractiveResult;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Type-erased interactive resolver stored on {@linkcode CommandSchema}.
|
|
123
|
+
*
|
|
124
|
+
* Advanced bridge type: most consumers should use {@link InteractiveResolver}
|
|
125
|
+
* via {@linkcode command | command().interactive()} and never reference this alias directly.
|
|
126
|
+
*
|
|
127
|
+
* At runtime, the resolver receives `{ flags: Record<string, unknown> }`
|
|
128
|
+
* and returns `Record<string, PromptConfig | falsy>`. The phantom types
|
|
129
|
+
* from `CommandBuilder<F, A>` are erased.
|
|
130
|
+
*
|
|
131
|
+
* @internal
|
|
132
|
+
*/
|
|
133
|
+
type ErasedInteractiveResolver = (params: {
|
|
134
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
135
|
+
}) => InteractiveResult;
|
|
136
|
+
|
|
137
|
+
// --- Handler types
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Output channel available inside action handlers.
|
|
141
|
+
*
|
|
142
|
+
* Provides structured methods for stdout/stderr, JSON output,
|
|
143
|
+
* spinners, progress bars, and tables. The real implementation lives in
|
|
144
|
+
* `src/core/output/`; this interface defines the shape that handlers consume.
|
|
145
|
+
*/
|
|
146
|
+
interface Out {
|
|
147
|
+
/** Write to stdout (normal output). */
|
|
148
|
+
log(message: string): void;
|
|
149
|
+
/** Informational (may be suppressed in quiet mode). */
|
|
150
|
+
info(message: string): void;
|
|
151
|
+
/** Warning to stderr. */
|
|
152
|
+
warn(message: string): void;
|
|
153
|
+
/** Error to stderr. */
|
|
154
|
+
error(message: string): void;
|
|
155
|
+
/**
|
|
156
|
+
* Emit a structured JSON value to stdout.
|
|
157
|
+
*
|
|
158
|
+
* Always serialises `value` as JSON to stdout regardless of output
|
|
159
|
+
* mode. Prefer this over `log(JSON.stringify(...))` so the output
|
|
160
|
+
* channel can enforce consistent formatting and future features
|
|
161
|
+
* (pretty-print in TTY, streaming JSON, etc.).
|
|
162
|
+
*/
|
|
163
|
+
json(value: unknown): void;
|
|
164
|
+
/**
|
|
165
|
+
* Whether the output channel is in JSON mode (`--json` flag active).
|
|
166
|
+
*
|
|
167
|
+
* Handlers can check this to skip decorative output (spinners,
|
|
168
|
+
* progress bars, ANSI formatting) when machine-readable output is
|
|
169
|
+
* expected.
|
|
170
|
+
*/
|
|
171
|
+
readonly jsonMode: boolean;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Whether stdout is connected to a TTY (terminal).
|
|
175
|
+
*
|
|
176
|
+
* Handlers can check this to decide whether to emit decorative output
|
|
177
|
+
* (spinners, progress bars, ANSI color codes). When `false`, the output
|
|
178
|
+
* is being piped or redirected — skip interactive decorations.
|
|
179
|
+
*
|
|
180
|
+
* Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
|
|
181
|
+
* decorative output should be suppressed regardless of `isTTY`.
|
|
182
|
+
*/
|
|
183
|
+
readonly isTTY: boolean;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Render tabular data.
|
|
187
|
+
*
|
|
188
|
+
* - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
|
|
189
|
+
* - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
|
|
190
|
+
* - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
|
|
191
|
+
* (useful for `grep`, `awk`, etc.).
|
|
192
|
+
* - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
|
|
193
|
+
* side channel while `json()` writes machine output to stdout.
|
|
194
|
+
*
|
|
195
|
+
* When `columns` is omitted, columns are auto-inferred from the keys
|
|
196
|
+
* of the first row. Column headers default to the key name.
|
|
197
|
+
*
|
|
198
|
+
* When `columns` is provided, both text and JSON output are projected to
|
|
199
|
+
* only the listed keys.
|
|
200
|
+
*
|
|
201
|
+
* @param rows - Array of row objects.
|
|
202
|
+
*/
|
|
203
|
+
table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
|
|
204
|
+
/**
|
|
205
|
+
* Render tabular data with explicit column selection.
|
|
206
|
+
*
|
|
207
|
+
* @param rows - Array of row objects.
|
|
208
|
+
* @param columns - Column descriptors controlling which keys are shown and header labels.
|
|
209
|
+
* @param options - Per-call rendering options (format, stream).
|
|
210
|
+
*/
|
|
211
|
+
table<T extends Record<string, unknown>>(
|
|
212
|
+
rows: readonly T[],
|
|
213
|
+
columns?: readonly TableColumn<T>[],
|
|
214
|
+
options?: TableOptions,
|
|
215
|
+
): void;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Create a spinner for indeterminate progress feedback.
|
|
219
|
+
*
|
|
220
|
+
* Returns a handle for lifecycle control. In non-TTY/jsonMode,
|
|
221
|
+
* returns a no-op handle (or static fallback if configured).
|
|
222
|
+
*
|
|
223
|
+
* @param text - Initial spinner text.
|
|
224
|
+
* @param options - Fallback strategy for non-TTY environments.
|
|
225
|
+
* @returns A {@link SpinnerHandle} for lifecycle control.
|
|
226
|
+
*/
|
|
227
|
+
spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Create a progress bar for measured work.
|
|
231
|
+
*
|
|
232
|
+
* Returns a handle for updating progress. Pass `total` for
|
|
233
|
+
* determinate mode (percentage bar); omit for indeterminate (pulsing).
|
|
234
|
+
*
|
|
235
|
+
* @param options - Progress configuration (total, label, fallback).
|
|
236
|
+
* @returns A {@link ProgressHandle} for updating progress.
|
|
237
|
+
*/
|
|
238
|
+
progress(options: ProgressOptions): ProgressHandle;
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Stop the currently active spinner or progress handle, if any.
|
|
242
|
+
*
|
|
243
|
+
* TTY spinner and progress handles start `setInterval` timers that
|
|
244
|
+
* prevent the process from exiting until a terminal method (`stop`,
|
|
245
|
+
* `succeed`, `fail`, `done`) is called. If a handler throws before
|
|
246
|
+
* reaching that call, the timer leaks and the process hangs.
|
|
247
|
+
*
|
|
248
|
+
* Call `stopActive()` in a `finally` block after handler execution
|
|
249
|
+
* to guarantee cleanup. It is idempotent — safe to call when no
|
|
250
|
+
* handle is active, or when the handle was already stopped.
|
|
251
|
+
*
|
|
252
|
+
* The framework calls this automatically in `runCommand()` and
|
|
253
|
+
* `cli().run()`. Direct users of `createOutput()` should call it
|
|
254
|
+
* themselves after the handler returns or throws.
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* ```ts
|
|
258
|
+
* const out = createOutput({ isTTY: true });
|
|
259
|
+
* try {
|
|
260
|
+
* await handler({ out });
|
|
261
|
+
* } finally {
|
|
262
|
+
* out.stopActive();
|
|
263
|
+
* }
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
stopActive(): void;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Runtime metadata about the CLI program and current command execution.
|
|
271
|
+
*
|
|
272
|
+
* Available to action handlers and middleware.
|
|
273
|
+
*
|
|
274
|
+
* Populated by the CLI dispatch layer from {@link CLISchema} and
|
|
275
|
+
* {@link CommandSchema}. For standalone `runCommand()` calls without
|
|
276
|
+
* a CLI wrapper, a minimal meta is constructed from the command's own schema.
|
|
277
|
+
*/
|
|
278
|
+
interface CommandMeta {
|
|
279
|
+
/** CLI program name (from `cli('name')` or package.json inference). */
|
|
280
|
+
readonly name: string;
|
|
281
|
+
/** Binary display name used in help/usage (may differ from `name`). */
|
|
282
|
+
readonly bin: string;
|
|
283
|
+
/** Program version, if set via `.version()` or discovered from package.json. */
|
|
284
|
+
readonly version: string | undefined;
|
|
285
|
+
/** The leaf command name currently being executed. */
|
|
286
|
+
readonly command: string;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* The bag of values received by an action handler.
|
|
291
|
+
*
|
|
292
|
+
* - `args` — fully resolved positional arguments
|
|
293
|
+
* - `flags` — fully resolved flags
|
|
294
|
+
* - `ctx` — derive/middleware-provided context
|
|
295
|
+
* - `out` — output channel
|
|
296
|
+
* - `meta` — CLI program metadata (name, bin, version, command)
|
|
297
|
+
*
|
|
298
|
+
* The `C` parameter defaults to `Record<string, never>`, making `ctx`
|
|
299
|
+
* property access a type error until derive or middleware extends it.
|
|
300
|
+
*/
|
|
301
|
+
interface ActionParams<
|
|
302
|
+
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
303
|
+
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
304
|
+
C extends Record<string, unknown> = Record<string, never>,
|
|
305
|
+
> {
|
|
306
|
+
/** Fully resolved positional argument values, typed from `.arg()` definitions. */
|
|
307
|
+
readonly args: Readonly<InferArgs<A>>;
|
|
308
|
+
/** Fully resolved flag values, typed from `.flag()` definitions. */
|
|
309
|
+
readonly flags: Readonly<InferFlags<F>>;
|
|
310
|
+
/** Middleware/derive-provided context, typed from `.middleware()` and `.derive()` chains. */
|
|
311
|
+
readonly ctx: Readonly<C>;
|
|
312
|
+
/** Structured output channel for stdout, stderr, JSON, tables, and spinners. */
|
|
313
|
+
readonly out: Out;
|
|
314
|
+
/** Runtime metadata about the CLI program and current command. */
|
|
315
|
+
readonly meta: CommandMeta;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Action handler function signature.
|
|
320
|
+
*
|
|
321
|
+
* May be sync or async — the framework will `await` the return value
|
|
322
|
+
* regardless. The `C` parameter carries the accumulated middleware
|
|
323
|
+
* context type (defaults to empty).
|
|
324
|
+
*/
|
|
325
|
+
type ActionHandler<
|
|
326
|
+
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
327
|
+
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
328
|
+
C extends Record<string, unknown> = Record<string, never>,
|
|
329
|
+
> = (params: ActionParams<F, A, C>) => void | Promise<void>;
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Type-erased action handler stored on {@linkcode CommandBuilder}.
|
|
333
|
+
*
|
|
334
|
+
* The typed {@linkcode ActionHandler} from `.action()` is cast to this
|
|
335
|
+
* erased form at the type-erasure boundary, keeping {@linkcode CommandBuilder}
|
|
336
|
+
* covariant in its generic parameters. This enables structural
|
|
337
|
+
* compatibility across TypeScript declaration-file boundaries where
|
|
338
|
+
* generic inference may fall back to constraint types.
|
|
339
|
+
*
|
|
340
|
+
* Follows the same erasure pattern as {@link ErasedDeriveHandler} and
|
|
341
|
+
* {@link ErasedMiddlewareHandler}.
|
|
342
|
+
*
|
|
343
|
+
* @internal
|
|
344
|
+
*/
|
|
345
|
+
type ErasedActionHandler = (params: {
|
|
346
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
347
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
348
|
+
readonly ctx: Readonly<Record<string, unknown>>;
|
|
349
|
+
readonly out: Out;
|
|
350
|
+
readonly meta: CommandMeta;
|
|
351
|
+
}) => void | Promise<void>;
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The bag of values received by a derive handler.
|
|
355
|
+
*
|
|
356
|
+
* Identical to {@link ActionParams}: derives run after full resolution and
|
|
357
|
+
* before the action handler, with typed args/flags/current context plus `out`
|
|
358
|
+
* and `meta`.
|
|
359
|
+
*/
|
|
360
|
+
type DeriveParams<
|
|
361
|
+
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
362
|
+
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
363
|
+
C extends Record<string, unknown> = Record<string, never>,
|
|
364
|
+
> = ActionParams<F, A, C>;
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Command-scoped typed pre-action handler.
|
|
368
|
+
*
|
|
369
|
+
* Derive handlers may:
|
|
370
|
+
* - validate resolved input and throw {@linkcode CLIError}
|
|
371
|
+
* - return `undefined` to continue without changing context
|
|
372
|
+
* - return an object whose properties merge into `ctx` downstream
|
|
373
|
+
*
|
|
374
|
+
* They cannot wrap downstream execution; use {@linkcode middleware} for that.
|
|
375
|
+
*/
|
|
376
|
+
type DeriveHandler<
|
|
377
|
+
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
378
|
+
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
379
|
+
C extends Record<string, unknown> = Record<string, never>,
|
|
380
|
+
Output extends Record<string, unknown> | undefined = undefined,
|
|
381
|
+
> = (params: DeriveParams<F, A, C>) => Output | Promise<Output>;
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Type-erased derive handler stored on the command builder.
|
|
385
|
+
*
|
|
386
|
+
* @internal
|
|
387
|
+
*/
|
|
388
|
+
type ErasedDeriveHandler = (params: {
|
|
389
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
390
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
391
|
+
readonly ctx: Readonly<Record<string, unknown>>;
|
|
392
|
+
readonly out: Out;
|
|
393
|
+
readonly meta: CommandMeta;
|
|
394
|
+
}) =>
|
|
395
|
+
| undefined
|
|
396
|
+
| Readonly<Record<string, unknown>>
|
|
397
|
+
| Promise<undefined | Readonly<Record<string, unknown>>>;
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Internal execution step union preserving registration order across
|
|
401
|
+
* {@linkcode CommandBuilder.derive | derive()} and {@linkcode CommandBuilder.middleware | middleware()}.
|
|
402
|
+
*
|
|
403
|
+
* @internal
|
|
404
|
+
*/
|
|
405
|
+
type ExecutionStep =
|
|
406
|
+
| {
|
|
407
|
+
readonly kind: 'derive';
|
|
408
|
+
readonly handler: ErasedDeriveHandler;
|
|
409
|
+
}
|
|
410
|
+
| {
|
|
411
|
+
readonly kind: 'middleware';
|
|
412
|
+
readonly handler: ErasedMiddlewareHandler;
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
// --- Runtime schema data
|
|
416
|
+
|
|
417
|
+
/** A single usage example shown in help text. */
|
|
418
|
+
interface CommandExample {
|
|
419
|
+
/** The command invocation (e.g. `'deploy production --force'`). */
|
|
420
|
+
readonly command: string;
|
|
421
|
+
/** Optional description of what this example does. */
|
|
422
|
+
readonly description?: string;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Runtime descriptor produced by {@link CommandBuilder}.
|
|
427
|
+
*
|
|
428
|
+
* Consumers (parser, help generator, CLI dispatcher) read this to
|
|
429
|
+
* understand the command's shape — flags, args, aliases, subcommands,
|
|
430
|
+
* middleware, and interactive resolver.
|
|
431
|
+
*/
|
|
432
|
+
interface CommandSchema {
|
|
433
|
+
/** The command name (used for dispatch, e.g. `'deploy'`). */
|
|
434
|
+
readonly name: string;
|
|
435
|
+
/** Human-readable description for help text. */
|
|
436
|
+
readonly description: string | undefined;
|
|
437
|
+
/** Alternative names for this command. */
|
|
438
|
+
readonly aliases: readonly string[];
|
|
439
|
+
/** Whether this command is hidden from help listings. */
|
|
440
|
+
readonly hidden: boolean;
|
|
441
|
+
/** Usage examples for help text. */
|
|
442
|
+
readonly examples: readonly CommandExample[];
|
|
443
|
+
/** Named flag schemas, keyed by flag name. */
|
|
444
|
+
readonly flags: Readonly<Record<string, FlagSchema>>;
|
|
445
|
+
/** Ordered positional arg entries (name + schema). */
|
|
446
|
+
readonly args: readonly CommandArgEntry[];
|
|
447
|
+
/** Whether an action handler has been registered. */
|
|
448
|
+
readonly hasAction: boolean;
|
|
449
|
+
/**
|
|
450
|
+
* Command-level interactive resolver for schema-driven prompt control.
|
|
451
|
+
*
|
|
452
|
+
* When set, called after CLI/env/config resolution with partially resolved
|
|
453
|
+
* flag values. Returns prompt configs for flags that need interactive input.
|
|
454
|
+
* Takes precedence over per-flag `.prompt()` configs for flags it returns
|
|
455
|
+
* configs for; flags not mentioned fall back to their per-flag configs.
|
|
456
|
+
*
|
|
457
|
+
* @see InteractiveResolver
|
|
458
|
+
*/
|
|
459
|
+
readonly interactive: ErasedInteractiveResolver | undefined;
|
|
460
|
+
/**
|
|
461
|
+
* Middleware handlers to run before the action handler.
|
|
462
|
+
*
|
|
463
|
+
* Executed in registration order — first middleware registered runs
|
|
464
|
+
* first and calls `next()` to proceed to subsequent middleware,
|
|
465
|
+
* ending with the action handler. Context accumulates via intersection
|
|
466
|
+
* at the type level and via object spread at runtime.
|
|
467
|
+
*/
|
|
468
|
+
readonly middleware: readonly ErasedMiddlewareHandler[];
|
|
469
|
+
/**
|
|
470
|
+
* Nested subcommand schemas (for help rendering and completion).
|
|
471
|
+
*
|
|
472
|
+
* Pure data — no execution closures. Populated by `.command()` on
|
|
473
|
+
* `CommandBuilder`. Empty for leaf commands.
|
|
474
|
+
*/
|
|
475
|
+
readonly commands: readonly CommandSchema[];
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* A named positional argument entry in the command schema.
|
|
480
|
+
*
|
|
481
|
+
* Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
|
|
482
|
+
* The array ordering in {@link CommandSchema.args} determines CLI position.
|
|
483
|
+
*/
|
|
484
|
+
interface CommandArgEntry {
|
|
485
|
+
/** User-facing argument name (shown in help as `<name>`). */
|
|
486
|
+
readonly name: string;
|
|
487
|
+
/** Runtime descriptor controlling parsing, presence, and coercion. */
|
|
488
|
+
readonly schema: ArgSchema;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Validate a new arg entry against invariants before adding it to the command.
|
|
493
|
+
*
|
|
494
|
+
* @param name - Arg name being registered.
|
|
495
|
+
* @param schema - Runtime descriptor of the arg.
|
|
496
|
+
* @param args - Already-registered arg entries on this command.
|
|
497
|
+
*
|
|
498
|
+
* @throws {@link CLIError} `INVALID_BUILDER_STATE` if both `.stdin()` and `.variadic()` are set.
|
|
499
|
+
* @throws {@link CLIError} `DUPLICATE_STDIN_ARG` if another arg already uses `.stdin()`.
|
|
500
|
+
*
|
|
501
|
+
* @internal
|
|
502
|
+
*/
|
|
503
|
+
function validateArgEntry(name: string, schema: ArgSchema, args: readonly CommandArgEntry[]): void {
|
|
504
|
+
if (schema.stdinMode && schema.variadic) {
|
|
505
|
+
throw new CLIError(`Argument <${name}> cannot be both variadic and stdin-backed`, {
|
|
506
|
+
code: 'INVALID_BUILDER_STATE',
|
|
507
|
+
details: { arg: name, stdinMode: true, variadic: true },
|
|
508
|
+
suggest: 'Remove .stdin() or .variadic() from this argument',
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if (!schema.stdinMode) {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const existing = args.find((entry) => entry.schema.stdinMode);
|
|
517
|
+
if (existing === undefined) {
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
throw new CLIError(
|
|
522
|
+
`Only one stdin argument is allowed; <${existing.name}> is already stdin-backed`,
|
|
523
|
+
{
|
|
524
|
+
code: 'DUPLICATE_STDIN_ARG',
|
|
525
|
+
details: { arg: name, existingArg: existing.name },
|
|
526
|
+
suggest: 'Keep .stdin() on a single argument per command',
|
|
527
|
+
},
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// --- Flag collision validation
|
|
532
|
+
|
|
533
|
+
type FlagFormKind = 'canonical' | 'alias';
|
|
534
|
+
|
|
535
|
+
interface FlagForm {
|
|
536
|
+
readonly owner: string;
|
|
537
|
+
readonly name: string;
|
|
538
|
+
readonly kind: FlagFormKind;
|
|
539
|
+
readonly hidden: boolean;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function formatFlagToken(name: string, kind: FlagFormKind): string {
|
|
543
|
+
return kind === 'alias' && name.length === 1 ? `-${name}` : `--${name}`;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function describeFlagForm(form: FlagForm): string {
|
|
547
|
+
if (form.kind === 'canonical') {
|
|
548
|
+
return `canonical flag ${formatFlagToken(form.name, form.kind)}`;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const aliasType = form.name.length === 1 ? 'short alias' : 'long alias';
|
|
552
|
+
return `${form.hidden ? 'hidden ' : ''}${aliasType} ${formatFlagToken(form.name, form.kind)}`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function listFlagForms(name: string, schema: FlagSchema): readonly FlagForm[] {
|
|
556
|
+
return [
|
|
557
|
+
{
|
|
558
|
+
owner: name,
|
|
559
|
+
name,
|
|
560
|
+
kind: 'canonical',
|
|
561
|
+
hidden: false,
|
|
562
|
+
},
|
|
563
|
+
...schema.aliases.map((alias) => ({
|
|
564
|
+
owner: name,
|
|
565
|
+
name: alias.name,
|
|
566
|
+
kind: 'alias' as const,
|
|
567
|
+
hidden: alias.hidden,
|
|
568
|
+
})),
|
|
569
|
+
];
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function throwFlagCollisionError(
|
|
573
|
+
commandName: string,
|
|
574
|
+
form: FlagForm,
|
|
575
|
+
existing: FlagForm,
|
|
576
|
+
options?: { inherited?: boolean },
|
|
577
|
+
): never {
|
|
578
|
+
const inherited = options?.inherited ?? false;
|
|
579
|
+
const existingOwner = `flag ${formatFlagToken(existing.owner, 'canonical')}`;
|
|
580
|
+
const subject = `Command '${commandName}' ${existingOwner}`;
|
|
581
|
+
|
|
582
|
+
throw new CLIError(
|
|
583
|
+
inherited
|
|
584
|
+
? `${subject} propagates ${describeFlagForm(existing)}, which collides with ${describeFlagForm(form)} on flag ${formatFlagToken(form.owner, 'canonical')}`
|
|
585
|
+
: `Command '${commandName}' flag ${formatFlagToken(form.owner, 'canonical')} ${describeFlagForm(form)} collides with ${describeFlagForm(existing)} on ${existingOwner}`,
|
|
586
|
+
{
|
|
587
|
+
code: inherited ? 'PROPAGATED_FLAG_COLLISION' : 'FLAG_NAME_COLLISION',
|
|
588
|
+
details: {
|
|
589
|
+
command: commandName,
|
|
590
|
+
flag: form.owner,
|
|
591
|
+
surface: form.name,
|
|
592
|
+
surfaceKind: form.kind,
|
|
593
|
+
hidden: form.hidden,
|
|
594
|
+
existingFlag: existing.owner,
|
|
595
|
+
existingSurface: existing.name,
|
|
596
|
+
existingSurfaceKind: existing.kind,
|
|
597
|
+
existingHidden: existing.hidden,
|
|
598
|
+
inherited,
|
|
599
|
+
},
|
|
600
|
+
},
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function validateLocalFlagCollisions(
|
|
605
|
+
commandName: string,
|
|
606
|
+
flags: Readonly<Record<string, FlagSchema>>,
|
|
607
|
+
): void {
|
|
608
|
+
const seen = new Map<string, FlagForm>();
|
|
609
|
+
|
|
610
|
+
for (const [name, schema] of Object.entries(flags)) {
|
|
611
|
+
for (const form of listFlagForms(name, schema)) {
|
|
612
|
+
const existing = seen.get(form.name);
|
|
613
|
+
if (existing !== undefined) {
|
|
614
|
+
throwFlagCollisionError(commandName, form, existing);
|
|
615
|
+
}
|
|
616
|
+
seen.set(form.name, form);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function validateInheritedFlagCollisions(
|
|
622
|
+
commandName: string,
|
|
623
|
+
inherited: Readonly<Record<string, FlagSchema>>,
|
|
624
|
+
local: Readonly<Record<string, FlagSchema>>,
|
|
625
|
+
): void {
|
|
626
|
+
const inheritedForms = new Map<string, FlagForm>();
|
|
627
|
+
|
|
628
|
+
for (const [name, schema] of Object.entries(inherited)) {
|
|
629
|
+
for (const form of listFlagForms(name, schema)) {
|
|
630
|
+
inheritedForms.set(form.name, form);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
for (const [name, schema] of Object.entries(local)) {
|
|
635
|
+
for (const form of listFlagForms(name, schema)) {
|
|
636
|
+
const existing = inheritedForms.get(form.name);
|
|
637
|
+
if (existing !== undefined) {
|
|
638
|
+
throwFlagCollisionError(commandName, form, existing, { inherited: true });
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function buildInheritedFlagsForChildren(
|
|
645
|
+
inherited: Readonly<Record<string, FlagSchema>>,
|
|
646
|
+
local: Readonly<Record<string, FlagSchema>>,
|
|
647
|
+
): Readonly<Record<string, FlagSchema>> {
|
|
648
|
+
const next: Record<string, FlagSchema> = { ...inherited };
|
|
649
|
+
|
|
650
|
+
for (const name of Object.keys(local)) {
|
|
651
|
+
delete next[name];
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
for (const [name, schema] of Object.entries(local)) {
|
|
655
|
+
if (schema.propagate) {
|
|
656
|
+
next[name] = schema;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
return next;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function validateCommandFlagTree(
|
|
664
|
+
command: CommandSchema,
|
|
665
|
+
inheritedFlags: Readonly<Record<string, FlagSchema>> = {},
|
|
666
|
+
): void {
|
|
667
|
+
validateLocalFlagCollisions(command.name, command.flags);
|
|
668
|
+
|
|
669
|
+
const visibleInherited: Record<string, FlagSchema> = { ...inheritedFlags };
|
|
670
|
+
for (const name of Object.keys(command.flags)) {
|
|
671
|
+
delete visibleInherited[name];
|
|
672
|
+
}
|
|
673
|
+
validateInheritedFlagCollisions(command.name, visibleInherited, command.flags);
|
|
674
|
+
|
|
675
|
+
const inheritedForChildren = buildInheritedFlagsForChildren(inheritedFlags, command.flags);
|
|
676
|
+
for (const child of command.commands) {
|
|
677
|
+
validateCommandFlagTree(child, inheritedForChildren);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// --- Type-erased command interface (shared between schema and CLI layers)
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* A type-erased command entry for heterogeneous command storage.
|
|
685
|
+
*
|
|
686
|
+
* Advanced/internal bridge type: most consumers should work with
|
|
687
|
+
* {@link CommandBuilder} and never reference `ErasedCommand` directly.
|
|
688
|
+
*
|
|
689
|
+
* Commands registered via `CLIBuilder.command()` have heterogeneous `F`, `A`,
|
|
690
|
+
* and `C` type parameters. At the dispatch level we only need the runtime
|
|
691
|
+
* schema (for name/alias matching and help) and the ability to delegate to
|
|
692
|
+
* `runCommand()`. This interface captures exactly that contract.
|
|
693
|
+
*
|
|
694
|
+
* The `_execute` function closes over the original typed {@linkcode CommandBuilder},
|
|
695
|
+
* preserving full type safety inside the closure while presenting a
|
|
696
|
+
* uniform interface to the dispatcher.
|
|
697
|
+
*
|
|
698
|
+
* Defined here (rather than in the CLI layer) so both {@linkcode CommandBuilder} and
|
|
699
|
+
* `CLIBuilder` can reference it without circular imports.
|
|
700
|
+
*
|
|
701
|
+
* @internal
|
|
702
|
+
*/
|
|
703
|
+
interface ErasedCommand {
|
|
704
|
+
/** Runtime schema for name matching and help rendering. */
|
|
705
|
+
readonly schema: CommandSchema;
|
|
706
|
+
/**
|
|
707
|
+
* Nested subcommands (name/alias → erased child).
|
|
708
|
+
*
|
|
709
|
+
* Built recursively by `eraseCommand()` in the CLI layer.
|
|
710
|
+
* Empty map for leaf commands. The dispatch layer uses this for
|
|
711
|
+
* recursive command tree traversal.
|
|
712
|
+
*
|
|
713
|
+
* @internal
|
|
714
|
+
*/
|
|
715
|
+
readonly subcommands: ReadonlyMap<string, ErasedCommand>;
|
|
716
|
+
/** Original command builder captured at the type-erasure boundary. */
|
|
717
|
+
readonly _command?: AnyCommandBuilder;
|
|
718
|
+
/** Execute this command against argv. Closes over the typed CommandBuilder. */
|
|
719
|
+
readonly _execute: (argv: readonly string[], options?: RunOptions) => Promise<RunResult>;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Structural subset of {@linkcode CommandBuilder} consumed by the execution pipeline.
|
|
724
|
+
*
|
|
725
|
+
* Avoids generic type parameters so any `CommandBuilder<F, A, C>` satisfies
|
|
726
|
+
* this interface structurally — no variance constraints, no inference needed.
|
|
727
|
+
* Used by `runCommand()` and the shared executor to accept commands without
|
|
728
|
+
* requiring TypeScript to resolve {@linkcode CommandBuilder}'s full generic signature.
|
|
729
|
+
*
|
|
730
|
+
* @internal
|
|
731
|
+
*/
|
|
732
|
+
interface RunnableCommand {
|
|
733
|
+
readonly schema: CommandSchema;
|
|
734
|
+
readonly handler: ErasedActionHandler | undefined;
|
|
735
|
+
readonly _executionSteps: readonly ExecutionStep[];
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// --- Type-erased builder alias (for heterogeneous subcommand storage)
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
|
|
742
|
+
*
|
|
743
|
+
* Advanced helper alias: useful only when working on DreamCLI internals or
|
|
744
|
+
* custom tooling that mirrors the framework's type-erasure boundary.
|
|
745
|
+
*
|
|
746
|
+
* Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
|
|
747
|
+
* assignable. The CLI layer's `eraseCommand()` traverses these to build
|
|
748
|
+
* the execution tree.
|
|
749
|
+
*
|
|
750
|
+
* @internal
|
|
751
|
+
*/
|
|
752
|
+
type AnyCommandBuilder = CommandBuilder<
|
|
753
|
+
Record<string, FlagBuilder<FlagConfig>>,
|
|
754
|
+
Record<string, ArgBuilder<ArgConfig>>,
|
|
755
|
+
Record<string, unknown>
|
|
756
|
+
>;
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* Erase a typed `CommandBuilder<F, A, C>` to `AnyCommandBuilder` for
|
|
760
|
+
* heterogeneous storage. Centralises the `as unknown as` double-cast
|
|
761
|
+
* required at the type-erasure boundary.
|
|
762
|
+
*
|
|
763
|
+
* @internal
|
|
764
|
+
*/
|
|
765
|
+
function eraseBuilder<
|
|
766
|
+
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
767
|
+
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
768
|
+
C extends Record<string, unknown>,
|
|
769
|
+
>(builder: CommandBuilder<F, A, C>): AnyCommandBuilder {
|
|
770
|
+
return builder as unknown as AnyCommandBuilder;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// --- CommandBuilder — immutable builder with type-level tracking
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Immutable command schema builder.
|
|
777
|
+
*
|
|
778
|
+
* The type parameters `F` (flags), `A` (args), and `C` (context) are
|
|
779
|
+
* phantom types that accumulate builder types as `.flag()`, `.arg()`,
|
|
780
|
+
* `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
|
|
781
|
+
* fully typed `ActionParams<F, A, C>`.
|
|
782
|
+
*
|
|
783
|
+
* `C` defaults to `Record<string, never>`, making `ctx` property
|
|
784
|
+
* access a type error until derive or middleware extends it.
|
|
785
|
+
*
|
|
786
|
+
* @example
|
|
787
|
+
* ```ts
|
|
788
|
+
* const deploy = command('deploy')
|
|
789
|
+
* .description('Deploy to an environment')
|
|
790
|
+
* .arg('target', arg.string().describe('Deploy target'))
|
|
791
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
792
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
793
|
+
* .action(async ({ args, flags, out }) => {
|
|
794
|
+
* // args.target: string
|
|
795
|
+
* // flags.force: boolean
|
|
796
|
+
* // flags.region: 'us' | 'eu' | 'ap' | undefined
|
|
797
|
+
* out.log(`Deploying ${args.target}...`);
|
|
798
|
+
* });
|
|
799
|
+
* ```
|
|
800
|
+
*/
|
|
801
|
+
class CommandBuilder<
|
|
802
|
+
/* biome-ignore lint/complexity/noBannedTypes: {} is the correct initial accumulator for intersection-based type growth (F & Record<N, B>) */ // deno-lint-ignore ban-types
|
|
803
|
+
F extends Record<string, FlagBuilder<FlagConfig>> = {},
|
|
804
|
+
/* biome-ignore lint/complexity/noBannedTypes: {} is the correct initial accumulator for intersection-based type growth (A & Record<N, B>) */ // deno-lint-ignore ban-types
|
|
805
|
+
A extends Record<string, ArgBuilder<ArgConfig>> = {},
|
|
806
|
+
C extends Record<string, unknown> = Record<string, never>,
|
|
807
|
+
> {
|
|
808
|
+
/** @internal Runtime schema descriptor. */
|
|
809
|
+
readonly schema: CommandSchema;
|
|
810
|
+
|
|
811
|
+
/** @internal The action handler, if registered (type-erased for covariance). */
|
|
812
|
+
readonly handler: ErasedActionHandler | undefined;
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* @internal Nested sub-command builders (type-erased for heterogeneous storage).
|
|
816
|
+
*
|
|
817
|
+
* Stored separately from `schema.commands` because builders carry action
|
|
818
|
+
* handlers and phantom types needed by `eraseCommand()` in the CLI layer.
|
|
819
|
+
* `schema.commands` holds pure `CommandSchema[]` for help/completion.
|
|
820
|
+
*/
|
|
821
|
+
readonly _subcommands: readonly AnyCommandBuilder[];
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* @internal Execution steps in registration order.
|
|
825
|
+
*
|
|
826
|
+
* Distinct from `schema.middleware`: middleware handlers remain in schema
|
|
827
|
+
* for backward compatibility, while derives stay command-local and builder-
|
|
828
|
+
* scoped so future shared/global middleware can compose cleanly.
|
|
829
|
+
*/
|
|
830
|
+
readonly _executionSteps: readonly ExecutionStep[];
|
|
831
|
+
|
|
832
|
+
/** @internal Phantom brand for accumulated flag builder types. No runtime value. */
|
|
833
|
+
declare readonly _flags: F;
|
|
834
|
+
/** @internal Phantom brand for accumulated arg builder types. No runtime value. */
|
|
835
|
+
declare readonly _args: A;
|
|
836
|
+
/** @internal Phantom brand for accumulated context type. No runtime value. */
|
|
837
|
+
declare readonly _ctx: C;
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Create a command builder from a pre-built schema descriptor.
|
|
841
|
+
*
|
|
842
|
+
* @param schema - Runtime command descriptor.
|
|
843
|
+
* @param handler - Action handler, if registered.
|
|
844
|
+
* @param subcommands - Nested sub-command builders (type-erased).
|
|
845
|
+
* @param executionSteps - Derive/middleware steps in registration order.
|
|
846
|
+
*/
|
|
847
|
+
constructor(
|
|
848
|
+
schema: CommandSchema,
|
|
849
|
+
handler?: ErasedActionHandler,
|
|
850
|
+
subcommands?: readonly AnyCommandBuilder[],
|
|
851
|
+
executionSteps?: readonly ExecutionStep[],
|
|
852
|
+
) {
|
|
853
|
+
this.schema = schema;
|
|
854
|
+
this.handler = handler;
|
|
855
|
+
this._subcommands = subcommands ?? [];
|
|
856
|
+
this._executionSteps = executionSteps ?? [];
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// -- Interactive resolver ------------------------------------------------
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* Register a command-level interactive resolver for schema-driven prompts.
|
|
863
|
+
*
|
|
864
|
+
* The resolver is called after CLI/env/config resolution with partially
|
|
865
|
+
* resolved flag values. It returns a prompt schema for flags that need
|
|
866
|
+
* interactive input based on the current state.
|
|
867
|
+
*
|
|
868
|
+
* For flags the resolver returns a {@linkcode PromptConfig}, that config is used
|
|
869
|
+
* instead of any per-flag `.prompt()` config. For flags returned as falsy
|
|
870
|
+
* (or not mentioned), per-flag `.prompt()` configs are used as fallback.
|
|
871
|
+
*
|
|
872
|
+
* Commands without `.interactive()` use per-flag prompt configs directly.
|
|
873
|
+
*
|
|
874
|
+
* @example
|
|
875
|
+
* ```ts
|
|
876
|
+
* const deploy = command('deploy')
|
|
877
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
878
|
+
* .flag('force', flag.boolean())
|
|
879
|
+
* .interactive(({ flags }) => ({
|
|
880
|
+
* region: !flags.region && {
|
|
881
|
+
* kind: 'select',
|
|
882
|
+
* message: 'Select region',
|
|
883
|
+
* },
|
|
884
|
+
* }))
|
|
885
|
+
* .action(({ flags }) => { ... });
|
|
886
|
+
* ```
|
|
887
|
+
*
|
|
888
|
+
* @param resolver - Function receiving partially resolved flags and returning prompt configs.
|
|
889
|
+
* @returns The builder (for chaining).
|
|
890
|
+
*/
|
|
891
|
+
interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C> {
|
|
892
|
+
// The resolver is type-erased for storage on CommandSchema.
|
|
893
|
+
// At runtime, `InteractiveResolver<F>` is just `(params: { flags }) => Record<...>`.
|
|
894
|
+
// The phantom types on F are erased — the resolver's runtime behaviour is
|
|
895
|
+
// identical to `ErasedInteractiveResolver`.
|
|
896
|
+
const erased = resolver as unknown as ErasedInteractiveResolver;
|
|
897
|
+
return new CommandBuilder(
|
|
898
|
+
{ ...this.schema, interactive: erased },
|
|
899
|
+
this.handler,
|
|
900
|
+
this._subcommands,
|
|
901
|
+
this._executionSteps,
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// -- Derive --------------------------------------------------------------
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Register a command-scoped typed pre-action handler.
|
|
909
|
+
*
|
|
910
|
+
* Derive runs after full resolution and before the action handler.
|
|
911
|
+
* It receives typed `{ args, flags, ctx, out, meta }` and may either:
|
|
912
|
+
*
|
|
913
|
+
* - return `undefined` for validation-only behavior
|
|
914
|
+
* - return an object to merge additional properties into `ctx`
|
|
915
|
+
*
|
|
916
|
+
* Unlike middleware, derive cannot wrap downstream execution and does not
|
|
917
|
+
* use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
|
|
918
|
+
* or error-boundary patterns.
|
|
919
|
+
*
|
|
920
|
+
* Adding derive drops the current handler (like `.flag()`, `.arg()`, and
|
|
921
|
+
* `.middleware()`) because the action handler's `ctx` type may change.
|
|
922
|
+
*
|
|
923
|
+
* @example
|
|
924
|
+
* ```ts
|
|
925
|
+
* command('deploy')
|
|
926
|
+
* .flag('token', flag.string().env('AUTH_TOKEN'))
|
|
927
|
+
* .derive(({ flags }) => {
|
|
928
|
+
* if (!flags.token) {
|
|
929
|
+
* throw new CLIError('Not authenticated', {
|
|
930
|
+
* code: 'AUTH_REQUIRED',
|
|
931
|
+
* suggest: 'Run `mycli login` or set AUTH_TOKEN',
|
|
932
|
+
* });
|
|
933
|
+
* }
|
|
934
|
+
* return { token: flags.token };
|
|
935
|
+
* })
|
|
936
|
+
* .action(({ ctx }) => {
|
|
937
|
+
* ctx.token; // string
|
|
938
|
+
* });
|
|
939
|
+
* ```
|
|
940
|
+
*
|
|
941
|
+
* @param handler - Derive function receiving typed args/flags/ctx.
|
|
942
|
+
* @returns The builder (for chaining).
|
|
943
|
+
*/
|
|
944
|
+
derive<Output extends Record<string, unknown> | undefined>(
|
|
945
|
+
handler: DeriveHandler<F, A, C, Output>,
|
|
946
|
+
): CommandBuilder<F, A, WidenDerivedContext<C, Output>> {
|
|
947
|
+
const erased = handler as unknown as ErasedDeriveHandler;
|
|
948
|
+
return new CommandBuilder<F, A, WidenDerivedContext<C, Output>>(
|
|
949
|
+
{ ...this.schema, hasAction: false },
|
|
950
|
+
undefined,
|
|
951
|
+
this._subcommands,
|
|
952
|
+
[
|
|
953
|
+
...this._executionSteps,
|
|
954
|
+
{
|
|
955
|
+
kind: 'derive',
|
|
956
|
+
handler: erased,
|
|
957
|
+
},
|
|
958
|
+
],
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// -- Middleware ----------------------------------------------------------
|
|
963
|
+
|
|
964
|
+
/**
|
|
965
|
+
* Register middleware to run before the action handler.
|
|
966
|
+
*
|
|
967
|
+
* Middleware executes in registration order. Each middleware receives
|
|
968
|
+
* `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
|
|
969
|
+
* to continue the chain. Context additions are merged and become
|
|
970
|
+
* typed downstream.
|
|
971
|
+
*
|
|
972
|
+
* Adding middleware widens `C` via intersection and drops the current
|
|
973
|
+
* handler (like `.flag()` / `.arg()` — the handler's type signature
|
|
974
|
+
* changes when context changes).
|
|
975
|
+
*
|
|
976
|
+
* @example
|
|
977
|
+
* ```ts
|
|
978
|
+
* import { CLIError, command, middleware } from '@kjanat/dreamcli';
|
|
979
|
+
*
|
|
980
|
+
* interface User {
|
|
981
|
+
* id: string;
|
|
982
|
+
* email: string;
|
|
983
|
+
* }
|
|
984
|
+
*
|
|
985
|
+
* async function getCurrentUser(): Promise<User | null> {
|
|
986
|
+
* return { id: 'u_123', email: 'dev@example.com' };
|
|
987
|
+
* }
|
|
988
|
+
*
|
|
989
|
+
* function startTrace(name: string): string {
|
|
990
|
+
* return `trace:${name}`;
|
|
991
|
+
* }
|
|
992
|
+
*
|
|
993
|
+
* // Resolve the current user and expose it as `ctx.user` downstream.
|
|
994
|
+
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
995
|
+
* const user = await getCurrentUser();
|
|
996
|
+
* if (!user) {
|
|
997
|
+
* throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
998
|
+
* }
|
|
999
|
+
* await next({ user });
|
|
1000
|
+
* });
|
|
1001
|
+
*
|
|
1002
|
+
* // Create a trace id for this command run and expose it as `ctx.traceId`.
|
|
1003
|
+
* const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
|
|
1004
|
+
* const traceId = startTrace(`${meta.name}.${meta.command}`);
|
|
1005
|
+
* await next({ traceId });
|
|
1006
|
+
* });
|
|
1007
|
+
*
|
|
1008
|
+
* command('deploy')
|
|
1009
|
+
* .middleware(auth) // C becomes { user: User }
|
|
1010
|
+
* .middleware(telemetry) // C becomes { user: User } & { traceId: string }
|
|
1011
|
+
* .action(({ ctx }) => {
|
|
1012
|
+
* ctx.user; // User — typed
|
|
1013
|
+
* ctx.traceId; // string — typed
|
|
1014
|
+
* });
|
|
1015
|
+
* ```
|
|
1016
|
+
*
|
|
1017
|
+
* @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
|
|
1018
|
+
* Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
|
|
1019
|
+
* @returns The builder (for chaining).
|
|
1020
|
+
*/
|
|
1021
|
+
middleware<Output extends Record<string, unknown>>(
|
|
1022
|
+
m: Middleware<Output>,
|
|
1023
|
+
): CommandBuilder<F, A, WidenContext<C, Output>> {
|
|
1024
|
+
return new CommandBuilder(
|
|
1025
|
+
{
|
|
1026
|
+
...this.schema,
|
|
1027
|
+
middleware: [...this.schema.middleware, m._handler],
|
|
1028
|
+
hasAction: false,
|
|
1029
|
+
},
|
|
1030
|
+
// Handler intentionally dropped — C changed, invalidating handler signature.
|
|
1031
|
+
undefined,
|
|
1032
|
+
this._subcommands,
|
|
1033
|
+
[
|
|
1034
|
+
...this._executionSteps,
|
|
1035
|
+
{
|
|
1036
|
+
kind: 'middleware',
|
|
1037
|
+
handler: m._handler,
|
|
1038
|
+
},
|
|
1039
|
+
],
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// -- Metadata modifiers --------------------------------------------------
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Set the command's description for help text.
|
|
1047
|
+
*
|
|
1048
|
+
* Displayed below the usage line in `--help` output and next to the
|
|
1049
|
+
* command name in parent command/group help listings.
|
|
1050
|
+
*
|
|
1051
|
+
* @param text - One-line description of what the command does.
|
|
1052
|
+
*
|
|
1053
|
+
* @example
|
|
1054
|
+
* ```ts
|
|
1055
|
+
* command('deploy')
|
|
1056
|
+
* .description('Deploy the application to a target environment')
|
|
1057
|
+
* .action(({ out }) => { out.log('deploying...'); });
|
|
1058
|
+
*
|
|
1059
|
+
* // $ mycli deploy --help
|
|
1060
|
+
* // Usage: deploy [flags]
|
|
1061
|
+
* //
|
|
1062
|
+
* // Deploy the application to a target environment
|
|
1063
|
+
* ```
|
|
1064
|
+
*
|
|
1065
|
+
* @returns The builder (for chaining).
|
|
1066
|
+
*/
|
|
1067
|
+
description(text: string): CommandBuilder<F, A, C> {
|
|
1068
|
+
return new CommandBuilder(
|
|
1069
|
+
{ ...this.schema, description: text },
|
|
1070
|
+
this.handler,
|
|
1071
|
+
this._subcommands,
|
|
1072
|
+
this._executionSteps,
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* Add an alternative name for this command.
|
|
1078
|
+
*
|
|
1079
|
+
* Aliases are accepted during dispatch alongside the primary name.
|
|
1080
|
+
* Multiple aliases can be chained. Aliases are shown in help output.
|
|
1081
|
+
*
|
|
1082
|
+
* @param name - Alternative command name (e.g. `'d'` for `deploy`).
|
|
1083
|
+
*
|
|
1084
|
+
* @example
|
|
1085
|
+
* ```ts
|
|
1086
|
+
* command('deploy')
|
|
1087
|
+
* .alias('d')
|
|
1088
|
+
* .alias('push')
|
|
1089
|
+
* .action(({ out }) => { out.log('deploying...'); });
|
|
1090
|
+
*
|
|
1091
|
+
* // All equivalent:
|
|
1092
|
+
* // $ mycli deploy
|
|
1093
|
+
* // $ mycli d
|
|
1094
|
+
* // $ mycli push
|
|
1095
|
+
* ```
|
|
1096
|
+
*
|
|
1097
|
+
* @returns The builder (for chaining).
|
|
1098
|
+
*/
|
|
1099
|
+
alias(name: string): CommandBuilder<F, A, C> {
|
|
1100
|
+
return new CommandBuilder(
|
|
1101
|
+
{ ...this.schema, aliases: [...this.schema.aliases, name] },
|
|
1102
|
+
this.handler,
|
|
1103
|
+
this._subcommands,
|
|
1104
|
+
this._executionSteps,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* Hide this command from help listings.
|
|
1110
|
+
*
|
|
1111
|
+
* The command remains fully functional and dispatchable — it just
|
|
1112
|
+
* won't appear in `--help` output or shell completions. Useful for
|
|
1113
|
+
* internal/debug commands.
|
|
1114
|
+
*
|
|
1115
|
+
* @example
|
|
1116
|
+
* ```ts
|
|
1117
|
+
* command('debug-dump')
|
|
1118
|
+
* .hidden()
|
|
1119
|
+
* .action(({ out }) => { out.log(JSON.stringify(internalState)); });
|
|
1120
|
+
*
|
|
1121
|
+
* // $ mycli --help → 'debug-dump' is not listed
|
|
1122
|
+
* // $ mycli debug-dump → still works
|
|
1123
|
+
* ```
|
|
1124
|
+
*
|
|
1125
|
+
* @returns The builder (for chaining).
|
|
1126
|
+
*/
|
|
1127
|
+
hidden(): CommandBuilder<F, A, C> {
|
|
1128
|
+
return new CommandBuilder(
|
|
1129
|
+
{ ...this.schema, hidden: true },
|
|
1130
|
+
this.handler,
|
|
1131
|
+
this._subcommands,
|
|
1132
|
+
this._executionSteps,
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* Add a usage example to help text.
|
|
1138
|
+
*
|
|
1139
|
+
* Examples are rendered in the "Examples:" section of `--help` output.
|
|
1140
|
+
* Call multiple times to add several examples. Each example shows a
|
|
1141
|
+
* shell invocation, optionally with a description.
|
|
1142
|
+
*
|
|
1143
|
+
* @param cmd - The example command line (without the program name prefix).
|
|
1144
|
+
* @param description - Optional one-line explanation of what the example does.
|
|
1145
|
+
*
|
|
1146
|
+
* @example
|
|
1147
|
+
* ```ts
|
|
1148
|
+
* command('deploy')
|
|
1149
|
+
* .arg('target', arg.string())
|
|
1150
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
1151
|
+
* .example('deploy production', 'Deploy to production')
|
|
1152
|
+
* .example('deploy staging -f', 'Force deploy to staging')
|
|
1153
|
+
* .action(({ args, flags }) => { ... });
|
|
1154
|
+
*
|
|
1155
|
+
* // $ mycli deploy --help
|
|
1156
|
+
* // ...
|
|
1157
|
+
* // Examples:
|
|
1158
|
+
* // deploy production Deploy to production
|
|
1159
|
+
* // deploy staging -f Force deploy to staging
|
|
1160
|
+
* ```
|
|
1161
|
+
*
|
|
1162
|
+
* @returns The builder (for chaining).
|
|
1163
|
+
*/
|
|
1164
|
+
example(cmd: string, description?: string): CommandBuilder<F, A, C> {
|
|
1165
|
+
const entry: CommandExample =
|
|
1166
|
+
description !== undefined ? { command: cmd, description } : { command: cmd };
|
|
1167
|
+
return new CommandBuilder(
|
|
1168
|
+
{ ...this.schema, examples: [...this.schema.examples, entry] },
|
|
1169
|
+
this.handler,
|
|
1170
|
+
this._subcommands,
|
|
1171
|
+
this._executionSteps,
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// -- Flag accumulation ---------------------------------------------------
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Register a named flag on this command.
|
|
1179
|
+
*
|
|
1180
|
+
* The flag name is added to the type-level `F` map. Duplicate flag names
|
|
1181
|
+
* are prevented at the type level via the `Exclude` constraint.
|
|
1182
|
+
*
|
|
1183
|
+
* The builder controls the flag's type, presence, aliases, env/config
|
|
1184
|
+
* bindings, and description. See {@link FlagBuilder} for available modifiers.
|
|
1185
|
+
*
|
|
1186
|
+
* @param name - Flag name (used as `--name` on CLI and `flags.*` in handler).
|
|
1187
|
+
* @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
|
|
1188
|
+
* `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
|
|
1189
|
+
*
|
|
1190
|
+
* @example
|
|
1191
|
+
* ```ts
|
|
1192
|
+
* command('serve')
|
|
1193
|
+
* .flag('port', flag.number()
|
|
1194
|
+
* .alias('p')
|
|
1195
|
+
* .env('PORT')
|
|
1196
|
+
* .default(3000)
|
|
1197
|
+
* .describe('Port to listen on'))
|
|
1198
|
+
* .flag('host', flag.string()
|
|
1199
|
+
* .env('HOST')
|
|
1200
|
+
* .default('localhost')
|
|
1201
|
+
* .describe('Bind address'))
|
|
1202
|
+
* .flag('verbose', flag.boolean()
|
|
1203
|
+
* .alias('v')
|
|
1204
|
+
* .describe('Enable verbose logging'))
|
|
1205
|
+
* .action(({ flags, out }) => {
|
|
1206
|
+
* flags.port; // number
|
|
1207
|
+
* flags.host; // string
|
|
1208
|
+
* flags.verbose; // boolean
|
|
1209
|
+
* out.log(`Listening on ${flags.host}:${flags.port}`);
|
|
1210
|
+
* });
|
|
1211
|
+
*
|
|
1212
|
+
* // $ mycli serve --port 8080 -v
|
|
1213
|
+
* // $ PORT=9090 mycli serve
|
|
1214
|
+
* ```
|
|
1215
|
+
*
|
|
1216
|
+
* @returns The builder (for chaining).
|
|
1217
|
+
*/
|
|
1218
|
+
flag<N extends string, B extends FlagBuilder<FlagConfig>>(
|
|
1219
|
+
name: N & Exclude<N, keyof F>,
|
|
1220
|
+
builder: B,
|
|
1221
|
+
): CommandBuilder<F & Record<N, B>, A, C> {
|
|
1222
|
+
if (name in this.schema.flags) {
|
|
1223
|
+
throw new CLIError(`Command '${this.schema.name}' already defines flag --${name}`, {
|
|
1224
|
+
code: 'FLAG_NAME_COLLISION',
|
|
1225
|
+
details: { command: this.schema.name, flag: name, surface: name, surfaceKind: 'canonical' },
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
const nextFlags = { ...this.schema.flags, [name]: builder.schema };
|
|
1230
|
+
const nextSchema = { ...this.schema, flags: nextFlags, hasAction: false };
|
|
1231
|
+
validateCommandFlagTree(nextSchema);
|
|
1232
|
+
return new CommandBuilder(
|
|
1233
|
+
nextSchema,
|
|
1234
|
+
// handler is intentionally dropped — adding a flag invalidates
|
|
1235
|
+
// the previous handler's type signature
|
|
1236
|
+
undefined,
|
|
1237
|
+
this._subcommands,
|
|
1238
|
+
this._executionSteps,
|
|
1239
|
+
);
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
// -- Arg accumulation ----------------------------------------------------
|
|
1243
|
+
|
|
1244
|
+
/**
|
|
1245
|
+
* Register a named positional argument on this command.
|
|
1246
|
+
*
|
|
1247
|
+
* Args are ordered by registration — position on the CLI matches the
|
|
1248
|
+
* order of `.arg()` calls. The arg name is added to the type-level `A`
|
|
1249
|
+
* map. Duplicate arg names are prevented at the type level via the
|
|
1250
|
+
* `Exclude` constraint.
|
|
1251
|
+
*
|
|
1252
|
+
* The builder controls the arg's type, presence, env binding, and
|
|
1253
|
+
* description. See {@link ArgBuilder} for available modifiers.
|
|
1254
|
+
*
|
|
1255
|
+
* @param name - Positional arg name (used in help text and `args.*`).
|
|
1256
|
+
* @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
|
|
1257
|
+
* or `arg.custom()`.
|
|
1258
|
+
*
|
|
1259
|
+
* @example
|
|
1260
|
+
* ```ts
|
|
1261
|
+
* command('deploy')
|
|
1262
|
+
* // Required string arg — first positional
|
|
1263
|
+
* .arg('target', arg.string()
|
|
1264
|
+
* .env('DEPLOY_TARGET')
|
|
1265
|
+
* .describe('Deploy target'))
|
|
1266
|
+
* // Optional number arg — second positional
|
|
1267
|
+
* .arg('port', arg.number()
|
|
1268
|
+
* .env('PORT')
|
|
1269
|
+
* .default(3000)
|
|
1270
|
+
* .describe('Port number'))
|
|
1271
|
+
* .action(({ args }) => {
|
|
1272
|
+
* args.target; // string
|
|
1273
|
+
* args.port; // number
|
|
1274
|
+
* });
|
|
1275
|
+
*
|
|
1276
|
+
* // Usage: deploy [flags] <target> [port]
|
|
1277
|
+
* // $ mycli deploy production 8080
|
|
1278
|
+
* // $ DEPLOY_TARGET=staging mycli deploy
|
|
1279
|
+
* ```
|
|
1280
|
+
*
|
|
1281
|
+
* @returns The builder (for chaining).
|
|
1282
|
+
*/
|
|
1283
|
+
arg<N extends string, B extends ArgBuilder<ArgConfig>>(
|
|
1284
|
+
name: N & Exclude<N, keyof A>,
|
|
1285
|
+
builder: B,
|
|
1286
|
+
): CommandBuilder<F, A & Record<N, B>, C> {
|
|
1287
|
+
validateArgEntry(name, builder.schema, this.schema.args);
|
|
1288
|
+
const entry: CommandArgEntry = { name, schema: builder.schema };
|
|
1289
|
+
const nextArgs = [...this.schema.args, entry];
|
|
1290
|
+
return new CommandBuilder(
|
|
1291
|
+
{ ...this.schema, args: nextArgs, hasAction: false },
|
|
1292
|
+
// handler is intentionally dropped — adding an arg invalidates
|
|
1293
|
+
// the previous handler's type signature
|
|
1294
|
+
undefined,
|
|
1295
|
+
this._subcommands,
|
|
1296
|
+
this._executionSteps,
|
|
1297
|
+
);
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// -- Subcommand nesting --------------------------------------------------
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* Register a nested subcommand on this command.
|
|
1304
|
+
*
|
|
1305
|
+
* The subcommand's builder is stored in `_subcommands` for the CLI layer's
|
|
1306
|
+
* `eraseCommand()` to traverse when building the execution tree. The
|
|
1307
|
+
* subcommand's `CommandSchema` is also appended to `schema.commands` for
|
|
1308
|
+
* help rendering and completion generation.
|
|
1309
|
+
*
|
|
1310
|
+
* Does not change `F`, `A`, or `C` — subcommands are type-erased at the
|
|
1311
|
+
* parent level (same semantics as `CLIBuilder.command()`). The handler is
|
|
1312
|
+
* preserved.
|
|
1313
|
+
*
|
|
1314
|
+
* @example
|
|
1315
|
+
* ```ts
|
|
1316
|
+
* const db = group('db')
|
|
1317
|
+
* .description('Database operations')
|
|
1318
|
+
* .command(migrateCmd)
|
|
1319
|
+
* .command(seedCmd);
|
|
1320
|
+
* ```
|
|
1321
|
+
*
|
|
1322
|
+
* @param sub - Child {@link CommandBuilder} to nest under this command.
|
|
1323
|
+
* @returns The builder (for chaining).
|
|
1324
|
+
*/
|
|
1325
|
+
command<
|
|
1326
|
+
F2 extends Record<string, FlagBuilder<FlagConfig>>,
|
|
1327
|
+
A2 extends Record<string, ArgBuilder<ArgConfig>>,
|
|
1328
|
+
C2 extends Record<string, unknown>,
|
|
1329
|
+
>(sub: CommandBuilder<F2, A2, C2>): CommandBuilder<F, A, C> {
|
|
1330
|
+
const nextSchema = {
|
|
1331
|
+
...this.schema,
|
|
1332
|
+
commands: [...this.schema.commands, sub.schema],
|
|
1333
|
+
};
|
|
1334
|
+
validateCommandFlagTree(nextSchema);
|
|
1335
|
+
return new CommandBuilder(
|
|
1336
|
+
nextSchema,
|
|
1337
|
+
this.handler,
|
|
1338
|
+
[...this._subcommands, eraseBuilder(sub)],
|
|
1339
|
+
this._executionSteps,
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// -- Action handler ------------------------------------------------------
|
|
1344
|
+
|
|
1345
|
+
/**
|
|
1346
|
+
* Register the action handler for this command.
|
|
1347
|
+
*
|
|
1348
|
+
* The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
|
|
1349
|
+
* from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
|
|
1350
|
+
* definitions.
|
|
1351
|
+
*
|
|
1352
|
+
* May be synchronous or async. Return values are ignored; command handlers
|
|
1353
|
+
* communicate through `out`, thrown errors, and side effects.
|
|
1354
|
+
*
|
|
1355
|
+
* @param handler - Function receiving `ActionParams<F, A, C>`.
|
|
1356
|
+
*
|
|
1357
|
+
* @example
|
|
1358
|
+
* ```ts
|
|
1359
|
+
* // Minimal
|
|
1360
|
+
* command('greet')
|
|
1361
|
+
* .arg('name', arg.string())
|
|
1362
|
+
* .action(({ args, out }) => {
|
|
1363
|
+
* out.log(`Hello, ${args.name}!`);
|
|
1364
|
+
* });
|
|
1365
|
+
* ```
|
|
1366
|
+
*
|
|
1367
|
+
* @example
|
|
1368
|
+
* ```ts
|
|
1369
|
+
* // Full params — flags, args, context, output, metadata
|
|
1370
|
+
* command('deploy')
|
|
1371
|
+
* .arg('target', arg.string().env('DEPLOY_TARGET'))
|
|
1372
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
1373
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
|
|
1374
|
+
* .middleware(auth)
|
|
1375
|
+
* .action(async ({ args, flags, ctx, out, meta }) => {
|
|
1376
|
+
* args.target; // string
|
|
1377
|
+
* flags.force; // boolean
|
|
1378
|
+
* flags.region; // 'us' | 'eu' | 'ap' | undefined
|
|
1379
|
+
* ctx.user; // User (from auth middleware)
|
|
1380
|
+
* meta.command; // string
|
|
1381
|
+
*
|
|
1382
|
+
* const spinner = out.spinner('Deploying...');
|
|
1383
|
+
* await deploy(args.target, { force: flags.force });
|
|
1384
|
+
* spinner.stop();
|
|
1385
|
+
* out.log('Done');
|
|
1386
|
+
* });
|
|
1387
|
+
* ```
|
|
1388
|
+
*
|
|
1389
|
+
* @returns The builder (for chaining).
|
|
1390
|
+
*/
|
|
1391
|
+
action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C> {
|
|
1392
|
+
return new CommandBuilder(
|
|
1393
|
+
{ ...this.schema, hasAction: true },
|
|
1394
|
+
handler as unknown as ErasedActionHandler,
|
|
1395
|
+
this._subcommands,
|
|
1396
|
+
this._executionSteps,
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// --- Factory function
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* Create a new command builder.
|
|
1405
|
+
*
|
|
1406
|
+
* @param name - The command name used for dispatch (e.g. `'deploy'`).
|
|
1407
|
+
*
|
|
1408
|
+
* @example
|
|
1409
|
+
* ```ts
|
|
1410
|
+
* import { arg, command, flag } from '@kjanat/dreamcli';
|
|
1411
|
+
*
|
|
1412
|
+
* const greet = command('greet')
|
|
1413
|
+
* .arg('name', arg.string())
|
|
1414
|
+
* .flag('loud', flag.boolean())
|
|
1415
|
+
* .action(({ args, flags, out }) => {
|
|
1416
|
+
* const msg = `Hello, ${args.name}!`;
|
|
1417
|
+
* out.log(flags.loud ? msg.toUpperCase() : msg);
|
|
1418
|
+
* });
|
|
1419
|
+
* ```
|
|
1420
|
+
*
|
|
1421
|
+
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
1422
|
+
*/
|
|
1423
|
+
function command(name: string): CommandBuilder {
|
|
1424
|
+
return new CommandBuilder({
|
|
1425
|
+
name,
|
|
1426
|
+
description: undefined,
|
|
1427
|
+
aliases: [],
|
|
1428
|
+
hidden: false,
|
|
1429
|
+
examples: [],
|
|
1430
|
+
flags: {},
|
|
1431
|
+
args: [],
|
|
1432
|
+
hasAction: false,
|
|
1433
|
+
interactive: undefined,
|
|
1434
|
+
middleware: [],
|
|
1435
|
+
commands: [],
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* Create a command builder intended for use as a command group.
|
|
1441
|
+
*
|
|
1442
|
+
* Semantically identical to {@linkcode command | command()} — a group is simply a command that
|
|
1443
|
+
* has subcommands registered via `.command()`. The separate factory
|
|
1444
|
+
* communicates intent: groups organise subcommands, leaf commands have actions.
|
|
1445
|
+
*
|
|
1446
|
+
* A group may also have its own `.action()` (e.g. `git remote` lists remotes
|
|
1447
|
+
* when invoked without a subcommand, but dispatches to `git remote add`, etc.).
|
|
1448
|
+
*
|
|
1449
|
+
* @param name - The group name used for dispatch (e.g. `'db'`).
|
|
1450
|
+
*
|
|
1451
|
+
* @example
|
|
1452
|
+
* ```ts
|
|
1453
|
+
* const db = group('db')
|
|
1454
|
+
* .description('Database operations')
|
|
1455
|
+
* .command(migrateCmd)
|
|
1456
|
+
* .command(seedCmd);
|
|
1457
|
+
* ```
|
|
1458
|
+
*
|
|
1459
|
+
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
1460
|
+
*/
|
|
1461
|
+
function group(name: string): CommandBuilder {
|
|
1462
|
+
return command(name);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// --- Exports
|
|
1466
|
+
|
|
1467
|
+
export type {
|
|
1468
|
+
ActionHandler,
|
|
1469
|
+
ActionParams,
|
|
1470
|
+
AnyCommandBuilder,
|
|
1471
|
+
CommandArgEntry,
|
|
1472
|
+
CommandConfig,
|
|
1473
|
+
CommandExample,
|
|
1474
|
+
CommandMeta,
|
|
1475
|
+
CommandSchema,
|
|
1476
|
+
DeriveHandler,
|
|
1477
|
+
DeriveParams,
|
|
1478
|
+
ErasedActionHandler,
|
|
1479
|
+
ErasedCommand,
|
|
1480
|
+
ErasedDeriveHandler,
|
|
1481
|
+
ErasedInteractiveResolver,
|
|
1482
|
+
InteractiveParams,
|
|
1483
|
+
InteractiveResolver,
|
|
1484
|
+
InteractiveResult,
|
|
1485
|
+
Out,
|
|
1486
|
+
RunnableCommand,
|
|
1487
|
+
WidenContext,
|
|
1488
|
+
WidenDerivedContext,
|
|
1489
|
+
};
|
|
1490
|
+
export { CommandBuilder, command, group };
|