@kjanat/dreamcli 1.0.0 → 2.0.1
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 +63 -6
- package/LICENSE +1 -1
- package/README.md +296 -164
- 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 -920
- package/dist/index.mjs +1 -10
- package/dist/runtime/adapter.d.mts +212 -0
- package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
- 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 +6 -252
- package/dist/runtime.mjs +1 -1
- package/dist/testkit.d.mts +5 -24
- package/dist/testkit.mjs +1 -1
- package/dist/version.d.mts +16 -0
- package/dist/version.mjs +1 -0
- package/dreamcli.schema.json +338 -0
- package/examples/basic.ts +2 -2
- package/examples/gh/package.json +7 -11
- package/examples/gh/src/commands/auth.ts +2 -2
- package/examples/gh/src/commands/issue.ts +4 -4
- package/examples/gh/src/commands/pr.ts +4 -4
- package/examples/gh/src/docs.ts +11 -0
- package/examples/gh/src/lib/auth.ts +1 -1
- package/examples/gh/src/main.test.ts +6 -5
- package/examples/gh/src/main.ts +8 -6
- package/examples/interactive.ts +3 -3
- package/examples/json-mode.ts +4 -6
- package/examples/middleware.ts +3 -3
- package/examples/multi-command.ts +3 -3
- package/examples/spinner-progress.ts +5 -5
- package/examples/testing.ts +8 -6
- package/package.json +70 -44
- package/src/core/cli/dispatch.ts +4 -0
- package/src/core/cli/index.ts +185 -632
- package/src/core/cli/planner.ts +413 -0
- package/src/core/cli/plugin.ts +7 -1
- package/src/core/cli/propagate.ts +1 -1
- package/src/core/cli/runtime-preflight.ts +409 -0
- package/src/core/completion/index.ts +15 -9
- package/src/core/completion/shells/bash.ts +6 -3
- package/src/core/completion/shells/fish.ts +245 -10
- package/src/core/completion/shells/powershell.ts +390 -9
- package/src/core/completion/shells/shared.ts +4 -4
- package/src/core/completion/shells/zsh.ts +12 -7
- package/src/core/config/index.ts +7 -4
- package/src/core/config/package-json.ts +6 -2
- package/src/core/errors/index.ts +23 -8
- package/src/core/execution/index.ts +270 -0
- package/src/core/help/index.ts +13 -15
- package/src/core/json-schema/index.ts +193 -7
- package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
- package/src/core/output/contracts.ts +194 -0
- package/src/core/output/index.ts +47 -82
- package/src/core/output/renderers.ts +125 -0
- package/src/core/parse/index.ts +39 -21
- package/src/core/prompt/index.ts +44 -27
- 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 +41 -1264
- package/src/core/resolve/property.ts +99 -0
- package/src/core/schema/activity.ts +3 -0
- package/src/core/schema/arg.ts +26 -14
- package/src/core/schema/command.ts +265 -38
- package/src/core/schema/flag.ts +120 -15
- package/src/core/schema/index.ts +11 -2
- package/src/core/schema/middleware.ts +6 -6
- package/src/core/schema/prompt.ts +9 -1
- package/src/core/schema/run.ts +25 -17
- 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 +55 -297
- package/src/index.ts +10 -4
- package/src/runtime/adapter.ts +13 -10
- package/src/runtime/auto.ts +3 -3
- package/src/runtime/bun.ts +4 -4
- package/src/runtime/deno.ts +43 -29
- package/src/runtime/detect.ts +4 -1
- package/src/runtime/index.ts +1 -1
- package/src/runtime/node.ts +43 -21
- package/src/runtime/paths.ts +9 -3
- package/src/runtime/support.ts +20 -4
- package/src/runtime.ts +1 -1
- package/src/testkit.ts +10 -8
- package/dist/adapter-CCSh5juX.cjs +0 -1
- package/dist/adapter-DIwO-q7K.d.mts +0 -3447
- package/dist/adapter-DQnxxLiE.d.cts +0 -3447
- package/dist/auto-5cjZaF9V.mjs +0 -3
- package/dist/auto-B0eSgoDw.cjs +0 -3
- package/dist/index.cjs +0 -10
- package/dist/index.d.cts +0 -920
- package/dist/runtime.cjs +0 -1
- package/dist/runtime.d.cts +0 -253
- package/dist/testkit-CEDYPvhF.mjs +0 -14
- package/dist/testkit-ClIKijxC.cjs +0 -14
- package/dist/testkit.cjs +0 -1
- package/dist/testkit.d.cts +0 -25
- package/examples/gh/tsconfig.json +0 -37
- package/examples/tsconfig.json +0 -17
- package/src/core/cli/AGENTS.md +0 -72
- package/src/core/completion/AGENTS.md +0 -72
- package/src/core/completion/completion-test-helpers.ts +0 -48
- package/src/core/output/AGENTS.md +0 -69
- package/src/core/resolve/AGENTS.md +0 -69
- package/src/core/schema/AGENTS.md +0 -61
- package/src/core/testkit/AGENTS.md +0 -55
- package/src/runtime/AGENTS.md +0 -74
- package/src/runtime/test-helpers.ts +0 -40
|
@@ -1,3447 +0,0 @@
|
|
|
1
|
-
//#region src/core/schema/activity.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Activity types — spinner and progress bar handles, options, events.
|
|
4
|
-
*
|
|
5
|
-
* These types define the contract for `Out.spinner()` and `Out.progress()`
|
|
6
|
-
* lifecycle management. Implementations live in `core/output/activity.ts`.
|
|
7
|
-
*
|
|
8
|
-
* @module dreamcli/core/schema/activity
|
|
9
|
-
*/
|
|
10
|
-
/**
|
|
11
|
-
* Non-TTY fallback strategy for spinners and progress bars.
|
|
12
|
-
*
|
|
13
|
-
* - `'silent'` — no output at all (default). Ideal for CI where decorative
|
|
14
|
-
* output is noise.
|
|
15
|
-
* - `'static'` — emit plain text via `out.log()` / `out.error()` at
|
|
16
|
-
* lifecycle boundaries (start, succeed, fail). No animation.
|
|
17
|
-
*/
|
|
18
|
-
type Fallback = 'silent' | 'static';
|
|
19
|
-
/** Options for {@link Out.spinner}. */
|
|
20
|
-
interface SpinnerOptions {
|
|
21
|
-
/**
|
|
22
|
-
* Fallback strategy when `!isTTY` or `jsonMode`.
|
|
23
|
-
* @defaultValue `'silent'`
|
|
24
|
-
*/
|
|
25
|
-
readonly fallback?: Fallback;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Handle returned by {@link Out.spinner} for lifecycle control.
|
|
29
|
-
*
|
|
30
|
-
* Terminal methods (`succeed`, `fail`, `stop`) are idempotent — calling any
|
|
31
|
-
* of them after the handle is already stopped is a no-op, not an error.
|
|
32
|
-
*/
|
|
33
|
-
interface SpinnerHandle {
|
|
34
|
-
/** Update the spinner text (no-op if stopped). */
|
|
35
|
-
update(text: string): void;
|
|
36
|
-
/** Stop with a success symbol and optional final text. */
|
|
37
|
-
succeed(text?: string): void;
|
|
38
|
-
/** Stop with a failure symbol and optional final text. */
|
|
39
|
-
fail(text?: string): void;
|
|
40
|
-
/** Stop the spinner without a status symbol. */
|
|
41
|
-
stop(): void;
|
|
42
|
-
/**
|
|
43
|
-
* Wrap a promise: auto-succeed on resolve, auto-fail on reject.
|
|
44
|
-
*
|
|
45
|
-
* @returns The resolved value of the wrapped promise.
|
|
46
|
-
*/
|
|
47
|
-
wrap<T>(promise: Promise<T>, options?: {
|
|
48
|
-
readonly succeed?: string;
|
|
49
|
-
readonly fail?: string;
|
|
50
|
-
}): Promise<T>;
|
|
51
|
-
}
|
|
52
|
-
/** Options for {@link Out.progress}. */
|
|
53
|
-
interface ProgressOptions {
|
|
54
|
-
/**
|
|
55
|
-
* Total units of work. When provided, the bar shows a determinate
|
|
56
|
-
* percentage. When omitted, the bar pulses in indeterminate mode.
|
|
57
|
-
*/
|
|
58
|
-
readonly total?: number;
|
|
59
|
-
/** Label displayed alongside the progress bar. */
|
|
60
|
-
readonly label?: string;
|
|
61
|
-
/**
|
|
62
|
-
* Fallback strategy when `!isTTY` or `jsonMode`.
|
|
63
|
-
* @defaultValue `'silent'`
|
|
64
|
-
*/
|
|
65
|
-
readonly fallback?: Fallback;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Handle returned by {@link Out.progress} for lifecycle control.
|
|
69
|
-
*
|
|
70
|
-
* Terminal methods (`done`, `fail`) are idempotent — calling any
|
|
71
|
-
* of them after the handle is already stopped is a no-op.
|
|
72
|
-
*/
|
|
73
|
-
interface ProgressHandle {
|
|
74
|
-
/** Advance progress by `n` units (default 1). */
|
|
75
|
-
increment(n?: number): void;
|
|
76
|
-
/** Set progress to an absolute value. */
|
|
77
|
-
update(value: number): void;
|
|
78
|
-
/** Mark progress as complete with an optional final message. */
|
|
79
|
-
done(text?: string): void;
|
|
80
|
-
/** Mark progress as failed with an optional final message. */
|
|
81
|
-
fail(text?: string): void;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Discriminated union of spinner and progress lifecycle events.
|
|
85
|
-
*
|
|
86
|
-
* Captured by testkit in {@link RunResult.activity} for assertion
|
|
87
|
-
* without polluting stdout/stderr arrays.
|
|
88
|
-
*/
|
|
89
|
-
type ActivityEvent = {
|
|
90
|
-
/** Spinner created and started. */readonly type: 'spinner:start'; /** Initial spinner text. */
|
|
91
|
-
readonly text: string;
|
|
92
|
-
} | {
|
|
93
|
-
/** Spinner text changed. */readonly type: 'spinner:update'; /** Updated spinner text. */
|
|
94
|
-
readonly text: string;
|
|
95
|
-
} | {
|
|
96
|
-
/** Spinner completed successfully. */readonly type: 'spinner:succeed'; /** Success message. */
|
|
97
|
-
readonly text: string;
|
|
98
|
-
} | {
|
|
99
|
-
/** Spinner stopped with an error. */readonly type: 'spinner:fail'; /** Failure message. */
|
|
100
|
-
readonly text: string;
|
|
101
|
-
} | {
|
|
102
|
-
/** Spinner stopped without a final status. */readonly type: 'spinner:stop';
|
|
103
|
-
} | {
|
|
104
|
-
/** Progress bar created and started. */readonly type: 'progress:start'; /** Bar label. */
|
|
105
|
-
readonly label: string; /** Known total, or `undefined` for indeterminate. */
|
|
106
|
-
readonly total: number | undefined;
|
|
107
|
-
} | {
|
|
108
|
-
/** Progress bar advanced. */readonly type: 'progress:increment'; /** Amount advanced. */
|
|
109
|
-
readonly delta: number;
|
|
110
|
-
} | {
|
|
111
|
-
/** Progress bar set to an absolute value. */readonly type: 'progress:update'; /** New absolute value. */
|
|
112
|
-
readonly value: number;
|
|
113
|
-
} | {
|
|
114
|
-
/** Progress bar completed. */readonly type: 'progress:done'; /** Completion message, if any. */
|
|
115
|
-
readonly text: string | undefined;
|
|
116
|
-
} | {
|
|
117
|
-
/** Progress bar stopped with an error. */readonly type: 'progress:fail'; /** Failure message, if any. */
|
|
118
|
-
readonly text: string | undefined;
|
|
119
|
-
};
|
|
120
|
-
/**
|
|
121
|
-
* Describes a single column in table output.
|
|
122
|
-
*
|
|
123
|
-
* @typeParam T - The row object type (inferred from the rows array).
|
|
124
|
-
*/
|
|
125
|
-
interface TableColumn<T extends Record<string, unknown>> {
|
|
126
|
-
/** Property key on the row objects to display in this column. */
|
|
127
|
-
readonly key: keyof T & string;
|
|
128
|
-
/**
|
|
129
|
-
* Header label for the column.
|
|
130
|
-
* @defaultValue the {@link TableColumn.key | key} value
|
|
131
|
-
*/
|
|
132
|
-
readonly header?: string;
|
|
133
|
-
}
|
|
134
|
-
/** Render format override for {@link Out.table}. */
|
|
135
|
-
type TableFormat = 'auto' | 'text' | 'json';
|
|
136
|
-
/** Output stream override for text table rendering. */
|
|
137
|
-
type TableStream = 'stdout' | 'stderr';
|
|
138
|
-
/**
|
|
139
|
-
* Per-call table output options.
|
|
140
|
-
*
|
|
141
|
-
* `format: 'auto'` preserves the current mode-dependent behavior.
|
|
142
|
-
* `format: 'json'` always emits a JSON array to stdout.
|
|
143
|
-
* `format: 'text'` always renders a human-readable table; when `stream` is
|
|
144
|
-
* omitted, text defaults to stdout in normal mode and stderr in jsonMode.
|
|
145
|
-
*/
|
|
146
|
-
/** Preserve the mode-dependent default — text tables in normal mode, JSON in `jsonMode`. */
|
|
147
|
-
interface TableOptionsAuto {
|
|
148
|
-
/**
|
|
149
|
-
* Follow the current output mode (text in normal, JSON in jsonMode).
|
|
150
|
-
* @defaultValue `'auto'`
|
|
151
|
-
*/
|
|
152
|
-
readonly format?: 'auto';
|
|
153
|
-
}
|
|
154
|
-
/** Force JSON array output to stdout regardless of output mode. */
|
|
155
|
-
interface TableOptionsJson {
|
|
156
|
-
/** Always emit a JSON array to stdout. */
|
|
157
|
-
readonly format: 'json';
|
|
158
|
-
}
|
|
159
|
-
/** Force human-readable text table output, optionally routed to a specific {@link TableStream}. */
|
|
160
|
-
interface TableOptionsText {
|
|
161
|
-
/** Always render a human-readable text table. */
|
|
162
|
-
readonly format: 'text';
|
|
163
|
-
/** Target stream for text output. Falls back to stdout (stderr in jsonMode). */
|
|
164
|
-
readonly stream?: TableStream;
|
|
165
|
-
}
|
|
166
|
-
/** Per-call rendering options for {@link Out.table}. */
|
|
167
|
-
type TableOptions = TableOptionsAuto | TableOptionsJson | TableOptionsText;
|
|
168
|
-
//#endregion
|
|
169
|
-
//#region src/core/schema/arg.d.ts
|
|
170
|
-
/**
|
|
171
|
-
* Positional argument schema builder with full type inference.
|
|
172
|
-
*
|
|
173
|
-
* Each factory (`arg.string()`, `arg.number()`, `arg.enum()`, `arg.custom()`) returns an
|
|
174
|
-
* immutable `ArgBuilder` whose generic parameter tracks the value type,
|
|
175
|
-
* presence state, and variadic flag through the fluent chain.
|
|
176
|
-
*
|
|
177
|
-
* @module dreamcli/core/schema/arg
|
|
178
|
-
*/
|
|
179
|
-
/**
|
|
180
|
-
* Presence describes whether a positional arg is guaranteed to exist when the
|
|
181
|
-
* action handler runs:
|
|
182
|
-
*
|
|
183
|
-
* - `'required'` — must be supplied; error if missing (default)
|
|
184
|
-
* - `'optional'` — may be `undefined` if not supplied
|
|
185
|
-
* - `'defaulted'` — always present (falls back to default value)
|
|
186
|
-
*/
|
|
187
|
-
type ArgPresence = 'required' | 'optional' | 'defaulted';
|
|
188
|
-
/**
|
|
189
|
-
* Compile-time state carried through the builder chain.
|
|
190
|
-
*/
|
|
191
|
-
interface ArgConfig {
|
|
192
|
-
/** The resolved value type (e.g. `string`, `number`, custom). */
|
|
193
|
-
readonly valueType: unknown;
|
|
194
|
-
/** Whether the arg is required, optional, or has a default. */
|
|
195
|
-
readonly presence: ArgPresence;
|
|
196
|
-
/** Whether this arg consumes remaining positionals. */
|
|
197
|
-
readonly variadic: boolean;
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Advanced type helper used by `ArgBuilder` modifiers to replace presence.
|
|
201
|
-
* Most consumers rely on inference and never reference this directly.
|
|
202
|
-
*/
|
|
203
|
-
type WithArgPresence<C extends ArgConfig, P extends ArgPresence> = {
|
|
204
|
-
readonly valueType: C['valueType'];
|
|
205
|
-
readonly presence: P;
|
|
206
|
-
readonly variadic: C['variadic'];
|
|
207
|
-
};
|
|
208
|
-
/**
|
|
209
|
-
* Advanced type helper used by `ArgBuilder.variadic()`.
|
|
210
|
-
* Most consumers rely on inference and never reference this directly.
|
|
211
|
-
*/
|
|
212
|
-
type WithVariadic<C extends ArgConfig> = {
|
|
213
|
-
readonly valueType: C['valueType'];
|
|
214
|
-
readonly presence: C['presence'];
|
|
215
|
-
readonly variadic: true;
|
|
216
|
-
};
|
|
217
|
-
/**
|
|
218
|
-
* Compute the final value type from config — this is what handlers receive.
|
|
219
|
-
*
|
|
220
|
-
* Advanced type helper: this powers {@link InferArg} and action-handler
|
|
221
|
-
* inference. Most apps do not need to mention it explicitly.
|
|
222
|
-
*
|
|
223
|
-
* Variadic args always produce an array. Non-variadic:
|
|
224
|
-
* - `'optional'` → `T | undefined`
|
|
225
|
-
* - `'required'` → `T`
|
|
226
|
-
* - `'defaulted'` → `T`
|
|
227
|
-
*/
|
|
228
|
-
type ResolvedArgValue<C extends ArgConfig> = C['variadic'] extends true ? C['valueType'][] : C['presence'] extends 'optional' ? C['valueType'] | undefined : C['valueType'];
|
|
229
|
-
/** Extract the resolved value type from an `ArgBuilder`. */
|
|
230
|
-
type InferArg<B> = B extends ArgBuilder<infer C extends ArgConfig> ? ResolvedArgValue<C> : never;
|
|
231
|
-
/** Extract resolved value types from a record of builders. */
|
|
232
|
-
type InferArgs<T extends Record<string, ArgBuilder<ArgConfig>>> = { [K in keyof T]: InferArg<T[K]> };
|
|
233
|
-
/** Discriminator for the kind of value an arg accepts. */
|
|
234
|
-
type ArgKind = 'string' | 'number' | 'enum' | 'custom';
|
|
235
|
-
/** Custom parse function for `arg.custom()`. */
|
|
236
|
-
type ArgParseFn<T> = (raw: string) => T;
|
|
237
|
-
/**
|
|
238
|
-
* The runtime descriptor stored inside every `ArgBuilder`. Consumers (parser,
|
|
239
|
-
* help generator) read this to understand the arg's shape without touching
|
|
240
|
-
* generics.
|
|
241
|
-
*/
|
|
242
|
-
interface ArgSchema {
|
|
243
|
-
/** What kind of value this arg accepts. */
|
|
244
|
-
readonly kind: ArgKind;
|
|
245
|
-
/** Current presence state. */
|
|
246
|
-
readonly presence: ArgPresence;
|
|
247
|
-
/** Whether this arg consumes all remaining positionals. */
|
|
248
|
-
readonly variadic: boolean;
|
|
249
|
-
/**
|
|
250
|
-
* Whether this arg may read from stdin during resolution.
|
|
251
|
-
* @defaultValue `false`
|
|
252
|
-
*/
|
|
253
|
-
readonly stdinMode: boolean;
|
|
254
|
-
/** Runtime default value (if any). */
|
|
255
|
-
readonly defaultValue: unknown;
|
|
256
|
-
/** Human-readable description for help text. */
|
|
257
|
-
readonly description: string | undefined;
|
|
258
|
-
/**
|
|
259
|
-
* Environment variable name for env resolution.
|
|
260
|
-
*
|
|
261
|
-
* When set and the CLI value is absent, the resolver reads this env var
|
|
262
|
-
* and coerces the string to the arg's declared kind.
|
|
263
|
-
*
|
|
264
|
-
* @see {@link ArgBuilder.env} for the builder method.
|
|
265
|
-
*/
|
|
266
|
-
readonly envVar: string | undefined;
|
|
267
|
-
/** Allowed literal values when `kind === 'enum'`. */
|
|
268
|
-
readonly enumValues: readonly string[] | undefined;
|
|
269
|
-
/** Custom parse function (only when `kind === 'custom'`). */
|
|
270
|
-
readonly parseFn: ArgParseFn<unknown> | undefined;
|
|
271
|
-
/**
|
|
272
|
-
* Deprecation marker.
|
|
273
|
-
*
|
|
274
|
-
* - `undefined` — not deprecated (default)
|
|
275
|
-
* - `true` — deprecated with no migration message
|
|
276
|
-
* - `string` — deprecated with a reason/migration message
|
|
277
|
-
*
|
|
278
|
-
* When a deprecated arg is used, a warning is emitted to stderr.
|
|
279
|
-
* Help text shows `[deprecated]` or `[deprecated: <reason>]`.
|
|
280
|
-
*/
|
|
281
|
-
readonly deprecated: string | true | undefined;
|
|
282
|
-
}
|
|
283
|
-
/**
|
|
284
|
-
* Create a raw {@link ArgSchema} object with sensible defaults.
|
|
285
|
-
*
|
|
286
|
-
* Most consumers should prefer the higher-level {@link arg} factory, which
|
|
287
|
-
* returns an immutable {@link ArgBuilder} with type inference and fluent
|
|
288
|
-
* modifiers. `createArgSchema()` exists for advanced schema composition,
|
|
289
|
-
* targeted tests, or custom builders that need the plain runtime descriptor.
|
|
290
|
-
*
|
|
291
|
-
* `overrides` are shallow-merged on top of the default shape, so callers are
|
|
292
|
-
* responsible for preserving invariants such as variadic ordering and
|
|
293
|
-
* compatible `parseFn` / `kind` combinations.
|
|
294
|
-
*
|
|
295
|
-
* @param kind - Discriminator for the value type this arg accepts.
|
|
296
|
-
* @param overrides - Partial schema fields shallow-merged onto defaults.
|
|
297
|
-
* @returns A fully populated {@link ArgSchema}.
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```ts
|
|
301
|
-
* const schema = createArgSchema('custom', {
|
|
302
|
-
* description: 'Hex color',
|
|
303
|
-
* parseFn: (raw) => `#${raw}`,
|
|
304
|
-
* });
|
|
305
|
-
* ```
|
|
306
|
-
*/
|
|
307
|
-
declare function createArgSchema(kind: ArgKind, overrides?: Partial<ArgSchema>): ArgSchema;
|
|
308
|
-
/**
|
|
309
|
-
* Immutable positional argument schema builder.
|
|
310
|
-
*
|
|
311
|
-
* The type parameter `C` is a phantom that tracks the value type, presence,
|
|
312
|
-
* and variadic state through the fluent chain. Each modifier returns a **new**
|
|
313
|
-
* builder — the original is never mutated.
|
|
314
|
-
*
|
|
315
|
-
* @example Full command with multiple args and modifiers
|
|
316
|
-
* ```ts
|
|
317
|
-
* command('deploy')
|
|
318
|
-
* .arg('target', arg.string()
|
|
319
|
-
* .env('DEPLOY_TARGET')
|
|
320
|
-
* .describe('Deploy target'))
|
|
321
|
-
* .arg('port', arg.number()
|
|
322
|
-
* .env('PORT')
|
|
323
|
-
* .default(3000)
|
|
324
|
-
* .describe('Port number'))
|
|
325
|
-
* .arg('files', arg.string()
|
|
326
|
-
* .variadic()
|
|
327
|
-
* .optional()
|
|
328
|
-
* .describe('Extra config files'))
|
|
329
|
-
* .action(({ args }) => {
|
|
330
|
-
* args.target; // string (required, from CLI or $DEPLOY_TARGET)
|
|
331
|
-
* args.port; // number (defaulted, from CLI, $PORT, or 3000)
|
|
332
|
-
* args.files; // string[] (optional variadic)
|
|
333
|
-
* });
|
|
334
|
-
* ```
|
|
335
|
-
*
|
|
336
|
-
* @example Type inference
|
|
337
|
-
* ```ts
|
|
338
|
-
* const target = arg.string();
|
|
339
|
-
* type T = InferArg<typeof target>; // string
|
|
340
|
-
*
|
|
341
|
-
* const opt = arg.string().optional();
|
|
342
|
-
* type O = InferArg<typeof opt>; // string | undefined
|
|
343
|
-
*
|
|
344
|
-
* const files = arg.string().variadic();
|
|
345
|
-
* type F = InferArg<typeof files>; // string[]
|
|
346
|
-
* ```
|
|
347
|
-
*/
|
|
348
|
-
declare class ArgBuilder<C extends ArgConfig> {
|
|
349
|
-
/** @internal Runtime schema descriptor. */
|
|
350
|
-
readonly schema: ArgSchema;
|
|
351
|
-
/**
|
|
352
|
-
* @internal Type brand — exists only in the type system (`declare`
|
|
353
|
-
* produces no runtime property). Used by `InferArg` / `InferArgs`.
|
|
354
|
-
*/
|
|
355
|
-
readonly _config: C;
|
|
356
|
-
/**
|
|
357
|
-
* @param schema - Runtime descriptor for this positional argument.
|
|
358
|
-
*/
|
|
359
|
-
constructor(schema: ArgSchema);
|
|
360
|
-
/**
|
|
361
|
-
* Mark the arg as required (this is the default for positional args).
|
|
362
|
-
* Produces an error if no value resolves from any configured source
|
|
363
|
-
* (CLI → stdin → env → default).
|
|
364
|
-
*
|
|
365
|
-
* @example
|
|
366
|
-
* ```ts
|
|
367
|
-
* arg.string().required() // explicit, same as default
|
|
368
|
-
*
|
|
369
|
-
* // In a command — omitting <target> causes a ValidationError:
|
|
370
|
-
* command('deploy')
|
|
371
|
-
* .arg('target', arg.string().required().describe('Deploy target'))
|
|
372
|
-
* // $ mycli deploy
|
|
373
|
-
* // Error: Missing required argument <target>
|
|
374
|
-
* ```
|
|
375
|
-
*
|
|
376
|
-
* @returns The builder (for chaining).
|
|
377
|
-
*/
|
|
378
|
-
required(): ArgBuilder<WithArgPresence<C, 'required'>>;
|
|
379
|
-
/**
|
|
380
|
-
* Mark the arg as optional. Handlers receive `undefined` when absent.
|
|
381
|
-
*
|
|
382
|
-
* @example
|
|
383
|
-
* ```ts
|
|
384
|
-
* arg.string().optional()
|
|
385
|
-
*
|
|
386
|
-
* // In a command — handler receives `undefined` when omitted:
|
|
387
|
-
* command('greet')
|
|
388
|
-
* .arg('name', arg.string().optional().describe('Who to greet'))
|
|
389
|
-
* .action(({ args }) => {
|
|
390
|
-
* args.name; // string | undefined
|
|
391
|
-
* });
|
|
392
|
-
* // $ mycli greet → args.name is undefined
|
|
393
|
-
* // $ mycli greet Alice → args.name is 'Alice'
|
|
394
|
-
* ```
|
|
395
|
-
*
|
|
396
|
-
* @returns The builder (for chaining).
|
|
397
|
-
*/
|
|
398
|
-
optional(): ArgBuilder<WithArgPresence<C, 'optional'>>;
|
|
399
|
-
/**
|
|
400
|
-
* Provide a default value. The arg becomes "always present" — handlers
|
|
401
|
-
* will never see `undefined`.
|
|
402
|
-
*
|
|
403
|
-
* The generic constraint `V extends C['valueType']` ensures the default
|
|
404
|
-
* matches the arg's declared type.
|
|
405
|
-
*
|
|
406
|
-
* Resolution order when extra sources are configured: CLI → stdin → env → **default**.
|
|
407
|
-
*
|
|
408
|
-
* @param value - Fallback used when no CLI value or env var resolves.
|
|
409
|
-
* @returns The builder (for chaining).
|
|
410
|
-
*
|
|
411
|
-
* @example
|
|
412
|
-
* ```ts
|
|
413
|
-
* arg.string().default('production')
|
|
414
|
-
* arg.number().default(3000)
|
|
415
|
-
*
|
|
416
|
-
* // In a command — default kicks in when CLI and env are both absent:
|
|
417
|
-
* command('deploy')
|
|
418
|
-
* .arg('env', arg.string()
|
|
419
|
-
* .env('DEPLOY_ENV')
|
|
420
|
-
* .default('staging')
|
|
421
|
-
* .describe('Target environment'))
|
|
422
|
-
* .action(({ args }) => {
|
|
423
|
-
* args.env; // string (never undefined)
|
|
424
|
-
* });
|
|
425
|
-
* // $ mycli deploy → 'staging' (default)
|
|
426
|
-
* // $ DEPLOY_ENV=prod mycli deploy → 'prod' (env)
|
|
427
|
-
* // $ mycli deploy production → 'production' (CLI)
|
|
428
|
-
* ```
|
|
429
|
-
*/
|
|
430
|
-
default<V extends C['valueType']>(value: V): ArgBuilder<WithArgPresence<C, 'defaulted'>>;
|
|
431
|
-
/**
|
|
432
|
-
* Mark this arg as variadic — it consumes all remaining positional
|
|
433
|
-
* arguments. The inferred type becomes `T[]`.
|
|
434
|
-
*
|
|
435
|
-
* A variadic arg must be the last positional in a command.
|
|
436
|
-
*
|
|
437
|
-
* @example
|
|
438
|
-
* ```ts
|
|
439
|
-
* arg.string().variadic()
|
|
440
|
-
*
|
|
441
|
-
* // In a command — collects all remaining positionals:
|
|
442
|
-
* command('build')
|
|
443
|
-
* .arg('entry', arg.string().describe('Main entry'))
|
|
444
|
-
* .arg('extras', arg.string().variadic().optional().describe('Extra files'))
|
|
445
|
-
* .action(({ args }) => {
|
|
446
|
-
* args.entry; // string
|
|
447
|
-
* args.extras; // string[]
|
|
448
|
-
* });
|
|
449
|
-
* // $ mycli build main.ts a.ts b.ts
|
|
450
|
-
* // → entry = 'main.ts', extras = ['a.ts', 'b.ts']
|
|
451
|
-
* ```
|
|
452
|
-
*
|
|
453
|
-
* @returns The builder (for chaining).
|
|
454
|
-
*/
|
|
455
|
-
variadic(): ArgBuilder<WithVariadic<C>>;
|
|
456
|
-
/**
|
|
457
|
-
* Allow this arg to resolve from stdin when CLI input is missing.
|
|
458
|
-
*
|
|
459
|
-
* Resolution order becomes: CLI value -> stdin -> env -> default.
|
|
460
|
-
* Only one arg per command may enable stdin mode.
|
|
461
|
-
*
|
|
462
|
-
* @returns The builder (for chaining).
|
|
463
|
-
*
|
|
464
|
-
* @example
|
|
465
|
-
* ```ts
|
|
466
|
-
* arg.string().describe('Input text').stdin()
|
|
467
|
-
* // $ echo "hello" | mycli transform → input = 'hello' (from stdin)
|
|
468
|
-
* // $ mycli transform "hello" → input = 'hello' (from CLI)
|
|
469
|
-
* ```
|
|
470
|
-
*/
|
|
471
|
-
stdin(): ArgBuilder<C>;
|
|
472
|
-
/**
|
|
473
|
-
* Bind to an environment variable.
|
|
474
|
-
*
|
|
475
|
-
* When the arg is not provided on the CLI, the resolver checks this
|
|
476
|
-
* env var before falling back to the default value. The env string is
|
|
477
|
-
* coerced to the arg's declared kind (passthrough for strings, parsed
|
|
478
|
-
* for numbers, run through `parseFn` for custom args).
|
|
479
|
-
*
|
|
480
|
-
* Resolution order when extra sources are configured: **CLI → stdin → env → default**.
|
|
481
|
-
*
|
|
482
|
-
* Help output shows `[env: VAR]` next to the arg description.
|
|
483
|
-
*
|
|
484
|
-
* @param varName - Environment variable name (e.g. `'DEPLOY_TARGET'`).
|
|
485
|
-
* @returns The builder (for chaining).
|
|
486
|
-
*
|
|
487
|
-
* @example
|
|
488
|
-
* ```ts
|
|
489
|
-
* command('deploy')
|
|
490
|
-
* .arg('target', arg.string().env('DEPLOY_TARGET').describe('Deploy target'))
|
|
491
|
-
* .arg('port', arg.number().env('PORT').default(3000))
|
|
492
|
-
* .action(({ args }) => {
|
|
493
|
-
* console.log(args.target); // from CLI, $DEPLOY_TARGET, or error
|
|
494
|
-
* console.log(args.port); // from CLI, $PORT, or 3000
|
|
495
|
-
* });
|
|
496
|
-
* ```
|
|
497
|
-
*/
|
|
498
|
-
env(varName: string): ArgBuilder<C>;
|
|
499
|
-
/**
|
|
500
|
-
* Human-readable description shown in help output.
|
|
501
|
-
*
|
|
502
|
-
* @param description - Text displayed next to the arg in `--help`.
|
|
503
|
-
* @returns The builder (for chaining).
|
|
504
|
-
*
|
|
505
|
-
* @example
|
|
506
|
-
* ```ts
|
|
507
|
-
* arg.string().describe('Deploy target')
|
|
508
|
-
*
|
|
509
|
-
* // Help output:
|
|
510
|
-
* // Arguments:
|
|
511
|
-
* // <target> Deploy target
|
|
512
|
-
* ```
|
|
513
|
-
*/
|
|
514
|
-
describe(description: string): ArgBuilder<C>;
|
|
515
|
-
/**
|
|
516
|
-
* Mark this arg as deprecated.
|
|
517
|
-
*
|
|
518
|
-
* When used, a warning is emitted to stderr. Help text shows
|
|
519
|
-
* `[deprecated]` or `[deprecated: <reason>]`.
|
|
520
|
-
*
|
|
521
|
-
* Does not change the arg's type-level config — it's metadata only.
|
|
522
|
-
*
|
|
523
|
-
* @param message - Optional migration reason/guidance.
|
|
524
|
-
* @returns The builder (for chaining).
|
|
525
|
-
*
|
|
526
|
-
* @example
|
|
527
|
-
* ```ts
|
|
528
|
-
* arg.string().deprecated() // generic
|
|
529
|
-
* arg.string().deprecated('use --target flag instead') // with guidance
|
|
530
|
-
*
|
|
531
|
-
* // Help output:
|
|
532
|
-
* // Arguments:
|
|
533
|
-
* // <target> Deploy target [deprecated: use --target flag instead]
|
|
534
|
-
* ```
|
|
535
|
-
*/
|
|
536
|
-
deprecated(message?: string): ArgBuilder<C>;
|
|
537
|
-
}
|
|
538
|
-
/**
|
|
539
|
-
* Arg factory functions — the public API for creating positional arguments.
|
|
540
|
-
*
|
|
541
|
-
* Each method returns an `ArgBuilder` seeded with the correct `ArgKind`
|
|
542
|
-
* and initial type-level config. Chain modifiers (`.optional()`, `.env()`,
|
|
543
|
-
* `.default()`, `.variadic()`, `.stdin()`, `.describe()`, `.deprecated()`) to refine.
|
|
544
|
-
*
|
|
545
|
-
* All args are **required** by default. Resolution order when extra
|
|
546
|
-
* sources are configured: **CLI → stdin → env → default**.
|
|
547
|
-
*
|
|
548
|
-
* @example Overview — all three kinds with common modifier patterns
|
|
549
|
-
* ```ts
|
|
550
|
-
* command('process')
|
|
551
|
-
* // String arg with env fallback
|
|
552
|
-
* .arg('input', arg.string()
|
|
553
|
-
* .env('INPUT_FILE')
|
|
554
|
-
* .describe('Input file path'))
|
|
555
|
-
*
|
|
556
|
-
* // Number arg with env + default
|
|
557
|
-
* .arg('concurrency', arg.number()
|
|
558
|
-
* .env('CONCURRENCY')
|
|
559
|
-
* .default(4)
|
|
560
|
-
* .describe('Worker threads'))
|
|
561
|
-
*
|
|
562
|
-
* // Custom arg — hex color parser with env
|
|
563
|
-
* .arg('color', arg.custom((raw) => {
|
|
564
|
-
* if (!/^#?[0-9a-f]{6}$/i.test(raw)) throw new Error('bad hex');
|
|
565
|
-
* return raw.startsWith('#') ? raw : `#${raw}`;
|
|
566
|
-
* })
|
|
567
|
-
* .env('THEME_COLOR')
|
|
568
|
-
* .optional()
|
|
569
|
-
* .describe('Theme color (hex)'))
|
|
570
|
-
*
|
|
571
|
-
* .action(({ args }) => {
|
|
572
|
-
* args.input; // string (required)
|
|
573
|
-
* args.concurrency; // number (defaulted)
|
|
574
|
-
* args.color; // string | undefined (optional custom)
|
|
575
|
-
* });
|
|
576
|
-
* ```
|
|
577
|
-
*/
|
|
578
|
-
interface ArgFactory {
|
|
579
|
-
/**
|
|
580
|
-
* String-valued positional argument. Required by default.
|
|
581
|
-
*
|
|
582
|
-
* @example
|
|
583
|
-
* ```ts
|
|
584
|
-
* arg.string() // required string
|
|
585
|
-
* arg.string().optional() // string | undefined
|
|
586
|
-
* arg.string().env('TARGET') // falls back to $TARGET
|
|
587
|
-
* arg.string().default('production') // always present
|
|
588
|
-
*
|
|
589
|
-
* // In a command:
|
|
590
|
-
* command('deploy')
|
|
591
|
-
* .arg('target', arg.string().env('DEPLOY_TARGET').describe('Deploy target'))
|
|
592
|
-
* ```
|
|
593
|
-
*
|
|
594
|
-
* @returns A required string {@link ArgBuilder}.
|
|
595
|
-
*/
|
|
596
|
-
string(): ArgBuilder<{
|
|
597
|
-
readonly valueType: string;
|
|
598
|
-
readonly presence: 'required';
|
|
599
|
-
readonly variadic: false;
|
|
600
|
-
}>;
|
|
601
|
-
/**
|
|
602
|
-
* Number-valued positional argument. Required by default.
|
|
603
|
-
*
|
|
604
|
-
* The parser coerces the raw CLI string to a number and emits a
|
|
605
|
-
* `ParseError` if conversion fails. Env values are coerced the same way.
|
|
606
|
-
*
|
|
607
|
-
* @example
|
|
608
|
-
* ```ts
|
|
609
|
-
* arg.number() // required number
|
|
610
|
-
* arg.number().default(8080) // defaults to 8080
|
|
611
|
-
* arg.number().env('PORT') // falls back to $PORT (coerced)
|
|
612
|
-
*
|
|
613
|
-
* // In a command:
|
|
614
|
-
* command('serve')
|
|
615
|
-
* .arg('port', arg.number().env('PORT').default(3000).describe('Port'))
|
|
616
|
-
* // $ mycli serve 8080 → 8080
|
|
617
|
-
* // $ PORT=9090 mycli serve → 9090
|
|
618
|
-
* // $ mycli serve → 3000
|
|
619
|
-
* ```
|
|
620
|
-
*
|
|
621
|
-
* @returns A required number {@link ArgBuilder}.
|
|
622
|
-
*/
|
|
623
|
-
number(): ArgBuilder<{
|
|
624
|
-
readonly valueType: number;
|
|
625
|
-
readonly presence: 'required';
|
|
626
|
-
readonly variadic: false;
|
|
627
|
-
}>;
|
|
628
|
-
/**
|
|
629
|
-
* Enum-valued positional argument. Required by default.
|
|
630
|
-
*
|
|
631
|
-
* Accepts only the listed string literals. The inferred type is the
|
|
632
|
-
* union of those literals (e.g. `'us' | 'eu' | 'ap'`), not `string`.
|
|
633
|
-
* Invalid values produce a `ParseError` listing allowed options.
|
|
634
|
-
*
|
|
635
|
-
* @param values - Non-empty tuple of allowed string values.
|
|
636
|
-
* @returns A required enum {@link ArgBuilder} typed to the union of `values`.
|
|
637
|
-
*
|
|
638
|
-
* @example
|
|
639
|
-
* ```ts
|
|
640
|
-
* arg.enum(['us', 'eu', 'ap']) // required, 'us' | 'eu' | 'ap'
|
|
641
|
-
* arg.enum(['dev', 'prod']).default('dev') // defaulted
|
|
642
|
-
* arg.enum(['json', 'csv']).optional() // 'json' | 'csv' | undefined
|
|
643
|
-
*
|
|
644
|
-
* // In a command:
|
|
645
|
-
* command('deploy')
|
|
646
|
-
* .arg('region', arg.enum(['us', 'eu', 'ap']).env('REGION').describe('Target region'))
|
|
647
|
-
* // $ mycli deploy us → 'us'
|
|
648
|
-
* // $ mycli deploy invalid → ParseError: Allowed: us, eu, ap
|
|
649
|
-
* ```
|
|
650
|
-
*/
|
|
651
|
-
enum<const T extends readonly [string, ...string[]]>(values: T): ArgBuilder<{
|
|
652
|
-
readonly valueType: T[number];
|
|
653
|
-
readonly presence: 'required';
|
|
654
|
-
readonly variadic: false;
|
|
655
|
-
}>;
|
|
656
|
-
/**
|
|
657
|
-
* Custom-parsed positional argument. Required by default.
|
|
658
|
-
*
|
|
659
|
-
* The parse function receives the raw string and must return a value of
|
|
660
|
-
* type `T`. Throw an `Error` (or `ParseError`) to signal invalid input.
|
|
661
|
-
* The same parse function is used for both CLI and env values.
|
|
662
|
-
*
|
|
663
|
-
* @param parseFn - Converts the raw CLI string to `T`.
|
|
664
|
-
* @returns A required custom {@link ArgBuilder} typed to the return of `parseFn`.
|
|
665
|
-
*
|
|
666
|
-
* @example
|
|
667
|
-
* ```ts
|
|
668
|
-
* arg.custom((raw) => Number.parseInt(raw, 16))
|
|
669
|
-
* // inferred type: number
|
|
670
|
-
*
|
|
671
|
-
* // In a command — parse hex color from CLI or $COLOR:
|
|
672
|
-
* command('theme')
|
|
673
|
-
* .arg('color', arg.custom((raw) => {
|
|
674
|
-
* if (!/^[0-9a-f]{6}$/i.test(raw)) throw new Error('Expected 6-digit hex');
|
|
675
|
-
* return `#${raw}`;
|
|
676
|
-
* }).env('COLOR').describe('Hex color code'))
|
|
677
|
-
* // $ mycli theme ff6600 → '#ff6600'
|
|
678
|
-
* // $ COLOR=aabbcc mycli theme → '#aabbcc'
|
|
679
|
-
* ```
|
|
680
|
-
*/
|
|
681
|
-
custom<T>(parseFn: ArgParseFn<T>): ArgBuilder<{
|
|
682
|
-
readonly valueType: T;
|
|
683
|
-
readonly presence: 'required';
|
|
684
|
-
readonly variadic: false;
|
|
685
|
-
}>;
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
* Positional argument schema factory.
|
|
689
|
-
*
|
|
690
|
-
* Entry point for defining args on a command. Use `arg.<kind>()` to create
|
|
691
|
-
* an `ArgBuilder`, then chain modifiers and pass the result to
|
|
692
|
-
* `command().arg(name, builder)`.
|
|
693
|
-
*
|
|
694
|
-
* Four kinds are available:
|
|
695
|
-
* - `arg.string()` — raw string (most common)
|
|
696
|
-
* - `arg.number()` — parsed to number, errors on NaN
|
|
697
|
-
* - `arg.enum(values)` — constrained to listed literals
|
|
698
|
-
* - `arg.custom(fn)` — arbitrary parse function, infers return type
|
|
699
|
-
*
|
|
700
|
-
* @example
|
|
701
|
-
* ```ts
|
|
702
|
-
* import { command, arg } from 'dreamcli';
|
|
703
|
-
*
|
|
704
|
-
* command('deploy')
|
|
705
|
-
* .arg('target', arg.string().env('DEPLOY_TARGET').describe('Where to deploy'))
|
|
706
|
-
* .arg('port', arg.number().env('PORT').default(3000))
|
|
707
|
-
* .action(({ args }) => {
|
|
708
|
-
* console.log(`Deploying to ${args.target} on port ${args.port}`);
|
|
709
|
-
* });
|
|
710
|
-
*
|
|
711
|
-
* // $ mycli deploy production 8080 → target='production', port=8080
|
|
712
|
-
* // $ DEPLOY_TARGET=staging mycli deploy → target='staging', port=3000
|
|
713
|
-
* ```
|
|
714
|
-
*/
|
|
715
|
-
declare const arg: ArgFactory;
|
|
716
|
-
//#endregion
|
|
717
|
-
//#region src/core/schema/prompt.d.ts
|
|
718
|
-
/**
|
|
719
|
-
* Prompt type definitions for interactive flag resolution.
|
|
720
|
-
*
|
|
721
|
-
* Prompt configuration is stored on `FlagSchema.prompt` and consumed by the
|
|
722
|
-
* resolution chain (v0.3+) when a flag value is missing after CLI/env/config
|
|
723
|
-
* resolution. The prompt engine reads this config to present the appropriate
|
|
724
|
-
* UI to the user.
|
|
725
|
-
*
|
|
726
|
-
* @module dreamcli/core/schema/prompt
|
|
727
|
-
*/
|
|
728
|
-
/**
|
|
729
|
-
* The kind of interactive prompt to present.
|
|
730
|
-
*
|
|
731
|
-
* - `'confirm'` — yes/no boolean question
|
|
732
|
-
* - `'input'` — free-text string input
|
|
733
|
-
* - `'select'` — single selection from a list
|
|
734
|
-
* - `'multiselect'` — multiple selections from a list
|
|
735
|
-
*/
|
|
736
|
-
type PromptKind = 'confirm' | 'input' | 'select' | 'multiselect';
|
|
737
|
-
/** Shared fields across all prompt kinds. */
|
|
738
|
-
interface PromptConfigBase {
|
|
739
|
-
/** The question displayed to the user. */
|
|
740
|
-
readonly message: string;
|
|
741
|
-
}
|
|
742
|
-
/** Yes/no confirmation prompt — maps to `boolean` flags. Part of {@link PromptConfig}. */
|
|
743
|
-
interface ConfirmPromptConfig extends PromptConfigBase {
|
|
744
|
-
readonly kind: 'confirm';
|
|
745
|
-
}
|
|
746
|
-
/** Free-text input prompt — maps to `string` and `number` flags. Part of {@link PromptConfig}. */
|
|
747
|
-
interface InputPromptConfig extends PromptConfigBase {
|
|
748
|
-
readonly kind: 'input';
|
|
749
|
-
/** Placeholder text shown before user types (informational only). */
|
|
750
|
-
readonly placeholder?: string;
|
|
751
|
-
/**
|
|
752
|
-
* Inline validation function. Return `true` if valid, or a string
|
|
753
|
-
* error message if invalid. Called before coercion to flag kind.
|
|
754
|
-
*/
|
|
755
|
-
readonly validate?: (value: string) => true | string;
|
|
756
|
-
}
|
|
757
|
-
/** Single-selection prompt — maps to `enum` flags or any flag with {@link SelectChoice choices}. Part of {@link PromptConfig}. */
|
|
758
|
-
interface SelectPromptConfig extends PromptConfigBase {
|
|
759
|
-
readonly kind: 'select';
|
|
760
|
-
/**
|
|
761
|
-
* Available choices. When omitted for `enum` flags, the enum values
|
|
762
|
-
* from the flag schema are used automatically.
|
|
763
|
-
*/
|
|
764
|
-
readonly choices?: readonly SelectChoice[];
|
|
765
|
-
}
|
|
766
|
-
/**
|
|
767
|
-
* Multi-selection prompt — maps to `array` flags.
|
|
768
|
-
* Returns an array of selected {@link SelectChoice} values. Part of {@link PromptConfig}.
|
|
769
|
-
*/
|
|
770
|
-
interface MultiselectPromptConfig extends PromptConfigBase {
|
|
771
|
-
readonly kind: 'multiselect';
|
|
772
|
-
/**
|
|
773
|
-
* Available choices. When omitted for `array` flags with enum elements,
|
|
774
|
-
* the enum values from the element schema are used automatically.
|
|
775
|
-
*/
|
|
776
|
-
readonly choices?: readonly SelectChoice[];
|
|
777
|
-
/**
|
|
778
|
-
* Minimum number of selections required.
|
|
779
|
-
* @defaultValue `0`
|
|
780
|
-
*/
|
|
781
|
-
readonly min?: number;
|
|
782
|
-
/**
|
|
783
|
-
* Maximum number of selections allowed.
|
|
784
|
-
* @defaultValue `Infinity`
|
|
785
|
-
*/
|
|
786
|
-
readonly max?: number;
|
|
787
|
-
}
|
|
788
|
-
/** A selectable option for {@link SelectPromptConfig} and {@link MultiselectPromptConfig} prompts. */
|
|
789
|
-
interface SelectChoice {
|
|
790
|
-
/** The value returned when this choice is selected. */
|
|
791
|
-
readonly value: string;
|
|
792
|
-
/**
|
|
793
|
-
* Display label shown to the user.
|
|
794
|
-
* @defaultValue {@link SelectChoice.value | value}
|
|
795
|
-
*/
|
|
796
|
-
readonly label?: string;
|
|
797
|
-
/** Optional description shown alongside the choice. */
|
|
798
|
-
readonly description?: string;
|
|
799
|
-
}
|
|
800
|
-
/**
|
|
801
|
-
* Discriminated union of all prompt configurations.
|
|
802
|
-
*
|
|
803
|
-
* Use the `kind` field to narrow:
|
|
804
|
-
* ```ts
|
|
805
|
-
* if (config.kind === 'select') {
|
|
806
|
-
* config.choices // readonly SelectChoice[] | undefined
|
|
807
|
-
* }
|
|
808
|
-
* ```
|
|
809
|
-
*/
|
|
810
|
-
type PromptConfig = ConfirmPromptConfig | InputPromptConfig | SelectPromptConfig | MultiselectPromptConfig;
|
|
811
|
-
/**
|
|
812
|
-
* The raw result returned by a prompt engine for a single prompt.
|
|
813
|
-
*
|
|
814
|
-
* - `answered: true` — user provided a value
|
|
815
|
-
* - `answered: false` — user cancelled/aborted (Ctrl+C, ESC, etc.)
|
|
816
|
-
*
|
|
817
|
-
* Coercion to the flag's kind is the resolver's responsibility, not the
|
|
818
|
-
* prompt engine's.
|
|
819
|
-
*/
|
|
820
|
-
type PromptResult = {
|
|
821
|
-
/** User provided a value. */readonly answered: true; /** The raw value from the prompt engine (not yet coerced). */
|
|
822
|
-
readonly value: unknown;
|
|
823
|
-
} | {
|
|
824
|
-
/** User cancelled or aborted (Ctrl+C, ESC, etc.). */readonly answered: false;
|
|
825
|
-
};
|
|
826
|
-
//#endregion
|
|
827
|
-
//#region src/core/schema/flag.d.ts
|
|
828
|
-
/**
|
|
829
|
-
* Presence describes whether a flag value is guaranteed to exist when the
|
|
830
|
-
* action handler runs:
|
|
831
|
-
*
|
|
832
|
-
* - `'optional'` — not required; unresolved value follows the kind-specific
|
|
833
|
-
* optional fallback (`undefined` for most flags, `[]` for arrays)
|
|
834
|
-
* - `'required'` — must be supplied; error if missing
|
|
835
|
-
* - `'defaulted'` — always present (falls back to default value)
|
|
836
|
-
*/
|
|
837
|
-
type FlagPresence = 'optional' | 'required' | 'defaulted';
|
|
838
|
-
/**
|
|
839
|
-
* Fallback behavior when an optional flag resolves no value from any source.
|
|
840
|
-
*
|
|
841
|
-
* Most optional flags resolve to `undefined`; array flags instead resolve to
|
|
842
|
-
* an empty array `[]`.
|
|
843
|
-
*/
|
|
844
|
-
type OptionalFallback = 'undefined' | 'empty-array';
|
|
845
|
-
/**
|
|
846
|
-
* Compile-time state carried through the builder chain.
|
|
847
|
-
*
|
|
848
|
-
* Adding new tracked properties only requires extending this interface — no
|
|
849
|
-
* builder signature changes.
|
|
850
|
-
*/
|
|
851
|
-
interface FlagConfig {
|
|
852
|
-
/** The resolved value type (e.g. `string`, `number`, `'us' | 'eu'`). */
|
|
853
|
-
readonly valueType: unknown;
|
|
854
|
-
/** Whether the flag is optional, required, or has a default. */
|
|
855
|
-
readonly presence: FlagPresence;
|
|
856
|
-
/** What an unresolved optional flag becomes at the action boundary. */
|
|
857
|
-
readonly optionalFallback: OptionalFallback;
|
|
858
|
-
}
|
|
859
|
-
/**
|
|
860
|
-
* Advanced type helper used by `FlagBuilder` modifiers to replace presence.
|
|
861
|
-
* Most consumers rely on inference and never reference this directly.
|
|
862
|
-
*/
|
|
863
|
-
type WithPresence<C extends FlagConfig, P extends FlagPresence> = {
|
|
864
|
-
readonly valueType: C['valueType'];
|
|
865
|
-
readonly presence: P;
|
|
866
|
-
readonly optionalFallback: C['optionalFallback'];
|
|
867
|
-
};
|
|
868
|
-
/**
|
|
869
|
-
* Compute the final value type from config — this is what handlers receive.
|
|
870
|
-
*
|
|
871
|
-
* Advanced type helper: this powers {@link InferFlag} and action-handler
|
|
872
|
-
* inference. Most apps do not need to mention it explicitly.
|
|
873
|
-
*
|
|
874
|
-
* - `'optional'` + `'undefined'` fallback → `T | undefined`
|
|
875
|
-
* - `'optional'` + `'empty-array'` fallback → `T`
|
|
876
|
-
* - `'required'` → `T`
|
|
877
|
-
* - `'defaulted'` → `T`
|
|
878
|
-
*/
|
|
879
|
-
type ResolvedValue<C extends FlagConfig> = C['presence'] extends 'optional' ? C['optionalFallback'] extends 'empty-array' ? C['valueType'] : C['valueType'] | undefined : C['valueType'];
|
|
880
|
-
/** Extract the resolved value type from a `FlagBuilder`. */
|
|
881
|
-
type InferFlag<B> = B extends FlagBuilder<infer C extends FlagConfig> ? ResolvedValue<C> : never;
|
|
882
|
-
/** Extract resolved value types from a record of builders. */
|
|
883
|
-
type InferFlags<T extends Record<string, FlagBuilder<FlagConfig>>> = { [K in keyof T]: InferFlag<T[K]> };
|
|
884
|
-
/** Discriminator for the kind of value a flag accepts. */
|
|
885
|
-
type FlagKind = 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'custom';
|
|
886
|
-
/**
|
|
887
|
-
* Custom parse function for `flag.custom()`.
|
|
888
|
-
*
|
|
889
|
-
* Receives `string` from CLI argv and env vars, or any JSON-representable
|
|
890
|
-
* value from config files. Narrow inside the function as needed.
|
|
891
|
-
*/
|
|
892
|
-
type FlagParseFn<T> = (raw: unknown) => T;
|
|
893
|
-
/**
|
|
894
|
-
* The runtime descriptor stored inside every `FlagBuilder`. Consumers (parser,
|
|
895
|
-
* help generator, resolution chain) read this to understand the flag's shape
|
|
896
|
-
* without touching generics.
|
|
897
|
-
*/
|
|
898
|
-
interface FlagSchema {
|
|
899
|
-
/** What kind of value this flag accepts. */
|
|
900
|
-
readonly kind: FlagKind;
|
|
901
|
-
/** Current presence state. */
|
|
902
|
-
readonly presence: FlagPresence;
|
|
903
|
-
/** Runtime default value (if any). */
|
|
904
|
-
readonly defaultValue: unknown;
|
|
905
|
-
/** Short/long aliases (e.g. `['f']` for `--force`). */
|
|
906
|
-
readonly aliases: readonly string[];
|
|
907
|
-
/** Environment variable name for v0.2+ resolution. */
|
|
908
|
-
readonly envVar: string | undefined;
|
|
909
|
-
/** Dotted config path for v0.2+ resolution (e.g. `'deploy.region'`). */
|
|
910
|
-
readonly configPath: string | undefined;
|
|
911
|
-
/** Human-readable description for help text. */
|
|
912
|
-
readonly description: string | undefined;
|
|
913
|
-
/** Allowed literal values when `kind === 'enum'`. */
|
|
914
|
-
readonly enumValues: readonly string[] | undefined;
|
|
915
|
-
/** Element schema when `kind === 'array'`. */
|
|
916
|
-
readonly elementSchema: FlagSchema | undefined;
|
|
917
|
-
/** Interactive prompt configuration for v0.3+ resolution. */
|
|
918
|
-
readonly prompt: PromptConfig | undefined;
|
|
919
|
-
/** Custom parse function (only when `kind === 'custom'`). */
|
|
920
|
-
readonly parseFn: FlagParseFn<unknown> | undefined;
|
|
921
|
-
/**
|
|
922
|
-
* Deprecation marker.
|
|
923
|
-
*
|
|
924
|
-
* - `undefined` — not deprecated (default)
|
|
925
|
-
* - `true` — deprecated with no migration message
|
|
926
|
-
* - `string` — deprecated with a reason/migration message
|
|
927
|
-
*
|
|
928
|
-
* When a deprecated flag is used, a warning is emitted to stderr.
|
|
929
|
-
* Help text shows `[deprecated]` or `[deprecated: <reason>]`.
|
|
930
|
-
*/
|
|
931
|
-
readonly deprecated: string | true | undefined;
|
|
932
|
-
/**
|
|
933
|
-
* Whether this flag propagates to subcommands in nested command trees.
|
|
934
|
-
*
|
|
935
|
-
* When `true`, the flag is automatically available to all descendant
|
|
936
|
-
* commands. A child command that defines a flag with the same name
|
|
937
|
-
* shadows the propagated parent flag.
|
|
938
|
-
*
|
|
939
|
-
* @defaultValue `false`
|
|
940
|
-
*/
|
|
941
|
-
readonly propagate: boolean;
|
|
942
|
-
}
|
|
943
|
-
/**
|
|
944
|
-
* Create a raw {@link FlagSchema} object with sensible defaults.
|
|
945
|
-
*
|
|
946
|
-
* Most consumers should prefer the higher-level {@link flag} factory,
|
|
947
|
-
* which returns an immutable {@link FlagBuilder} with type inference and
|
|
948
|
-
* safe modifier chaining. `createSchema()` is the low-level escape hatch
|
|
949
|
-
* for advanced schema composition, tests, or custom factories that need to
|
|
950
|
-
* work directly with the runtime descriptor.
|
|
951
|
-
*
|
|
952
|
-
* `overrides` are shallow-merged on top of the default shape, so callers are
|
|
953
|
-
* responsible for keeping the resulting schema internally consistent.
|
|
954
|
-
*
|
|
955
|
-
* @param kind - Discriminator for the value type this flag accepts.
|
|
956
|
-
* @param overrides - Partial {@link FlagSchema} fields merged onto defaults.
|
|
957
|
-
* @returns A fully populated {@link FlagSchema}.
|
|
958
|
-
*
|
|
959
|
-
* @example
|
|
960
|
-
* ```ts
|
|
961
|
-
* const schema = createSchema('enum', {
|
|
962
|
-
* enumValues: ['us', 'eu', 'ap'],
|
|
963
|
-
* description: 'Deployment region',
|
|
964
|
-
* });
|
|
965
|
-
* ```
|
|
966
|
-
*/
|
|
967
|
-
declare function createSchema(kind: FlagKind, overrides?: Partial<FlagSchema>): FlagSchema;
|
|
968
|
-
/**
|
|
969
|
-
* Immutable flag schema builder.
|
|
970
|
-
*
|
|
971
|
-
* The type parameter `C` is a phantom that tracks the value type and presence
|
|
972
|
-
* through the fluent chain. Each modifier returns a **new** builder — the
|
|
973
|
-
* original is never mutated.
|
|
974
|
-
*
|
|
975
|
-
* @example
|
|
976
|
-
* ```ts
|
|
977
|
-
* const port = flag.number().default(8080);
|
|
978
|
-
* type Port = InferFlag<typeof port>; // number
|
|
979
|
-
*
|
|
980
|
-
* const region = flag.enum(['us', 'eu', 'ap']);
|
|
981
|
-
* type Region = InferFlag<typeof region>; // 'us' | 'eu' | 'ap' | undefined
|
|
982
|
-
* ```
|
|
983
|
-
*/
|
|
984
|
-
declare class FlagBuilder<C extends FlagConfig> {
|
|
985
|
-
/** @internal Runtime schema descriptor. */
|
|
986
|
-
readonly schema: FlagSchema;
|
|
987
|
-
/**
|
|
988
|
-
* @internal Type brand — exists only in the type system (`declare`
|
|
989
|
-
* produces no runtime property). Used by `InferFlag` / `InferFlags`.
|
|
990
|
-
*/
|
|
991
|
-
readonly _config: C;
|
|
992
|
-
/**
|
|
993
|
-
* @param schema - Runtime descriptor seeding this builder's state.
|
|
994
|
-
*/
|
|
995
|
-
constructor(schema: FlagSchema);
|
|
996
|
-
/**
|
|
997
|
-
* Provide a default value. The flag becomes "always present" — handlers
|
|
998
|
-
* will never see `undefined`.
|
|
999
|
-
*
|
|
1000
|
-
* The generic constraint `V extends C['valueType']` ensures the default
|
|
1001
|
-
* matches the flag's declared type.
|
|
1002
|
-
*
|
|
1003
|
-
* @param value - Fallback value used when no source provides one.
|
|
1004
|
-
* @returns The builder (for chaining).
|
|
1005
|
-
*
|
|
1006
|
-
* @example
|
|
1007
|
-
* ```ts
|
|
1008
|
-
* flag.number().default(8080).describe('Port to listen on')
|
|
1009
|
-
*
|
|
1010
|
-
* // $ mycli serve → port = 8080
|
|
1011
|
-
* // $ mycli serve --port 443 → port = 443
|
|
1012
|
-
* ```
|
|
1013
|
-
*/
|
|
1014
|
-
default<V extends C['valueType']>(value: V): FlagBuilder<WithPresence<C, 'defaulted'>>;
|
|
1015
|
-
/**
|
|
1016
|
-
* Mark the flag as required. If not resolved from any source the framework
|
|
1017
|
-
* will emit a `ValidationError` before the action handler runs.
|
|
1018
|
-
*
|
|
1019
|
-
* @returns The builder (for chaining).
|
|
1020
|
-
*
|
|
1021
|
-
* @example
|
|
1022
|
-
* ```ts
|
|
1023
|
-
* flag.string().required().describe('Deploy target')
|
|
1024
|
-
*
|
|
1025
|
-
* // $ mycli deploy
|
|
1026
|
-
* // # → Error: Missing required flag --target
|
|
1027
|
-
* // $ mycli deploy --target staging
|
|
1028
|
-
* // # → target = 'staging'
|
|
1029
|
-
* ```
|
|
1030
|
-
*/
|
|
1031
|
-
required(): FlagBuilder<WithPresence<C, 'required'>>;
|
|
1032
|
-
/**
|
|
1033
|
-
* Add a short or long alias (e.g. `'f'` for `--force`, `'verbose'` as an
|
|
1034
|
-
* alternative long name).
|
|
1035
|
-
*
|
|
1036
|
-
* @param name - Single-char short alias or alternative long name.
|
|
1037
|
-
* @returns The builder (for chaining).
|
|
1038
|
-
*
|
|
1039
|
-
* @example
|
|
1040
|
-
* ```ts
|
|
1041
|
-
* flag.boolean().alias('v').describe('Enable verbose output')
|
|
1042
|
-
*
|
|
1043
|
-
* // $ mycli build -v → verbose = true
|
|
1044
|
-
* // $ mycli build --verbose → verbose = true
|
|
1045
|
-
* ```
|
|
1046
|
-
*/
|
|
1047
|
-
alias(name: string): FlagBuilder<C>;
|
|
1048
|
-
/**
|
|
1049
|
-
* Bind to an environment variable (resolved in v0.2+).
|
|
1050
|
-
*
|
|
1051
|
-
* @param varName - Environment variable name (e.g. `'PORT'`).
|
|
1052
|
-
* @returns The builder (for chaining).
|
|
1053
|
-
*
|
|
1054
|
-
* @example
|
|
1055
|
-
* ```ts
|
|
1056
|
-
* flag.string().env('API_KEY').describe('Service API key')
|
|
1057
|
-
*
|
|
1058
|
-
* // $ API_KEY=sk-123 mycli request → apiKey = 'sk-123'
|
|
1059
|
-
* // $ mycli request --api-key sk-456 → apiKey = 'sk-456' (CLI wins)
|
|
1060
|
-
* ```
|
|
1061
|
-
*/
|
|
1062
|
-
env(varName: string): FlagBuilder<C>;
|
|
1063
|
-
/**
|
|
1064
|
-
* Bind to a dotted config path (resolved in v0.2+).
|
|
1065
|
-
*
|
|
1066
|
-
* @param path - Dotted config key (e.g. `'deploy.region'`).
|
|
1067
|
-
* @returns The builder (for chaining).
|
|
1068
|
-
*
|
|
1069
|
-
* @example
|
|
1070
|
-
* ```ts
|
|
1071
|
-
* flag.string().config('deploy.region').default('us-east-1')
|
|
1072
|
-
* // Config file: { "deploy": { "region": "eu-west-1" } }
|
|
1073
|
-
* // $ mycli deploy
|
|
1074
|
-
* // # → region = 'eu-west-1' (from config)
|
|
1075
|
-
* // $ mycli deploy --region ap-south-1
|
|
1076
|
-
* // # → CLI flag wins
|
|
1077
|
-
* ```
|
|
1078
|
-
*/
|
|
1079
|
-
config(path: string): FlagBuilder<C>;
|
|
1080
|
-
/**
|
|
1081
|
-
* Human-readable description shown in help output.
|
|
1082
|
-
*
|
|
1083
|
-
* @param description - Text displayed next to the flag in `--help`.
|
|
1084
|
-
* @returns The builder (for chaining).
|
|
1085
|
-
*/
|
|
1086
|
-
describe(description: string): FlagBuilder<C>;
|
|
1087
|
-
/**
|
|
1088
|
-
* Attach interactive prompt configuration for v0.3+ resolution.
|
|
1089
|
-
*
|
|
1090
|
-
* When a flag value is not resolved from CLI, env, or config, the
|
|
1091
|
-
* prompt engine uses this config to interactively ask the user.
|
|
1092
|
-
* In non-interactive contexts (CI, piped stdin) prompts are skipped
|
|
1093
|
-
* and resolution falls through to default or required validation.
|
|
1094
|
-
*
|
|
1095
|
-
* @param config - {@link PromptConfig} describing the interactive prompt.
|
|
1096
|
-
* @returns The builder (for chaining).
|
|
1097
|
-
*
|
|
1098
|
-
* @example
|
|
1099
|
-
* ```ts
|
|
1100
|
-
* flag.string().prompt({ kind: 'input', message: 'Enter value:' })
|
|
1101
|
-
*
|
|
1102
|
-
* // $ mycli init → prompts "Enter value:" interactively
|
|
1103
|
-
* // $ mycli init --name foo → skips prompt, uses CLI value
|
|
1104
|
-
* ```
|
|
1105
|
-
*/
|
|
1106
|
-
prompt(config: PromptConfig): FlagBuilder<C>;
|
|
1107
|
-
/**
|
|
1108
|
-
* Mark this flag as deprecated.
|
|
1109
|
-
*
|
|
1110
|
-
* When used, a warning is emitted to stderr. Help text shows
|
|
1111
|
-
* `[deprecated]` or `[deprecated: <reason>]`.
|
|
1112
|
-
*
|
|
1113
|
-
* Does not change the flag's type-level config — it's metadata only.
|
|
1114
|
-
*
|
|
1115
|
-
* @param message - Optional migration reason/guidance.
|
|
1116
|
-
* @returns The builder (for chaining).
|
|
1117
|
-
*
|
|
1118
|
-
* @example
|
|
1119
|
-
* ```ts
|
|
1120
|
-
* flag.string().deprecated('Use --target instead')
|
|
1121
|
-
*
|
|
1122
|
-
* // $ mycli deploy --dest staging
|
|
1123
|
-
* // ⚠ --dest is deprecated: Use --target instead
|
|
1124
|
-
* ```
|
|
1125
|
-
*/
|
|
1126
|
-
deprecated(message?: string): FlagBuilder<C>;
|
|
1127
|
-
/**
|
|
1128
|
-
* Mark this flag as propagated to subcommands.
|
|
1129
|
-
*
|
|
1130
|
-
* Propagated flags are automatically available to all descendant
|
|
1131
|
-
* commands in a nested command tree. A child command that defines
|
|
1132
|
-
* a flag with the same name shadows the propagated parent flag.
|
|
1133
|
-
*
|
|
1134
|
-
* Does not change the flag's type-level config — it's metadata only.
|
|
1135
|
-
*
|
|
1136
|
-
* @returns The builder (for chaining).
|
|
1137
|
-
*
|
|
1138
|
-
* @example
|
|
1139
|
-
* ```ts
|
|
1140
|
-
* flag.boolean().alias('v').propagate().describe('Enable verbose output')
|
|
1141
|
-
*
|
|
1142
|
-
* // $ mycli --verbose deploy staging
|
|
1143
|
-
* // # → verbose = true in deploy handler
|
|
1144
|
-
* // $ mycli deploy --verbose staging
|
|
1145
|
-
* // # → same, inherited from parent
|
|
1146
|
-
* ```
|
|
1147
|
-
*/
|
|
1148
|
-
propagate(): FlagBuilder<C>;
|
|
1149
|
-
}
|
|
1150
|
-
/**
|
|
1151
|
-
* Factory that creates {@link FlagBuilder} instances seeded with the correct
|
|
1152
|
-
* {@link FlagKind} and initial type-level config.
|
|
1153
|
-
*/
|
|
1154
|
-
interface FlagFactory {
|
|
1155
|
-
/**
|
|
1156
|
-
* String-valued flag.
|
|
1157
|
-
*
|
|
1158
|
-
* @returns A {@link FlagBuilder} for `string` values.
|
|
1159
|
-
*/
|
|
1160
|
-
string(): FlagBuilder<{
|
|
1161
|
-
readonly valueType: string;
|
|
1162
|
-
readonly presence: 'optional';
|
|
1163
|
-
readonly optionalFallback: 'undefined';
|
|
1164
|
-
}>;
|
|
1165
|
-
/**
|
|
1166
|
-
* Number-valued flag.
|
|
1167
|
-
*
|
|
1168
|
-
* @returns A {@link FlagBuilder} for `number` values.
|
|
1169
|
-
*/
|
|
1170
|
-
number(): FlagBuilder<{
|
|
1171
|
-
readonly valueType: number;
|
|
1172
|
-
readonly presence: 'optional';
|
|
1173
|
-
readonly optionalFallback: 'undefined';
|
|
1174
|
-
}>;
|
|
1175
|
-
/**
|
|
1176
|
-
* Boolean flag. Implicitly defaults to `false` — the only flag kind where
|
|
1177
|
-
* the absence of a value is still meaningful (not `undefined`).
|
|
1178
|
-
*
|
|
1179
|
-
* @returns A {@link FlagBuilder} for `boolean` values (defaulted to `false`).
|
|
1180
|
-
*/
|
|
1181
|
-
boolean(): FlagBuilder<{
|
|
1182
|
-
readonly valueType: boolean;
|
|
1183
|
-
readonly presence: 'defaulted';
|
|
1184
|
-
readonly optionalFallback: 'undefined';
|
|
1185
|
-
}>;
|
|
1186
|
-
/**
|
|
1187
|
-
* Enum flag with literal type inference.
|
|
1188
|
-
*
|
|
1189
|
-
* Requires a **non-empty** readonly tuple so that `T[number]` produces a
|
|
1190
|
-
* union of string literals rather than just `string`.
|
|
1191
|
-
*
|
|
1192
|
-
* @example
|
|
1193
|
-
* ```ts
|
|
1194
|
-
* flag.enum(['us', 'eu', 'ap'])
|
|
1195
|
-
* // inferred type: 'us' | 'eu' | 'ap'
|
|
1196
|
-
* ```
|
|
1197
|
-
*
|
|
1198
|
-
* @param values - Non-empty tuple of allowed string literals.
|
|
1199
|
-
* @returns A {@link FlagBuilder} whose value type is the union of `values`.
|
|
1200
|
-
*/
|
|
1201
|
-
enum<const T extends readonly [string, ...string[]]>(values: T): FlagBuilder<{
|
|
1202
|
-
readonly valueType: T[number];
|
|
1203
|
-
readonly presence: 'optional';
|
|
1204
|
-
readonly optionalFallback: 'undefined';
|
|
1205
|
-
}>;
|
|
1206
|
-
/**
|
|
1207
|
-
* Array flag — collects multiple values of the same element type.
|
|
1208
|
-
*
|
|
1209
|
-
* @example
|
|
1210
|
-
* ```ts
|
|
1211
|
-
* flag.array(flag.string())
|
|
1212
|
-
* // inferred type: string[]
|
|
1213
|
-
* ```
|
|
1214
|
-
*
|
|
1215
|
-
* @param element - {@link FlagBuilder} describing the element type.
|
|
1216
|
-
* @returns A {@link FlagBuilder} for arrays of the element type.
|
|
1217
|
-
*/
|
|
1218
|
-
array<E extends FlagConfig>(element: FlagBuilder<E>): FlagBuilder<{
|
|
1219
|
-
readonly valueType: E['valueType'][];
|
|
1220
|
-
readonly presence: 'optional';
|
|
1221
|
-
readonly optionalFallback: 'empty-array';
|
|
1222
|
-
}>;
|
|
1223
|
-
/**
|
|
1224
|
-
* Custom-parsed flag. The parse function receives the raw value and must
|
|
1225
|
-
* return a value of type `T`. The return type is inferred from `parseFn`.
|
|
1226
|
-
*
|
|
1227
|
-
* The input is `string` from CLI argv and env vars, or any JSON value
|
|
1228
|
-
* from config files. Narrow inside the function as needed:
|
|
1229
|
-
*
|
|
1230
|
-
* ```ts
|
|
1231
|
-
* flag.custom((raw: unknown): string[] => {
|
|
1232
|
-
* if (Array.isArray(raw)) return raw.map(String);
|
|
1233
|
-
* if (typeof raw === 'string') return raw.split(',');
|
|
1234
|
-
* throw new Error(`Expected string or array, got ${typeof raw}`);
|
|
1235
|
-
* })
|
|
1236
|
-
* ```
|
|
1237
|
-
*
|
|
1238
|
-
* Throw an `Error` (or `ParseError`) to signal invalid input — it will
|
|
1239
|
-
* be wrapped with context and re-thrown as a `ParseError`.
|
|
1240
|
-
*
|
|
1241
|
-
* @see `coerceConfigValue` `'custom'` case in `core/resolve/index.ts`
|
|
1242
|
-
*
|
|
1243
|
-
* @example
|
|
1244
|
-
* ```ts
|
|
1245
|
-
* flag.custom((raw) => new URL(String(raw)))
|
|
1246
|
-
* // inferred type: URL | undefined
|
|
1247
|
-
* ```
|
|
1248
|
-
*
|
|
1249
|
-
* @param parseFn - Converts the raw input into a value of type `T`.
|
|
1250
|
-
* @returns A {@link FlagBuilder} whose value type is inferred from `parseFn`.
|
|
1251
|
-
*/
|
|
1252
|
-
custom<T>(parseFn: FlagParseFn<T>): FlagBuilder<{
|
|
1253
|
-
readonly valueType: T;
|
|
1254
|
-
readonly presence: 'optional';
|
|
1255
|
-
readonly optionalFallback: 'undefined';
|
|
1256
|
-
}>;
|
|
1257
|
-
}
|
|
1258
|
-
/**
|
|
1259
|
-
* Flag schema factory. Call `flag.<kind>()` to create an immutable
|
|
1260
|
-
* {@link FlagBuilder} with full type inference and safe modifier chaining.
|
|
1261
|
-
*/
|
|
1262
|
-
declare const flag: FlagFactory;
|
|
1263
|
-
//#endregion
|
|
1264
|
-
//#region src/core/schema/middleware.d.ts
|
|
1265
|
-
/**
|
|
1266
|
-
* Parameters received by a middleware function at runtime.
|
|
1267
|
-
*
|
|
1268
|
-
* Middleware receives erased args/flags (since it's defined independently
|
|
1269
|
-
* of commands) plus the accumulated context from prior middleware and a
|
|
1270
|
-
* `next` function to continue the chain.
|
|
1271
|
-
*/
|
|
1272
|
-
interface MiddlewareParams {
|
|
1273
|
-
/** Fully resolved positional arguments (type-erased). */
|
|
1274
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
1275
|
-
/** Fully resolved flags (type-erased). */
|
|
1276
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
1277
|
-
/** Context accumulated from previous middleware in the chain. */
|
|
1278
|
-
readonly ctx: Readonly<Record<string, unknown>>;
|
|
1279
|
-
/** Output channel. */
|
|
1280
|
-
readonly out: Out;
|
|
1281
|
-
/** CLI program metadata (name, bin, version, command). */
|
|
1282
|
-
readonly meta: CommandMeta;
|
|
1283
|
-
/**
|
|
1284
|
-
* Continue to the next middleware or action handler.
|
|
1285
|
-
*
|
|
1286
|
-
* Call with context additions that merge into `ctx` for downstream.
|
|
1287
|
-
* Returns when the entire downstream chain completes — enabling
|
|
1288
|
-
* wrap-around patterns (timing, try/catch, cleanup).
|
|
1289
|
-
*/
|
|
1290
|
-
readonly next: (additions: Record<string, unknown>) => Promise<void>;
|
|
1291
|
-
}
|
|
1292
|
-
/**
|
|
1293
|
-
* Type-erased middleware handler stored on `CommandSchema`.
|
|
1294
|
-
*
|
|
1295
|
-
* At runtime, all middleware handlers have this signature. The phantom
|
|
1296
|
-
* `Output` type on `Middleware<O>` is erased.
|
|
1297
|
-
*
|
|
1298
|
-
* @internal
|
|
1299
|
-
*/
|
|
1300
|
-
type ErasedMiddlewareHandler = (params: MiddlewareParams) => void | Promise<void>;
|
|
1301
|
-
/**
|
|
1302
|
-
* Middleware handler function with typed `next()` parameter.
|
|
1303
|
-
*
|
|
1304
|
-
* The `Output` generic constrains what properties must be passed to
|
|
1305
|
-
* `next()`, ensuring type-safe context additions at the call site.
|
|
1306
|
-
*/
|
|
1307
|
-
type MiddlewareHandler<Output extends Record<string, unknown>> = (params: {
|
|
1308
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
1309
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
1310
|
-
readonly ctx: Readonly<Record<string, unknown>>;
|
|
1311
|
-
readonly out: Out;
|
|
1312
|
-
readonly meta: CommandMeta; /** Pass context additions downstream. Must include all `Output` properties. */
|
|
1313
|
-
readonly next: (additions: Output) => Promise<void>;
|
|
1314
|
-
}) => void | Promise<void>;
|
|
1315
|
-
/**
|
|
1316
|
-
* Internal runtime representation of middleware.
|
|
1317
|
-
* @internal
|
|
1318
|
-
*/
|
|
1319
|
-
interface MiddlewareImpl {
|
|
1320
|
-
readonly _handler: ErasedMiddlewareHandler;
|
|
1321
|
-
}
|
|
1322
|
-
/**
|
|
1323
|
-
* Middleware with phantom output type.
|
|
1324
|
-
*
|
|
1325
|
-
* The `Output` parameter tracks what this middleware adds to context at
|
|
1326
|
-
* compile time. The `_output` brand is phantom — it exists only in the
|
|
1327
|
-
* type system for inference, not at runtime.
|
|
1328
|
-
*
|
|
1329
|
-
* Created via the `middleware()` factory. Attached to commands via
|
|
1330
|
-
* `CommandBuilder.middleware()`.
|
|
1331
|
-
*
|
|
1332
|
-
* @example
|
|
1333
|
-
* ```ts
|
|
1334
|
-
* interface User { id: string; name: string }
|
|
1335
|
-
*
|
|
1336
|
-
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
1337
|
-
* const user = await getUser();
|
|
1338
|
-
* if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
1339
|
-
* return next({ user });
|
|
1340
|
-
* });
|
|
1341
|
-
* ```
|
|
1342
|
-
*/
|
|
1343
|
-
type Middleware<Output extends Record<string, unknown>> = MiddlewareImpl & {
|
|
1344
|
-
/** @internal Phantom type brand — compile-time only. */readonly _output: Output;
|
|
1345
|
-
};
|
|
1346
|
-
/**
|
|
1347
|
-
* Create a middleware definition.
|
|
1348
|
-
*
|
|
1349
|
-
* Middleware runs before the action handler and can add typed context,
|
|
1350
|
-
* short-circuit execution, or wrap downstream processing.
|
|
1351
|
-
*
|
|
1352
|
-
* @param handler - Function receiving `{ args, flags, ctx, out, next }`.
|
|
1353
|
-
* Call `next(additions)` to continue the chain with added context.
|
|
1354
|
-
* Omitting the `next()` call short-circuits (e.g., for auth guards).
|
|
1355
|
-
* @returns Middleware to attach via `CommandBuilder.middleware()`.
|
|
1356
|
-
*
|
|
1357
|
-
* @example
|
|
1358
|
-
* ```ts
|
|
1359
|
-
* // Auth guard — adds user to context or throws
|
|
1360
|
-
* const auth = middleware(async ({ next }) => {
|
|
1361
|
-
* const user = await getUser();
|
|
1362
|
-
* if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
1363
|
-
* return next({ user });
|
|
1364
|
-
* });
|
|
1365
|
-
*
|
|
1366
|
-
* // Timing wrapper — measures downstream execution
|
|
1367
|
-
* const timing = middleware(async ({ out, next }) => {
|
|
1368
|
-
* const start = Date.now();
|
|
1369
|
-
* await next({});
|
|
1370
|
-
* out.info(`Done in ${Date.now() - start}ms`);
|
|
1371
|
-
* });
|
|
1372
|
-
*
|
|
1373
|
-
* command('deploy')
|
|
1374
|
-
* .middleware(timing)
|
|
1375
|
-
* .middleware(auth)
|
|
1376
|
-
* .action(({ ctx }) => {
|
|
1377
|
-
* console.log(ctx.user.name); // typed!
|
|
1378
|
-
* });
|
|
1379
|
-
* ```
|
|
1380
|
-
*/
|
|
1381
|
-
declare function middleware<Output extends Record<string, unknown>>(handler: MiddlewareHandler<Output>): Middleware<Output>;
|
|
1382
|
-
//#endregion
|
|
1383
|
-
//#region src/core/parse/index.d.ts
|
|
1384
|
-
/**
|
|
1385
|
-
* Token discriminated union.
|
|
1386
|
-
*
|
|
1387
|
-
* The tokenizer produces these from raw argv strings. The parser then
|
|
1388
|
-
* interprets them against a command schema.
|
|
1389
|
-
*/
|
|
1390
|
-
type Token = {
|
|
1391
|
-
readonly kind: 'long-flag';
|
|
1392
|
-
readonly name: string;
|
|
1393
|
-
readonly value: string | undefined;
|
|
1394
|
-
} | {
|
|
1395
|
-
readonly kind: 'short-flags';
|
|
1396
|
-
readonly chars: string;
|
|
1397
|
-
} | {
|
|
1398
|
-
readonly kind: 'positional';
|
|
1399
|
-
readonly value: string;
|
|
1400
|
-
} | {
|
|
1401
|
-
readonly kind: 'separator';
|
|
1402
|
-
};
|
|
1403
|
-
/**
|
|
1404
|
-
* Tokenize raw argv into structured tokens.
|
|
1405
|
-
*
|
|
1406
|
-
* Low-level utility: most apps should use {@link parse}, `cli().run()`, or
|
|
1407
|
-
* `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
|
|
1408
|
-
* building custom tooling such as debuggers, inspectors, or parser tests.
|
|
1409
|
-
*
|
|
1410
|
-
* Rules:
|
|
1411
|
-
* - `--` → separator (everything after is positional)
|
|
1412
|
-
* - `--flag` → long flag, no inline value
|
|
1413
|
-
* - `--flag=v` → long flag with inline value
|
|
1414
|
-
* - `-abc` → short flags (expanded individually by parser)
|
|
1415
|
-
* - `-` → positional (convention: stdin placeholder)
|
|
1416
|
-
* - everything else → positional
|
|
1417
|
-
*
|
|
1418
|
-
* @param argv - Raw argument strings to tokenize
|
|
1419
|
-
* @returns Ordered token array ready for {@link parse}
|
|
1420
|
-
*
|
|
1421
|
-
* @example
|
|
1422
|
-
* ```ts
|
|
1423
|
-
* tokenize(['deploy', '--force', '--region=eu', '-v']);
|
|
1424
|
-
* ```
|
|
1425
|
-
*/
|
|
1426
|
-
declare function tokenize(argv: readonly string[]): readonly Token[];
|
|
1427
|
-
/**
|
|
1428
|
-
* Raw parsed values before resolution (defaults, env, config, etc.).
|
|
1429
|
-
*
|
|
1430
|
-
* Flag values are `unknown` because type coercion happens here but the
|
|
1431
|
-
* generic type info lives in the schema builders, not at runtime.
|
|
1432
|
-
*/
|
|
1433
|
-
interface ParseResult {
|
|
1434
|
-
/** Flag values keyed by canonical flag name. */
|
|
1435
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
1436
|
-
/** Positional arg values keyed by arg name. */
|
|
1437
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
1438
|
-
}
|
|
1439
|
-
/**
|
|
1440
|
-
* Parse tokenized argv against a command schema.
|
|
1441
|
-
*
|
|
1442
|
-
* Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
|
|
1443
|
-
* automatically. Call `parse()` directly when you need raw parsed values before
|
|
1444
|
-
* env/config/default resolution or when writing custom tooling around schemas.
|
|
1445
|
-
*
|
|
1446
|
-
* @param schema - The command schema to parse against
|
|
1447
|
-
* @param argv - Raw argv strings (NOT including the command name itself)
|
|
1448
|
-
* @returns Parsed flag and arg values
|
|
1449
|
-
* @throws ParseError for unknown flags, missing values, type mismatches
|
|
1450
|
-
*
|
|
1451
|
-
* @example
|
|
1452
|
-
* ```ts
|
|
1453
|
-
* const parsed = parse(deploy.schema, ['production', '--force']);
|
|
1454
|
-
* // => { args: { target: 'production' }, flags: { force: true } }
|
|
1455
|
-
* ```
|
|
1456
|
-
*/
|
|
1457
|
-
declare function parse(schema: CommandSchema, argv: readonly string[]): ParseResult;
|
|
1458
|
-
//#endregion
|
|
1459
|
-
//#region src/core/output/writer.d.ts
|
|
1460
|
-
/**
|
|
1461
|
-
* Minimal I/O seam — the only write primitive the output module depends on.
|
|
1462
|
-
*
|
|
1463
|
-
* Extracted to its own file so that both `index.ts` (OutputChannel) and
|
|
1464
|
-
* `activity.ts` (handle classes) can import it without a circular dependency.
|
|
1465
|
-
*
|
|
1466
|
-
* @module dreamcli/core/output/writer
|
|
1467
|
-
* @internal
|
|
1468
|
-
*/
|
|
1469
|
-
/**
|
|
1470
|
-
* A function that writes a string somewhere.
|
|
1471
|
-
*
|
|
1472
|
-
* This is the only write primitive the output layer depends on.
|
|
1473
|
-
* In production it usually wraps `process.stdout.write` or
|
|
1474
|
-
* `process.stderr.write`; in tests it is often a simple string accumulator.
|
|
1475
|
-
*
|
|
1476
|
-
* The contract is intentionally tiny:
|
|
1477
|
-
* - writes are synchronous fire-and-forget
|
|
1478
|
-
* - callers decide whether to append a trailing newline
|
|
1479
|
-
* - there is no backpressure or flush signal
|
|
1480
|
-
*
|
|
1481
|
-
* @example
|
|
1482
|
-
* ```ts
|
|
1483
|
-
* const lines: string[] = [];
|
|
1484
|
-
* const write: WriteFn = (data) => {
|
|
1485
|
-
* lines.push(data);
|
|
1486
|
-
* };
|
|
1487
|
-
* ```
|
|
1488
|
-
*/
|
|
1489
|
-
type WriteFn = (data: string) => void;
|
|
1490
|
-
/**
|
|
1491
|
-
* Write a message followed by a newline.
|
|
1492
|
-
*
|
|
1493
|
-
* @param write - The underlying write function.
|
|
1494
|
-
* @param message - The text to write.
|
|
1495
|
-
*/
|
|
1496
|
-
//#endregion
|
|
1497
|
-
//#region src/core/output/index.d.ts
|
|
1498
|
-
/**
|
|
1499
|
-
* Controls which messages are emitted.
|
|
1500
|
-
*
|
|
1501
|
-
* - `'normal'` — all messages
|
|
1502
|
-
* - `'quiet'` — suppresses `info`; keeps `log`, `warn`, `error`
|
|
1503
|
-
*/
|
|
1504
|
-
type Verbosity = 'normal' | 'quiet';
|
|
1505
|
-
/**
|
|
1506
|
-
* Configuration for creating an output channel.
|
|
1507
|
-
*
|
|
1508
|
-
* Every field is optional — sensible defaults are applied when omitted.
|
|
1509
|
-
*/
|
|
1510
|
-
interface OutputOptions {
|
|
1511
|
-
/**
|
|
1512
|
-
* Writer for stdout-bound messages (`log`, `info`, `json`).
|
|
1513
|
-
* Defaults to `process.stdout.write` when running in Node/Bun.
|
|
1514
|
-
*/
|
|
1515
|
-
readonly stdout?: WriteFn;
|
|
1516
|
-
/**
|
|
1517
|
-
* Writer for stderr-bound messages (`warn`, `error`).
|
|
1518
|
-
* In JSON mode, `log` and `info` are also redirected here so that
|
|
1519
|
-
* stdout contains only structured JSON output.
|
|
1520
|
-
* Defaults to `process.stderr.write` when running in Node/Bun.
|
|
1521
|
-
*/
|
|
1522
|
-
readonly stderr?: WriteFn;
|
|
1523
|
-
/**
|
|
1524
|
-
* Whether stdout is connected to a TTY.
|
|
1525
|
-
* When `false`, output may omit ANSI codes and decorations.
|
|
1526
|
-
* Defaults to `false` (safe default — non-TTY until proven otherwise).
|
|
1527
|
-
*/
|
|
1528
|
-
readonly isTTY?: boolean;
|
|
1529
|
-
/**
|
|
1530
|
-
* Verbosity level.
|
|
1531
|
-
* - `'normal'` (default) — emit all messages
|
|
1532
|
-
* - `'quiet'` — suppress `info` messages
|
|
1533
|
-
*/
|
|
1534
|
-
readonly verbosity?: Verbosity;
|
|
1535
|
-
/**
|
|
1536
|
-
* Enable JSON output mode.
|
|
1537
|
-
*
|
|
1538
|
-
* When `true`, `log` and `info` messages are redirected to stderr
|
|
1539
|
-
* so that stdout is reserved exclusively for structured `json()` output.
|
|
1540
|
-
* `warn` and `error` continue to write to stderr as normal.
|
|
1541
|
-
*
|
|
1542
|
-
* @defaultValue `false`
|
|
1543
|
-
*/
|
|
1544
|
-
readonly jsonMode?: boolean;
|
|
1545
|
-
}
|
|
1546
|
-
/** Fully resolved output options with no optional fields. */
|
|
1547
|
-
/**
|
|
1548
|
-
* Create an output channel.
|
|
1549
|
-
*
|
|
1550
|
-
* Low-level factory: action handlers already receive `out` automatically from
|
|
1551
|
-
* `cli()`, `.execute()`, and `runCommand()`. Call `createOutput()` when you
|
|
1552
|
-
* are embedding DreamCLI primitives into a custom runtime or need a standalone
|
|
1553
|
-
* output implementation outside the normal command pipeline.
|
|
1554
|
-
*
|
|
1555
|
-
* @param options - Optional configuration. When omitted, output is
|
|
1556
|
-
* discarded (useful for silent test runs). Pass `stdout`/`stderr`
|
|
1557
|
-
* writers to direct output somewhere useful.
|
|
1558
|
-
*
|
|
1559
|
-
* @returns An {@link Out} instance backed by an {@link OutputChannel}.
|
|
1560
|
-
*
|
|
1561
|
-
* @example
|
|
1562
|
-
* ```ts
|
|
1563
|
-
* // Production (wired by the runtime adapter)
|
|
1564
|
-
* const out = createOutput({
|
|
1565
|
-
* stdout: (s) => process.stdout.write(s),
|
|
1566
|
-
* stderr: (s) => process.stderr.write(s),
|
|
1567
|
-
* isTTY: process.stdout.isTTY === true,
|
|
1568
|
-
* });
|
|
1569
|
-
*
|
|
1570
|
-
* // Test (capture output)
|
|
1571
|
-
* const lines: string[] = [];
|
|
1572
|
-
* const out = createOutput({
|
|
1573
|
-
* stdout: (s) => lines.push(s),
|
|
1574
|
-
* stderr: (s) => lines.push(s),
|
|
1575
|
-
* });
|
|
1576
|
-
* ```
|
|
1577
|
-
*/
|
|
1578
|
-
declare function createOutput(options?: OutputOptions): Out;
|
|
1579
|
-
/** Captured output from a `createCaptureOutput` instance. */
|
|
1580
|
-
interface CapturedOutput {
|
|
1581
|
-
/**
|
|
1582
|
-
* Lines written to stdout.
|
|
1583
|
-
*
|
|
1584
|
-
* In normal mode: `log`, `info`, and `json` output.
|
|
1585
|
-
* In JSON mode: only `json` output (log/info redirected to stderr).
|
|
1586
|
-
*/
|
|
1587
|
-
readonly stdout: string[];
|
|
1588
|
-
/**
|
|
1589
|
-
* Lines written to stderr.
|
|
1590
|
-
*
|
|
1591
|
-
* In normal mode: `warn` and `error` output.
|
|
1592
|
-
* In JSON mode: `warn`, `error`, `log`, and `info` output.
|
|
1593
|
-
*/
|
|
1594
|
-
readonly stderr: string[];
|
|
1595
|
-
/**
|
|
1596
|
-
* Activity events from spinner and progress handles.
|
|
1597
|
-
*
|
|
1598
|
-
* Captured separately from stdout/stderr to allow targeted assertions
|
|
1599
|
-
* on activity lifecycle without parsing text output. Events are
|
|
1600
|
-
* recorded in chronological order.
|
|
1601
|
-
*/
|
|
1602
|
-
readonly activity: ActivityEvent[];
|
|
1603
|
-
}
|
|
1604
|
-
/**
|
|
1605
|
-
* Create an output channel that captures all output into arrays.
|
|
1606
|
-
*
|
|
1607
|
-
* Useful in tests to assert on what a handler wrote without touching
|
|
1608
|
-
* real I/O.
|
|
1609
|
-
*
|
|
1610
|
-
* @param options - Optional {@link OutputOptions} (minus `stdout`/`stderr`,
|
|
1611
|
-
* which are wired to the capture buffers automatically).
|
|
1612
|
-
*
|
|
1613
|
-
* @returns A tuple of `[out, captured]` — the {@link Out} channel and the
|
|
1614
|
-
* {@link CapturedOutput} buffers.
|
|
1615
|
-
*
|
|
1616
|
-
* @example
|
|
1617
|
-
* ```ts
|
|
1618
|
-
* const [out, captured] = createCaptureOutput();
|
|
1619
|
-
* out.log('hello');
|
|
1620
|
-
* out.warn('danger');
|
|
1621
|
-
* expect(captured.stdout).toEqual(['hello\n']);
|
|
1622
|
-
* expect(captured.stderr).toEqual(['danger\n']);
|
|
1623
|
-
* ```
|
|
1624
|
-
*/
|
|
1625
|
-
declare function createCaptureOutput(options?: Omit<OutputOptions, 'stdout' | 'stderr'>): [out: Out, captured: CapturedOutput];
|
|
1626
|
-
//#endregion
|
|
1627
|
-
//#region src/core/prompt/index.d.ts
|
|
1628
|
-
/**
|
|
1629
|
-
* A select prompt config with choices guaranteed non-empty.
|
|
1630
|
-
*
|
|
1631
|
-
* The resolution chain populates choices from `FlagSchema.enumValues`
|
|
1632
|
-
* when the user's `PromptConfig` omits them.
|
|
1633
|
-
*/
|
|
1634
|
-
interface ResolvedSelectPromptConfig {
|
|
1635
|
-
readonly kind: 'select';
|
|
1636
|
-
readonly message: string;
|
|
1637
|
-
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
1638
|
-
}
|
|
1639
|
-
/**
|
|
1640
|
-
* A multiselect prompt config with choices guaranteed non-empty.
|
|
1641
|
-
*
|
|
1642
|
-
* Same guarantee as `ResolvedSelectPromptConfig` — choices are always
|
|
1643
|
-
* present and non-empty.
|
|
1644
|
-
*/
|
|
1645
|
-
interface ResolvedMultiselectPromptConfig {
|
|
1646
|
-
readonly kind: 'multiselect';
|
|
1647
|
-
readonly message: string;
|
|
1648
|
-
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
1649
|
-
readonly min?: number;
|
|
1650
|
-
readonly max?: number;
|
|
1651
|
-
}
|
|
1652
|
-
/**
|
|
1653
|
-
* Prompt config variant where select/multiselect choices are guaranteed
|
|
1654
|
-
* present. The prompt engine receives this (not raw `PromptConfig`),
|
|
1655
|
-
* so it never needs to merge enum values from `FlagSchema`.
|
|
1656
|
-
*
|
|
1657
|
-
* confirm and input configs pass through unchanged.
|
|
1658
|
-
*/
|
|
1659
|
-
type ResolvedPromptConfig = ConfirmPromptConfig | InputPromptConfig | ResolvedSelectPromptConfig | ResolvedMultiselectPromptConfig;
|
|
1660
|
-
/**
|
|
1661
|
-
* Prompt engine interface.
|
|
1662
|
-
*
|
|
1663
|
-
* Implementations render a single prompt to the user and return the
|
|
1664
|
-
* result. The engine is stateless per call — each `promptOne` is
|
|
1665
|
-
* independent.
|
|
1666
|
-
*
|
|
1667
|
-
* The resolution chain calls `promptOne` for each flag that needs
|
|
1668
|
-
* interactive input. Engines do not need schema knowledge — all
|
|
1669
|
-
* relevant context (message, choices, validation) is in the config.
|
|
1670
|
-
*
|
|
1671
|
-
* @example
|
|
1672
|
-
* ```ts
|
|
1673
|
-
* // Custom engine (e.g. wrapping @clack/prompts)
|
|
1674
|
-
* const engine: PromptEngine = {
|
|
1675
|
-
* async promptOne(config) {
|
|
1676
|
-
* // ... render with your library
|
|
1677
|
-
* return { answered: true, value: userInput };
|
|
1678
|
-
* }
|
|
1679
|
-
* };
|
|
1680
|
-
* ```
|
|
1681
|
-
*/
|
|
1682
|
-
interface PromptEngine {
|
|
1683
|
-
/**
|
|
1684
|
-
* Present a single prompt and return the user's response.
|
|
1685
|
-
*
|
|
1686
|
-
* @param config - The resolved prompt configuration (choices guaranteed
|
|
1687
|
-
* for select/multiselect).
|
|
1688
|
-
* @returns The user's answer, or `{ answered: false }` if cancelled.
|
|
1689
|
-
*/
|
|
1690
|
-
promptOne(config: ResolvedPromptConfig): Promise<PromptResult>;
|
|
1691
|
-
}
|
|
1692
|
-
/**
|
|
1693
|
-
* A function that reads a single line of user input.
|
|
1694
|
-
*
|
|
1695
|
-
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
1696
|
-
* indicating the user closed the input stream (treated as cancel).
|
|
1697
|
-
*
|
|
1698
|
-
* The terminal prompter uses this as its sole input seam. The
|
|
1699
|
-
* resolution chain (prompt-adapter-1) will wire this to the
|
|
1700
|
-
* runtime adapter's stdin.
|
|
1701
|
-
*/
|
|
1702
|
-
type ReadFn = () => Promise<string | null>;
|
|
1703
|
-
/**
|
|
1704
|
-
* Sentinel value representing a cancelled/aborted prompt in the test
|
|
1705
|
-
* prompter's answer queue.
|
|
1706
|
-
*
|
|
1707
|
-
* Uses `Symbol.for()` for cross-bundle safety — the same symbol is
|
|
1708
|
-
* returned regardless of which copy of the module is loaded.
|
|
1709
|
-
*
|
|
1710
|
-
* @example
|
|
1711
|
-
* ```ts
|
|
1712
|
-
* const prompter = createTestPrompter([
|
|
1713
|
-
* 'us', // first prompt answered 'us'
|
|
1714
|
-
* PROMPT_CANCEL, // second prompt cancelled
|
|
1715
|
-
* ]);
|
|
1716
|
-
* ```
|
|
1717
|
-
*/
|
|
1718
|
-
declare const PROMPT_CANCEL: unique symbol;
|
|
1719
|
-
/**
|
|
1720
|
-
* A queued answer consumed by {@link createTestPrompter}.
|
|
1721
|
-
*
|
|
1722
|
-
* The test prompter returns these values exactly as provided; it does not
|
|
1723
|
-
* coerce or validate them. The normal resolution pipeline performs any later
|
|
1724
|
-
* type coercion, so tests can supply values in the same shapes real prompts
|
|
1725
|
-
* would yield:
|
|
1726
|
-
*
|
|
1727
|
-
* - `string` for `input` and `select`
|
|
1728
|
-
* - `boolean` for `confirm`
|
|
1729
|
-
* - `string[]` for `multiselect`
|
|
1730
|
-
* - {@link PROMPT_CANCEL} to simulate user cancellation
|
|
1731
|
-
*
|
|
1732
|
-
* Because the type is intentionally `unknown`, tests may also inject malformed
|
|
1733
|
-
* answers to exercise downstream validation and error reporting.
|
|
1734
|
-
*/
|
|
1735
|
-
type TestAnswer = unknown;
|
|
1736
|
-
/**
|
|
1737
|
-
* Options for `createTestPrompter`.
|
|
1738
|
-
*/
|
|
1739
|
-
interface TestPrompterOptions {
|
|
1740
|
-
/**
|
|
1741
|
-
* Behavior when all answers have been consumed.
|
|
1742
|
-
*
|
|
1743
|
-
* - `'throw'` (default) — throws an error, making the test fail
|
|
1744
|
-
* loudly if more prompts fire than expected.
|
|
1745
|
-
* - `'cancel'` — returns `{ answered: false }`, simulating the
|
|
1746
|
-
* user cancelling all subsequent prompts.
|
|
1747
|
-
*/
|
|
1748
|
-
readonly onExhausted?: 'throw' | 'cancel';
|
|
1749
|
-
}
|
|
1750
|
-
/**
|
|
1751
|
-
* Create a prompt engine that returns pre-configured answers.
|
|
1752
|
-
*
|
|
1753
|
-
* Each call to `promptOne` consumes the next answer from the queue.
|
|
1754
|
-
* Pass `PROMPT_CANCEL` as an answer to simulate the user cancelling
|
|
1755
|
-
* that prompt.
|
|
1756
|
-
*
|
|
1757
|
-
* @param answers - Ordered queue of answers. Use `PROMPT_CANCEL` for
|
|
1758
|
-
* cancellation.
|
|
1759
|
-
* @param options - Controls behavior when the queue is exhausted.
|
|
1760
|
-
* @returns A `PromptEngine` suitable for testing.
|
|
1761
|
-
*
|
|
1762
|
-
* @example
|
|
1763
|
-
* ```ts
|
|
1764
|
-
* const prompter = createTestPrompter(['eu', true, PROMPT_CANCEL]);
|
|
1765
|
-
*
|
|
1766
|
-
* // First promptOne → { answered: true, value: 'eu' }
|
|
1767
|
-
* // Second promptOne → { answered: true, value: true }
|
|
1768
|
-
* // Third promptOne → { answered: false }
|
|
1769
|
-
* ```
|
|
1770
|
-
*/
|
|
1771
|
-
declare function createTestPrompter(answers: readonly TestAnswer[], options?: TestPrompterOptions): PromptEngine;
|
|
1772
|
-
/**
|
|
1773
|
-
* Create a prompt engine backed by line-based terminal I/O.
|
|
1774
|
-
*
|
|
1775
|
-
* Uses a `ReadFn` for input and a `WriteFn` for output. This is the
|
|
1776
|
-
* built-in renderer — sufficient for most CLI use cases. For richer
|
|
1777
|
-
* TUI experiences, users can implement `PromptEngine` with a library
|
|
1778
|
-
* like `@clack/prompts` or `inquirer`.
|
|
1779
|
-
*
|
|
1780
|
-
* The prompter does **not** use raw mode — all input is line-based.
|
|
1781
|
-
* This keeps the implementation portable across Node, Bun, and Deno
|
|
1782
|
-
* without platform-specific stdin configuration.
|
|
1783
|
-
*
|
|
1784
|
-
* @param read - Line reader function (returns `null` on EOF)
|
|
1785
|
-
* @param write - Output writer function
|
|
1786
|
-
* @returns A `PromptEngine` that prompts via terminal I/O
|
|
1787
|
-
*
|
|
1788
|
-
* @example
|
|
1789
|
-
* ```ts
|
|
1790
|
-
* import { createInterface } from 'readline';
|
|
1791
|
-
*
|
|
1792
|
-
* const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
1793
|
-
* const read = () => new Promise<string | null>((resolve) => {
|
|
1794
|
-
* rl.question('', (answer) => resolve(answer));
|
|
1795
|
-
* });
|
|
1796
|
-
* const write: WriteFn = (s) => process.stdout.write(s);
|
|
1797
|
-
*
|
|
1798
|
-
* const prompter = createTerminalPrompter(read, write);
|
|
1799
|
-
* ```
|
|
1800
|
-
*/
|
|
1801
|
-
declare function createTerminalPrompter(read: ReadFn, write: WriteFn): PromptEngine;
|
|
1802
|
-
/**
|
|
1803
|
-
* Prepare a `ResolvedPromptConfig` from a raw `PromptConfig` and optional
|
|
1804
|
-
* enum values from the flag schema.
|
|
1805
|
-
*
|
|
1806
|
-
* For select/multiselect prompts without explicit choices, this merges
|
|
1807
|
-
* the flag's enum values into the choices list. Throws if no choices
|
|
1808
|
-
* are available.
|
|
1809
|
-
*
|
|
1810
|
-
* This function is called by the resolution chain (prompt-resolve-1),
|
|
1811
|
-
* not by the engine itself — keeping the engine free of schema knowledge.
|
|
1812
|
-
*
|
|
1813
|
-
* @param config - Raw prompt config from `FlagSchema.prompt`
|
|
1814
|
-
* @param enumValues - Optional enum values from `FlagSchema.enumValues`
|
|
1815
|
-
* @returns Resolved config with choices guaranteed for select kinds
|
|
1816
|
-
* @throws Error if select/multiselect has no choices and no enum values
|
|
1817
|
-
*/
|
|
1818
|
-
declare function resolvePromptConfig(config: PromptConfig, enumValues: readonly string[] | undefined): ResolvedPromptConfig;
|
|
1819
|
-
//#endregion
|
|
1820
|
-
//#region src/core/resolve/index.d.ts
|
|
1821
|
-
/**
|
|
1822
|
-
* Options controlling the resolution chain.
|
|
1823
|
-
*
|
|
1824
|
-
* These provide external state (env vars, config objects) that the resolver
|
|
1825
|
-
* reads from when CLI-provided values are absent.
|
|
1826
|
-
*/
|
|
1827
|
-
interface ResolveOptions {
|
|
1828
|
-
/**
|
|
1829
|
-
* Full stdin contents for args configured with `.stdin()`.
|
|
1830
|
-
*
|
|
1831
|
-
* When an arg has `stdinMode: true`, resolution checks this value after
|
|
1832
|
-
* CLI argv and before env/default. `null` means stdin was checked but no
|
|
1833
|
-
* piped data was available.
|
|
1834
|
-
*/
|
|
1835
|
-
readonly stdinData?: string | null;
|
|
1836
|
-
/**
|
|
1837
|
-
* Environment variables to resolve against.
|
|
1838
|
-
*
|
|
1839
|
-
* For each flag with `schema.envVar` set, the resolver looks up the
|
|
1840
|
-
* env var value here. Values are coerced to the flag's declared kind.
|
|
1841
|
-
*
|
|
1842
|
-
* @example
|
|
1843
|
-
* ```ts
|
|
1844
|
-
* resolve(schema, parsed, { env: { DEPLOY_REGION: 'eu' } })
|
|
1845
|
-
* ```
|
|
1846
|
-
*/
|
|
1847
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
1848
|
-
/**
|
|
1849
|
-
* Configuration object to resolve against.
|
|
1850
|
-
*
|
|
1851
|
-
* For each flag with `schema.configPath` set, the resolver looks up the
|
|
1852
|
-
* value at the dotted path (e.g. `'deploy.region'`). Config values may
|
|
1853
|
-
* already be typed (number, boolean, array) so coercion is lenient —
|
|
1854
|
-
* only validates kind compatibility rather than string-parsing.
|
|
1855
|
-
*
|
|
1856
|
-
* Config is plain JSON — file loading is the caller's responsibility.
|
|
1857
|
-
*
|
|
1858
|
-
* @example
|
|
1859
|
-
* ```ts
|
|
1860
|
-
* resolve(schema, parsed, { config: { deploy: { region: 'eu' } } })
|
|
1861
|
-
* ```
|
|
1862
|
-
*/
|
|
1863
|
-
readonly config?: Readonly<Record<string, unknown>>;
|
|
1864
|
-
/**
|
|
1865
|
-
* Prompt engine for interactive flag resolution.
|
|
1866
|
-
*
|
|
1867
|
-
* When provided, flags with `schema.prompt` configured that have no
|
|
1868
|
-
* value after CLI/env/config resolution will be prompted interactively.
|
|
1869
|
-
*
|
|
1870
|
-
* When absent (or in non-interactive contexts), prompting is skipped
|
|
1871
|
-
* and resolution falls through to default/required.
|
|
1872
|
-
*
|
|
1873
|
-
* @example
|
|
1874
|
-
* ```ts
|
|
1875
|
-
* resolve(schema, parsed, { prompter: createTestPrompter(['eu']) })
|
|
1876
|
-
* ```
|
|
1877
|
-
*/
|
|
1878
|
-
readonly prompter?: PromptEngine;
|
|
1879
|
-
}
|
|
1880
|
-
/**
|
|
1881
|
-
* Fully resolved flag and arg values — guaranteed present for required
|
|
1882
|
-
* and defaulted entries.
|
|
1883
|
-
*
|
|
1884
|
-
* At runtime the maps are `Record<string, unknown>` because the generic
|
|
1885
|
-
* type info lives in the builder phantom types, not here. Type narrowing
|
|
1886
|
-
* happens at the `CommandBuilder.action()` boundary via `InferFlags`/
|
|
1887
|
-
* `InferArgs`.
|
|
1888
|
-
*/
|
|
1889
|
-
interface ResolveResult {
|
|
1890
|
-
/** Resolved flag values keyed by canonical flag name. */
|
|
1891
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
1892
|
-
/** Resolved arg values keyed by arg name. */
|
|
1893
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
1894
|
-
/**
|
|
1895
|
-
* Deprecation notices for flags/args that were explicitly provided.
|
|
1896
|
-
*
|
|
1897
|
-
* Populated when a deprecated flag or arg receives a value from any
|
|
1898
|
-
* explicit source (CLI, env, config, prompt). Not populated for
|
|
1899
|
-
* default fallthrough.
|
|
1900
|
-
*
|
|
1901
|
-
* Consumers decide how to render these — the resolve layer provides
|
|
1902
|
-
* structured data, not formatted strings.
|
|
1903
|
-
*/
|
|
1904
|
-
readonly deprecations: readonly DeprecationWarning[];
|
|
1905
|
-
}
|
|
1906
|
-
/**
|
|
1907
|
-
* Structured deprecation notice emitted when a deprecated flag or arg
|
|
1908
|
-
* is explicitly provided.
|
|
1909
|
-
*
|
|
1910
|
-
* Consumers (testkit, CLI layer) decide formatting. The resolve layer
|
|
1911
|
-
* only collects facts.
|
|
1912
|
-
*/
|
|
1913
|
-
interface DeprecationWarning {
|
|
1914
|
-
/** Whether the deprecated entity is a flag or a positional arg. */
|
|
1915
|
-
readonly kind: 'flag' | 'arg';
|
|
1916
|
-
/** Canonical name of the flag or arg. */
|
|
1917
|
-
readonly name: string;
|
|
1918
|
-
/**
|
|
1919
|
-
* Deprecation reason/migration guidance, or `true` for generic
|
|
1920
|
-
* deprecation with no specific message.
|
|
1921
|
-
*/
|
|
1922
|
-
readonly message: string | true;
|
|
1923
|
-
}
|
|
1924
|
-
/**
|
|
1925
|
-
* Resolve parsed values against a command schema.
|
|
1926
|
-
*
|
|
1927
|
-
* Low-level API: most applications should rely on `cli().run()`, `.execute()`,
|
|
1928
|
-
* or `runCommand()`, which already call `resolve()` at the right time. Reach
|
|
1929
|
-
* for this function when testing precedence rules directly or building custom
|
|
1930
|
-
* execution flows around `CommandSchema`.
|
|
1931
|
-
*
|
|
1932
|
-
* Resolution order:
|
|
1933
|
-
* 1. CLI parsed value (from `ParseResult`)
|
|
1934
|
-
* 2. Env variable (from `ResolveOptions.env`, if flag declares `envVar`)
|
|
1935
|
-
* 3. Config value (from `ResolveOptions.config`, if flag declares `configPath`)
|
|
1936
|
-
* 4. Prompt (from `ResolveOptions.prompter`, if flag declares `prompt`)
|
|
1937
|
-
* 5. Default value (from schema)
|
|
1938
|
-
*
|
|
1939
|
-
* After resolution, validates that all required flags and args have
|
|
1940
|
-
* a value. Collects **all** validation errors before throwing, so the
|
|
1941
|
-
* user sees every missing field at once.
|
|
1942
|
-
*
|
|
1943
|
-
* @param schema - The command schema defining flags and args
|
|
1944
|
-
* @param parsed - Raw parsed values from the parser
|
|
1945
|
-
* @param options - External state for the resolution chain
|
|
1946
|
-
* @returns Fully resolved flag and arg values
|
|
1947
|
-
* @throws ValidationError if any required flag or arg is missing,
|
|
1948
|
-
* or if an env/config value fails coercion
|
|
1949
|
-
*
|
|
1950
|
-
* @example
|
|
1951
|
-
* ```ts
|
|
1952
|
-
* const parsed = parse(deploy.schema, ['production']);
|
|
1953
|
-
* const resolved = await resolve(deploy.schema, parsed, {
|
|
1954
|
-
* env: { DEPLOY_REGION: 'eu' },
|
|
1955
|
-
* });
|
|
1956
|
-
* ```
|
|
1957
|
-
*/
|
|
1958
|
-
declare function resolve(schema: CommandSchema, parsed: ParseResult, options?: ResolveOptions): Promise<ResolveResult>;
|
|
1959
|
-
//#endregion
|
|
1960
|
-
//#region src/core/cli/plugin.d.ts
|
|
1961
|
-
/** Shared hook payload for a concrete command execution. */
|
|
1962
|
-
interface PluginCommandContext {
|
|
1963
|
-
/** Runtime command schema being executed. */
|
|
1964
|
-
readonly command: CommandSchema;
|
|
1965
|
-
/** CLI metadata for this execution. */
|
|
1966
|
-
readonly meta: CommandMeta;
|
|
1967
|
-
/** Output channel for this execution. */
|
|
1968
|
-
readonly out: Out;
|
|
1969
|
-
}
|
|
1970
|
-
/** Payload for `beforeParse`. */
|
|
1971
|
-
interface BeforeParseParams extends PluginCommandContext {
|
|
1972
|
-
/** Raw argv that will be parsed for the leaf command. */
|
|
1973
|
-
readonly argv: readonly string[];
|
|
1974
|
-
}
|
|
1975
|
-
/** Payload for hooks that observe resolved inputs. */
|
|
1976
|
-
interface ResolvedCommandParams extends PluginCommandContext {
|
|
1977
|
-
/** Fully resolved flag values. */
|
|
1978
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
1979
|
-
/** Fully resolved argument values. */
|
|
1980
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
1981
|
-
/** Structured deprecation warnings collected during resolution. */
|
|
1982
|
-
readonly deprecations: readonly DeprecationWarning[];
|
|
1983
|
-
}
|
|
1984
|
-
/**
|
|
1985
|
-
* Individual lifecycle hooks that a plugin may implement.
|
|
1986
|
-
*
|
|
1987
|
-
* Hook order for a successful command run is:
|
|
1988
|
-
* `beforeParse` → `afterResolve` → `beforeAction` → middleware/action → `afterAction`.
|
|
1989
|
-
*
|
|
1990
|
-
* Hooks are awaited serially and run in plugin registration order at each
|
|
1991
|
-
* stage. Throwing from any hook aborts the command just like throwing from
|
|
1992
|
-
* middleware or the action handler. `afterAction` runs only after the
|
|
1993
|
-
* middleware chain and action complete successfully.
|
|
1994
|
-
*/
|
|
1995
|
-
interface CLIPluginHooks {
|
|
1996
|
-
/** Called immediately before leaf-command argv is parsed. */
|
|
1997
|
-
readonly beforeParse?: (params: BeforeParseParams) => void | Promise<void>;
|
|
1998
|
-
/** Called after parse + resolve, before middleware or action execution. */
|
|
1999
|
-
readonly afterResolve?: (params: ResolvedCommandParams) => void | Promise<void>;
|
|
2000
|
-
/** Called immediately before the middleware chain and action handler run. */
|
|
2001
|
-
readonly beforeAction?: (params: ResolvedCommandParams) => void | Promise<void>;
|
|
2002
|
-
/** Called after the middleware chain and action handler complete successfully. */
|
|
2003
|
-
readonly afterAction?: (params: ResolvedCommandParams) => void | Promise<void>;
|
|
2004
|
-
}
|
|
2005
|
-
/**
|
|
2006
|
-
* Immutable plugin definition registered via `CLIBuilder.plugin()`.
|
|
2007
|
-
*
|
|
2008
|
-
* Use {@link plugin} to construct values of this shape instead of manually
|
|
2009
|
-
* assembling the object.
|
|
2010
|
-
*/
|
|
2011
|
-
interface CLIPlugin {
|
|
2012
|
-
/** Optional label for diagnostics and debugging. */
|
|
2013
|
-
readonly name: string | undefined;
|
|
2014
|
-
/** Lifecycle hooks implemented by the plugin. */
|
|
2015
|
-
readonly hooks: CLIPluginHooks;
|
|
2016
|
-
}
|
|
2017
|
-
/**
|
|
2018
|
-
* Create a CLI plugin from lifecycle hooks.
|
|
2019
|
-
*
|
|
2020
|
-
* @param hooks - Lifecycle hooks to register.
|
|
2021
|
-
* @param name - Optional plugin name for diagnostics.
|
|
2022
|
-
*
|
|
2023
|
-
* @example
|
|
2024
|
-
* ```ts
|
|
2025
|
-
* const trace = plugin(
|
|
2026
|
-
* {
|
|
2027
|
-
* beforeParse: ({ argv, out }) => {
|
|
2028
|
-
* out.info(`argv: ${argv.join(' ')}`);
|
|
2029
|
-
* },
|
|
2030
|
-
* afterResolve: ({ flags, args }) => {
|
|
2031
|
-
* console.log({ flags, args });
|
|
2032
|
-
* },
|
|
2033
|
-
* },
|
|
2034
|
-
* 'trace',
|
|
2035
|
-
* );
|
|
2036
|
-
*
|
|
2037
|
-
* cli('mycli').plugin(trace).command(deploy);
|
|
2038
|
-
* ```
|
|
2039
|
-
*
|
|
2040
|
-
* @returns A frozen {@link CLIPlugin} definition.
|
|
2041
|
-
*/
|
|
2042
|
-
declare function plugin(hooks: CLIPluginHooks, name?: string): CLIPlugin;
|
|
2043
|
-
//#endregion
|
|
2044
|
-
//#region src/core/errors/index.d.ts
|
|
2045
|
-
/**
|
|
2046
|
-
* Structured error types for DreamCLI.
|
|
2047
|
-
*
|
|
2048
|
-
* Base `CLIError` carries stable code, exit code, suggestion, and structured
|
|
2049
|
-
* details. `ParseError` and `ValidationError` derive from it with
|
|
2050
|
-
* category-appropriate defaults.
|
|
2051
|
-
*
|
|
2052
|
-
* @module dreamcli/core/errors
|
|
2053
|
-
*/
|
|
2054
|
-
/** Codes emitted during argv parsing. */
|
|
2055
|
-
type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'UNEXPECTED_POSITIONAL';
|
|
2056
|
-
/** Codes emitted during post-parse validation / resolution. */
|
|
2057
|
-
type ValidationErrorCode = 'REQUIRED_FLAG' | 'REQUIRED_ARG' | 'INVALID_ENUM' | 'TYPE_MISMATCH' | 'CONSTRAINT_VIOLATED';
|
|
2058
|
-
/** Any framework error code (extensible via `string & {}`). */
|
|
2059
|
-
type ErrorCode = ParseErrorCode | ValidationErrorCode | (string & {});
|
|
2060
|
-
/** Options accepted by the `CLIError` constructor. */
|
|
2061
|
-
interface CLIErrorOptions {
|
|
2062
|
-
/** Stable machine-readable identifier (e.g. `"UNKNOWN_FLAG"`). */
|
|
2063
|
-
readonly code: ErrorCode;
|
|
2064
|
-
/**
|
|
2065
|
-
* Process exit code.
|
|
2066
|
-
* @defaultValue `1`
|
|
2067
|
-
*/
|
|
2068
|
-
readonly exitCode?: number;
|
|
2069
|
-
/** One-liner actionable hint shown to the user. */
|
|
2070
|
-
readonly suggest?: string;
|
|
2071
|
-
/** Arbitrary structured payload (serialised in `--json` mode). */
|
|
2072
|
-
readonly details?: Readonly<Record<string, unknown>>;
|
|
2073
|
-
/** Original error, if this wraps another. */
|
|
2074
|
-
readonly cause?: unknown;
|
|
2075
|
-
}
|
|
2076
|
-
/**
|
|
2077
|
-
* Base structured error for DreamCLI.
|
|
2078
|
-
*
|
|
2079
|
-
* Every error surfaced by the framework extends this class, ensuring a
|
|
2080
|
-
* consistent shape for rendering (TTY pretty-print, `--json`, test assertions).
|
|
2081
|
-
*/
|
|
2082
|
-
declare class CLIError extends Error {
|
|
2083
|
-
/** @override */
|
|
2084
|
-
readonly name: string;
|
|
2085
|
-
/** Stable machine-readable identifier. */
|
|
2086
|
-
readonly code: ErrorCode;
|
|
2087
|
-
/** Process exit code (defaults to `1`). */
|
|
2088
|
-
readonly exitCode: number;
|
|
2089
|
-
/** One-liner actionable hint. */
|
|
2090
|
-
readonly suggest: string | undefined;
|
|
2091
|
-
/** Structured payload for machine output. */
|
|
2092
|
-
readonly details: Readonly<Record<string, unknown>> | undefined;
|
|
2093
|
-
constructor(message: string, options: CLIErrorOptions);
|
|
2094
|
-
/**
|
|
2095
|
-
* Serialise to a plain object suitable for JSON output.
|
|
2096
|
-
* @sealed
|
|
2097
|
-
*/
|
|
2098
|
-
toJSON(): CLIErrorJSON;
|
|
2099
|
-
}
|
|
2100
|
-
/** Shape returned by `CLIError.toJSON()`. */
|
|
2101
|
-
interface CLIErrorJSON {
|
|
2102
|
-
readonly name: string;
|
|
2103
|
-
readonly code: ErrorCode;
|
|
2104
|
-
readonly message: string;
|
|
2105
|
-
readonly exitCode: number;
|
|
2106
|
-
readonly suggest?: string;
|
|
2107
|
-
readonly details?: Readonly<Record<string, unknown>>;
|
|
2108
|
-
}
|
|
2109
|
-
/** Options for `ParseError`. Code is narrowed to parse-specific codes. */
|
|
2110
|
-
interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
|
|
2111
|
-
readonly code: ParseErrorCode;
|
|
2112
|
-
/**
|
|
2113
|
-
* @defaultValue `2`
|
|
2114
|
-
*/
|
|
2115
|
-
readonly exitCode?: number;
|
|
2116
|
-
}
|
|
2117
|
-
/**
|
|
2118
|
-
* Error thrown when argv tokenization / parsing fails.
|
|
2119
|
-
*
|
|
2120
|
-
* Exit code defaults to `2` (standard for CLI usage errors).
|
|
2121
|
-
*/
|
|
2122
|
-
declare class ParseError extends CLIError {
|
|
2123
|
-
/** @override */
|
|
2124
|
-
readonly name: 'ParseError';
|
|
2125
|
-
readonly code: ParseErrorCode;
|
|
2126
|
-
constructor(message: string, options: ParseErrorOptions);
|
|
2127
|
-
}
|
|
2128
|
-
/** Options for `ValidationError`. Code is narrowed to validation-specific codes. */
|
|
2129
|
-
interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
|
|
2130
|
-
readonly code: ValidationErrorCode;
|
|
2131
|
-
/**
|
|
2132
|
-
* @defaultValue `2`
|
|
2133
|
-
*/
|
|
2134
|
-
readonly exitCode?: number;
|
|
2135
|
-
}
|
|
2136
|
-
/**
|
|
2137
|
-
* Error thrown when resolved values fail validation constraints.
|
|
2138
|
-
*
|
|
2139
|
-
* Exit code defaults to `2` (standard for CLI usage errors).
|
|
2140
|
-
*/
|
|
2141
|
-
declare class ValidationError extends CLIError {
|
|
2142
|
-
/** @override */
|
|
2143
|
-
readonly name: 'ValidationError';
|
|
2144
|
-
readonly code: ValidationErrorCode;
|
|
2145
|
-
constructor(message: string, options: ValidationErrorOptions);
|
|
2146
|
-
}
|
|
2147
|
-
/** Narrows an unknown value to `CLIError`. */
|
|
2148
|
-
declare function isCLIError(value: unknown): value is CLIError;
|
|
2149
|
-
/** Narrows an unknown value to `ParseError`. */
|
|
2150
|
-
declare function isParseError(value: unknown): value is ParseError;
|
|
2151
|
-
/** Narrows an unknown value to `ValidationError`. */
|
|
2152
|
-
declare function isValidationError(value: unknown): value is ValidationError;
|
|
2153
|
-
//#endregion
|
|
2154
|
-
//#region src/core/help/index.d.ts
|
|
2155
|
-
/** Options for customising help output. */
|
|
2156
|
-
interface HelpOptions {
|
|
2157
|
-
/** Maximum line width (columns). Defaults to 80. */
|
|
2158
|
-
readonly width?: number;
|
|
2159
|
-
/** Binary/program name shown in the usage line. Defaults to command name. */
|
|
2160
|
-
readonly binName?: string;
|
|
2161
|
-
/** @internal Whether this usage line is being rendered as merged root/default help. */
|
|
2162
|
-
readonly isDefaultHelp?: boolean;
|
|
2163
|
-
}
|
|
2164
|
-
/**
|
|
2165
|
-
* Build the ordered help sections without joining them.
|
|
2166
|
-
*
|
|
2167
|
-
* @internal
|
|
2168
|
-
* @param schema - The {@link CommandSchema} to render.
|
|
2169
|
-
* @param options - Optional {@link HelpOptions} for width/bin name.
|
|
2170
|
-
* @returns Array of section strings (usage, description, commands, args, flags, examples).
|
|
2171
|
-
*/
|
|
2172
|
-
/**
|
|
2173
|
-
* Generate help text from a command schema.
|
|
2174
|
-
*
|
|
2175
|
-
* Low-level formatter: most applications reach this through `--help`,
|
|
2176
|
-
* `help <command>`, or root help rendering in `CLIBuilder`. Call
|
|
2177
|
-
* `formatHelp()` directly when embedding DreamCLI help text into custom UIs,
|
|
2178
|
-
* tests, or generated docs.
|
|
2179
|
-
*
|
|
2180
|
-
* Sections rendered (in order):
|
|
2181
|
-
* 1. **Usage** line — `program <command> [flags] <args>`
|
|
2182
|
-
* 2. **Description** — the command's `.description()` text
|
|
2183
|
-
* 3. **Commands** — subcommands table (if any, skips hidden)
|
|
2184
|
-
* 4. **Arguments** — positional args table (if any)
|
|
2185
|
-
* 5. **Flags** — flags table with type hints and defaults
|
|
2186
|
-
* 6. **Examples** — usage examples (if any)
|
|
2187
|
-
*
|
|
2188
|
-
* @param schema - The command schema to render help for.
|
|
2189
|
-
* @param options - Formatting options (width, binary name).
|
|
2190
|
-
* @returns The formatted help string.
|
|
2191
|
-
*
|
|
2192
|
-
* @example
|
|
2193
|
-
* ```ts
|
|
2194
|
-
* const text = formatHelp(deploy.schema, { binName: 'mycli' });
|
|
2195
|
-
* ```
|
|
2196
|
-
*/
|
|
2197
|
-
declare function formatHelp(schema: CommandSchema, options?: HelpOptions): string;
|
|
2198
|
-
//#endregion
|
|
2199
|
-
//#region src/core/schema/run.d.ts
|
|
2200
|
-
/**
|
|
2201
|
-
* Options accepted by `commandBuilder.run()` and `runCommand()`.
|
|
2202
|
-
*
|
|
2203
|
-
* Every field is optional — sensible defaults are applied. This is the
|
|
2204
|
-
* primary execution seam: inject env, config, prompt I/O, and dispatch-layer
|
|
2205
|
-
* metadata without touching process state.
|
|
2206
|
-
*/
|
|
2207
|
-
interface RunOptions {
|
|
2208
|
-
/**
|
|
2209
|
-
* Environment variables for flag resolution.
|
|
2210
|
-
*
|
|
2211
|
-
* Flags with `.env('VAR')` configured resolve from this record
|
|
2212
|
-
* when no CLI value is provided (CLI → env → config → prompt → default).
|
|
2213
|
-
*/
|
|
2214
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
2215
|
-
/**
|
|
2216
|
-
* Configuration object for flag resolution.
|
|
2217
|
-
*
|
|
2218
|
-
* Flags with `.config('path')` configured resolve from this record
|
|
2219
|
-
* when no CLI or env value is provided (CLI → env → config → prompt → default).
|
|
2220
|
-
* Config is plain JSON — file loading is the caller's responsibility.
|
|
2221
|
-
*/
|
|
2222
|
-
readonly config?: Readonly<Record<string, unknown>>;
|
|
2223
|
-
/**
|
|
2224
|
-
* Full stdin contents for args configured with `.stdin()`.
|
|
2225
|
-
*
|
|
2226
|
-
* Lets tests inject piped input without a runtime adapter.
|
|
2227
|
-
*/
|
|
2228
|
-
readonly stdinData?: string | null;
|
|
2229
|
-
/**
|
|
2230
|
-
* Prompt engine for interactive flag resolution.
|
|
2231
|
-
*
|
|
2232
|
-
* When provided, flags with `.prompt()` configured that have no value
|
|
2233
|
-
* after CLI/env/config resolution will be prompted interactively.
|
|
2234
|
-
*
|
|
2235
|
-
* When absent (and `answers` is also absent), prompting is skipped
|
|
2236
|
-
* and resolution falls through to default/required.
|
|
2237
|
-
*
|
|
2238
|
-
* Takes precedence over `answers` when both are provided.
|
|
2239
|
-
*/
|
|
2240
|
-
readonly prompter?: PromptEngine;
|
|
2241
|
-
/**
|
|
2242
|
-
* Pre-configured prompt answers for testing convenience.
|
|
2243
|
-
*
|
|
2244
|
-
* When provided, a test prompter is created from these answers via
|
|
2245
|
-
* `createTestPrompter(answers)`. Each entry is consumed in order —
|
|
2246
|
-
* use `PROMPT_CANCEL` to simulate cancellation.
|
|
2247
|
-
*
|
|
2248
|
-
* Ignored when an explicit `prompter` is provided.
|
|
2249
|
-
*/
|
|
2250
|
-
readonly answers?: readonly TestAnswer[];
|
|
2251
|
-
/**
|
|
2252
|
-
* Verbosity level for the output channel.
|
|
2253
|
-
* @defaultValue `'normal'`
|
|
2254
|
-
*/
|
|
2255
|
-
readonly verbosity?: Verbosity;
|
|
2256
|
-
/**
|
|
2257
|
-
* Enable JSON output mode.
|
|
2258
|
-
*
|
|
2259
|
-
* When `true`, `log` and `info` messages are redirected to stderr
|
|
2260
|
-
* so that stdout is reserved exclusively for structured `json()` output.
|
|
2261
|
-
* Errors are also rendered as JSON to stderr.
|
|
2262
|
-
*
|
|
2263
|
-
* @defaultValue `false`
|
|
2264
|
-
*/
|
|
2265
|
-
readonly jsonMode?: boolean;
|
|
2266
|
-
/**
|
|
2267
|
-
* Whether stdout is connected to a TTY.
|
|
2268
|
-
*
|
|
2269
|
-
* Handlers can check `out.isTTY` to decide whether to emit decorative
|
|
2270
|
-
* output (spinners, progress bars, ANSI codes). Defaults to `false`
|
|
2271
|
-
* (safe default for tests — non-TTY until proven otherwise).
|
|
2272
|
-
*
|
|
2273
|
-
* @defaultValue `false`
|
|
2274
|
-
*/
|
|
2275
|
-
readonly isTTY?: boolean;
|
|
2276
|
-
/**
|
|
2277
|
-
* Output channel override used by live CLI execution.
|
|
2278
|
-
*
|
|
2279
|
-
* @internal — `run()` passes a real output channel so activity renders to
|
|
2280
|
-
* the terminal instead of being captured.
|
|
2281
|
-
*/
|
|
2282
|
-
readonly out?: Out;
|
|
2283
|
-
/**
|
|
2284
|
-
* Capture buffers override paired with `out`.
|
|
2285
|
-
*
|
|
2286
|
-
* @internal — when omitted, `runCommand()` creates empty buffers for the
|
|
2287
|
-
* returned `RunResult` while writing directly to the provided `out`.
|
|
2288
|
-
*/
|
|
2289
|
-
readonly captured?: CapturedOutput;
|
|
2290
|
-
/**
|
|
2291
|
-
* Help formatting options (width, binName).
|
|
2292
|
-
* Used when `--help` is detected.
|
|
2293
|
-
*/
|
|
2294
|
-
readonly help?: HelpOptions;
|
|
2295
|
-
/**
|
|
2296
|
-
* Command schema with propagated flags merged in.
|
|
2297
|
-
*
|
|
2298
|
-
* When provided, used for parsing and resolution instead of `cmd.schema`.
|
|
2299
|
-
* Set by the CLI dispatch layer after collecting propagated flags from
|
|
2300
|
-
* the command ancestry path.
|
|
2301
|
-
*
|
|
2302
|
-
* @internal — set by dispatch layer, not for public use.
|
|
2303
|
-
*/
|
|
2304
|
-
readonly mergedSchema?: CommandSchema;
|
|
2305
|
-
/**
|
|
2306
|
-
* CLI program metadata passed to action handlers and middleware.
|
|
2307
|
-
*
|
|
2308
|
-
* When provided (by CLI dispatch layer), handlers receive this as `meta`.
|
|
2309
|
-
* When absent (standalone `runCommand()`), a minimal meta is constructed
|
|
2310
|
-
* from the command's own schema.
|
|
2311
|
-
*
|
|
2312
|
-
* @internal — populated by CLI dispatch, not for public use.
|
|
2313
|
-
*/
|
|
2314
|
-
readonly meta?: CommandMeta;
|
|
2315
|
-
/**
|
|
2316
|
-
* CLI plugins registered on the parent `CLIBuilder`.
|
|
2317
|
-
*
|
|
2318
|
-
* @internal — threaded through from CLI dispatch.
|
|
2319
|
-
*/
|
|
2320
|
-
readonly plugins?: readonly CLIPlugin[];
|
|
2321
|
-
}
|
|
2322
|
-
/**
|
|
2323
|
-
* Structured result from running a command.
|
|
2324
|
-
*
|
|
2325
|
-
* Contains the exit code, captured stdout/stderr output, and an `error`
|
|
2326
|
-
* field that is `undefined` on success and populated on failure.
|
|
2327
|
-
*/
|
|
2328
|
-
interface RunResult {
|
|
2329
|
-
/** Process exit code. 0 = success. */
|
|
2330
|
-
readonly exitCode: number;
|
|
2331
|
-
/** Captured stdout lines (from `out.log` and `out.info`). */
|
|
2332
|
-
readonly stdout: readonly string[];
|
|
2333
|
-
/** Captured stderr lines (from `out.warn` and `out.error`). */
|
|
2334
|
-
readonly stderr: readonly string[];
|
|
2335
|
-
/**
|
|
2336
|
-
* Captured spinner and progress lifecycle events.
|
|
2337
|
-
*
|
|
2338
|
-
* Recorded separately from stdout/stderr — handlers that call
|
|
2339
|
-
* `out.spinner()` or `out.progress()` produce events here, enabling
|
|
2340
|
-
* targeted assertions on activity lifecycle without parsing text.
|
|
2341
|
-
*/
|
|
2342
|
-
readonly activity: readonly ActivityEvent[];
|
|
2343
|
-
/**
|
|
2344
|
-
* The error that caused a non-zero exit, or `undefined` on success.
|
|
2345
|
-
* `CLIError` instances are preserved; unknown errors are wrapped.
|
|
2346
|
-
*/
|
|
2347
|
-
readonly error: CLIError | undefined;
|
|
2348
|
-
}
|
|
2349
|
-
//#endregion
|
|
2350
|
-
//#region src/core/schema/command.d.ts
|
|
2351
|
-
/**
|
|
2352
|
-
* Widen the context type when adding middleware.
|
|
2353
|
-
*
|
|
2354
|
-
* The default `C = Record<string, never>` uses an index signature where
|
|
2355
|
-
* every key maps to `never` — making property access a type error until
|
|
2356
|
-
* middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
|
|
2357
|
-
* collapses all properties to `never` because `never & T = never`.
|
|
2358
|
-
*
|
|
2359
|
-
* This utility replaces `Record<string, never>` entirely on the first
|
|
2360
|
-
* `.middleware()` call. Subsequent calls use plain intersection.
|
|
2361
|
-
*/
|
|
2362
|
-
type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
|
|
2363
|
-
/**
|
|
2364
|
-
* Widen the context type when adding command-scoped derived context.
|
|
2365
|
-
*
|
|
2366
|
-
* Validation-only derive handlers return `undefined`, preserving `C`.
|
|
2367
|
-
* Context-producing derive handlers return an object that merges into `C`
|
|
2368
|
-
* using the same first-call replacement rules as middleware.
|
|
2369
|
-
*/
|
|
2370
|
-
type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
|
|
2371
|
-
/**
|
|
2372
|
-
* Compile-time state carried through the command builder chain.
|
|
2373
|
-
*
|
|
2374
|
-
* `F` accumulates named flag builders; `A` accumulates named arg builders.
|
|
2375
|
-
* Both start empty (`{}`) and grow as `.flag()` / `.arg()` are called.
|
|
2376
|
-
*/
|
|
2377
|
-
interface CommandConfig {
|
|
2378
|
-
readonly flags: Record<string, FlagBuilder<FlagConfig>>;
|
|
2379
|
-
readonly args: Record<string, ArgBuilder<ArgConfig>>;
|
|
2380
|
-
}
|
|
2381
|
-
/**
|
|
2382
|
-
* Parameters received by the interactive resolver function.
|
|
2383
|
-
*
|
|
2384
|
-
* `flags` contains partially resolved values — present for flags resolved
|
|
2385
|
-
* via CLI, env, or config, `undefined` for unresolved flags. The resolver
|
|
2386
|
-
* uses this to decide which prompts to show based on current state.
|
|
2387
|
-
*/
|
|
2388
|
-
interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
|
|
2389
|
-
/** Partially resolved flag values (after CLI/env/config, before prompts). */
|
|
2390
|
-
readonly flags: Readonly<Partial<InferFlags<F>>>;
|
|
2391
|
-
}
|
|
2392
|
-
/**
|
|
2393
|
-
* A record mapping flag names to prompt configs or falsy values.
|
|
2394
|
-
*
|
|
2395
|
-
* - `PromptConfig` — show this prompt for the flag
|
|
2396
|
-
* - `false | undefined | null | 0 | ''` — skip prompting for this flag
|
|
2397
|
-
*
|
|
2398
|
-
* Only flag names that need prompting should have truthy values.
|
|
2399
|
-
* Flags not mentioned are handled by their per-flag `.prompt()` config.
|
|
2400
|
-
*/
|
|
2401
|
-
type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
|
|
2402
|
-
/**
|
|
2403
|
-
* Interactive resolver function for command-level prompt control.
|
|
2404
|
-
*
|
|
2405
|
-
* Called after CLI/env/config resolution but before per-flag prompts fire.
|
|
2406
|
-
* Receives partially resolved values and returns a prompt schema for
|
|
2407
|
-
* flags that should be prompted. Commands without `.interactive()` use
|
|
2408
|
-
* per-flag prompt configs directly.
|
|
2409
|
-
*
|
|
2410
|
-
* @example
|
|
2411
|
-
* ```ts
|
|
2412
|
-
* const deploy = command('deploy')
|
|
2413
|
-
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
2414
|
-
* .interactive(({ flags }) => ({
|
|
2415
|
-
* region: !flags.region && {
|
|
2416
|
-
* kind: 'select',
|
|
2417
|
-
* message: 'Select region',
|
|
2418
|
-
* },
|
|
2419
|
-
* }))
|
|
2420
|
-
* .action(({ flags }) => { ... });
|
|
2421
|
-
* ```
|
|
2422
|
-
*/
|
|
2423
|
-
type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (params: InteractiveParams<F>) => InteractiveResult;
|
|
2424
|
-
/**
|
|
2425
|
-
* Type-erased interactive resolver stored on `CommandSchema`.
|
|
2426
|
-
*
|
|
2427
|
-
* Advanced bridge type: most consumers should use {@link InteractiveResolver}
|
|
2428
|
-
* via `command().interactive(...)` and never reference this alias directly.
|
|
2429
|
-
*
|
|
2430
|
-
* At runtime, the resolver receives `{ flags: Record<string, unknown> }`
|
|
2431
|
-
* and returns `Record<string, PromptConfig | falsy>`. The phantom types
|
|
2432
|
-
* from `CommandBuilder<F, A>` are erased.
|
|
2433
|
-
*
|
|
2434
|
-
* @internal
|
|
2435
|
-
*/
|
|
2436
|
-
type ErasedInteractiveResolver = (params: {
|
|
2437
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
2438
|
-
}) => InteractiveResult;
|
|
2439
|
-
/**
|
|
2440
|
-
* Output channel available inside action handlers.
|
|
2441
|
-
*
|
|
2442
|
-
* Provides structured methods for stdout/stderr, JSON output,
|
|
2443
|
-
* spinners, progress bars, and tables. The real implementation lives in
|
|
2444
|
-
* `src/core/output/`; this interface defines the shape that handlers consume.
|
|
2445
|
-
*/
|
|
2446
|
-
interface Out {
|
|
2447
|
-
/** Write to stdout (normal output). */
|
|
2448
|
-
log(message: string): void;
|
|
2449
|
-
/** Informational (may be suppressed in quiet mode). */
|
|
2450
|
-
info(message: string): void;
|
|
2451
|
-
/** Warning to stderr. */
|
|
2452
|
-
warn(message: string): void;
|
|
2453
|
-
/** Error to stderr. */
|
|
2454
|
-
error(message: string): void;
|
|
2455
|
-
/**
|
|
2456
|
-
* Emit a structured JSON value to stdout.
|
|
2457
|
-
*
|
|
2458
|
-
* Always serialises `value` as JSON to stdout regardless of output
|
|
2459
|
-
* mode. Prefer this over `log(JSON.stringify(...))` so the output
|
|
2460
|
-
* channel can enforce consistent formatting and future features
|
|
2461
|
-
* (pretty-print in TTY, streaming JSON, etc.).
|
|
2462
|
-
*/
|
|
2463
|
-
json(value: unknown): void;
|
|
2464
|
-
/**
|
|
2465
|
-
* Whether the output channel is in JSON mode (`--json` flag active).
|
|
2466
|
-
*
|
|
2467
|
-
* Handlers can check this to skip decorative output (spinners,
|
|
2468
|
-
* progress bars, ANSI formatting) when machine-readable output is
|
|
2469
|
-
* expected.
|
|
2470
|
-
*/
|
|
2471
|
-
readonly jsonMode: boolean;
|
|
2472
|
-
/**
|
|
2473
|
-
* Whether stdout is connected to a TTY (terminal).
|
|
2474
|
-
*
|
|
2475
|
-
* Handlers can check this to decide whether to emit decorative output
|
|
2476
|
-
* (spinners, progress bars, ANSI color codes). When `false`, the output
|
|
2477
|
-
* is being piped or redirected — skip interactive decorations.
|
|
2478
|
-
*
|
|
2479
|
-
* Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
|
|
2480
|
-
* decorative output should be suppressed regardless of `isTTY`.
|
|
2481
|
-
*/
|
|
2482
|
-
readonly isTTY: boolean;
|
|
2483
|
-
/**
|
|
2484
|
-
* Render tabular data.
|
|
2485
|
-
*
|
|
2486
|
-
* - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
|
|
2487
|
-
* - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
|
|
2488
|
-
* - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
|
|
2489
|
-
* (useful for `grep`, `awk`, etc.).
|
|
2490
|
-
* - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
|
|
2491
|
-
* side channel while `json()` writes machine output to stdout.
|
|
2492
|
-
*
|
|
2493
|
-
* When `columns` is omitted, columns are auto-inferred from the keys
|
|
2494
|
-
* of the first row. Column headers default to the key name.
|
|
2495
|
-
*
|
|
2496
|
-
* When `columns` is provided, both text and JSON output are projected to
|
|
2497
|
-
* only the listed keys.
|
|
2498
|
-
*
|
|
2499
|
-
* @param rows - Array of row objects.
|
|
2500
|
-
*/
|
|
2501
|
-
table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
|
|
2502
|
-
/**
|
|
2503
|
-
* Render tabular data with explicit column selection.
|
|
2504
|
-
*
|
|
2505
|
-
* @param rows - Array of row objects.
|
|
2506
|
-
* @param columns - Column descriptors controlling which keys are shown and header labels.
|
|
2507
|
-
* @param options - Per-call rendering options (format, stream).
|
|
2508
|
-
*/
|
|
2509
|
-
table<T extends Record<string, unknown>>(rows: readonly T[], columns?: readonly TableColumn<T>[], options?: TableOptions): void;
|
|
2510
|
-
/**
|
|
2511
|
-
* Create a spinner for indeterminate progress feedback.
|
|
2512
|
-
*
|
|
2513
|
-
* Returns a handle for lifecycle control. In non-TTY/jsonMode,
|
|
2514
|
-
* returns a no-op handle (or static fallback if configured).
|
|
2515
|
-
*
|
|
2516
|
-
* @param text - Initial spinner text.
|
|
2517
|
-
* @param options - Fallback strategy for non-TTY environments.
|
|
2518
|
-
* @returns A {@link SpinnerHandle} for lifecycle control.
|
|
2519
|
-
*/
|
|
2520
|
-
spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
|
|
2521
|
-
/**
|
|
2522
|
-
* Create a progress bar for measured work.
|
|
2523
|
-
*
|
|
2524
|
-
* Returns a handle for updating progress. Pass `total` for
|
|
2525
|
-
* determinate mode (percentage bar); omit for indeterminate (pulsing).
|
|
2526
|
-
*
|
|
2527
|
-
* @param options - Progress configuration (total, label, fallback).
|
|
2528
|
-
* @returns A {@link ProgressHandle} for updating progress.
|
|
2529
|
-
*/
|
|
2530
|
-
progress(options: ProgressOptions): ProgressHandle;
|
|
2531
|
-
/**
|
|
2532
|
-
* Stop the currently active spinner or progress handle, if any.
|
|
2533
|
-
*
|
|
2534
|
-
* TTY spinner and progress handles start `setInterval` timers that
|
|
2535
|
-
* prevent the process from exiting until a terminal method (`stop`,
|
|
2536
|
-
* `succeed`, `fail`, `done`) is called. If a handler throws before
|
|
2537
|
-
* reaching that call, the timer leaks and the process hangs.
|
|
2538
|
-
*
|
|
2539
|
-
* Call `stopActive()` in a `finally` block after handler execution
|
|
2540
|
-
* to guarantee cleanup. It is idempotent — safe to call when no
|
|
2541
|
-
* handle is active, or when the handle was already stopped.
|
|
2542
|
-
*
|
|
2543
|
-
* The framework calls this automatically in `runCommand()` and
|
|
2544
|
-
* `cli.run()`. Direct users of `createOutput()` should call it
|
|
2545
|
-
* themselves after the handler returns or throws.
|
|
2546
|
-
*
|
|
2547
|
-
* @example
|
|
2548
|
-
* ```ts
|
|
2549
|
-
* const out = createOutput({ isTTY: true });
|
|
2550
|
-
* try {
|
|
2551
|
-
* await handler({ out });
|
|
2552
|
-
* } finally {
|
|
2553
|
-
* out.stopActive();
|
|
2554
|
-
* }
|
|
2555
|
-
* ```
|
|
2556
|
-
*/
|
|
2557
|
-
stopActive(): void;
|
|
2558
|
-
}
|
|
2559
|
-
/**
|
|
2560
|
-
* Runtime metadata about the CLI program and current command execution.
|
|
2561
|
-
*
|
|
2562
|
-
* Available to action handlers and middleware.
|
|
2563
|
-
*
|
|
2564
|
-
* Populated by the CLI dispatch layer from {@link CLISchema} and
|
|
2565
|
-
* {@link CommandSchema}. For standalone `runCommand()` calls without
|
|
2566
|
-
* a CLI wrapper, a minimal meta is constructed from the command's own schema.
|
|
2567
|
-
*/
|
|
2568
|
-
interface CommandMeta {
|
|
2569
|
-
/** CLI program name (from `cli('name')` or package.json inference). */
|
|
2570
|
-
readonly name: string;
|
|
2571
|
-
/** Binary display name used in help/usage (may differ from `name`). */
|
|
2572
|
-
readonly bin: string;
|
|
2573
|
-
/** Program version, if set via `.version()` or discovered from package.json. */
|
|
2574
|
-
readonly version: string | undefined;
|
|
2575
|
-
/** The leaf command name currently being executed. */
|
|
2576
|
-
readonly command: string;
|
|
2577
|
-
}
|
|
2578
|
-
/**
|
|
2579
|
-
* The bag of values received by an action handler.
|
|
2580
|
-
*
|
|
2581
|
-
* - `args` — fully resolved positional arguments
|
|
2582
|
-
* - `flags` — fully resolved flags
|
|
2583
|
-
* - `ctx` — derive/middleware-provided context
|
|
2584
|
-
* - `out` — output channel
|
|
2585
|
-
* - `meta` — CLI program metadata (name, bin, version, command)
|
|
2586
|
-
*
|
|
2587
|
-
* The `C` parameter defaults to `Record<string, never>`, making `ctx`
|
|
2588
|
-
* property access a type error until derive or middleware extends it.
|
|
2589
|
-
*/
|
|
2590
|
-
interface ActionParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> {
|
|
2591
|
-
readonly args: Readonly<InferArgs<A>>;
|
|
2592
|
-
readonly flags: Readonly<InferFlags<F>>;
|
|
2593
|
-
readonly ctx: Readonly<C>;
|
|
2594
|
-
readonly out: Out;
|
|
2595
|
-
readonly meta: CommandMeta;
|
|
2596
|
-
}
|
|
2597
|
-
/**
|
|
2598
|
-
* Action handler function signature.
|
|
2599
|
-
*
|
|
2600
|
-
* May be sync or async — the framework will `await` the return value
|
|
2601
|
-
* regardless. The `C` parameter carries the accumulated middleware
|
|
2602
|
-
* context type (defaults to empty).
|
|
2603
|
-
*/
|
|
2604
|
-
type ActionHandler<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> = (params: ActionParams<F, A, C>) => void | Promise<void>;
|
|
2605
|
-
/**
|
|
2606
|
-
* The bag of values received by a derive handler.
|
|
2607
|
-
*
|
|
2608
|
-
* Identical to {@link ActionParams}: derives run after full resolution and
|
|
2609
|
-
* before the action handler, with typed args/flags/current context plus `out`
|
|
2610
|
-
* and `meta`.
|
|
2611
|
-
*/
|
|
2612
|
-
type DeriveParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> = ActionParams<F, A, C>;
|
|
2613
|
-
/**
|
|
2614
|
-
* Command-scoped typed pre-action handler.
|
|
2615
|
-
*
|
|
2616
|
-
* Derive handlers may:
|
|
2617
|
-
* - validate resolved input and throw `CLIError`
|
|
2618
|
-
* - return `undefined` to continue without changing context
|
|
2619
|
-
* - return an object whose properties merge into `ctx` downstream
|
|
2620
|
-
*
|
|
2621
|
-
* They cannot wrap downstream execution; use `middleware()` for that.
|
|
2622
|
-
*/
|
|
2623
|
-
type DeriveHandler<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>, Output extends Record<string, unknown> | undefined = undefined> = (params: DeriveParams<F, A, C>) => Output | Promise<Output>;
|
|
2624
|
-
/**
|
|
2625
|
-
* Type-erased derive handler stored on the command builder.
|
|
2626
|
-
*
|
|
2627
|
-
* @internal
|
|
2628
|
-
*/
|
|
2629
|
-
type ErasedDeriveHandler = (params: {
|
|
2630
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
2631
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
2632
|
-
readonly ctx: Readonly<Record<string, unknown>>;
|
|
2633
|
-
readonly out: Out;
|
|
2634
|
-
readonly meta: CommandMeta;
|
|
2635
|
-
}) => undefined | Readonly<Record<string, unknown>> | Promise<undefined | Readonly<Record<string, unknown>>>;
|
|
2636
|
-
/**
|
|
2637
|
-
* Internal execution step union preserving registration order across
|
|
2638
|
-
* `derive()` and `middleware()`.
|
|
2639
|
-
*
|
|
2640
|
-
* @internal
|
|
2641
|
-
*/
|
|
2642
|
-
type ExecutionStep = {
|
|
2643
|
-
readonly kind: 'derive';
|
|
2644
|
-
readonly handler: ErasedDeriveHandler;
|
|
2645
|
-
} | {
|
|
2646
|
-
readonly kind: 'middleware';
|
|
2647
|
-
readonly handler: ErasedMiddlewareHandler;
|
|
2648
|
-
};
|
|
2649
|
-
/** A single usage example shown in help text. */
|
|
2650
|
-
interface CommandExample {
|
|
2651
|
-
/** The command invocation (e.g. `'deploy production --force'`). */
|
|
2652
|
-
readonly command: string;
|
|
2653
|
-
/** Optional description of what this example does. */
|
|
2654
|
-
readonly description?: string;
|
|
2655
|
-
}
|
|
2656
|
-
/**
|
|
2657
|
-
* Runtime descriptor produced by {@link CommandBuilder}.
|
|
2658
|
-
*
|
|
2659
|
-
* Consumers (parser, help generator, CLI dispatcher) read this to
|
|
2660
|
-
* understand the command's shape — flags, args, aliases, subcommands,
|
|
2661
|
-
* middleware, and interactive resolver.
|
|
2662
|
-
*/
|
|
2663
|
-
interface CommandSchema {
|
|
2664
|
-
/** The command name (used for dispatch, e.g. `'deploy'`). */
|
|
2665
|
-
readonly name: string;
|
|
2666
|
-
/** Human-readable description for help text. */
|
|
2667
|
-
readonly description: string | undefined;
|
|
2668
|
-
/** Alternative names for this command. */
|
|
2669
|
-
readonly aliases: readonly string[];
|
|
2670
|
-
/** Whether this command is hidden from help listings. */
|
|
2671
|
-
readonly hidden: boolean;
|
|
2672
|
-
/** Usage examples for help text. */
|
|
2673
|
-
readonly examples: readonly CommandExample[];
|
|
2674
|
-
/** Named flag schemas, keyed by flag name. */
|
|
2675
|
-
readonly flags: Readonly<Record<string, FlagSchema>>;
|
|
2676
|
-
/** Ordered positional arg entries (name + schema). */
|
|
2677
|
-
readonly args: readonly CommandArgEntry[];
|
|
2678
|
-
/** Whether an action handler has been registered. */
|
|
2679
|
-
readonly hasAction: boolean;
|
|
2680
|
-
/**
|
|
2681
|
-
* Command-level interactive resolver for schema-driven prompt control.
|
|
2682
|
-
*
|
|
2683
|
-
* When set, called after CLI/env/config resolution with partially resolved
|
|
2684
|
-
* flag values. Returns prompt configs for flags that need interactive input.
|
|
2685
|
-
* Takes precedence over per-flag `.prompt()` configs for flags it returns
|
|
2686
|
-
* configs for; flags not mentioned fall back to their per-flag configs.
|
|
2687
|
-
*
|
|
2688
|
-
* @see InteractiveResolver
|
|
2689
|
-
*/
|
|
2690
|
-
readonly interactive: ErasedInteractiveResolver | undefined;
|
|
2691
|
-
/**
|
|
2692
|
-
* Middleware handlers to run before the action handler.
|
|
2693
|
-
*
|
|
2694
|
-
* Executed in registration order — first middleware registered runs
|
|
2695
|
-
* first and calls `next()` to proceed to subsequent middleware,
|
|
2696
|
-
* ending with the action handler. Context accumulates via intersection
|
|
2697
|
-
* at the type level and via object spread at runtime.
|
|
2698
|
-
*/
|
|
2699
|
-
readonly middleware: readonly ErasedMiddlewareHandler[];
|
|
2700
|
-
/**
|
|
2701
|
-
* Nested subcommand schemas (for help rendering and completion).
|
|
2702
|
-
*
|
|
2703
|
-
* Pure data — no execution closures. Populated by `.command()` on
|
|
2704
|
-
* `CommandBuilder`. Empty for leaf commands.
|
|
2705
|
-
*/
|
|
2706
|
-
readonly commands: readonly CommandSchema[];
|
|
2707
|
-
}
|
|
2708
|
-
/**
|
|
2709
|
-
* A named positional argument entry in the command schema.
|
|
2710
|
-
*
|
|
2711
|
-
* Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
|
|
2712
|
-
* The array ordering in {@link CommandSchema.args} determines CLI position.
|
|
2713
|
-
*/
|
|
2714
|
-
interface CommandArgEntry {
|
|
2715
|
-
readonly name: string;
|
|
2716
|
-
readonly schema: ArgSchema;
|
|
2717
|
-
}
|
|
2718
|
-
/**
|
|
2719
|
-
* A type-erased command entry for heterogeneous command storage.
|
|
2720
|
-
*
|
|
2721
|
-
* Advanced/internal bridge type: most consumers should work with
|
|
2722
|
-
* {@link CommandBuilder} and never reference `ErasedCommand` directly.
|
|
2723
|
-
*
|
|
2724
|
-
* Commands registered via `CLIBuilder.command()` have heterogeneous `F`, `A`,
|
|
2725
|
-
* and `C` type parameters. At the dispatch level we only need the runtime
|
|
2726
|
-
* schema (for name/alias matching and help) and the ability to delegate to
|
|
2727
|
-
* `runCommand()`. This interface captures exactly that contract.
|
|
2728
|
-
*
|
|
2729
|
-
* The `_execute` function closes over the original typed `CommandBuilder`,
|
|
2730
|
-
* preserving full type safety inside the closure while presenting a
|
|
2731
|
-
* uniform interface to the dispatcher.
|
|
2732
|
-
*
|
|
2733
|
-
* Defined here (rather than in the CLI layer) so both `CommandBuilder` and
|
|
2734
|
-
* `CLIBuilder` can reference it without circular imports.
|
|
2735
|
-
*
|
|
2736
|
-
* @internal
|
|
2737
|
-
*/
|
|
2738
|
-
interface ErasedCommand {
|
|
2739
|
-
/** Runtime schema for name matching and help rendering. */
|
|
2740
|
-
readonly schema: CommandSchema;
|
|
2741
|
-
/**
|
|
2742
|
-
* Nested subcommands (name/alias → erased child).
|
|
2743
|
-
*
|
|
2744
|
-
* Built recursively by `eraseCommand()` in the CLI layer.
|
|
2745
|
-
* Empty map for leaf commands. The dispatch layer uses this for
|
|
2746
|
-
* recursive command tree traversal.
|
|
2747
|
-
*
|
|
2748
|
-
* @internal
|
|
2749
|
-
*/
|
|
2750
|
-
readonly subcommands: ReadonlyMap<string, ErasedCommand>;
|
|
2751
|
-
/** Execute this command against argv. Closes over the typed CommandBuilder. */
|
|
2752
|
-
readonly _execute: (argv: readonly string[], options?: RunOptions) => Promise<RunResult>;
|
|
2753
|
-
}
|
|
2754
|
-
/**
|
|
2755
|
-
* Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
|
|
2756
|
-
*
|
|
2757
|
-
* Advanced helper alias: useful only when working on DreamCLI internals or
|
|
2758
|
-
* custom tooling that mirrors the framework's type-erasure boundary.
|
|
2759
|
-
*
|
|
2760
|
-
* Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
|
|
2761
|
-
* assignable. The CLI layer's `eraseCommand()` traverses these to build
|
|
2762
|
-
* the execution tree.
|
|
2763
|
-
*
|
|
2764
|
-
* @internal
|
|
2765
|
-
*/
|
|
2766
|
-
type AnyCommandBuilder = CommandBuilder<Record<string, FlagBuilder<FlagConfig>>, Record<string, ArgBuilder<ArgConfig>>, Record<string, unknown>>;
|
|
2767
|
-
/**
|
|
2768
|
-
* Immutable command schema builder.
|
|
2769
|
-
*
|
|
2770
|
-
* The type parameters `F` (flags), `A` (args), and `C` (context) are
|
|
2771
|
-
* phantom types that accumulate builder types as `.flag()`, `.arg()`,
|
|
2772
|
-
* `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
|
|
2773
|
-
* fully typed `ActionParams<F, A, C>`.
|
|
2774
|
-
*
|
|
2775
|
-
* `C` defaults to `Record<string, never>`, making `ctx` property
|
|
2776
|
-
* access a type error until derive or middleware extends it.
|
|
2777
|
-
*
|
|
2778
|
-
* @example
|
|
2779
|
-
* ```ts
|
|
2780
|
-
* const deploy = command('deploy')
|
|
2781
|
-
* .description('Deploy to an environment')
|
|
2782
|
-
* .arg('target', arg.string().describe('Deploy target'))
|
|
2783
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
2784
|
-
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
2785
|
-
* .action(async ({ args, flags, out }) => {
|
|
2786
|
-
* // args.target: string
|
|
2787
|
-
* // flags.force: boolean
|
|
2788
|
-
* // flags.region: 'us' | 'eu' | 'ap' | undefined
|
|
2789
|
-
* out.log(`Deploying ${args.target}...`);
|
|
2790
|
-
* });
|
|
2791
|
-
* ```
|
|
2792
|
-
*/
|
|
2793
|
-
declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> = {}, A extends Record<string, ArgBuilder<ArgConfig>> = {}, C extends Record<string, unknown> = Record<string, never>> {
|
|
2794
|
-
/** @internal Runtime schema descriptor. */
|
|
2795
|
-
readonly schema: CommandSchema;
|
|
2796
|
-
/** @internal The action handler, if registered. */
|
|
2797
|
-
readonly handler: ActionHandler<F, A, C> | undefined;
|
|
2798
|
-
/**
|
|
2799
|
-
* @internal Nested sub-command builders (type-erased for heterogeneous storage).
|
|
2800
|
-
*
|
|
2801
|
-
* Stored separately from `schema.commands` because builders carry action
|
|
2802
|
-
* handlers and phantom types needed by `eraseCommand()` in the CLI layer.
|
|
2803
|
-
* `schema.commands` holds pure `CommandSchema[]` for help/completion.
|
|
2804
|
-
*/
|
|
2805
|
-
readonly _subcommands: readonly AnyCommandBuilder[];
|
|
2806
|
-
/**
|
|
2807
|
-
* @internal Execution steps in registration order.
|
|
2808
|
-
*
|
|
2809
|
-
* Distinct from `schema.middleware`: middleware handlers remain in schema
|
|
2810
|
-
* for backward compatibility, while derives stay command-local and builder-
|
|
2811
|
-
* scoped so future shared/global middleware can compose cleanly.
|
|
2812
|
-
*/
|
|
2813
|
-
readonly _executionSteps: readonly ExecutionStep[];
|
|
2814
|
-
/**
|
|
2815
|
-
* @internal Type brands — exist only in the type system (`declare`
|
|
2816
|
-
* produces no runtime property). Used for type inference.
|
|
2817
|
-
*/
|
|
2818
|
-
readonly _flags: F;
|
|
2819
|
-
readonly _args: A;
|
|
2820
|
-
readonly _ctx: C;
|
|
2821
|
-
/**
|
|
2822
|
-
* @param schema - Runtime command descriptor.
|
|
2823
|
-
* @param handler - Action handler, if registered.
|
|
2824
|
-
* @param subcommands - Nested sub-command builders (type-erased).
|
|
2825
|
-
* @param executionSteps - Derive/middleware steps in registration order.
|
|
2826
|
-
*/
|
|
2827
|
-
constructor(schema: CommandSchema, handler?: ActionHandler<F, A, C>, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);
|
|
2828
|
-
/**
|
|
2829
|
-
* Register a command-level interactive resolver for schema-driven prompts.
|
|
2830
|
-
*
|
|
2831
|
-
* The resolver is called after CLI/env/config resolution with partially
|
|
2832
|
-
* resolved flag values. It returns a prompt schema for flags that need
|
|
2833
|
-
* interactive input based on the current state.
|
|
2834
|
-
*
|
|
2835
|
-
* For flags the resolver returns a `PromptConfig`, that config is used
|
|
2836
|
-
* instead of any per-flag `.prompt()` config. For flags returned as falsy
|
|
2837
|
-
* (or not mentioned), per-flag `.prompt()` configs are used as fallback.
|
|
2838
|
-
*
|
|
2839
|
-
* Commands without `.interactive()` use per-flag prompt configs directly.
|
|
2840
|
-
*
|
|
2841
|
-
* @example
|
|
2842
|
-
* ```ts
|
|
2843
|
-
* const deploy = command('deploy')
|
|
2844
|
-
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
2845
|
-
* .flag('force', flag.boolean())
|
|
2846
|
-
* .interactive(({ flags }) => ({
|
|
2847
|
-
* region: !flags.region && {
|
|
2848
|
-
* kind: 'select',
|
|
2849
|
-
* message: 'Select region',
|
|
2850
|
-
* },
|
|
2851
|
-
* }))
|
|
2852
|
-
* .action(({ flags }) => { ... });
|
|
2853
|
-
* ```
|
|
2854
|
-
*
|
|
2855
|
-
* @param resolver - Function receiving partially resolved flags and returning prompt configs.
|
|
2856
|
-
* @returns The builder (for chaining).
|
|
2857
|
-
*/
|
|
2858
|
-
interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;
|
|
2859
|
-
/**
|
|
2860
|
-
* Register a command-scoped typed pre-action handler.
|
|
2861
|
-
*
|
|
2862
|
-
* Derive runs after full resolution and before the action handler.
|
|
2863
|
-
* It receives typed `{ args, flags, ctx, out, meta }` and may either:
|
|
2864
|
-
*
|
|
2865
|
-
* - return `undefined` for validation-only behavior
|
|
2866
|
-
* - return an object to merge additional properties into `ctx`
|
|
2867
|
-
*
|
|
2868
|
-
* Unlike middleware, derive cannot wrap downstream execution and does not
|
|
2869
|
-
* use `next()`. Use `middleware()` for timing, logging, retries, cleanup,
|
|
2870
|
-
* or error-boundary patterns.
|
|
2871
|
-
*
|
|
2872
|
-
* Adding derive drops the current handler (like `.flag()`, `.arg()`, and
|
|
2873
|
-
* `.middleware()`) because the action handler's `ctx` type may change.
|
|
2874
|
-
*
|
|
2875
|
-
* @example
|
|
2876
|
-
* ```ts
|
|
2877
|
-
* command('deploy')
|
|
2878
|
-
* .flag('token', flag.string().env('AUTH_TOKEN'))
|
|
2879
|
-
* .derive(({ flags }) => {
|
|
2880
|
-
* if (!flags.token) {
|
|
2881
|
-
* throw new CLIError('Not authenticated', {
|
|
2882
|
-
* code: 'AUTH_REQUIRED',
|
|
2883
|
-
* suggest: 'Run `mycli login` or set AUTH_TOKEN',
|
|
2884
|
-
* });
|
|
2885
|
-
* }
|
|
2886
|
-
* return { token: flags.token };
|
|
2887
|
-
* })
|
|
2888
|
-
* .action(({ ctx }) => {
|
|
2889
|
-
* ctx.token; // string
|
|
2890
|
-
* });
|
|
2891
|
-
* ```
|
|
2892
|
-
*
|
|
2893
|
-
* @param handler - Derive function receiving typed args/flags/ctx.
|
|
2894
|
-
* @returns The builder (for chaining).
|
|
2895
|
-
*/
|
|
2896
|
-
derive<Output extends Record<string, unknown> | undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;
|
|
2897
|
-
/**
|
|
2898
|
-
* Register middleware to run before the action handler.
|
|
2899
|
-
*
|
|
2900
|
-
* Middleware executes in registration order. Each middleware receives
|
|
2901
|
-
* `{ args, flags, ctx, out, next }` and must call `next(additions)`
|
|
2902
|
-
* to continue the chain. Context additions are merged and become
|
|
2903
|
-
* typed downstream.
|
|
2904
|
-
*
|
|
2905
|
-
* Adding middleware widens `C` via intersection and drops the current
|
|
2906
|
-
* handler (like `.flag()` / `.arg()` — the handler's type signature
|
|
2907
|
-
* changes when context changes).
|
|
2908
|
-
*
|
|
2909
|
-
* @example
|
|
2910
|
-
* ```ts
|
|
2911
|
-
* import { CLIError, command, middleware } from 'dreamcli';
|
|
2912
|
-
*
|
|
2913
|
-
* interface User {
|
|
2914
|
-
* id: string;
|
|
2915
|
-
* email: string;
|
|
2916
|
-
* }
|
|
2917
|
-
*
|
|
2918
|
-
* async function getCurrentUser(): Promise<User | null> {
|
|
2919
|
-
* return { id: 'u_123', email: 'dev@example.com' };
|
|
2920
|
-
* }
|
|
2921
|
-
*
|
|
2922
|
-
* function startTrace(name: string): string {
|
|
2923
|
-
* return `trace:${name}`;
|
|
2924
|
-
* }
|
|
2925
|
-
*
|
|
2926
|
-
* // Resolve the current user and expose it as `ctx.user` downstream.
|
|
2927
|
-
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
2928
|
-
* const user = await getCurrentUser();
|
|
2929
|
-
* if (!user) {
|
|
2930
|
-
* throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
2931
|
-
* }
|
|
2932
|
-
* await next({ user });
|
|
2933
|
-
* });
|
|
2934
|
-
*
|
|
2935
|
-
* // Create a trace id for this command run and expose it as `ctx.traceId`.
|
|
2936
|
-
* const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
|
|
2937
|
-
* const traceId = startTrace(`${meta.name}.${meta.command}`);
|
|
2938
|
-
* await next({ traceId });
|
|
2939
|
-
* });
|
|
2940
|
-
*
|
|
2941
|
-
* command('deploy')
|
|
2942
|
-
* .middleware(auth) // C becomes { user: User }
|
|
2943
|
-
* .middleware(telemetry) // C becomes { user: User } & { traceId: string }
|
|
2944
|
-
* .action(({ ctx }) => {
|
|
2945
|
-
* ctx.user; // User — typed
|
|
2946
|
-
* ctx.traceId; // string — typed
|
|
2947
|
-
* });
|
|
2948
|
-
* ```
|
|
2949
|
-
*
|
|
2950
|
-
* @param m - {@link Middleware} instance created via `middleware()`.
|
|
2951
|
-
* @returns The builder (for chaining).
|
|
2952
|
-
*/
|
|
2953
|
-
middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;
|
|
2954
|
-
/**
|
|
2955
|
-
* Set the command's description for help text.
|
|
2956
|
-
*
|
|
2957
|
-
* Displayed below the usage line in `--help` output and next to the
|
|
2958
|
-
* command name in parent command/group help listings.
|
|
2959
|
-
*
|
|
2960
|
-
* @param text - One-line description of what the command does.
|
|
2961
|
-
*
|
|
2962
|
-
* @example
|
|
2963
|
-
* ```ts
|
|
2964
|
-
* command('deploy')
|
|
2965
|
-
* .description('Deploy the application to a target environment')
|
|
2966
|
-
* .action(({ out }) => { out.log('deploying...'); });
|
|
2967
|
-
*
|
|
2968
|
-
* // $ mycli deploy --help
|
|
2969
|
-
* // Usage: deploy [flags]
|
|
2970
|
-
* //
|
|
2971
|
-
* // Deploy the application to a target environment
|
|
2972
|
-
* ```
|
|
2973
|
-
*
|
|
2974
|
-
* @returns The builder (for chaining).
|
|
2975
|
-
*/
|
|
2976
|
-
description(text: string): CommandBuilder<F, A, C>;
|
|
2977
|
-
/**
|
|
2978
|
-
* Add an alternative name for this command.
|
|
2979
|
-
*
|
|
2980
|
-
* Aliases are accepted during dispatch alongside the primary name.
|
|
2981
|
-
* Multiple aliases can be chained. Aliases are shown in help output.
|
|
2982
|
-
*
|
|
2983
|
-
* @param name - Alternative command name (e.g. `'d'` for `deploy`).
|
|
2984
|
-
*
|
|
2985
|
-
* @example
|
|
2986
|
-
* ```ts
|
|
2987
|
-
* command('deploy')
|
|
2988
|
-
* .alias('d')
|
|
2989
|
-
* .alias('push')
|
|
2990
|
-
* .action(({ out }) => { out.log('deploying...'); });
|
|
2991
|
-
*
|
|
2992
|
-
* // All equivalent:
|
|
2993
|
-
* // $ mycli deploy
|
|
2994
|
-
* // $ mycli d
|
|
2995
|
-
* // $ mycli push
|
|
2996
|
-
* ```
|
|
2997
|
-
*
|
|
2998
|
-
* @returns The builder (for chaining).
|
|
2999
|
-
*/
|
|
3000
|
-
alias(name: string): CommandBuilder<F, A, C>;
|
|
3001
|
-
/**
|
|
3002
|
-
* Hide this command from help listings.
|
|
3003
|
-
*
|
|
3004
|
-
* The command remains fully functional and dispatchable — it just
|
|
3005
|
-
* won't appear in `--help` output or shell completions. Useful for
|
|
3006
|
-
* internal/debug commands.
|
|
3007
|
-
*
|
|
3008
|
-
* @example
|
|
3009
|
-
* ```ts
|
|
3010
|
-
* command('debug-dump')
|
|
3011
|
-
* .hidden()
|
|
3012
|
-
* .action(({ out }) => { out.log(JSON.stringify(internalState)); });
|
|
3013
|
-
*
|
|
3014
|
-
* // $ mycli --help → 'debug-dump' is not listed
|
|
3015
|
-
* // $ mycli debug-dump → still works
|
|
3016
|
-
* ```
|
|
3017
|
-
*
|
|
3018
|
-
* @returns The builder (for chaining).
|
|
3019
|
-
*/
|
|
3020
|
-
hidden(): CommandBuilder<F, A, C>;
|
|
3021
|
-
/**
|
|
3022
|
-
* Add a usage example to help text.
|
|
3023
|
-
*
|
|
3024
|
-
* Examples are rendered in the "Examples:" section of `--help` output.
|
|
3025
|
-
* Call multiple times to add several examples. Each example shows a
|
|
3026
|
-
* shell invocation, optionally with a description.
|
|
3027
|
-
*
|
|
3028
|
-
* @param cmd - The example command line (without the program name prefix).
|
|
3029
|
-
* @param description - Optional one-line explanation of what the example does.
|
|
3030
|
-
*
|
|
3031
|
-
* @example
|
|
3032
|
-
* ```ts
|
|
3033
|
-
* command('deploy')
|
|
3034
|
-
* .arg('target', arg.string())
|
|
3035
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
3036
|
-
* .example('deploy production', 'Deploy to production')
|
|
3037
|
-
* .example('deploy staging -f', 'Force deploy to staging')
|
|
3038
|
-
* .action(({ args, flags }) => { ... });
|
|
3039
|
-
*
|
|
3040
|
-
* // $ mycli deploy --help
|
|
3041
|
-
* // ...
|
|
3042
|
-
* // Examples:
|
|
3043
|
-
* // deploy production Deploy to production
|
|
3044
|
-
* // deploy staging -f Force deploy to staging
|
|
3045
|
-
* ```
|
|
3046
|
-
*
|
|
3047
|
-
* @returns The builder (for chaining).
|
|
3048
|
-
*/
|
|
3049
|
-
example(cmd: string, description?: string): CommandBuilder<F, A, C>;
|
|
3050
|
-
/**
|
|
3051
|
-
* Register a named flag on this command.
|
|
3052
|
-
*
|
|
3053
|
-
* The flag name is added to the type-level `F` map. Duplicate flag names
|
|
3054
|
-
* are prevented at the type level via the `Exclude` constraint.
|
|
3055
|
-
*
|
|
3056
|
-
* The builder controls the flag's type, presence, aliases, env/config
|
|
3057
|
-
* bindings, and description. See {@link FlagBuilder} for available modifiers.
|
|
3058
|
-
*
|
|
3059
|
-
* @param name - Flag name (used as `--name` on CLI and `flags.*` in handler).
|
|
3060
|
-
* @param builder - Configured `FlagBuilder` from `flag.string()`, `flag.boolean()`,
|
|
3061
|
-
* `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
|
|
3062
|
-
*
|
|
3063
|
-
* @example
|
|
3064
|
-
* ```ts
|
|
3065
|
-
* command('serve')
|
|
3066
|
-
* .flag('port', flag.number()
|
|
3067
|
-
* .alias('p')
|
|
3068
|
-
* .env('PORT')
|
|
3069
|
-
* .default(3000)
|
|
3070
|
-
* .describe('Port to listen on'))
|
|
3071
|
-
* .flag('host', flag.string()
|
|
3072
|
-
* .env('HOST')
|
|
3073
|
-
* .default('localhost')
|
|
3074
|
-
* .describe('Bind address'))
|
|
3075
|
-
* .flag('verbose', flag.boolean()
|
|
3076
|
-
* .alias('v')
|
|
3077
|
-
* .describe('Enable verbose logging'))
|
|
3078
|
-
* .action(({ flags, out }) => {
|
|
3079
|
-
* flags.port; // number
|
|
3080
|
-
* flags.host; // string
|
|
3081
|
-
* flags.verbose; // boolean
|
|
3082
|
-
* out.log(`Listening on ${flags.host}:${flags.port}`);
|
|
3083
|
-
* });
|
|
3084
|
-
*
|
|
3085
|
-
* // $ mycli serve --port 8080 -v
|
|
3086
|
-
* // $ PORT=9090 mycli serve
|
|
3087
|
-
* ```
|
|
3088
|
-
*
|
|
3089
|
-
* @returns The builder (for chaining).
|
|
3090
|
-
*/
|
|
3091
|
-
flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof F>, builder: B): CommandBuilder<F & Record<N, B>, A, C>;
|
|
3092
|
-
/**
|
|
3093
|
-
* Register a named positional argument on this command.
|
|
3094
|
-
*
|
|
3095
|
-
* Args are ordered by registration — position on the CLI matches the
|
|
3096
|
-
* order of `.arg()` calls. The arg name is added to the type-level `A`
|
|
3097
|
-
* map. Duplicate arg names are prevented at the type level via the
|
|
3098
|
-
* `Exclude` constraint.
|
|
3099
|
-
*
|
|
3100
|
-
* The builder controls the arg's type, presence, env binding, and
|
|
3101
|
-
* description. See {@link ArgBuilder} for available modifiers.
|
|
3102
|
-
*
|
|
3103
|
-
* @param name - Positional arg name (used in help text and `args.*`).
|
|
3104
|
-
* @param builder - Configured `ArgBuilder` from `arg.string()`, `arg.number()`,
|
|
3105
|
-
* or `arg.custom()`.
|
|
3106
|
-
*
|
|
3107
|
-
* @example
|
|
3108
|
-
* ```ts
|
|
3109
|
-
* command('deploy')
|
|
3110
|
-
* // Required string arg — first positional
|
|
3111
|
-
* .arg('target', arg.string()
|
|
3112
|
-
* .env('DEPLOY_TARGET')
|
|
3113
|
-
* .describe('Deploy target'))
|
|
3114
|
-
* // Optional number arg — second positional
|
|
3115
|
-
* .arg('port', arg.number()
|
|
3116
|
-
* .env('PORT')
|
|
3117
|
-
* .default(3000)
|
|
3118
|
-
* .describe('Port number'))
|
|
3119
|
-
* .action(({ args }) => {
|
|
3120
|
-
* args.target; // string
|
|
3121
|
-
* args.port; // number
|
|
3122
|
-
* });
|
|
3123
|
-
*
|
|
3124
|
-
* // Usage: deploy [flags] <target> [port]
|
|
3125
|
-
* // $ mycli deploy production 8080
|
|
3126
|
-
* // $ DEPLOY_TARGET=staging mycli deploy
|
|
3127
|
-
* ```
|
|
3128
|
-
*
|
|
3129
|
-
* @returns The builder (for chaining).
|
|
3130
|
-
*/
|
|
3131
|
-
arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
|
|
3132
|
-
/**
|
|
3133
|
-
* Register a nested subcommand on this command.
|
|
3134
|
-
*
|
|
3135
|
-
* The subcommand's builder is stored in `_subcommands` for the CLI layer's
|
|
3136
|
-
* `eraseCommand()` to traverse when building the execution tree. The
|
|
3137
|
-
* subcommand's `CommandSchema` is also appended to `schema.commands` for
|
|
3138
|
-
* help rendering and completion generation.
|
|
3139
|
-
*
|
|
3140
|
-
* Does not change `F`, `A`, or `C` — subcommands are type-erased at the
|
|
3141
|
-
* parent level (same semantics as `CLIBuilder.command()`). The handler is
|
|
3142
|
-
* preserved.
|
|
3143
|
-
*
|
|
3144
|
-
* @example
|
|
3145
|
-
* ```ts
|
|
3146
|
-
* const db = group('db')
|
|
3147
|
-
* .description('Database operations')
|
|
3148
|
-
* .command(migrateCmd)
|
|
3149
|
-
* .command(seedCmd);
|
|
3150
|
-
* ```
|
|
3151
|
-
*
|
|
3152
|
-
* @param sub - Child {@link CommandBuilder} to nest under this command.
|
|
3153
|
-
* @returns The builder (for chaining).
|
|
3154
|
-
*/
|
|
3155
|
-
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>;
|
|
3156
|
-
/**
|
|
3157
|
-
* Register the action handler for this command.
|
|
3158
|
-
*
|
|
3159
|
-
* The handler receives fully typed `{ args, flags, ctx, out }` derived
|
|
3160
|
-
* from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
|
|
3161
|
-
* definitions.
|
|
3162
|
-
*
|
|
3163
|
-
* May be synchronous or async. Return values are ignored; command handlers
|
|
3164
|
-
* communicate through `out`, thrown errors, and side effects.
|
|
3165
|
-
*
|
|
3166
|
-
* @param handler - Function receiving `ActionParams<F, A, C>`.
|
|
3167
|
-
*
|
|
3168
|
-
* @example
|
|
3169
|
-
* // Minimal
|
|
3170
|
-
* command('greet')
|
|
3171
|
-
* .arg('name', arg.string())
|
|
3172
|
-
* .action(({ args, out }) => {
|
|
3173
|
-
* out.log(`Hello, ${args.name}!`);
|
|
3174
|
-
* });
|
|
3175
|
-
*
|
|
3176
|
-
* @example
|
|
3177
|
-
* // Full params — flags, args, context, output
|
|
3178
|
-
* command('deploy')
|
|
3179
|
-
* .arg('target', arg.string().env('DEPLOY_TARGET'))
|
|
3180
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
3181
|
-
* .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
|
|
3182
|
-
* .middleware(auth)
|
|
3183
|
-
* .action(async ({ args, flags, ctx, out }) => {
|
|
3184
|
-
* args.target; // string
|
|
3185
|
-
* flags.force; // boolean
|
|
3186
|
-
* flags.region; // 'us' | 'eu' | 'ap' | undefined
|
|
3187
|
-
* ctx.user; // User (from auth middleware)
|
|
3188
|
-
*
|
|
3189
|
-
* const spinner = out.spinner('Deploying...');
|
|
3190
|
-
* await deploy(args.target, { force: flags.force });
|
|
3191
|
-
* spinner.stop();
|
|
3192
|
-
* out.log('Done');
|
|
3193
|
-
* });
|
|
3194
|
-
*
|
|
3195
|
-
* @returns The builder (for chaining).
|
|
3196
|
-
*/
|
|
3197
|
-
action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
|
|
3198
|
-
}
|
|
3199
|
-
/**
|
|
3200
|
-
* Create a new command builder.
|
|
3201
|
-
*
|
|
3202
|
-
* @param name - The command name used for dispatch (e.g. `'deploy'`).
|
|
3203
|
-
*
|
|
3204
|
-
* @example
|
|
3205
|
-
* ```ts
|
|
3206
|
-
* const greet = command('greet')
|
|
3207
|
-
* .arg('name', arg.string())
|
|
3208
|
-
* .flag('loud', flag.boolean())
|
|
3209
|
-
* .action(({ args, flags, out }) => {
|
|
3210
|
-
* const msg = `Hello, ${args.name}!`;
|
|
3211
|
-
* out.log(flags.loud ? msg.toUpperCase() : msg);
|
|
3212
|
-
* });
|
|
3213
|
-
* ```
|
|
3214
|
-
*
|
|
3215
|
-
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
3216
|
-
*/
|
|
3217
|
-
declare function command(name: string): CommandBuilder;
|
|
3218
|
-
/**
|
|
3219
|
-
* Create a command builder intended for use as a command group.
|
|
3220
|
-
*
|
|
3221
|
-
* Semantically identical to `command()` — a group is simply a command that
|
|
3222
|
-
* has subcommands registered via `.command()`. The separate factory
|
|
3223
|
-
* communicates intent: groups organise subcommands, leaf commands have actions.
|
|
3224
|
-
*
|
|
3225
|
-
* A group may also have its own `.action()` (e.g. `git remote` lists remotes
|
|
3226
|
-
* when invoked without a subcommand, but dispatches to `git remote add`, etc.).
|
|
3227
|
-
*
|
|
3228
|
-
* @param name - The group name used for dispatch (e.g. `'db'`).
|
|
3229
|
-
*
|
|
3230
|
-
* @example
|
|
3231
|
-
* ```ts
|
|
3232
|
-
* const db = group('db')
|
|
3233
|
-
* .description('Database operations')
|
|
3234
|
-
* .command(migrateCmd)
|
|
3235
|
-
* .command(seedCmd);
|
|
3236
|
-
* ```
|
|
3237
|
-
*
|
|
3238
|
-
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
3239
|
-
*/
|
|
3240
|
-
declare function group(name: string): CommandBuilder;
|
|
3241
|
-
//#endregion
|
|
3242
|
-
//#region src/runtime/adapter.d.ts
|
|
3243
|
-
/**
|
|
3244
|
-
* Runtime adapter interface.
|
|
3245
|
-
*
|
|
3246
|
-
* Defines the minimal contract between the platform-agnostic core and
|
|
3247
|
-
* the host runtime (Node.js, Bun, Deno). Every platform-dependent
|
|
3248
|
-
* operation flows through this interface — the core never calls
|
|
3249
|
-
* `process.*`, `Deno.*`, or `Bun.*` directly.
|
|
3250
|
-
*
|
|
3251
|
-
* Adapters are designed to be:
|
|
3252
|
-
* - **Immutable in shape:** all properties are readonly
|
|
3253
|
-
* - **Minimal:** only the operations the framework actually needs
|
|
3254
|
-
* - **Testable:** easily stubbed in tests via `createTestAdapter()`
|
|
3255
|
-
*
|
|
3256
|
-
* @example
|
|
3257
|
-
* ```ts
|
|
3258
|
-
* // Production: auto-detected
|
|
3259
|
-
* cli('mycli').run(); // uses Node/Bun/Deno adapter
|
|
3260
|
-
*
|
|
3261
|
-
* // Test: explicit adapter
|
|
3262
|
-
* cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
|
|
3263
|
-
* ```
|
|
3264
|
-
*/
|
|
3265
|
-
interface RuntimeAdapter {
|
|
3266
|
-
/** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
|
|
3267
|
-
readonly argv: readonly string[];
|
|
3268
|
-
/**
|
|
3269
|
-
* Environment variables.
|
|
3270
|
-
* Values are `string | undefined` — mirrors Node's `process.env` semantics.
|
|
3271
|
-
*/
|
|
3272
|
-
readonly env: Readonly<Record<string, string | undefined>>;
|
|
3273
|
-
/** Current working directory (absolute path). */
|
|
3274
|
-
readonly cwd: string;
|
|
3275
|
-
/** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
|
|
3276
|
-
readonly stdout: WriteFn;
|
|
3277
|
-
/** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
|
|
3278
|
-
readonly stderr: WriteFn;
|
|
3279
|
-
/**
|
|
3280
|
-
* Line reader for stdin. Used by the prompt engine for interactive input.
|
|
3281
|
-
*
|
|
3282
|
-
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
3283
|
-
* indicating the user closed the input stream (treated as cancel).
|
|
3284
|
-
*/
|
|
3285
|
-
readonly stdin: ReadFn;
|
|
3286
|
-
/**
|
|
3287
|
-
* Read all of stdin as a single string (for piped data).
|
|
3288
|
-
*
|
|
3289
|
-
* Returns the full stdin contents when data is piped (`stdinIsTTY` is
|
|
3290
|
-
* false), or `null` when stdin is a TTY (no piped data available).
|
|
3291
|
-
*
|
|
3292
|
-
* Used by the resolve chain for args with `.stdin()` configured.
|
|
3293
|
-
* Unlike {@link stdin} (which reads one line for prompts), this
|
|
3294
|
-
* consumes the entire stream to EOF.
|
|
3295
|
-
*
|
|
3296
|
-
* @returns Full stdin contents as a string, or `null` if stdin is a TTY.
|
|
3297
|
-
*/
|
|
3298
|
-
readonly readStdin: () => Promise<string | null>;
|
|
3299
|
-
/** Whether stdout is connected to a TTY. */
|
|
3300
|
-
readonly isTTY: boolean;
|
|
3301
|
-
/** Whether stdin is connected to a TTY (used for prompt gating). */
|
|
3302
|
-
readonly stdinIsTTY: boolean;
|
|
3303
|
-
/**
|
|
3304
|
-
* Exit the process with the given code.
|
|
3305
|
-
* Must not return (divergent function).
|
|
3306
|
-
*/
|
|
3307
|
-
readonly exit: (code: number) => never;
|
|
3308
|
-
/**
|
|
3309
|
-
* Read a file as UTF-8 text.
|
|
3310
|
-
*
|
|
3311
|
-
* Returns file contents on success, `null` if the file does not exist
|
|
3312
|
-
* (ENOENT/NotFound). Throws on other I/O errors (permission denied,
|
|
3313
|
-
* is-directory, etc.) — those indicate unexpected failures, not
|
|
3314
|
-
* "try the next path".
|
|
3315
|
-
*
|
|
3316
|
-
* Used by config file discovery to probe multiple candidate paths.
|
|
3317
|
-
*/
|
|
3318
|
-
readonly readFile: (path: string) => Promise<string | null>;
|
|
3319
|
-
/**
|
|
3320
|
-
* User home directory (absolute path).
|
|
3321
|
-
*
|
|
3322
|
-
* - Node/Bun: derived from `HOME` / `USERPROFILE` env
|
|
3323
|
-
* - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
|
|
3324
|
-
*/
|
|
3325
|
-
readonly homedir: string;
|
|
3326
|
-
/**
|
|
3327
|
-
* Platform-specific user configuration directory (absolute path).
|
|
3328
|
-
*
|
|
3329
|
-
* - Unix: `$XDG_CONFIG_HOME` or `~/.config`
|
|
3330
|
-
* - Windows: `%APPDATA%` or `~\AppData\Roaming`
|
|
3331
|
-
*
|
|
3332
|
-
* Config discovery appends the app-specific subdirectory.
|
|
3333
|
-
*/
|
|
3334
|
-
readonly configDir: string;
|
|
3335
|
-
}
|
|
3336
|
-
/**
|
|
3337
|
-
* Options for creating a test adapter.
|
|
3338
|
-
*
|
|
3339
|
-
* All fields are optional — sensible defaults are applied for testing
|
|
3340
|
-
* scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
|
|
3341
|
-
* throws instead of killing the process).
|
|
3342
|
-
*/
|
|
3343
|
-
interface TestAdapterOptions {
|
|
3344
|
-
/** Raw argv (defaults to `['node', 'test']`). */
|
|
3345
|
-
readonly argv?: readonly string[];
|
|
3346
|
-
/** Environment variables (defaults to `{}`). */
|
|
3347
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
3348
|
-
/** Working directory (defaults to `'/test'`). */
|
|
3349
|
-
readonly cwd?: string;
|
|
3350
|
-
/** Stdout writer (defaults to noop). */
|
|
3351
|
-
readonly stdout?: WriteFn;
|
|
3352
|
-
/** Stderr writer (defaults to noop). */
|
|
3353
|
-
readonly stderr?: WriteFn;
|
|
3354
|
-
/**
|
|
3355
|
-
* Stdin line reader (defaults to returning `null` — immediate EOF).
|
|
3356
|
-
*
|
|
3357
|
-
* Use a custom `ReadFn` to simulate user input in tests.
|
|
3358
|
-
*/
|
|
3359
|
-
readonly stdin?: ReadFn;
|
|
3360
|
-
/**
|
|
3361
|
-
* Piped stdin data for testing args with `.stdin()` configured.
|
|
3362
|
-
*
|
|
3363
|
-
* When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
|
|
3364
|
-
* string once, then `null` on subsequent reads. When absent, or when
|
|
3365
|
-
* `stdinIsTTY` is `true`, `readStdin()` returns `null`.
|
|
3366
|
-
*
|
|
3367
|
-
* @example
|
|
3368
|
-
* ```ts
|
|
3369
|
-
* createTestAdapter({
|
|
3370
|
-
* stdinData: '{"key": "value"}',
|
|
3371
|
-
* })
|
|
3372
|
-
* ```
|
|
3373
|
-
*/
|
|
3374
|
-
readonly stdinData?: string;
|
|
3375
|
-
/** TTY flag for stdout (defaults to `false`). */
|
|
3376
|
-
readonly isTTY?: boolean;
|
|
3377
|
-
/** TTY flag for stdin (defaults to `false`). */
|
|
3378
|
-
readonly stdinIsTTY?: boolean;
|
|
3379
|
-
/**
|
|
3380
|
-
* Exit function (defaults to throwing `ExitError`).
|
|
3381
|
-
* The default throw-based exit allows tests to catch the exit code.
|
|
3382
|
-
*/
|
|
3383
|
-
readonly exit?: (code: number) => never;
|
|
3384
|
-
/**
|
|
3385
|
-
* File reader stub (defaults to returning `null` — all files not found).
|
|
3386
|
-
*
|
|
3387
|
-
* Supply a custom function to simulate a virtual filesystem in tests:
|
|
3388
|
-
* ```ts
|
|
3389
|
-
* createTestAdapter({
|
|
3390
|
-
* readFile: (path) => Promise.resolve(
|
|
3391
|
-
* path === '/home/test/.config/myapp/config.json'
|
|
3392
|
-
* ? '{"region":"eu"}'
|
|
3393
|
-
* : null
|
|
3394
|
-
* ),
|
|
3395
|
-
* })
|
|
3396
|
-
* ```
|
|
3397
|
-
*/
|
|
3398
|
-
readonly readFile?: (path: string) => Promise<string | null>;
|
|
3399
|
-
/** Home directory (defaults to `'/home/test'`). */
|
|
3400
|
-
readonly homedir?: string;
|
|
3401
|
-
/** Config directory (defaults to `'/home/test/.config'`). */
|
|
3402
|
-
readonly configDir?: string;
|
|
3403
|
-
}
|
|
3404
|
-
/**
|
|
3405
|
-
* Error thrown by the default test adapter exit function.
|
|
3406
|
-
*
|
|
3407
|
-
* In tests, `process.exit` would kill the test runner. Instead, the test
|
|
3408
|
-
* adapter throws this error, allowing tests to assert on exit codes:
|
|
3409
|
-
*
|
|
3410
|
-
* ```ts
|
|
3411
|
-
* try {
|
|
3412
|
-
* await cli.run({ adapter: createTestAdapter() });
|
|
3413
|
-
* } catch (e) {
|
|
3414
|
-
* if (e instanceof ExitError) expect(e.code).toBe(0);
|
|
3415
|
-
* }
|
|
3416
|
-
* ```
|
|
3417
|
-
*/
|
|
3418
|
-
declare class ExitError extends Error {
|
|
3419
|
-
/** @override */
|
|
3420
|
-
readonly name = "ExitError";
|
|
3421
|
-
/** The exit code passed to `exit()`. */
|
|
3422
|
-
readonly code: number;
|
|
3423
|
-
constructor(code: number);
|
|
3424
|
-
}
|
|
3425
|
-
/**
|
|
3426
|
-
* Create a test runtime adapter with injectable process state.
|
|
3427
|
-
*
|
|
3428
|
-
* Use this in `dreamcli/testkit` tests when you need to simulate argv,
|
|
3429
|
-
* environment variables, TTY state, stdin, or config-file reads without
|
|
3430
|
-
* touching the host process.
|
|
3431
|
-
*
|
|
3432
|
-
* @param options - Optional overrides for any adapter field.
|
|
3433
|
-
* @returns A `RuntimeAdapter` suitable for test scenarios.
|
|
3434
|
-
*
|
|
3435
|
-
* @example
|
|
3436
|
-
* ```ts
|
|
3437
|
-
* const adapter = createTestAdapter({
|
|
3438
|
-
* argv: ['node', 'cli.js', 'deploy', '--force'],
|
|
3439
|
-
* env: { DEPLOY_REGION: 'us' },
|
|
3440
|
-
* });
|
|
3441
|
-
*
|
|
3442
|
-
* const result = await cli('mycli').run({ adapter });
|
|
3443
|
-
* ```
|
|
3444
|
-
*/
|
|
3445
|
-
declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
|
|
3446
|
-
//#endregion
|
|
3447
|
-
export { ResolvedMultiselectPromptConfig as $, WithArgPresence as $t, ErrorCode as A, ResolvedValue as At, BeforeParseParams as B, PromptResult as Bt, RunOptions as C, FlagFactory as Ct, CLIError as D, FlagSchema as Dt, formatHelp as E, FlagPresence as Et, ValidationErrorCode as F, InputPromptConfig as Ft, plugin as G, ArgFactory as Gt, CLIPluginHooks as H, SelectPromptConfig as Ht, ValidationErrorOptions as I, MultiselectPromptConfig as It, ResolveResult as J, ArgPresence as Jt, DeprecationWarning as K, ArgKind as Kt, isCLIError as L, PromptConfig as Lt, ParseErrorCode as M, createSchema as Mt, ParseErrorOptions as N, flag as Nt, CLIErrorJSON as O, InferFlag as Ot, ValidationError as P, ConfirmPromptConfig as Pt, ReadFn as Q, ResolvedArgValue as Qt, isParseError as R, PromptConfigBase as Rt, group as S, FlagConfig as St, HelpOptions as T, FlagParseFn as Tt, PluginCommandContext as U, ArgBuilder as Ut, CLIPlugin as V, SelectChoice as Vt, ResolvedCommandParams as W, ArgConfig as Wt, PROMPT_CANCEL as X, InferArg as Xt, resolve as Y, ArgSchema as Yt, PromptEngine as Z, InferArgs as Zt, InteractiveParams as _, Middleware as _t, ActionHandler as a, ProgressHandle as an, createTestPrompter as at, Out as b, middleware as bt, CommandArgEntry as c, SpinnerOptions as cn, OutputOptions as ct, CommandExample as d, TableOptions as dn, createOutput as dt, WithVariadic as en, ResolvedPromptConfig as et, CommandMeta as f, TableStream as fn, WriteFn as ft, ErasedCommand as g, tokenize as gt, DeriveParams as h, parse as ht, createTestAdapter as i, Fallback as in, createTerminalPrompter as it, ParseError as j, WithPresence as jt, CLIErrorOptions as k, InferFlags as kt, CommandBuilder as l, TableColumn as ln, Verbosity as lt, DeriveHandler as m, Token as mt, RuntimeAdapter as n, createArgSchema as nn, TestAnswer as nt, ActionParams as o, ProgressOptions as on, resolvePromptConfig as ot, CommandSchema as p, ParseResult as pt, ResolveOptions as q, ArgParseFn as qt, TestAdapterOptions as r, ActivityEvent as rn, TestPrompterOptions as rt, AnyCommandBuilder as s, SpinnerHandle as sn, CapturedOutput as st, ExitError as t, arg as tn, ResolvedSelectPromptConfig as tt, CommandConfig as u, TableFormat as un, createCaptureOutput as ut, InteractiveResolver as v, MiddlewareHandler as vt, RunResult as w, FlagKind as wt, command as x, FlagBuilder as xt, InteractiveResult as y, MiddlewareParams as yt, isValidationError as z, PromptKind as zt };
|