@kjanat/dreamcli 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-CuhI1Ynv.d.mts → command-Cq6YZjEH.d.mts} +1693 -1591
- package/dist/completion-DCWRvQjQ.mjs +59 -0
- package/dist/completion.d.mts +1 -1
- package/dist/completion.mjs +1 -1
- package/dist/{config-DSh3QJpX.mjs → config-CANc4lsA.mjs} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/core-CPh0FcFg.mjs +25 -0
- package/dist/dynamic-xPNS3_vL.mjs +1 -0
- package/dist/{index-DIWRV_wp.d.mts → index-8EiEDJfX.d.mts} +33 -7
- package/dist/{index-DDhRLoTu.d.mts → index-BZ3jYjyh.d.mts} +12 -3
- package/dist/{index-Vjl2_m23.d.mts → index-Bkk86gFg.d.mts} +16 -11
- package/dist/{index-aTmg9yfl.d.mts → index-CLg6j-KJ.d.mts} +1 -1
- package/dist/{index-CLtWJqwn.d.mts → index-DBepo8jX.d.mts} +23 -4
- package/dist/index.d.mts +9 -9
- package/dist/index.mjs +1 -1
- package/dist/json-schema-DmFJR8c6.mjs +59 -0
- package/dist/json-schema.d.mts +1 -1
- package/dist/json-schema.mjs +1 -1
- package/dist/prompt.d.mts +1 -1
- package/dist/prompt.mjs +1 -1
- package/dist/runtime.d.mts +2 -2
- package/dist/runtime.mjs +1 -1
- package/dist/{session-BEKj0yLA.mjs → session-BBRg9p2u.mjs} +1 -1
- package/dist/{terminal-Dws_b5UK.mjs → terminal-mINn5p7B.mjs} +1 -1
- package/dist/{test-prompter-euLYzWWO.mjs → test-prompter-BI9sA9n7.mjs} +1 -1
- package/dist/testkit.d.mts +3 -3
- package/dist/testkit.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/dreamcli.schema.json +175 -0
- package/package.json +9 -10
- package/dist/completion-B4oRc2Ae.mjs +0 -59
- package/dist/core-BZx351-p.mjs +0 -21
- package/dist/dynamic-BK2lQF2M.mjs +0 -1
- package/dist/json-schema-CYgq_hFu.mjs +0 -59
|
@@ -1097,6 +1097,10 @@ interface FlagSchema<K extends FlagKind = FlagKind> {
|
|
|
1097
1097
|
readonly configPath: string | undefined;
|
|
1098
1098
|
/** Human-readable description for help text. */
|
|
1099
1099
|
readonly description: HelpDescription | undefined;
|
|
1100
|
+
/** Named section in command help. */
|
|
1101
|
+
readonly group: string | undefined;
|
|
1102
|
+
/** Whether the flag is shown only in full text help. */
|
|
1103
|
+
readonly advanced?: true | undefined;
|
|
1100
1104
|
/** Allowed literal values when `kind === 'enum'`. */
|
|
1101
1105
|
readonly enumValues: readonly string[] | undefined;
|
|
1102
1106
|
/**
|
|
@@ -1278,6 +1282,10 @@ interface FlagDefinitionBase {
|
|
|
1278
1282
|
* @defaultValue `undefined`
|
|
1279
1283
|
*/
|
|
1280
1284
|
readonly description?: HelpDescription | undefined;
|
|
1285
|
+
/** Named section in command help. */
|
|
1286
|
+
readonly group?: string | undefined;
|
|
1287
|
+
/** Whether the flag is shown only in full text help. */
|
|
1288
|
+
readonly advanced?: true | undefined;
|
|
1281
1289
|
/**
|
|
1282
1290
|
* Help placeholder label (`'url'` renders as `<url>`).
|
|
1283
1291
|
* @defaultValue `undefined`
|
|
@@ -1765,6 +1773,10 @@ declare class FlagBuilder<C extends FlagConfig> {
|
|
|
1765
1773
|
* @returns The builder (for chaining).
|
|
1766
1774
|
*/
|
|
1767
1775
|
describe(description: HelpDescription): FlagBuilder<WithoutElementEligibility<C>>;
|
|
1776
|
+
/** Place this flag in a named options section in command help. */
|
|
1777
|
+
group(name: string): FlagBuilder<WithoutElementEligibility<C>>;
|
|
1778
|
+
/** Show this flag only in full text help, requested with `--help=all`. */
|
|
1779
|
+
advanced(): FlagBuilder<WithoutElementEligibility<C>>;
|
|
1768
1780
|
/**
|
|
1769
1781
|
* Attach interactive prompt configuration for v0.3+ resolution.
|
|
1770
1782
|
*
|
|
@@ -2716,6 +2728,8 @@ interface ArgSchema<K extends ArgKind = ArgKind> {
|
|
|
2716
2728
|
readonly sensitive: boolean;
|
|
2717
2729
|
/** Human-readable description for help text. */
|
|
2718
2730
|
readonly description: HelpDescription | undefined;
|
|
2731
|
+
/** Named section in command help. */
|
|
2732
|
+
readonly group: string | undefined;
|
|
2719
2733
|
/**
|
|
2720
2734
|
* Environment variable name for env resolution.
|
|
2721
2735
|
*
|
|
@@ -2896,6 +2910,8 @@ interface ArgDefinitionBase {
|
|
|
2896
2910
|
* @defaultValue `undefined`
|
|
2897
2911
|
*/
|
|
2898
2912
|
readonly description?: HelpDescription | undefined;
|
|
2913
|
+
/** Named section in command help. */
|
|
2914
|
+
readonly group?: string | undefined;
|
|
2899
2915
|
/**
|
|
2900
2916
|
* Environment variable name for env resolution.
|
|
2901
2917
|
* @defaultValue `undefined`
|
|
@@ -3547,6 +3563,8 @@ declare class ArgBuilder<C extends ArgConfig> {
|
|
|
3547
3563
|
* ```
|
|
3548
3564
|
*/
|
|
3549
3565
|
describe(description: HelpDescription): ArgBuilder<WithoutArgElementEligibility<C>>;
|
|
3566
|
+
/** Place this argument in a named arguments section in command help. */
|
|
3567
|
+
group(name: string): ArgBuilder<WithoutArgElementEligibility<C>>;
|
|
3550
3568
|
/**
|
|
3551
3569
|
* Mark this arg as deprecated.
|
|
3552
3570
|
*
|
|
@@ -4147,1947 +4165,2031 @@ declare const prompt: {
|
|
|
4147
4165
|
};
|
|
4148
4166
|
};
|
|
4149
4167
|
/**
|
|
4150
|
-
*
|
|
4168
|
+
* Minimal I/O seam — the only write primitive the output module depends on.
|
|
4151
4169
|
*
|
|
4152
|
-
*
|
|
4153
|
-
*
|
|
4154
|
-
*
|
|
4170
|
+
* Extracted to its own file so that both `index.ts` (OutputChannel) and
|
|
4171
|
+
* `activity.ts` (handle classes) can import it without a circular dependency.
|
|
4172
|
+
*
|
|
4173
|
+
* @module dreamcli/core/output/writer
|
|
4155
4174
|
*/
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4175
|
+
/**
|
|
4176
|
+
* A function that writes a string somewhere.
|
|
4177
|
+
*
|
|
4178
|
+
* This is the only write primitive the output layer depends on.
|
|
4179
|
+
* In production it usually wraps `process.stdout.write` or
|
|
4180
|
+
* `process.stderr.write`; in tests it is often a simple string accumulator.
|
|
4181
|
+
*
|
|
4182
|
+
* The contract is intentionally tiny:
|
|
4183
|
+
* - writes are synchronous fire-and-forget
|
|
4184
|
+
* - callers decide whether to append a trailing newline
|
|
4185
|
+
* - there is no backpressure or flush signal
|
|
4186
|
+
*
|
|
4187
|
+
* @example
|
|
4188
|
+
* ```ts
|
|
4189
|
+
* const lines: string[] = [];
|
|
4190
|
+
* const write: WriteFn = (data) => {
|
|
4191
|
+
* lines.push(data);
|
|
4192
|
+
* };
|
|
4193
|
+
* ```
|
|
4194
|
+
*/
|
|
4195
|
+
type WriteFn = (data: string) => void;
|
|
4196
|
+
/**
|
|
4197
|
+
* Configuration for creating an output channel.
|
|
4198
|
+
*
|
|
4199
|
+
* Every field is optional — sensible defaults are applied when omitted.
|
|
4200
|
+
*/
|
|
4201
|
+
interface OutputOptions {
|
|
4161
4202
|
/**
|
|
4162
|
-
*
|
|
4203
|
+
* Writer for stdout-bound messages (`log`, `info`, `json`).
|
|
4204
|
+
* Defaults to `process.stdout.write` when running in Node/Bun.
|
|
4205
|
+
*/
|
|
4206
|
+
readonly stdout?: WriteFn;
|
|
4207
|
+
/**
|
|
4208
|
+
* Writer for stderr-bound messages (`warn`, `error`).
|
|
4209
|
+
* In JSON mode, `log` and `info` are also redirected here so that
|
|
4210
|
+
* stdout contains only structured JSON output.
|
|
4211
|
+
* Defaults to `process.stderr.write` when running in Node/Bun.
|
|
4212
|
+
*/
|
|
4213
|
+
readonly stderr?: WriteFn;
|
|
4214
|
+
/**
|
|
4215
|
+
* Whether stdout is connected to a TTY.
|
|
4216
|
+
* When `false`, output may omit ANSI codes and decorations.
|
|
4217
|
+
* Defaults to `false` (safe default — non-TTY until proven otherwise).
|
|
4218
|
+
*/
|
|
4219
|
+
readonly isTTY?: boolean;
|
|
4220
|
+
/** Terminal dimensions captured on the output channel for custom rendering. */
|
|
4221
|
+
readonly terminalSize?: TerminalSize;
|
|
4222
|
+
/**
|
|
4223
|
+
* Read the terminal's current dimensions before concurrent activity redraws.
|
|
4224
|
+
* `.run()` supplies the runtime adapter's getter. Without usable dimensions,
|
|
4225
|
+
* concurrent activities emit static start and completion messages.
|
|
4226
|
+
*/
|
|
4227
|
+
readonly getTerminalSize?: () => TerminalSize | undefined;
|
|
4228
|
+
/**
|
|
4229
|
+
* Verbosity level.
|
|
4230
|
+
* - `'normal'` (default) — emit all messages
|
|
4231
|
+
* - `'quiet'` — suppress `info` messages
|
|
4232
|
+
*/
|
|
4233
|
+
readonly verbosity?: Verbosity;
|
|
4234
|
+
/**
|
|
4235
|
+
* Enable JSON output mode.
|
|
4163
4236
|
*
|
|
4164
|
-
*
|
|
4165
|
-
*
|
|
4166
|
-
*
|
|
4237
|
+
* When `true`, `log` and `info` messages are redirected to stderr
|
|
4238
|
+
* so that stdout is reserved exclusively for structured `json()` output.
|
|
4239
|
+
* `warn` and `error` continue to write to stderr as normal.
|
|
4240
|
+
*
|
|
4241
|
+
* @defaultValue `false`
|
|
4167
4242
|
*/
|
|
4168
|
-
readonly
|
|
4169
|
-
/** Context accumulated from previous middleware in the chain. */
|
|
4170
|
-
readonly ctx: Readonly<Record<string, unknown>>;
|
|
4171
|
-
/** Output channel. */
|
|
4172
|
-
readonly out: Out;
|
|
4173
|
-
/** Invocation-scoped interactive questions. */
|
|
4174
|
-
readonly ask: Ask;
|
|
4175
|
-
/** CLI program metadata (name, bin, version, command). */
|
|
4176
|
-
readonly meta: CommandMeta;
|
|
4243
|
+
readonly jsonMode?: boolean;
|
|
4177
4244
|
/**
|
|
4178
|
-
*
|
|
4245
|
+
* Explicitly enable or disable ANSI colors on `out.color`.
|
|
4179
4246
|
*
|
|
4180
|
-
*
|
|
4181
|
-
*
|
|
4182
|
-
*
|
|
4247
|
+
* When set, this wins over the auto-gate — use it to force colors in
|
|
4248
|
+
* captured test output or when embedding into a host that manages its
|
|
4249
|
+
* own color policy.
|
|
4250
|
+
*
|
|
4251
|
+
* @defaultValue auto — enabled when `isTTY` is `true`, `jsonMode` is
|
|
4252
|
+
* `false`, and the environment supports color (`NO_COLOR`,
|
|
4253
|
+
* `FORCE_COLOR`, `--no-color`, `--color`, `CI` are respected).
|
|
4183
4254
|
*/
|
|
4184
|
-
readonly
|
|
4255
|
+
readonly color?: boolean;
|
|
4256
|
+
/**
|
|
4257
|
+
* Resolved OSC 8 hyperlink support for `out.isHyperlinkSupported`.
|
|
4258
|
+
*
|
|
4259
|
+
* When set, this wins over the `isTTY` fallback. Callers pass the
|
|
4260
|
+
* `NO_HYPERLINKS`/`FORCE_HYPERLINKS` (and `--no-hyperlinks`/`--hyperlinks`)
|
|
4261
|
+
* decision here via {@linkcode resolveHyperlinkOverride}, keeping `process`
|
|
4262
|
+
* access out of the output layer.
|
|
4263
|
+
*
|
|
4264
|
+
* @defaultValue `isTTY`
|
|
4265
|
+
*/
|
|
4266
|
+
readonly hyperlinks?: boolean;
|
|
4185
4267
|
}
|
|
4186
4268
|
/**
|
|
4187
|
-
*
|
|
4188
|
-
*
|
|
4189
|
-
* At runtime, all middleware handlers have this signature. The phantom
|
|
4190
|
-
* `Output` type on {@linkcode Middleware} is erased.
|
|
4191
|
-
*/
|
|
4192
|
-
type ErasedMiddlewareHandler = (params: MiddlewareParams) => void | Promise<void>;
|
|
4193
|
-
/**
|
|
4194
|
-
* Middleware handler function with typed `next()` parameter.
|
|
4269
|
+
* Create an output channel.
|
|
4195
4270
|
*
|
|
4196
|
-
*
|
|
4197
|
-
*
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
readonly args: Readonly<Record<string, unknown>>;
|
|
4201
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
4202
|
-
readonly sources: ErasedInputSources;
|
|
4203
|
-
readonly ctx: Readonly<Record<string, unknown>>;
|
|
4204
|
-
readonly out: Out;
|
|
4205
|
-
/** Invocation-scoped interactive questions. */
|
|
4206
|
-
readonly ask: Ask;
|
|
4207
|
-
readonly meta: CommandMeta;
|
|
4208
|
-
/** Pass context additions downstream. Must include all `Output` properties. */
|
|
4209
|
-
readonly next: (additions: Output) => Promise<void>;
|
|
4210
|
-
}) => void | Promise<void>;
|
|
4211
|
-
/**
|
|
4212
|
-
* Internal runtime representation of middleware.
|
|
4213
|
-
*/
|
|
4214
|
-
interface MiddlewareImpl {
|
|
4215
|
-
readonly _handler: ErasedMiddlewareHandler;
|
|
4216
|
-
}
|
|
4217
|
-
/**
|
|
4218
|
-
* Middleware with phantom output type.
|
|
4271
|
+
* Low-level factory: action handlers already receive `out` automatically from
|
|
4272
|
+
* `cli()`, `.execute()`, and `runCommand()`. Call `createOutput()` when you
|
|
4273
|
+
* are embedding DreamCLI primitives into a custom runtime or need a standalone
|
|
4274
|
+
* output implementation outside the normal command pipeline.
|
|
4219
4275
|
*
|
|
4220
|
-
*
|
|
4221
|
-
*
|
|
4222
|
-
*
|
|
4276
|
+
* @param options - Optional configuration. When omitted, output is
|
|
4277
|
+
* discarded (useful for silent test runs). Pass `stdout`/`stderr`
|
|
4278
|
+
* writers to direct output somewhere useful.
|
|
4223
4279
|
*
|
|
4224
|
-
*
|
|
4225
|
-
* `CommandBuilder.middleware()`.
|
|
4280
|
+
* @returns An {@link Out} instance backed by an {@link OutputChannel}.
|
|
4226
4281
|
*
|
|
4227
4282
|
* @example
|
|
4228
4283
|
* ```ts
|
|
4229
|
-
*
|
|
4284
|
+
* // Production (wired by the runtime adapter)
|
|
4285
|
+
* const out = createOutput({
|
|
4286
|
+
* stdout: (s) => process.stdout.write(s),
|
|
4287
|
+
* stderr: (s) => process.stderr.write(s),
|
|
4288
|
+
* isTTY: process.stdout.isTTY === true,
|
|
4289
|
+
* });
|
|
4230
4290
|
*
|
|
4231
|
-
*
|
|
4232
|
-
*
|
|
4233
|
-
*
|
|
4234
|
-
*
|
|
4291
|
+
* // Test (capture output)
|
|
4292
|
+
* const lines: string[] = [];
|
|
4293
|
+
* const out = createOutput({
|
|
4294
|
+
* stdout: (s) => lines.push(s),
|
|
4295
|
+
* stderr: (s) => lines.push(s),
|
|
4235
4296
|
* });
|
|
4236
4297
|
* ```
|
|
4237
4298
|
*/
|
|
4238
|
-
|
|
4239
|
-
|
|
4240
|
-
|
|
4241
|
-
|
|
4299
|
+
declare function createOutput(options?: OutputOptions): Out;
|
|
4300
|
+
/** Captured output from a `createCaptureOutput` instance. */
|
|
4301
|
+
interface CapturedOutput {
|
|
4302
|
+
/**
|
|
4303
|
+
* Lines written to stdout.
|
|
4304
|
+
*
|
|
4305
|
+
* In normal mode: `log`, `info`, and `json` output.
|
|
4306
|
+
* In JSON mode: only `json` output (log/info redirected to stderr).
|
|
4307
|
+
*/
|
|
4308
|
+
readonly stdout: string[];
|
|
4309
|
+
/**
|
|
4310
|
+
* Lines written to stderr.
|
|
4311
|
+
*
|
|
4312
|
+
* In normal mode: `warn` and `error` output.
|
|
4313
|
+
* In JSON mode: `warn`, `error`, `log`, and `info` output.
|
|
4314
|
+
*/
|
|
4315
|
+
readonly stderr: string[];
|
|
4316
|
+
/**
|
|
4317
|
+
* Activity events from spinner and progress handles.
|
|
4318
|
+
*
|
|
4319
|
+
* Captured separately from stdout/stderr to allow targeted assertions
|
|
4320
|
+
* on activity lifecycle without parsing text output. Events are
|
|
4321
|
+
* recorded in chronological order.
|
|
4322
|
+
*/
|
|
4323
|
+
readonly activity: ActivityEvent[];
|
|
4324
|
+
}
|
|
4242
4325
|
/**
|
|
4243
|
-
* Create
|
|
4326
|
+
* Create an output channel that captures all output into arrays.
|
|
4244
4327
|
*
|
|
4245
|
-
*
|
|
4246
|
-
*
|
|
4328
|
+
* Useful in tests to assert on what a handler wrote without touching
|
|
4329
|
+
* real I/O.
|
|
4247
4330
|
*
|
|
4248
|
-
* @param
|
|
4249
|
-
*
|
|
4250
|
-
*
|
|
4251
|
-
* @returns {@
|
|
4331
|
+
* @param options - Optional {@link OutputOptions} (minus `stdout`/`stderr`,
|
|
4332
|
+
* which are wired to the capture buffers automatically).
|
|
4333
|
+
*
|
|
4334
|
+
* @returns A tuple of `[out, captured]` — the {@link Out} channel and the
|
|
4335
|
+
* {@link CapturedOutput} buffers.
|
|
4252
4336
|
*
|
|
4253
4337
|
* @example
|
|
4254
4338
|
* ```ts
|
|
4255
|
-
*
|
|
4256
|
-
*
|
|
4257
|
-
*
|
|
4258
|
-
*
|
|
4259
|
-
*
|
|
4260
|
-
* });
|
|
4261
|
-
*
|
|
4262
|
-
* // Timing wrapper — measures downstream execution
|
|
4263
|
-
* const timing = middleware(async ({ out, next }) => {
|
|
4264
|
-
* const start = Date.now();
|
|
4265
|
-
* await next({});
|
|
4266
|
-
* out.info(`Done in ${Date.now() - start}ms`);
|
|
4267
|
-
* });
|
|
4268
|
-
*
|
|
4269
|
-
* command('deploy')
|
|
4270
|
-
* .middleware(timing)
|
|
4271
|
-
* .middleware(auth)
|
|
4272
|
-
* .action(({ ctx }) => {
|
|
4273
|
-
* console.log(ctx.user.name); // typed!
|
|
4274
|
-
* });
|
|
4339
|
+
* const [out, captured] = createCaptureOutput();
|
|
4340
|
+
* out.log('hello');
|
|
4341
|
+
* out.warn('danger');
|
|
4342
|
+
* expect(captured.stdout).toEqual(['hello\n']);
|
|
4343
|
+
* expect(captured.stderr).toEqual(['danger\n']);
|
|
4275
4344
|
* ```
|
|
4276
4345
|
*/
|
|
4277
|
-
declare function
|
|
4346
|
+
declare function createCaptureOutput(options?: Omit<OutputOptions, 'stdout' | 'stderr'>): [out: Out, captured: CapturedOutput];
|
|
4278
4347
|
/**
|
|
4279
|
-
*
|
|
4348
|
+
* A select prompt config with choices guaranteed non-empty.
|
|
4280
4349
|
*
|
|
4281
|
-
*
|
|
4282
|
-
*
|
|
4283
|
-
* `resolve()` caller through `ResolveResult.provenance`. {@link wasExplicit}
|
|
4284
|
-
* derives the explicit-versus-defaulted question from it.
|
|
4285
|
-
*
|
|
4286
|
-
* @module dreamcli/core/schema/provenance
|
|
4287
|
-
*/
|
|
4288
|
-
/**
|
|
4289
|
-
* Which stage produced a resolved value, and how.
|
|
4290
|
-
*
|
|
4291
|
-
* `via` and `trigger` distinguish the two ways stdin delivers bytes. An explicit
|
|
4292
|
-
* `-` keeps CLI precedence and reports `{ stage: 'cli', via: 'stdin', trigger:
|
|
4293
|
-
* 'dash' }`; an absent input takes the fallback stage between CLI and env and
|
|
4294
|
-
* reports `{ stage: 'stdin', via: 'stdin', trigger: 'fallback' }`.
|
|
4295
|
-
*
|
|
4296
|
-
* The `'env'` stage is two records the same way. A variable bound by name
|
|
4297
|
-
* reports `{ stage: 'env', envVar }`, the one concrete variable that supplied
|
|
4298
|
-
* the value. An indexed family bound with an `IndexedEnvBinding` reports
|
|
4299
|
-
* `{ stage: 'env', via: 'indexed', count, envVars }`: the count variable that
|
|
4300
|
-
* claimed the input and every member variable read, in entry order and, within
|
|
4301
|
-
* an entry, in field order. `envVars` is empty when the count is `0`. Test
|
|
4302
|
-
* `'envVar' in source` (or `source.via`) before reading either shape's fields.
|
|
4303
|
-
*
|
|
4304
|
-
* @example
|
|
4305
|
-
* ```ts
|
|
4306
|
-
* command('deploy')
|
|
4307
|
-
* .flag('region', flag.string().env('REGION').default('us'))
|
|
4308
|
-
* .action(({ sources }) => {
|
|
4309
|
-
* const region = sources.flags.region;
|
|
4310
|
-
* if (region?.stage === 'env' && 'envVar' in region) console.log(`from ${region.envVar}`);
|
|
4311
|
-
* });
|
|
4312
|
-
* ```
|
|
4350
|
+
* The resolution chain populates choices from `FlagSchema.enumValues`
|
|
4351
|
+
* when the user's {@linkcode PromptConfig} omits them.
|
|
4313
4352
|
*/
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
readonly
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
readonly via: 'stdin';
|
|
4323
|
-
readonly trigger: 'fallback';
|
|
4324
|
-
} | {
|
|
4325
|
-
readonly stage: 'env';
|
|
4326
|
-
readonly envVar: string;
|
|
4327
|
-
} | {
|
|
4328
|
-
readonly stage: 'env';
|
|
4329
|
-
readonly via: 'indexed';
|
|
4330
|
-
readonly count: string;
|
|
4331
|
-
readonly envVars: readonly string[];
|
|
4332
|
-
} | {
|
|
4333
|
-
readonly stage: 'config';
|
|
4334
|
-
readonly configPath: string;
|
|
4335
|
-
} | {
|
|
4336
|
-
readonly stage: 'prompt';
|
|
4337
|
-
} | {
|
|
4338
|
-
readonly stage: 'default';
|
|
4339
|
-
};
|
|
4353
|
+
interface ResolvedSelectPromptConfig extends PromptConfigBase {
|
|
4354
|
+
/** Discriminant — single-choice selection prompt. */
|
|
4355
|
+
readonly kind: 'select';
|
|
4356
|
+
/** User-facing question text. */
|
|
4357
|
+
readonly message: string;
|
|
4358
|
+
/** Non-empty list of selectable options (populated from flag enum values when omitted). */
|
|
4359
|
+
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
4360
|
+
}
|
|
4340
4361
|
/**
|
|
4341
|
-
*
|
|
4342
|
-
*
|
|
4343
|
-
* An input that resolved no value has no record, so every member is optional in
|
|
4344
|
-
* value even though the key set is the surface's own.
|
|
4362
|
+
* A multiselect prompt config with choices guaranteed non-empty.
|
|
4345
4363
|
*
|
|
4346
|
-
*
|
|
4364
|
+
* Same guarantee as {@linkcode ResolvedSelectPromptConfig} — choices are always
|
|
4365
|
+
* present and non-empty.
|
|
4347
4366
|
*/
|
|
4348
|
-
|
|
4367
|
+
interface ResolvedMultiselectPromptConfig extends PromptConfigBase {
|
|
4368
|
+
/** Discriminant — multiple-choice selection prompt. */
|
|
4369
|
+
readonly kind: 'multiselect';
|
|
4370
|
+
/** User-facing question text. */
|
|
4371
|
+
readonly message: string;
|
|
4372
|
+
/** Non-empty list of selectable options (populated from flag enum values when omitted). */
|
|
4373
|
+
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
4374
|
+
/** Minimum number of selections required (validated after input). */
|
|
4375
|
+
readonly min?: number;
|
|
4376
|
+
/** Maximum number of selections allowed (validated after input). */
|
|
4377
|
+
readonly max?: number;
|
|
4378
|
+
}
|
|
4349
4379
|
/**
|
|
4350
|
-
*
|
|
4351
|
-
*
|
|
4352
|
-
*
|
|
4353
|
-
* same names as `flags` and `args`.
|
|
4380
|
+
* Prompt config variant where select/multiselect choices are guaranteed
|
|
4381
|
+
* present. The prompt engine receives this (not raw {@linkcode PromptConfig}),
|
|
4382
|
+
* so it never needs to merge enum values from `FlagSchema`.
|
|
4354
4383
|
*
|
|
4355
|
-
*
|
|
4356
|
-
* @typeParam A - The command's arg builders.
|
|
4384
|
+
* confirm and input configs pass through unchanged.
|
|
4357
4385
|
*/
|
|
4358
|
-
|
|
4359
|
-
/** Provenance of every declared flag, keyed by flag name. */
|
|
4360
|
-
readonly flags: SourcesOf<F>;
|
|
4361
|
-
/** Provenance of every declared arg, keyed by arg name. */
|
|
4362
|
-
readonly args: SourcesOf<A>;
|
|
4363
|
-
}
|
|
4386
|
+
type ResolvedPromptConfig = ConfirmPromptConfig | InputPromptConfig | PasswordPromptConfig | ResolvedSelectPromptConfig | ResolvedMultiselectPromptConfig;
|
|
4364
4387
|
/**
|
|
4365
|
-
*
|
|
4366
|
-
*
|
|
4367
|
-
* Every stage but `'default'` means the value was supplied: typed on the command
|
|
4368
|
-
* line, piped, exported, written in a config file, or answered at a prompt. An
|
|
4369
|
-
* input that resolved no value at all has no record and is not explicit.
|
|
4388
|
+
* Prompt engine interface.
|
|
4370
4389
|
*
|
|
4371
|
-
*
|
|
4372
|
-
*
|
|
4390
|
+
* Implementations present one prompt per `promptOne()` call and return
|
|
4391
|
+
* the result. Engines may retain state across calls, such as an answer queue.
|
|
4373
4392
|
*
|
|
4374
|
-
*
|
|
4375
|
-
*
|
|
4393
|
+
* The resolution chain calls `promptOne` for each flag that needs
|
|
4394
|
+
* interactive input. Engines do not need schema knowledge — all
|
|
4395
|
+
* relevant context (message, choices, validation) is in the config.
|
|
4376
4396
|
*
|
|
4377
4397
|
* @example
|
|
4378
4398
|
* ```ts
|
|
4379
|
-
*
|
|
4380
|
-
*
|
|
4381
|
-
*
|
|
4382
|
-
*
|
|
4383
|
-
*
|
|
4399
|
+
* // Custom engine (e.g. wrapping @clack/prompts)
|
|
4400
|
+
* const engine: PromptEngine = {
|
|
4401
|
+
* async promptOne(config) {
|
|
4402
|
+
* // ... render with your library
|
|
4403
|
+
* return { answered: true, value: userInput };
|
|
4404
|
+
* }
|
|
4405
|
+
* };
|
|
4384
4406
|
* ```
|
|
4385
4407
|
*/
|
|
4386
|
-
|
|
4408
|
+
interface PromptEngine {
|
|
4409
|
+
/**
|
|
4410
|
+
* Present a single prompt and return the user's response.
|
|
4411
|
+
*
|
|
4412
|
+
* @param config - The resolved prompt configuration (choices guaranteed
|
|
4413
|
+
* for select/multiselect).
|
|
4414
|
+
* @returns The user's answer, `{ answered: false }` if cancelled, or
|
|
4415
|
+
* `{ answered: false, reason: 'invalid' }` when invalid attempts are exhausted.
|
|
4416
|
+
*/
|
|
4417
|
+
promptOne(config: ResolvedPromptConfig): Promise<PromptResult>;
|
|
4418
|
+
}
|
|
4387
4419
|
/**
|
|
4388
|
-
*
|
|
4389
|
-
*
|
|
4390
|
-
* The default `C = Record<string, never>` uses an index signature where
|
|
4391
|
-
* every key maps to `never` — making property access a type error until
|
|
4392
|
-
* middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
|
|
4393
|
-
* collapses all properties to `never` because `never & T = never`.
|
|
4420
|
+
* A function that reads a single line of user input.
|
|
4394
4421
|
*
|
|
4395
|
-
*
|
|
4396
|
-
*
|
|
4397
|
-
*/
|
|
4398
|
-
type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
|
|
4399
|
-
/**
|
|
4400
|
-
* Widen the context type when adding command-scoped derived context.
|
|
4422
|
+
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
4423
|
+
* indicating the user closed the input stream (treated as cancel).
|
|
4401
4424
|
*
|
|
4402
|
-
*
|
|
4403
|
-
*
|
|
4404
|
-
*
|
|
4425
|
+
* The terminal prompter uses this as its sole input seam. The
|
|
4426
|
+
* resolution chain (prompt-adapter-1) will wire this to the
|
|
4427
|
+
* runtime adapter's stdin.
|
|
4405
4428
|
*/
|
|
4406
|
-
type
|
|
4429
|
+
type ReadFn = () => Promise<string | null>;
|
|
4407
4430
|
/**
|
|
4408
|
-
*
|
|
4431
|
+
* Prepare a {@linkcode ResolvedPromptConfig} from a raw {@linkcode PromptConfig} and optional
|
|
4432
|
+
* enum values from the flag schema.
|
|
4409
4433
|
*
|
|
4410
|
-
*
|
|
4411
|
-
*
|
|
4412
|
-
*
|
|
4413
|
-
*/
|
|
4414
|
-
interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
|
|
4415
|
-
/** Partially resolved flag values (after CLI/env/config, before prompts). */
|
|
4416
|
-
readonly flags: Readonly<Partial<InferFlags<F>>>;
|
|
4417
|
-
}
|
|
4418
|
-
/**
|
|
4419
|
-
* A record mapping flag names to prompt configs or falsy values.
|
|
4434
|
+
* For select/multiselect prompts without explicit choices, this merges
|
|
4435
|
+
* the flag's enum values into the choices list. Throws if no choices
|
|
4436
|
+
* are available.
|
|
4420
4437
|
*
|
|
4421
|
-
*
|
|
4422
|
-
*
|
|
4438
|
+
* This function is called by the resolution chain (prompt-resolve-1),
|
|
4439
|
+
* not by the engine itself — keeping the engine free of schema knowledge.
|
|
4423
4440
|
*
|
|
4424
|
-
*
|
|
4425
|
-
*
|
|
4441
|
+
* @param config - Raw prompt config from `FlagSchema.prompt`
|
|
4442
|
+
* @param enumValues - Optional enum values from `FlagSchema.enumValues`
|
|
4443
|
+
* @returns Resolved config with choices guaranteed for select kinds
|
|
4444
|
+
* @throws Error if select/multiselect has no choices and no enum values
|
|
4426
4445
|
*/
|
|
4427
|
-
|
|
4446
|
+
declare function resolvePromptConfig(config: PromptConfig, enumValues: readonly string[] | undefined): ResolvedPromptConfig;
|
|
4428
4447
|
/**
|
|
4429
|
-
*
|
|
4448
|
+
* Runtime adapter interface.
|
|
4430
4449
|
*
|
|
4431
|
-
*
|
|
4432
|
-
*
|
|
4433
|
-
*
|
|
4434
|
-
*
|
|
4450
|
+
* Defines the minimal contract between the platform-agnostic core and
|
|
4451
|
+
* the host runtime (Node.js, Bun, Deno). Every platform-dependent
|
|
4452
|
+
* operation flows through this interface — the core never calls
|
|
4453
|
+
* `process.*`, `Deno.*`, or `Bun.*` directly.
|
|
4454
|
+
*
|
|
4455
|
+
* Adapters are designed to be:
|
|
4456
|
+
* - **Immutable in shape:** all properties are readonly
|
|
4457
|
+
* - **Minimal:** only the operations the framework actually needs
|
|
4458
|
+
* - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
|
|
4435
4459
|
*
|
|
4436
4460
|
* @example
|
|
4437
4461
|
* ```ts
|
|
4438
|
-
*
|
|
4462
|
+
* // Production: auto-detected
|
|
4463
|
+
* cli('mycli').run(); // uses Node/Bun/Deno adapter
|
|
4439
4464
|
*
|
|
4440
|
-
*
|
|
4441
|
-
*
|
|
4442
|
-
* .interactive(({ flags }) => ({
|
|
4443
|
-
* region: !flags.region && {
|
|
4444
|
-
* kind: 'select',
|
|
4445
|
-
* message: 'Select region',
|
|
4446
|
-
* },
|
|
4447
|
-
* }))
|
|
4448
|
-
* .action(({ flags, out }) => {
|
|
4449
|
-
* out.log(`Deploying to ${flags.region}`);
|
|
4450
|
-
* });
|
|
4465
|
+
* // Test: explicit adapter
|
|
4466
|
+
* cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
|
|
4451
4467
|
* ```
|
|
4452
4468
|
*/
|
|
4453
|
-
|
|
4454
|
-
/**
|
|
4455
|
-
|
|
4456
|
-
*
|
|
4457
|
-
* Advanced bridge type: most consumers should use {@link InteractiveResolver}
|
|
4458
|
-
* via {@linkcode command | command().interactive()} and never reference this alias directly.
|
|
4459
|
-
*
|
|
4460
|
-
* At runtime, the resolver receives `{ flags: Record<string, unknown> }`
|
|
4461
|
-
* and returns `Record<string, PromptConfig | falsy>`. The phantom types
|
|
4462
|
-
* from `CommandBuilder<F, A>` are erased.
|
|
4463
|
-
*/
|
|
4464
|
-
type ErasedInteractiveResolver = (params: {
|
|
4465
|
-
readonly flags: Readonly<Record<string, unknown>>;
|
|
4466
|
-
}) => InteractiveResult;
|
|
4467
|
-
/**
|
|
4468
|
-
* Seals {@linkcode Out} against structural construction outside the framework.
|
|
4469
|
-
*
|
|
4470
|
-
* @internal
|
|
4471
|
-
*/
|
|
4472
|
-
declare const outBrand: unique symbol;
|
|
4473
|
-
/**
|
|
4474
|
-
* Output channel available inside action handlers.
|
|
4475
|
-
*
|
|
4476
|
-
* Provides structured methods for stdout/stderr, JSON output,
|
|
4477
|
-
* spinners, progress bars, and tables. The real implementation lives in
|
|
4478
|
-
* `src/core/output/`; this interface defines the shape that handlers consume.
|
|
4479
|
-
*
|
|
4480
|
-
* `Out` is a framework-created, non-exhaustive value: obtain instances from
|
|
4481
|
-
* action parameters, `createOutput()`, or `createCaptureOutput()` — do not
|
|
4482
|
-
* implement it. New readonly members may be added in minor releases.
|
|
4483
|
-
*/
|
|
4484
|
-
interface Out {
|
|
4485
|
-
/** Framework-construction seal. Obtain `Out` values from DreamCLI; do not implement this interface. */
|
|
4486
|
-
readonly [outBrand]: never;
|
|
4487
|
-
/** Write to stdout (normal output). */
|
|
4488
|
-
log(message: string): void;
|
|
4489
|
-
/** Informational (may be suppressed in quiet mode). */
|
|
4490
|
-
info(message: string): void;
|
|
4469
|
+
interface RuntimeAdapter {
|
|
4470
|
+
/** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
|
|
4471
|
+
readonly argv: readonly string[];
|
|
4491
4472
|
/**
|
|
4492
|
-
*
|
|
4493
|
-
*
|
|
4494
|
-
* Keeps stdout clean for piping; for success and progress notes like
|
|
4495
|
-
* `Wrote <path>` that scripts silence with `--quiet`.
|
|
4473
|
+
* Environment variables.
|
|
4474
|
+
* Values are `string | undefined` — mirrors Node's `process.env` semantics.
|
|
4496
4475
|
*/
|
|
4497
|
-
|
|
4498
|
-
/**
|
|
4499
|
-
|
|
4500
|
-
/**
|
|
4501
|
-
|
|
4476
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
4477
|
+
/** Current working directory (absolute path). */
|
|
4478
|
+
readonly cwd: string;
|
|
4479
|
+
/** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
|
|
4480
|
+
readonly stdout: WriteFn;
|
|
4481
|
+
/** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
|
|
4482
|
+
readonly stderr: WriteFn;
|
|
4483
|
+
/** Wait for pending output writes to settle, rejecting with a recorded output failure. */
|
|
4484
|
+
readonly flush?: () => Promise<void>;
|
|
4502
4485
|
/**
|
|
4503
|
-
*
|
|
4486
|
+
* Line reader for stdin. Used by the prompt engine for interactive input.
|
|
4504
4487
|
*
|
|
4505
|
-
*
|
|
4506
|
-
*
|
|
4507
|
-
* later calls overwrite earlier calls, and thrown errors still win.
|
|
4488
|
+
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
4489
|
+
* indicating the user closed the input stream (treated as cancel).
|
|
4508
4490
|
*/
|
|
4509
|
-
|
|
4491
|
+
readonly stdin: ReadFn;
|
|
4492
|
+
/** Hidden terminal input. Absent when echo suppression is unsupported. */
|
|
4493
|
+
readonly readSecret?: ReadFn;
|
|
4510
4494
|
/**
|
|
4511
|
-
*
|
|
4495
|
+
* Read all of stdin as a single string (for piped data).
|
|
4512
4496
|
*
|
|
4513
|
-
*
|
|
4514
|
-
*
|
|
4515
|
-
*
|
|
4516
|
-
*
|
|
4497
|
+
* Returns the full stdin contents when data is piped (`stdinIsTTY` is
|
|
4498
|
+
* false), or `null` when stdin is a TTY (no piped data available).
|
|
4499
|
+
*
|
|
4500
|
+
* Used by the resolve chain for args with `.stdin()` configured.
|
|
4501
|
+
* Unlike {@link stdin} (which reads one line for prompts), this
|
|
4502
|
+
* consumes the entire stream to EOF.
|
|
4503
|
+
*
|
|
4504
|
+
* @returns Full stdin contents as a string, or `null` if stdin is a TTY.
|
|
4517
4505
|
*/
|
|
4518
|
-
|
|
4506
|
+
readonly readStdin: () => Promise<string | null>;
|
|
4507
|
+
/** Whether stdout is connected to a TTY. */
|
|
4508
|
+
readonly isTTY: boolean;
|
|
4509
|
+
/** Whether stdin is connected to a TTY (used for prompt gating). */
|
|
4510
|
+
readonly stdinIsTTY: boolean;
|
|
4511
|
+
/** Read current terminal dimensions for stdout, if available. */
|
|
4512
|
+
readonly getTerminalSize: () => TerminalSize | undefined;
|
|
4513
|
+
/** Subscribe to terminal resize events when the runtime supports them. */
|
|
4514
|
+
readonly onTerminalResize: (listener: () => void) => (() => void) | undefined;
|
|
4519
4515
|
/**
|
|
4520
|
-
*
|
|
4521
|
-
*
|
|
4522
|
-
* Handlers can check this to skip decorative output (spinners,
|
|
4523
|
-
* progress bars, ANSI formatting) when machine-readable output is
|
|
4524
|
-
* expected.
|
|
4516
|
+
* Exit the process with the given code.
|
|
4517
|
+
* Must not return (divergent function).
|
|
4525
4518
|
*/
|
|
4526
|
-
readonly
|
|
4519
|
+
readonly exit: (code: number) => never;
|
|
4527
4520
|
/**
|
|
4528
|
-
*
|
|
4521
|
+
* Read a file as UTF-8 text.
|
|
4529
4522
|
*
|
|
4530
|
-
*
|
|
4531
|
-
*
|
|
4532
|
-
*
|
|
4533
|
-
*
|
|
4534
|
-
*
|
|
4535
|
-
*
|
|
4523
|
+
* Returns file contents on success, `null` if the file does not exist
|
|
4524
|
+
* (ENOENT/NotFound). Throws on other I/O errors (permission denied,
|
|
4525
|
+
* is-directory, etc.) — those indicate unexpected failures, not
|
|
4526
|
+
* "try the next path".
|
|
4527
|
+
*
|
|
4528
|
+
* Used by config file discovery to probe multiple candidate paths.
|
|
4536
4529
|
*/
|
|
4537
|
-
readonly
|
|
4530
|
+
readonly readFile: (path: string) => Promise<string | null>;
|
|
4531
|
+
/** Import a local executable config and return its default export. */
|
|
4532
|
+
readonly importConfigModule?: (path: string) => Promise<unknown>;
|
|
4538
4533
|
/**
|
|
4539
|
-
*
|
|
4534
|
+
* Probe what exists at a filesystem path.
|
|
4540
4535
|
*
|
|
4541
|
-
*
|
|
4542
|
-
*
|
|
4543
|
-
* is being piped or redirected — skip interactive decorations.
|
|
4536
|
+
* Returns `'file'` or `'directory'` for existing paths (other kinds such
|
|
4537
|
+
* as sockets report `'file'`), or `null` when nothing exists there.
|
|
4544
4538
|
*
|
|
4545
|
-
*
|
|
4546
|
-
* decorative output should be suppressed regardless of `isTTY`.
|
|
4539
|
+
* Used by `flag.path()` existence/type checks after resolution.
|
|
4547
4540
|
*/
|
|
4548
|
-
readonly
|
|
4541
|
+
readonly stat: (path: string) => Promise<'file' | 'directory' | null>;
|
|
4549
4542
|
/**
|
|
4550
|
-
*
|
|
4543
|
+
* Create a directory, including missing parents.
|
|
4551
4544
|
*
|
|
4552
|
-
*
|
|
4553
|
-
*
|
|
4554
|
-
* `--color`, `CI` are respected). When disabled, every formatter is an
|
|
4555
|
-
* identity function — `out.color.red('x')` returns `'x'` — so handlers can
|
|
4556
|
-
* style unconditionally without gating on `isTTY`/`jsonMode` themselves.
|
|
4545
|
+
* Succeeds when the directory already exists. Throws on other I/O errors
|
|
4546
|
+
* (permission denied, existing file at the path, etc.).
|
|
4557
4547
|
*
|
|
4558
|
-
*
|
|
4559
|
-
* ```ts
|
|
4560
|
-
* .action(({ out }) => {
|
|
4561
|
-
* out.log(`${out.color.green('✔')} deployed ${out.color.bold('api')}`);
|
|
4562
|
-
* });
|
|
4563
|
-
* ```
|
|
4548
|
+
* Used by `flag.path()` `create` checks after resolution.
|
|
4564
4549
|
*/
|
|
4565
|
-
readonly
|
|
4550
|
+
readonly mkdir: (path: string) => Promise<void>;
|
|
4566
4551
|
/**
|
|
4567
|
-
*
|
|
4552
|
+
* User home directory (absolute path).
|
|
4568
4553
|
*
|
|
4569
|
-
*
|
|
4570
|
-
*
|
|
4571
|
-
* Handlers rendering their own `out.color.link(...)` output can gate on
|
|
4572
|
-
* this to keep OSC 8 escapes out of piped or opted-out contexts.
|
|
4554
|
+
* - Node/Bun: derived from `HOME` / `USERPROFILE` env
|
|
4555
|
+
* - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
|
|
4573
4556
|
*/
|
|
4574
|
-
readonly
|
|
4557
|
+
readonly homedir: string;
|
|
4575
4558
|
/**
|
|
4576
|
-
*
|
|
4577
|
-
*
|
|
4578
|
-
* - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
|
|
4579
|
-
* - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
|
|
4580
|
-
* - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
|
|
4581
|
-
* (useful for `grep`, `awk`, etc.).
|
|
4582
|
-
* - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
|
|
4583
|
-
* side channel while `json()` writes machine output to stdout.
|
|
4584
|
-
*
|
|
4585
|
-
* When `columns` is omitted, columns are auto-inferred from the keys
|
|
4586
|
-
* of the first row. Column headers default to the key name.
|
|
4559
|
+
* Platform-specific user configuration directory (absolute path).
|
|
4587
4560
|
*
|
|
4588
|
-
*
|
|
4589
|
-
*
|
|
4561
|
+
* - Unix: `$XDG_CONFIG_HOME` or `~/.config`
|
|
4562
|
+
* - Windows: `%APPDATA%` or `~\AppData\Roaming`
|
|
4590
4563
|
*
|
|
4591
|
-
*
|
|
4564
|
+
* Config discovery appends the app-specific subdirectory.
|
|
4592
4565
|
*/
|
|
4593
|
-
|
|
4566
|
+
readonly configDir: string;
|
|
4594
4567
|
/**
|
|
4595
|
-
*
|
|
4568
|
+
* User-scope config roots for discovery, highest priority first.
|
|
4596
4569
|
*
|
|
4597
|
-
*
|
|
4598
|
-
*
|
|
4599
|
-
*
|
|
4570
|
+
* - Unix: `[configDir]`
|
|
4571
|
+
* - macOS: `[configDir, ~/Library/Application Support]`
|
|
4572
|
+
* - Windows: `[configDir]`
|
|
4573
|
+
*
|
|
4574
|
+
* When absent, discovery falls back to `[configDir]`.
|
|
4600
4575
|
*/
|
|
4601
|
-
|
|
4576
|
+
readonly userConfigDirs?: readonly string[];
|
|
4602
4577
|
/**
|
|
4603
|
-
*
|
|
4604
|
-
*
|
|
4605
|
-
* Returns a no-op handle in quiet or JSON mode. Otherwise, non-TTY output
|
|
4606
|
-
* uses a no-op handle or the configured static fallback.
|
|
4607
|
-
*
|
|
4608
|
-
* @param text - Initial spinner text.
|
|
4609
|
-
* @param options - Fallback strategy for non-TTY environments.
|
|
4610
|
-
* @returns A {@link SpinnerHandle} for lifecycle control.
|
|
4578
|
+
* System-scope config roots for discovery (`['/etc']` on Linux and
|
|
4579
|
+
* macOS, `[]` on Windows). When absent, discovery probes none.
|
|
4611
4580
|
*/
|
|
4612
|
-
|
|
4581
|
+
readonly systemConfigDirs?: readonly string[];
|
|
4582
|
+
}
|
|
4583
|
+
/** Current terminal dimensions in columns and rows. */
|
|
4584
|
+
interface TerminalSize {
|
|
4585
|
+
/** Terminal width in columns. */
|
|
4586
|
+
readonly columns: number;
|
|
4587
|
+
/** Terminal height in rows. */
|
|
4588
|
+
readonly rows: number;
|
|
4589
|
+
}
|
|
4590
|
+
/**
|
|
4591
|
+
* Options for creating a test adapter.
|
|
4592
|
+
*
|
|
4593
|
+
* All fields are optional — sensible defaults are applied for testing
|
|
4594
|
+
* scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
|
|
4595
|
+
* throws instead of killing the process).
|
|
4596
|
+
*/
|
|
4597
|
+
interface TestAdapterOptions {
|
|
4598
|
+
/** Raw argv (defaults to `['node', 'test']`). */
|
|
4599
|
+
readonly argv?: readonly string[];
|
|
4600
|
+
/** Environment variables (defaults to `{}`). */
|
|
4601
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
4602
|
+
/** Working directory (defaults to `'/test'`). */
|
|
4603
|
+
readonly cwd?: string;
|
|
4604
|
+
/** Stdout writer (defaults to noop). */
|
|
4605
|
+
readonly stdout?: WriteFn;
|
|
4606
|
+
/** Stderr writer (defaults to noop). */
|
|
4607
|
+
readonly stderr?: WriteFn;
|
|
4613
4608
|
/**
|
|
4614
|
-
*
|
|
4615
|
-
*
|
|
4616
|
-
* Returns a no-op handle in quiet or JSON mode. Otherwise, pass `total` for
|
|
4617
|
-
* determinate mode (percentage bar); omit for indeterminate (pulsing).
|
|
4609
|
+
* Stdin line reader (defaults to returning `null` — immediate EOF).
|
|
4618
4610
|
*
|
|
4619
|
-
* @
|
|
4620
|
-
* @returns A {@link ProgressHandle} for updating progress.
|
|
4611
|
+
* Use a custom {@linkcode ReadFn} to simulate user input in tests.
|
|
4621
4612
|
*/
|
|
4622
|
-
|
|
4613
|
+
readonly stdin?: ReadFn;
|
|
4614
|
+
/** Hidden reader stub; omitted adapters report unsupported hidden input. */
|
|
4615
|
+
readonly readSecret?: ReadFn;
|
|
4623
4616
|
/**
|
|
4624
|
-
*
|
|
4625
|
-
*
|
|
4626
|
-
* TTY spinner and progress handles start `setInterval` timers that
|
|
4627
|
-
* prevent the process from exiting until a terminal method (`stop`,
|
|
4628
|
-
* `succeed`, `fail`, `done`) is called. If a handler throws before
|
|
4629
|
-
* reaching that call, the timer leaks and the process hangs.
|
|
4630
|
-
*
|
|
4631
|
-
* Call `stopActive()` in a `finally` block after handler execution
|
|
4632
|
-
* to guarantee cleanup. It is idempotent — safe to call when no
|
|
4633
|
-
* handle is active, or when the handle was already stopped.
|
|
4617
|
+
* Piped stdin data for testing args with `.stdin()` configured.
|
|
4634
4618
|
*
|
|
4635
|
-
*
|
|
4636
|
-
*
|
|
4637
|
-
*
|
|
4619
|
+
* When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
|
|
4620
|
+
* string once, then `null` on subsequent reads. When absent, or when
|
|
4621
|
+
* `stdinIsTTY` is `true`, `readStdin()` returns `null`.
|
|
4638
4622
|
*
|
|
4639
4623
|
* @example
|
|
4640
4624
|
* ```ts
|
|
4641
|
-
*
|
|
4642
|
-
*
|
|
4643
|
-
*
|
|
4644
|
-
* } finally {
|
|
4645
|
-
* out.stopActive();
|
|
4646
|
-
* }
|
|
4625
|
+
* createTestAdapter({
|
|
4626
|
+
* stdinData: '{"key": "value"}',
|
|
4627
|
+
* })
|
|
4647
4628
|
* ```
|
|
4648
4629
|
*/
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
readonly
|
|
4663
|
-
/**
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4630
|
+
readonly stdinData?: string;
|
|
4631
|
+
/** TTY flag for stdout (defaults to `false`). */
|
|
4632
|
+
readonly isTTY?: boolean;
|
|
4633
|
+
/** TTY flag for stdin (defaults to `false`). */
|
|
4634
|
+
readonly stdinIsTTY?: boolean;
|
|
4635
|
+
/** Terminal dimensions returned by `getTerminalSize()`. */
|
|
4636
|
+
readonly terminalSize?: TerminalSize;
|
|
4637
|
+
/** Resize subscription hook returned by `onTerminalResize()`. */
|
|
4638
|
+
readonly onTerminalResize?: (listener: () => void) => (() => void) | undefined;
|
|
4639
|
+
/**
|
|
4640
|
+
* Exit function (defaults to throwing {@linkcode ExitError}).
|
|
4641
|
+
* The default throw-based exit allows tests to catch the exit code.
|
|
4642
|
+
*/
|
|
4643
|
+
readonly exit?: (code: number) => never;
|
|
4644
|
+
/**
|
|
4645
|
+
* File reader stub (defaults to returning `null` — all files not found).
|
|
4646
|
+
*
|
|
4647
|
+
* Supply a custom function to simulate a virtual filesystem in tests:
|
|
4648
|
+
* ```ts
|
|
4649
|
+
* createTestAdapter({
|
|
4650
|
+
* readFile: (path) => Promise.resolve(
|
|
4651
|
+
* path === '/home/test/.config/myapp/config.json'
|
|
4652
|
+
* ? '{"region":"eu"}'
|
|
4653
|
+
* : null
|
|
4654
|
+
* ),
|
|
4655
|
+
* })
|
|
4656
|
+
* ```
|
|
4657
|
+
*/
|
|
4658
|
+
readonly readFile?: (path: string) => Promise<string | null>;
|
|
4659
|
+
/** Optional executable-config loader for a virtual filesystem. */
|
|
4660
|
+
readonly importConfigModule?: RuntimeAdapter['importConfigModule'];
|
|
4661
|
+
/**
|
|
4662
|
+
* Filesystem probe stub for `flag.path()` checks (defaults to returning
|
|
4663
|
+
* `null` — nothing exists).
|
|
4664
|
+
*
|
|
4665
|
+
* Supply a custom function to simulate a virtual filesystem in tests:
|
|
4666
|
+
* ```ts
|
|
4667
|
+
* createTestAdapter({
|
|
4668
|
+
* stat: (path) => Promise.resolve(path === '/data' ? 'directory' : null),
|
|
4669
|
+
* })
|
|
4670
|
+
* ```
|
|
4671
|
+
*/
|
|
4672
|
+
readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
|
|
4673
|
+
/**
|
|
4674
|
+
* Directory creation stub for `flag.path()` `create` checks (defaults to
|
|
4675
|
+
* a noop that resolves without creating anything).
|
|
4676
|
+
*/
|
|
4677
|
+
readonly mkdir?: (path: string) => Promise<void>;
|
|
4678
|
+
/** Home directory (defaults to `'/home/test'`). */
|
|
4679
|
+
readonly homedir?: string;
|
|
4680
|
+
/** Config directory (defaults to `'/home/test/.config'`). */
|
|
4681
|
+
readonly configDir?: string;
|
|
4682
|
+
/** User-scope config roots for discovery (defaults to `[configDir]`). */
|
|
4683
|
+
readonly userConfigDirs?: readonly string[];
|
|
4684
|
+
/** System-scope config roots for discovery (defaults to `[]`). */
|
|
4685
|
+
readonly systemConfigDirs?: readonly string[];
|
|
4669
4686
|
}
|
|
4670
4687
|
/**
|
|
4671
|
-
*
|
|
4688
|
+
* Error thrown by adapter implementations that model process exit as an
|
|
4689
|
+
* exception instead of terminating immediately.
|
|
4672
4690
|
*
|
|
4673
|
-
*
|
|
4674
|
-
*
|
|
4675
|
-
*
|
|
4676
|
-
* - `ctx`: derive/middleware-provided context
|
|
4677
|
-
* - `out`: output channel
|
|
4678
|
-
* - `meta`: CLI program metadata (name, bin, version, command)
|
|
4691
|
+
* Runtime and CLI dispatch layers can catch this to perform real process
|
|
4692
|
+
* termination, while tests can assert on exit codes without killing the
|
|
4693
|
+
* runner:
|
|
4679
4694
|
*
|
|
4680
|
-
*
|
|
4681
|
-
*
|
|
4695
|
+
* ```ts
|
|
4696
|
+
* try {
|
|
4697
|
+
* await cli.run({ adapter: createTestAdapter() });
|
|
4698
|
+
* } catch (e) {
|
|
4699
|
+
* if (e instanceof ExitError) expect(e.code).toBe(0);
|
|
4700
|
+
* }
|
|
4701
|
+
* ```
|
|
4682
4702
|
*/
|
|
4683
|
-
|
|
4684
|
-
/**
|
|
4685
|
-
readonly
|
|
4686
|
-
/**
|
|
4687
|
-
readonly
|
|
4688
|
-
/**
|
|
4689
|
-
|
|
4690
|
-
*
|
|
4691
|
-
* An input that resolved no value has no record. {@link wasExplicit} answers
|
|
4692
|
-
* the explicit-versus-defaulted question; read `stage` for the rest.
|
|
4693
|
-
*/
|
|
4694
|
-
readonly sources: InputSources<F, A>;
|
|
4695
|
-
/** Middleware/derive-provided context, typed from `.middleware()` and `.derive()` chains. */
|
|
4696
|
-
readonly ctx: Readonly<C>;
|
|
4697
|
-
/** Structured output channel for stdout, stderr, JSON, tables, and spinners. */
|
|
4698
|
-
readonly out: Out;
|
|
4699
|
-
/** Ask a typed question after selecting the operation or receiving a server challenge. */
|
|
4700
|
-
readonly ask: Ask;
|
|
4701
|
-
/** Runtime metadata about the CLI program and current command. */
|
|
4702
|
-
readonly meta: CommandMeta;
|
|
4703
|
+
declare class ExitError extends Error {
|
|
4704
|
+
/** Error name — always `'ExitError'` for `instanceof` checks. */
|
|
4705
|
+
readonly name = "ExitError";
|
|
4706
|
+
/** The exit code passed to `exit()`. */
|
|
4707
|
+
readonly code: number;
|
|
4708
|
+
/** Create an ExitError for the given process exit code. */
|
|
4709
|
+
constructor(code: number);
|
|
4703
4710
|
}
|
|
4704
4711
|
/**
|
|
4705
|
-
*
|
|
4712
|
+
* Create a test runtime adapter with injectable process state.
|
|
4706
4713
|
*
|
|
4707
|
-
*
|
|
4708
|
-
*
|
|
4709
|
-
*
|
|
4714
|
+
* Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
|
|
4715
|
+
* environment variables, TTY state, stdin, or config-file reads without
|
|
4716
|
+
* touching the host process.
|
|
4717
|
+
*
|
|
4718
|
+
* @param options - Optional overrides for any adapter field.
|
|
4719
|
+
* @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
|
|
4720
|
+
*
|
|
4721
|
+
* @example
|
|
4722
|
+
* ```ts
|
|
4723
|
+
* const adapter = createTestAdapter({
|
|
4724
|
+
* argv: ['node', 'cli.js', 'deploy', '--force'],
|
|
4725
|
+
* env: { DEPLOY_REGION: 'us' },
|
|
4726
|
+
* });
|
|
4727
|
+
*
|
|
4728
|
+
* const result = await cli('mycli').run({ adapter });
|
|
4729
|
+
* ```
|
|
4710
4730
|
*/
|
|
4711
|
-
|
|
4731
|
+
declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
|
|
4732
|
+
/** A canonical reference to one declared flag or positional argument. */
|
|
4733
|
+
type ConstraintInput = {
|
|
4734
|
+
readonly kind: 'flag' | 'arg';
|
|
4735
|
+
readonly name: string;
|
|
4736
|
+
};
|
|
4737
|
+
/** A declarative relationship between two or more command inputs. */
|
|
4738
|
+
type CommandConstraint = {
|
|
4739
|
+
readonly kind: 'conflicts' | 'requires';
|
|
4740
|
+
readonly inputs: readonly [ConstraintInput, ConstraintInput];
|
|
4741
|
+
} | {
|
|
4742
|
+
readonly kind: 'exactlyOne' | 'atMostOne' | 'allOrNone';
|
|
4743
|
+
readonly inputs: readonly [ConstraintInput, ConstraintInput, ...ConstraintInput[]];
|
|
4744
|
+
};
|
|
4745
|
+
type InputName<F extends string, A extends string> = F | A | {
|
|
4746
|
+
readonly kind: 'flag';
|
|
4747
|
+
readonly name: F;
|
|
4748
|
+
} | {
|
|
4749
|
+
readonly kind: 'arg';
|
|
4750
|
+
readonly name: A;
|
|
4751
|
+
};
|
|
4752
|
+
/** Build relationships using the names declared on a command. */
|
|
4753
|
+
interface ConstraintBuilder<F extends string, A extends string> {
|
|
4754
|
+
/** Reference a flag explicitly when a positional argument has the same name. */
|
|
4755
|
+
flag<N extends F>(name: N): {
|
|
4756
|
+
readonly kind: 'flag';
|
|
4757
|
+
readonly name: N;
|
|
4758
|
+
};
|
|
4759
|
+
/** Reference a positional argument explicitly. */
|
|
4760
|
+
arg<N extends A>(name: N): {
|
|
4761
|
+
readonly kind: 'arg';
|
|
4762
|
+
readonly name: N;
|
|
4763
|
+
};
|
|
4764
|
+
/** Disallow supplying both inputs. */
|
|
4765
|
+
conflicts(left: InputName<F, A>, right: InputName<F, A>): CommandConstraint;
|
|
4766
|
+
/** Require the second input when the first is supplied. */
|
|
4767
|
+
requires(input: InputName<F, A>, dependency: InputName<F, A>): CommandConstraint;
|
|
4768
|
+
/** Require exactly one of the inputs. */
|
|
4769
|
+
exactlyOne(...inputs: [InputName<F, A>, InputName<F, A>, ...InputName<F, A>[]]): CommandConstraint;
|
|
4770
|
+
/** Allow at most one of the inputs. */
|
|
4771
|
+
atMostOne(...inputs: [InputName<F, A>, InputName<F, A>, ...InputName<F, A>[]]): CommandConstraint;
|
|
4772
|
+
/** Require every member when any member is supplied. */
|
|
4773
|
+
allOrNone(...inputs: [InputName<F, A>, InputName<F, A>, ...InputName<F, A>[]]): CommandConstraint;
|
|
4774
|
+
}
|
|
4775
|
+
/** Select the object passed to a command-level Standard Schema validator. */
|
|
4776
|
+
interface CommandValidationOptions {
|
|
4777
|
+
/** Validate the flags object, or validate an object containing flags, args, and sources. */
|
|
4778
|
+
readonly input?: 'flags' | 'resolved';
|
|
4779
|
+
}
|
|
4780
|
+
/** Registered validator and its input selection. @internal */
|
|
4781
|
+
interface CommandValidator {
|
|
4782
|
+
readonly schema: StandardSchemaV1;
|
|
4783
|
+
readonly input: NonNullable<CommandValidationOptions['input']>;
|
|
4784
|
+
}
|
|
4712
4785
|
/**
|
|
4713
|
-
*
|
|
4714
|
-
*
|
|
4715
|
-
* The typed {@linkcode ActionHandler} from `.action()` is cast to this
|
|
4716
|
-
* erased form at the type-erasure boundary, keeping {@linkcode CommandBuilder}
|
|
4717
|
-
* covariant in its generic parameters. This enables structural
|
|
4718
|
-
* compatibility across TypeScript declaration-file boundaries where
|
|
4719
|
-
* generic inference may fall back to constraint types.
|
|
4786
|
+
* Parameters received by a middleware function at runtime.
|
|
4720
4787
|
*
|
|
4721
|
-
*
|
|
4722
|
-
*
|
|
4788
|
+
* Middleware receives erased args, flags, and provenance (since it's defined
|
|
4789
|
+
* independently of commands) plus the accumulated context from prior middleware
|
|
4790
|
+
* and a `next` function to continue the chain.
|
|
4723
4791
|
*/
|
|
4724
|
-
|
|
4792
|
+
interface MiddlewareParams {
|
|
4793
|
+
/** Fully resolved positional arguments (type-erased). */
|
|
4725
4794
|
readonly args: Readonly<Record<string, unknown>>;
|
|
4795
|
+
/** Fully resolved flags (type-erased). */
|
|
4726
4796
|
readonly flags: Readonly<Record<string, unknown>>;
|
|
4797
|
+
/**
|
|
4798
|
+
* Where each resolved value came from, keyed like `flags` and `args`.
|
|
4799
|
+
*
|
|
4800
|
+
* Erased alongside them, so any key reads as `ResolutionProvenance |
|
|
4801
|
+
* undefined`. A key the bound command never declared, and one an input
|
|
4802
|
+
* resolved no value for, both read `undefined`.
|
|
4803
|
+
*/
|
|
4727
4804
|
readonly sources: ErasedInputSources;
|
|
4805
|
+
/** Context accumulated from previous middleware in the chain. */
|
|
4728
4806
|
readonly ctx: Readonly<Record<string, unknown>>;
|
|
4807
|
+
/** Output channel. */
|
|
4729
4808
|
readonly out: Out;
|
|
4730
|
-
/**
|
|
4809
|
+
/** Invocation-scoped interactive questions. */
|
|
4731
4810
|
readonly ask: Ask;
|
|
4811
|
+
/** CLI program metadata (name, bin, version, command). */
|
|
4732
4812
|
readonly meta: CommandMeta;
|
|
4733
|
-
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
4737
|
-
|
|
4738
|
-
|
|
4813
|
+
/**
|
|
4814
|
+
* Continue to the next middleware or action handler.
|
|
4815
|
+
*
|
|
4816
|
+
* Call with context additions that merge into `ctx` for downstream.
|
|
4817
|
+
* Returns when the entire downstream chain completes — enabling
|
|
4818
|
+
* wrap-around patterns (timing, try/catch, cleanup).
|
|
4819
|
+
*/
|
|
4820
|
+
readonly next: (additions: Record<string, unknown>) => Promise<void>;
|
|
4821
|
+
}
|
|
4739
4822
|
/**
|
|
4740
|
-
*
|
|
4823
|
+
* Type-erased middleware handler stored on the command builder.
|
|
4741
4824
|
*
|
|
4742
|
-
*
|
|
4743
|
-
*
|
|
4744
|
-
* context plus `out` and `meta`.
|
|
4825
|
+
* At runtime, all middleware handlers have this signature. The phantom
|
|
4826
|
+
* `Output` type on {@linkcode Middleware} is erased.
|
|
4745
4827
|
*/
|
|
4746
|
-
type
|
|
4828
|
+
type ErasedMiddlewareHandler = (params: MiddlewareParams) => void | Promise<void>;
|
|
4747
4829
|
/**
|
|
4748
|
-
*
|
|
4749
|
-
*
|
|
4750
|
-
* Derive handlers may:
|
|
4751
|
-
* - validate resolved input and throw {@linkcode CLIError}
|
|
4752
|
-
* - return nothing (or `undefined`) to continue without changing context
|
|
4753
|
-
* - return an object whose properties merge into `ctx` downstream
|
|
4830
|
+
* Middleware handler function with typed `next()` parameter.
|
|
4754
4831
|
*
|
|
4755
|
-
*
|
|
4756
|
-
*
|
|
4757
|
-
*/
|
|
4758
|
-
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> | void | Promise<void>;
|
|
4759
|
-
/**
|
|
4760
|
-
* Type-erased derive handler stored on the command builder.
|
|
4832
|
+
* The `Output` generic constrains what properties must be passed to
|
|
4833
|
+
* {@linkcode MiddlewareParams.next | next()}, ensuring type-safe context additions at the call site.
|
|
4761
4834
|
*/
|
|
4762
|
-
type
|
|
4835
|
+
type MiddlewareHandler<Output extends Record<string, unknown>> = (params: {
|
|
4763
4836
|
readonly args: Readonly<Record<string, unknown>>;
|
|
4764
4837
|
readonly flags: Readonly<Record<string, unknown>>;
|
|
4765
4838
|
readonly sources: ErasedInputSources;
|
|
4766
4839
|
readonly ctx: Readonly<Record<string, unknown>>;
|
|
4767
4840
|
readonly out: Out;
|
|
4768
|
-
/**
|
|
4841
|
+
/** Invocation-scoped interactive questions. */
|
|
4769
4842
|
readonly ask: Ask;
|
|
4770
4843
|
readonly meta: CommandMeta;
|
|
4771
|
-
|
|
4844
|
+
/** Pass context additions downstream. Must include all `Output` properties. */
|
|
4845
|
+
readonly next: (additions: Output) => Promise<void>;
|
|
4846
|
+
}) => void | Promise<void>;
|
|
4772
4847
|
/**
|
|
4773
|
-
* Internal
|
|
4774
|
-
* {@linkcode CommandBuilder.derive | derive()} and {@linkcode CommandBuilder.middleware | middleware()}.
|
|
4848
|
+
* Internal runtime representation of middleware.
|
|
4775
4849
|
*/
|
|
4776
|
-
|
|
4777
|
-
readonly
|
|
4778
|
-
|
|
4779
|
-
} | {
|
|
4780
|
-
readonly kind: 'middleware';
|
|
4781
|
-
readonly handler: ErasedMiddlewareHandler;
|
|
4782
|
-
};
|
|
4850
|
+
interface MiddlewareImpl {
|
|
4851
|
+
readonly _handler: ErasedMiddlewareHandler;
|
|
4852
|
+
}
|
|
4783
4853
|
/**
|
|
4784
|
-
*
|
|
4854
|
+
* Middleware with phantom output type.
|
|
4785
4855
|
*
|
|
4786
|
-
* `
|
|
4787
|
-
*
|
|
4788
|
-
*
|
|
4789
|
-
*
|
|
4856
|
+
* The `Output` parameter tracks what this middleware adds to context at
|
|
4857
|
+
* compile time. The `_output` brand is phantom — it exists only in the
|
|
4858
|
+
* type system for inference, not at runtime.
|
|
4859
|
+
*
|
|
4860
|
+
* Created via the {@linkcode middleware} factory. Attached to commands via
|
|
4861
|
+
* `CommandBuilder.middleware()`.
|
|
4862
|
+
*
|
|
4863
|
+
* @example
|
|
4864
|
+
* ```ts
|
|
4865
|
+
* interface User { id: string; name: string }
|
|
4866
|
+
*
|
|
4867
|
+
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
4868
|
+
* const user = await getUser();
|
|
4869
|
+
* if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
4870
|
+
* return next({ user });
|
|
4871
|
+
* });
|
|
4872
|
+
* ```
|
|
4790
4873
|
*/
|
|
4791
|
-
|
|
4792
|
-
|
|
4793
|
-
readonly
|
|
4794
|
-
}
|
|
4874
|
+
type Middleware<Output extends Record<string, unknown>> = MiddlewareImpl & {
|
|
4875
|
+
/** @internal Phantom type brand — compile-time only. */
|
|
4876
|
+
readonly _output: Output;
|
|
4877
|
+
};
|
|
4795
4878
|
/**
|
|
4796
|
-
*
|
|
4797
|
-
*
|
|
4798
|
-
*
|
|
4879
|
+
* Create a middleware definition.
|
|
4880
|
+
*
|
|
4881
|
+
* Middleware runs before the action handler and can add typed context,
|
|
4882
|
+
* short-circuit execution, or wrap downstream processing.
|
|
4883
|
+
*
|
|
4884
|
+
* @param handler - Function receiving `{ args, flags, ctx, out, meta, next }`.
|
|
4885
|
+
* Call `next(additions)` to continue the chain with added context.
|
|
4886
|
+
* Omitting the `next()` call short-circuits (e.g., for auth guards).
|
|
4887
|
+
* @returns {@linkcode Middleware} to attach via `CommandBuilder.middleware()`.
|
|
4888
|
+
*
|
|
4889
|
+
* @example
|
|
4890
|
+
* ```ts
|
|
4891
|
+
* // Auth guard — adds user to context or throws
|
|
4892
|
+
* const auth = middleware(async ({ next }) => {
|
|
4893
|
+
* const user = await getUser();
|
|
4894
|
+
* if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
4895
|
+
* return next({ user });
|
|
4896
|
+
* });
|
|
4897
|
+
*
|
|
4898
|
+
* // Timing wrapper — measures downstream execution
|
|
4899
|
+
* const timing = middleware(async ({ out, next }) => {
|
|
4900
|
+
* const start = Date.now();
|
|
4901
|
+
* await next({});
|
|
4902
|
+
* out.info(`Done in ${Date.now() - start}ms`);
|
|
4903
|
+
* });
|
|
4904
|
+
*
|
|
4905
|
+
* command('deploy')
|
|
4906
|
+
* .middleware(timing)
|
|
4907
|
+
* .middleware(auth)
|
|
4908
|
+
* .action(({ ctx }) => {
|
|
4909
|
+
* console.log(ctx.user.name); // typed!
|
|
4910
|
+
* });
|
|
4911
|
+
* ```
|
|
4799
4912
|
*/
|
|
4800
|
-
|
|
4801
|
-
/** A single usage example shown in help text. */
|
|
4802
|
-
interface CommandExample {
|
|
4803
|
-
/** The command invocation (e.g. `'deploy production --force'`). */
|
|
4804
|
-
readonly command: ExampleCommand;
|
|
4805
|
-
/** Optional description of what this example does. */
|
|
4806
|
-
readonly description?: string;
|
|
4807
|
-
}
|
|
4808
|
-
/** Resolve an {@link ExampleCommand} to its string form for the given meta. */
|
|
4809
|
-
declare function resolveExampleCommand(command: ExampleCommand, meta: ExampleMeta): string;
|
|
4913
|
+
declare function middleware<Output extends Record<string, unknown>>(handler: MiddlewareHandler<Output>): Middleware<Output>;
|
|
4810
4914
|
/**
|
|
4811
|
-
*
|
|
4915
|
+
* Where a resolved value came from.
|
|
4812
4916
|
*
|
|
4813
|
-
*
|
|
4814
|
-
*
|
|
4815
|
-
*
|
|
4917
|
+
* Resolution records one {@link ResolutionProvenance} per input that produced a
|
|
4918
|
+
* value, and the same record reaches a handler through `sources` and a
|
|
4919
|
+
* `resolve()` caller through `ResolveResult.provenance`. {@link wasExplicit}
|
|
4920
|
+
* derives the explicit-versus-defaulted question from it.
|
|
4921
|
+
*
|
|
4922
|
+
* @module dreamcli/core/schema/provenance
|
|
4816
4923
|
*/
|
|
4817
|
-
interface CommandSchema {
|
|
4818
|
-
/** Type-only seal produced by {@link createCommandSchema}. */
|
|
4819
|
-
readonly [schemaBrand]: 'command';
|
|
4820
|
-
/** The command name (used for dispatch, e.g. `'deploy'`). */
|
|
4821
|
-
readonly name: string;
|
|
4822
|
-
/** Human-readable description for help text. */
|
|
4823
|
-
readonly description: string | undefined;
|
|
4824
|
-
/** Longer explanation shown only in this command's help, with paragraphs wrapped to its width. */
|
|
4825
|
-
readonly details?: HelpDescription | undefined;
|
|
4826
|
-
/** Alternative names for this command. */
|
|
4827
|
-
readonly aliases: readonly string[];
|
|
4828
|
-
/** Whether this command is hidden from help listings. */
|
|
4829
|
-
readonly hidden: boolean;
|
|
4830
|
-
/** Usage examples for help text. */
|
|
4831
|
-
readonly examples: readonly CommandExample[];
|
|
4832
|
-
/** Named flag schemas, keyed by flag name. */
|
|
4833
|
-
readonly flags: Readonly<Record<string, FlagSchema>>;
|
|
4834
|
-
/** Ordered positional arg entries (name + schema). */
|
|
4835
|
-
readonly args: readonly CommandArgEntry[];
|
|
4836
|
-
/** Whether an action handler has been registered. */
|
|
4837
|
-
readonly hasAction: boolean;
|
|
4838
|
-
/**
|
|
4839
|
-
* Command-level interactive resolver for schema-driven prompt control.
|
|
4840
|
-
*
|
|
4841
|
-
* When set, called after CLI/env/config resolution with partially resolved
|
|
4842
|
-
* flag values. Returns prompt configs for flags that need interactive input.
|
|
4843
|
-
* Takes precedence over per-flag `.prompt()` configs for flags it returns
|
|
4844
|
-
* configs for; flags not mentioned fall back to their per-flag configs.
|
|
4845
|
-
*
|
|
4846
|
-
* @see InteractiveResolver
|
|
4847
|
-
*/
|
|
4848
|
-
readonly interactive: ErasedInteractiveResolver | undefined;
|
|
4849
|
-
/**
|
|
4850
|
-
* Nested subcommand schemas (for help rendering and completion).
|
|
4851
|
-
*
|
|
4852
|
-
* Pure data — no execution closures. Populated by `.command()` on
|
|
4853
|
-
* `CommandBuilder`. Empty for leaf commands.
|
|
4854
|
-
*/
|
|
4855
|
-
readonly commands: readonly CommandSchema[];
|
|
4856
|
-
}
|
|
4857
4924
|
/**
|
|
4858
|
-
*
|
|
4925
|
+
* Which stage produced a resolved value, and how.
|
|
4859
4926
|
*
|
|
4860
|
-
*
|
|
4861
|
-
*
|
|
4927
|
+
* `via` and `trigger` distinguish the two ways stdin delivers bytes. An explicit
|
|
4928
|
+
* `-` keeps CLI precedence and reports `{ stage: 'cli', via: 'stdin', trigger:
|
|
4929
|
+
* 'dash' }`; an absent input takes the fallback stage between CLI and env and
|
|
4930
|
+
* reports `{ stage: 'stdin', via: 'stdin', trigger: 'fallback' }`.
|
|
4931
|
+
*
|
|
4932
|
+
* The `'env'` stage is two records the same way. A variable bound by name
|
|
4933
|
+
* reports `{ stage: 'env', envVar }`, the one concrete variable that supplied
|
|
4934
|
+
* the value. An indexed family bound with an `IndexedEnvBinding` reports
|
|
4935
|
+
* `{ stage: 'env', via: 'indexed', count, envVars }`: the count variable that
|
|
4936
|
+
* claimed the input and every member variable read, in entry order and, within
|
|
4937
|
+
* an entry, in field order. `envVars` is empty when the count is `0`. Test
|
|
4938
|
+
* `'envVar' in source` (or `source.via`) before reading either shape's fields.
|
|
4939
|
+
*
|
|
4940
|
+
* @example
|
|
4941
|
+
* ```ts
|
|
4942
|
+
* command('deploy')
|
|
4943
|
+
* .flag('region', flag.string().env('REGION').default('us'))
|
|
4944
|
+
* .action(({ sources }) => {
|
|
4945
|
+
* const region = sources.flags.region;
|
|
4946
|
+
* if (region?.stage === 'env' && 'envVar' in region) console.log(`from ${region.envVar}`);
|
|
4947
|
+
* });
|
|
4948
|
+
* ```
|
|
4862
4949
|
*/
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
readonly
|
|
4868
|
-
|
|
4950
|
+
type ResolutionProvenance = {
|
|
4951
|
+
readonly stage: 'cli';
|
|
4952
|
+
} | {
|
|
4953
|
+
readonly stage: 'cli';
|
|
4954
|
+
readonly via: 'stdin';
|
|
4955
|
+
readonly trigger: 'dash';
|
|
4956
|
+
} | {
|
|
4957
|
+
readonly stage: 'stdin';
|
|
4958
|
+
readonly via: 'stdin';
|
|
4959
|
+
readonly trigger: 'fallback';
|
|
4960
|
+
} | {
|
|
4961
|
+
readonly stage: 'env';
|
|
4962
|
+
readonly envVar: string;
|
|
4963
|
+
} | {
|
|
4964
|
+
readonly stage: 'env';
|
|
4965
|
+
readonly via: 'indexed';
|
|
4966
|
+
readonly count: string;
|
|
4967
|
+
readonly envVars: readonly string[];
|
|
4968
|
+
} | {
|
|
4969
|
+
readonly stage: 'config';
|
|
4970
|
+
readonly configPath: string;
|
|
4971
|
+
} | {
|
|
4972
|
+
readonly stage: 'prompt';
|
|
4973
|
+
} | {
|
|
4974
|
+
readonly stage: 'default';
|
|
4975
|
+
};
|
|
4869
4976
|
/**
|
|
4870
|
-
*
|
|
4977
|
+
* Provenance of every input of one surface, keyed by input name.
|
|
4871
4978
|
*
|
|
4872
|
-
*
|
|
4979
|
+
* An input that resolved no value has no record, so every member is optional in
|
|
4980
|
+
* value even though the key set is the surface's own.
|
|
4981
|
+
*
|
|
4982
|
+
* @typeParam T - The record of flag or arg builders whose keys this mirrors.
|
|
4873
4983
|
*/
|
|
4874
|
-
|
|
4875
|
-
/** User-facing argument name (shown in help as `<name>`). */
|
|
4876
|
-
readonly name: string;
|
|
4877
|
-
/** Arg definition or an already-built schema. */
|
|
4878
|
-
readonly schema: ArgDefinition | ArgSchema;
|
|
4879
|
-
}
|
|
4984
|
+
type SourcesOf<T> = { readonly [K in keyof T]: ResolutionProvenance | undefined; };
|
|
4880
4985
|
/**
|
|
4881
|
-
*
|
|
4986
|
+
* Where each of a command's resolved values came from.
|
|
4882
4987
|
*
|
|
4883
|
-
*
|
|
4884
|
-
*
|
|
4988
|
+
* Handed to an action, derive, or middleware handler as `sources`, keyed by the
|
|
4989
|
+
* same names as `flags` and `args`.
|
|
4990
|
+
*
|
|
4991
|
+
* @typeParam F - The command's flag builders.
|
|
4992
|
+
* @typeParam A - The command's arg builders.
|
|
4885
4993
|
*/
|
|
4886
|
-
interface
|
|
4887
|
-
/**
|
|
4888
|
-
readonly
|
|
4889
|
-
/**
|
|
4890
|
-
|
|
4891
|
-
* @defaultValue `undefined`
|
|
4892
|
-
*/
|
|
4893
|
-
readonly description?: string | undefined;
|
|
4894
|
-
/** Longer explanation shown only in this command's help. */
|
|
4895
|
-
readonly details?: HelpDescription | undefined;
|
|
4896
|
-
/**
|
|
4897
|
-
* Alternative names for this command.
|
|
4898
|
-
* @defaultValue `[]`
|
|
4899
|
-
*/
|
|
4900
|
-
readonly aliases?: readonly string[] | undefined;
|
|
4901
|
-
/**
|
|
4902
|
-
* Whether this command is hidden from help listings.
|
|
4903
|
-
* @defaultValue `false`
|
|
4904
|
-
*/
|
|
4905
|
-
readonly hidden?: boolean | undefined;
|
|
4906
|
-
/**
|
|
4907
|
-
* Usage examples for help text.
|
|
4908
|
-
* @defaultValue `[]`
|
|
4909
|
-
*/
|
|
4910
|
-
readonly examples?: readonly CommandExample[] | undefined;
|
|
4911
|
-
/**
|
|
4912
|
-
* Flag definitions or built schemas, keyed by flag name.
|
|
4913
|
-
* @defaultValue `{}`
|
|
4914
|
-
*/
|
|
4915
|
-
readonly flags?: Readonly<Record<string, FlagDefinition | FlagSchema>> | undefined;
|
|
4916
|
-
/**
|
|
4917
|
-
* Ordered positional arg entries.
|
|
4918
|
-
* @defaultValue `[]`
|
|
4919
|
-
*/
|
|
4920
|
-
readonly args?: readonly CommandArgEntryDefinition[] | undefined;
|
|
4921
|
-
/**
|
|
4922
|
-
* Whether an action handler has been registered.
|
|
4923
|
-
* @defaultValue `false`
|
|
4924
|
-
*/
|
|
4925
|
-
readonly hasAction?: boolean | undefined;
|
|
4926
|
-
/**
|
|
4927
|
-
* Command-level interactive resolver.
|
|
4928
|
-
* @defaultValue `undefined`
|
|
4929
|
-
*/
|
|
4930
|
-
readonly interactive?: ErasedInteractiveResolver | undefined;
|
|
4931
|
-
/**
|
|
4932
|
-
* Nested subcommand definitions or built schemas.
|
|
4933
|
-
* @defaultValue `[]`
|
|
4934
|
-
*/
|
|
4935
|
-
readonly commands?: readonly (CommandDefinition | CommandSchema)[] | undefined;
|
|
4994
|
+
interface InputSources<F, A> {
|
|
4995
|
+
/** Provenance of every declared flag, keyed by flag name. */
|
|
4996
|
+
readonly flags: SourcesOf<F>;
|
|
4997
|
+
/** Provenance of every declared arg, keyed by arg name. */
|
|
4998
|
+
readonly args: SourcesOf<A>;
|
|
4936
4999
|
}
|
|
4937
5000
|
/**
|
|
4938
|
-
*
|
|
5001
|
+
* Whether a value came from somewhere other than its declared default.
|
|
4939
5002
|
*
|
|
4940
|
-
*
|
|
4941
|
-
*
|
|
4942
|
-
*
|
|
5003
|
+
* Every stage but `'default'` means the value was supplied: typed on the command
|
|
5004
|
+
* line, piped, exported, written in a config file, or answered at a prompt. An
|
|
5005
|
+
* input that resolved no value at all has no record and is not explicit.
|
|
4943
5006
|
*
|
|
4944
|
-
*
|
|
4945
|
-
*
|
|
5007
|
+
* Read `stage` directly for a narrower question, such as `stage === 'cli'` for
|
|
5008
|
+
* "the user typed it on this command line".
|
|
4946
5009
|
*
|
|
4947
|
-
*
|
|
4948
|
-
*
|
|
4949
|
-
* ancestor flag is rejected here. Both flags still parse under their canonical
|
|
4950
|
-
* names, so what a collision costs is the shared spelling. Help advertises it on
|
|
4951
|
-
* both flags and the parser answers it with one of them.
|
|
4952
|
-
* Args go through the same invariants {@link CommandBuilder.arg} enforces.
|
|
4953
|
-
* These are the checks the {@link CommandBuilder} applies as flags, args, and
|
|
4954
|
-
* subcommands are registered.
|
|
4955
|
-
*
|
|
4956
|
-
* @param definition - Command name plus optional flags, args, and subcommands.
|
|
4957
|
-
* @returns A fully populated {@link CommandSchema}.
|
|
4958
|
-
* @throws {CLIError} With code `'INVALID_SCHEMA'` when a name at any depth is
|
|
4959
|
-
* empty or contains whitespace, a flag or arg at any depth is named
|
|
4960
|
-
* `__proto__`, which JavaScript cannot carry as a plain record key, or a flag
|
|
4961
|
-
* record at any depth has a
|
|
4962
|
-
* replaced prototype, which hides the entries a name check would read.
|
|
4963
|
-
* @throws {CLIError} With code `'FLAG_NAME_COLLISION'` when two flags on one
|
|
4964
|
-
* command share a spelling.
|
|
4965
|
-
* @throws {CLIError} With code `'PROPAGATED_FLAG_COLLISION'` when a flag shadows
|
|
4966
|
-
* a spelling propagated from an ancestor command.
|
|
4967
|
-
* @throws {CLIError} With code `'INVALID_BUILDER_STATE'` when a positional comes
|
|
4968
|
-
* after a variadic one, or `'DUPLICATE_STDIN_INPUT'` when two inputs on one
|
|
4969
|
-
* command consume stdin and either is exclusive.
|
|
5010
|
+
* @param source - The provenance record of one input, or `undefined`.
|
|
5011
|
+
* @returns `true` when a source other than the default produced the value.
|
|
4970
5012
|
*
|
|
4971
5013
|
* @example
|
|
4972
5014
|
* ```ts
|
|
4973
|
-
*
|
|
4974
|
-
*
|
|
4975
|
-
*
|
|
4976
|
-
*
|
|
4977
|
-
*
|
|
4978
|
-
* });
|
|
5015
|
+
* command('build')
|
|
5016
|
+
* .flag('out', flag.string().default('dist'))
|
|
5017
|
+
* .action(({ sources, out }) => {
|
|
5018
|
+
* if (wasExplicit(sources.flags.out)) out.info('using an overridden output');
|
|
5019
|
+
* });
|
|
4979
5020
|
* ```
|
|
4980
5021
|
*/
|
|
4981
|
-
declare function
|
|
5022
|
+
declare function wasExplicit(source: ResolutionProvenance | undefined): boolean;
|
|
4982
5023
|
/**
|
|
4983
|
-
*
|
|
5024
|
+
* Widen the context type when adding middleware.
|
|
4984
5025
|
*
|
|
4985
|
-
*
|
|
4986
|
-
*
|
|
5026
|
+
* The default `C = Record<string, never>` uses an index signature where
|
|
5027
|
+
* every key maps to `never` — making property access a type error until
|
|
5028
|
+
* middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
|
|
5029
|
+
* collapses all properties to `never` because `never & T = never`.
|
|
4987
5030
|
*
|
|
4988
|
-
*
|
|
4989
|
-
*
|
|
4990
|
-
|
|
5031
|
+
* This utility replaces `Record<string, never>` entirely on the first
|
|
5032
|
+
* `.middleware()` call. Subsequent calls use plain intersection.
|
|
5033
|
+
*/
|
|
5034
|
+
type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
|
|
5035
|
+
/**
|
|
5036
|
+
* Widen the context type when adding command-scoped derived context.
|
|
4991
5037
|
*
|
|
5038
|
+
* Validation-only derive handlers return `undefined` (or nothing), preserving `C`.
|
|
5039
|
+
* Context-producing derive handlers return an object that merges into `C`
|
|
5040
|
+
* using the same first-call replacement rules as middleware.
|
|
4992
5041
|
*/
|
|
4993
|
-
type
|
|
4994
|
-
/** Retain declared flag names for duplicate checks alongside an index signature. */
|
|
4995
|
-
type KnownFlags<F> = { [K in keyof F as string extends K ? never : number extends K ? never : K]: F[K]; };
|
|
4996
|
-
/** Generated names can carry any registered builder, while declared names keep their types. */
|
|
4997
|
-
type MergeFlags<F extends Record<string, FlagBuilder<FlagConfig>>, R extends Record<string, FlagBuilder<FlagConfig>>> = string extends keyof F | keyof R ? KnownFlags<F> & KnownFlags<R> & Record<string, F[keyof F] | R[keyof R]> : F & R;
|
|
5042
|
+
type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
|
|
4998
5043
|
/**
|
|
4999
|
-
*
|
|
5044
|
+
* Parameters received by the interactive resolver function.
|
|
5000
5045
|
*
|
|
5001
|
-
*
|
|
5002
|
-
*
|
|
5003
|
-
*
|
|
5004
|
-
|
|
5046
|
+
* `flags` contains partially resolved values — present for flags resolved
|
|
5047
|
+
* via CLI, env, or config, `undefined` for unresolved flags. The resolver
|
|
5048
|
+
* uses this to decide which prompts to show based on current state.
|
|
5049
|
+
*/
|
|
5050
|
+
interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
|
|
5051
|
+
/** Partially resolved flag values (after CLI/env/config, before prompts). */
|
|
5052
|
+
readonly flags: Readonly<Partial<InferFlags<F>>>;
|
|
5053
|
+
}
|
|
5054
|
+
/**
|
|
5055
|
+
* A record mapping flag names to prompt configs or falsy values.
|
|
5005
5056
|
*
|
|
5006
|
-
* `
|
|
5007
|
-
*
|
|
5057
|
+
* - `PromptConfig` — show this prompt for the flag
|
|
5058
|
+
* - `false | undefined | null | 0 | ''` — skip prompting for this flag
|
|
5059
|
+
*
|
|
5060
|
+
* Only flag names that need prompting should have truthy values.
|
|
5061
|
+
* Flags not mentioned are handled by their per-flag `.prompt()` config.
|
|
5062
|
+
*/
|
|
5063
|
+
type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
|
|
5064
|
+
/**
|
|
5065
|
+
* Interactive resolver function for command-level prompt control.
|
|
5066
|
+
*
|
|
5067
|
+
* Called after CLI/env/config resolution but before per-flag prompts fire.
|
|
5068
|
+
* Receives partially resolved values and returns a prompt schema for
|
|
5069
|
+
* flags that should be prompted. Commands without `.interactive()` use
|
|
5070
|
+
* per-flag prompt configs directly.
|
|
5008
5071
|
*
|
|
5009
5072
|
* @example
|
|
5010
5073
|
* ```ts
|
|
5074
|
+
* import { command, flag } from '@kjanat/dreamcli';
|
|
5075
|
+
*
|
|
5011
5076
|
* const deploy = command('deploy')
|
|
5012
|
-
* .description('Deploy to an environment')
|
|
5013
|
-
* .arg('target', arg.string().describe('Deploy target'))
|
|
5014
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
5015
5077
|
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
5016
|
-
* .
|
|
5017
|
-
*
|
|
5018
|
-
*
|
|
5019
|
-
*
|
|
5020
|
-
*
|
|
5078
|
+
* .interactive(({ flags }) => ({
|
|
5079
|
+
* region: !flags.region && {
|
|
5080
|
+
* kind: 'select',
|
|
5081
|
+
* message: 'Select region',
|
|
5082
|
+
* },
|
|
5083
|
+
* }))
|
|
5084
|
+
* .action(({ flags, out }) => {
|
|
5085
|
+
* out.log(`Deploying to ${flags.region}`);
|
|
5021
5086
|
* });
|
|
5022
5087
|
* ```
|
|
5023
5088
|
*/
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
|
|
5032
|
-
|
|
5033
|
-
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
readonly
|
|
5037
|
-
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
|
|
5042
|
-
|
|
5043
|
-
|
|
5044
|
-
|
|
5045
|
-
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
/**
|
|
5059
|
-
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
* resolved flag values. It returns a prompt schema for flags that need
|
|
5063
|
-
* interactive input based on the current state.
|
|
5064
|
-
*
|
|
5065
|
-
* For flags the resolver returns a {@linkcode PromptConfig}, that config is used
|
|
5066
|
-
* instead of any per-flag `.prompt()` config. For flags returned as falsy
|
|
5067
|
-
* (or not mentioned), per-flag `.prompt()` configs are used as fallback.
|
|
5068
|
-
*
|
|
5069
|
-
* Commands without `.interactive()` use per-flag prompt configs directly.
|
|
5070
|
-
*
|
|
5071
|
-
* @example
|
|
5072
|
-
* ```ts
|
|
5073
|
-
* const deploy = command('deploy')
|
|
5074
|
-
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
5075
|
-
* .flag('force', flag.boolean())
|
|
5076
|
-
* .interactive(({ flags }) => ({
|
|
5077
|
-
* region: !flags.region && {
|
|
5078
|
-
* kind: 'select',
|
|
5079
|
-
* message: 'Select region',
|
|
5080
|
-
* },
|
|
5081
|
-
* }))
|
|
5082
|
-
* .action(({ flags }) => { ... });
|
|
5083
|
-
* ```
|
|
5084
|
-
*
|
|
5085
|
-
* @param resolver - Function receiving partially resolved flags and returning prompt configs.
|
|
5086
|
-
* @returns The builder (for chaining).
|
|
5087
|
-
*/
|
|
5088
|
-
interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;
|
|
5089
|
-
/**
|
|
5090
|
-
* Register a command-scoped typed pre-action handler.
|
|
5091
|
-
*
|
|
5092
|
-
* Derive runs after full resolution and before the action handler.
|
|
5093
|
-
* It receives typed `{ args, flags, ctx, out, meta }` and may either:
|
|
5094
|
-
*
|
|
5095
|
-
* - return nothing (or `undefined`) for validation-only behavior
|
|
5096
|
-
* - return an object to merge additional properties into `ctx`
|
|
5097
|
-
*
|
|
5098
|
-
* Handlers may be async — the runtime awaits them before continuing.
|
|
5099
|
-
*
|
|
5100
|
-
* Unlike middleware, derive cannot wrap downstream execution and does not
|
|
5101
|
-
* use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
|
|
5102
|
-
* or error-boundary patterns.
|
|
5103
|
-
*
|
|
5104
|
-
* Adding derive drops the current handler (like `.flag()`, `.arg()`, and
|
|
5105
|
-
* `.middleware()`) because the action handler's `ctx` type may change.
|
|
5106
|
-
*
|
|
5107
|
-
* @example
|
|
5108
|
-
* ```ts
|
|
5109
|
-
* command('deploy')
|
|
5110
|
-
* .flag('token', flag.string().env('AUTH_TOKEN'))
|
|
5111
|
-
* .derive(({ flags }) => {
|
|
5112
|
-
* if (!flags.token) {
|
|
5113
|
-
* throw new CLIError('Not authenticated', {
|
|
5114
|
-
* code: 'AUTH_REQUIRED',
|
|
5115
|
-
* suggest: 'Run `mycli login` or set AUTH_TOKEN',
|
|
5116
|
-
* });
|
|
5117
|
-
* }
|
|
5118
|
-
* return { token: flags.token };
|
|
5119
|
-
* })
|
|
5120
|
-
* .action(({ ctx }) => {
|
|
5121
|
-
* ctx.token; // string
|
|
5122
|
-
* });
|
|
5123
|
-
* ```
|
|
5124
|
-
*
|
|
5125
|
-
* @param handler - Derive function receiving typed args/flags/ctx.
|
|
5126
|
-
* @returns The builder (for chaining).
|
|
5127
|
-
*/
|
|
5128
|
-
derive<Output extends Record<string, unknown> | undefined = undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;
|
|
5129
|
-
/**
|
|
5130
|
-
* Register middleware to run before the action handler.
|
|
5131
|
-
*
|
|
5132
|
-
* Middleware executes in registration order. Each middleware receives
|
|
5133
|
-
* `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
|
|
5134
|
-
* to continue the chain. Context additions are merged and become
|
|
5135
|
-
* typed downstream.
|
|
5136
|
-
*
|
|
5137
|
-
* Adding middleware widens `C` via intersection and drops the current
|
|
5138
|
-
* handler (like `.flag()` / `.arg()` — the handler's type signature
|
|
5139
|
-
* changes when context changes).
|
|
5140
|
-
*
|
|
5141
|
-
* @example
|
|
5142
|
-
* ```ts
|
|
5143
|
-
* import { CLIError, command, middleware } from '@kjanat/dreamcli';
|
|
5144
|
-
*
|
|
5145
|
-
* interface User {
|
|
5146
|
-
* id: string;
|
|
5147
|
-
* email: string;
|
|
5148
|
-
* }
|
|
5149
|
-
*
|
|
5150
|
-
* async function getCurrentUser(): Promise<User | null> {
|
|
5151
|
-
* return { id: 'u_123', email: 'dev@example.com' };
|
|
5152
|
-
* }
|
|
5153
|
-
*
|
|
5154
|
-
* function startTrace(name: string): string {
|
|
5155
|
-
* return `trace:${name}`;
|
|
5156
|
-
* }
|
|
5157
|
-
*
|
|
5158
|
-
* // Resolve the current user and expose it as `ctx.user` downstream.
|
|
5159
|
-
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
5160
|
-
* const user = await getCurrentUser();
|
|
5161
|
-
* if (!user) {
|
|
5162
|
-
* throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
5163
|
-
* }
|
|
5164
|
-
* await next({ user });
|
|
5165
|
-
* });
|
|
5166
|
-
*
|
|
5167
|
-
* // Create a trace id for this command run and expose it as `ctx.traceId`.
|
|
5168
|
-
* const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
|
|
5169
|
-
* const traceId = startTrace(`${meta.name}.${meta.command}`);
|
|
5170
|
-
* await next({ traceId });
|
|
5171
|
-
* });
|
|
5172
|
-
*
|
|
5173
|
-
* command('deploy')
|
|
5174
|
-
* .middleware(auth) // C becomes { user: User }
|
|
5175
|
-
* .middleware(telemetry) // C becomes { user: User } & { traceId: string }
|
|
5176
|
-
* .action(({ ctx }) => {
|
|
5177
|
-
* ctx.user; // User — typed
|
|
5178
|
-
* ctx.traceId; // string — typed
|
|
5179
|
-
* });
|
|
5180
|
-
* ```
|
|
5181
|
-
*
|
|
5182
|
-
* @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
|
|
5183
|
-
* Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
|
|
5184
|
-
* @returns The builder (for chaining).
|
|
5185
|
-
*/
|
|
5186
|
-
middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;
|
|
5187
|
-
/**
|
|
5188
|
-
* Set the command's description for help text.
|
|
5189
|
-
*
|
|
5190
|
-
* Displayed below the usage line in `--help` output and next to the
|
|
5191
|
-
* command name in parent command/group help listings.
|
|
5192
|
-
*
|
|
5193
|
-
* @param text - One-line description of what the command does.
|
|
5194
|
-
*
|
|
5195
|
-
* @example
|
|
5196
|
-
* ```ts
|
|
5197
|
-
* command('deploy')
|
|
5198
|
-
* .description('Deploy the application to a target environment')
|
|
5199
|
-
* .action(({ out }) => { out.log('deploying...'); });
|
|
5200
|
-
*
|
|
5201
|
-
* // $ mycli deploy --help
|
|
5202
|
-
* // Usage: deploy [flags]
|
|
5203
|
-
* //
|
|
5204
|
-
* // Deploy the application to a target environment
|
|
5205
|
-
* ```
|
|
5206
|
-
*
|
|
5207
|
-
* @returns The builder (for chaining).
|
|
5208
|
-
*/
|
|
5209
|
-
description(text: string): CommandBuilder<F, A, C>;
|
|
5210
|
-
/**
|
|
5211
|
-
* Add a longer explanation to this command's help.
|
|
5212
|
-
*
|
|
5213
|
-
* Paragraphs wrap to the help width. Parent command listings use only
|
|
5214
|
-
* `.description()`. A function receives the current help description theme.
|
|
5215
|
-
*
|
|
5216
|
-
* @param text - Literal text or a function that styles the explanation.
|
|
5217
|
-
* @returns A new builder with the explanation.
|
|
5218
|
-
*/
|
|
5219
|
-
details(text: HelpDescription): CommandBuilder<F, A, C>;
|
|
5220
|
-
/**
|
|
5221
|
-
* Add an alternative name for this command.
|
|
5222
|
-
*
|
|
5223
|
-
* Aliases are accepted during dispatch alongside the primary name.
|
|
5224
|
-
* Multiple aliases can be chained. Aliases are shown in help output.
|
|
5225
|
-
*
|
|
5226
|
-
* @param name - Alternative command name (e.g. `'d'` for `deploy`).
|
|
5227
|
-
*
|
|
5228
|
-
* @example
|
|
5229
|
-
* ```ts
|
|
5230
|
-
* command('deploy')
|
|
5231
|
-
* .alias('d')
|
|
5232
|
-
* .alias('push')
|
|
5233
|
-
* .action(({ out }) => { out.log('deploying...'); });
|
|
5234
|
-
*
|
|
5235
|
-
* // All equivalent:
|
|
5236
|
-
* // $ mycli deploy
|
|
5237
|
-
* // $ mycli d
|
|
5238
|
-
* // $ mycli push
|
|
5239
|
-
* ```
|
|
5240
|
-
*
|
|
5241
|
-
* @returns The builder (for chaining).
|
|
5242
|
-
*/
|
|
5243
|
-
alias(name: string): CommandBuilder<F, A, C>;
|
|
5089
|
+
type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (params: InteractiveParams<F>) => InteractiveResult;
|
|
5090
|
+
/**
|
|
5091
|
+
* Type-erased interactive resolver stored on {@linkcode CommandSchema}.
|
|
5092
|
+
*
|
|
5093
|
+
* Advanced bridge type: most consumers should use {@link InteractiveResolver}
|
|
5094
|
+
* via {@linkcode command | command().interactive()} and never reference this alias directly.
|
|
5095
|
+
*
|
|
5096
|
+
* At runtime, the resolver receives `{ flags: Record<string, unknown> }`
|
|
5097
|
+
* and returns `Record<string, PromptConfig | falsy>`. The phantom types
|
|
5098
|
+
* from `CommandBuilder<F, A>` are erased.
|
|
5099
|
+
*/
|
|
5100
|
+
type ErasedInteractiveResolver = (params: {
|
|
5101
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
5102
|
+
}) => InteractiveResult;
|
|
5103
|
+
/**
|
|
5104
|
+
* Seals {@linkcode Out} against structural construction outside the framework.
|
|
5105
|
+
*
|
|
5106
|
+
* @internal
|
|
5107
|
+
*/
|
|
5108
|
+
declare const outBrand: unique symbol;
|
|
5109
|
+
/**
|
|
5110
|
+
* Output channel available inside action handlers.
|
|
5111
|
+
*
|
|
5112
|
+
* Provides structured methods for stdout/stderr, JSON output,
|
|
5113
|
+
* spinners, progress bars, and tables. The real implementation lives in
|
|
5114
|
+
* `src/core/output/`; this interface defines the shape that handlers consume.
|
|
5115
|
+
*
|
|
5116
|
+
* `Out` is a framework-created, non-exhaustive value: obtain instances from
|
|
5117
|
+
* action parameters, `createOutput()`, or `createCaptureOutput()` — do not
|
|
5118
|
+
* implement it. New readonly members may be added in minor releases.
|
|
5119
|
+
*/
|
|
5120
|
+
interface Out {
|
|
5121
|
+
/** Framework-construction seal. Obtain `Out` values from DreamCLI; do not implement this interface. */
|
|
5122
|
+
readonly [outBrand]: never;
|
|
5123
|
+
/** Write to stdout (normal output). */
|
|
5124
|
+
log(message: string): void;
|
|
5125
|
+
/** Informational (may be suppressed in quiet mode). */
|
|
5126
|
+
info(message: string): void;
|
|
5244
5127
|
/**
|
|
5245
|
-
*
|
|
5246
|
-
*
|
|
5247
|
-
* The command remains fully functional and dispatchable — it just
|
|
5248
|
-
* won't appear in `--help` output or shell completions. Useful for
|
|
5249
|
-
* internal/debug commands.
|
|
5250
|
-
*
|
|
5251
|
-
* @example
|
|
5252
|
-
* ```ts
|
|
5253
|
-
* command('debug-dump')
|
|
5254
|
-
* .hidden()
|
|
5255
|
-
* .action(({ out }) => { out.log(JSON.stringify(internalState)); });
|
|
5256
|
-
*
|
|
5257
|
-
* // $ mycli --help → 'debug-dump' is not listed
|
|
5258
|
-
* // $ mycli debug-dump → still works
|
|
5259
|
-
* ```
|
|
5128
|
+
* Status line to stderr, suppressed in quiet mode.
|
|
5260
5129
|
*
|
|
5261
|
-
*
|
|
5130
|
+
* Keeps stdout clean for piping; for success and progress notes like
|
|
5131
|
+
* `Wrote <path>` that scripts silence with `--quiet`.
|
|
5262
5132
|
*/
|
|
5263
|
-
|
|
5133
|
+
status(message: string): void;
|
|
5134
|
+
/** Warning to stderr. */
|
|
5135
|
+
warn(message: string): void;
|
|
5136
|
+
/** Error to stderr. */
|
|
5137
|
+
error(message: string): void;
|
|
5264
5138
|
/**
|
|
5265
|
-
*
|
|
5266
|
-
*
|
|
5267
|
-
* Examples are rendered in the "Examples:" section of `--help` output.
|
|
5268
|
-
* Call multiple times to add several examples. Each example shows a
|
|
5269
|
-
* shell invocation, optionally with a description.
|
|
5270
|
-
*
|
|
5271
|
-
* `cmd` may be a literal string or a function receiving the program
|
|
5272
|
-
* {@link ExampleMeta} (`name`, `version`), resolved at render time. Use the
|
|
5273
|
-
* function form to reference the invoked program name instead of hardcoding
|
|
5274
|
-
* it, so examples stay truthful under symlinks, `inheritName`, and
|
|
5275
|
-
* `npx x` vs a global install.
|
|
5276
|
-
*
|
|
5277
|
-
* @param cmd - The example command line, or a `(meta) => string` builder.
|
|
5278
|
-
* @param description - Optional one-line explanation of what the example does.
|
|
5279
|
-
*
|
|
5280
|
-
* @example
|
|
5281
|
-
* ```ts
|
|
5282
|
-
* command('deploy')
|
|
5283
|
-
* .arg('target', arg.string())
|
|
5284
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
5285
|
-
* .example('deploy production', 'Deploy to production')
|
|
5286
|
-
* .example((m) => `${m.name} deploy staging -f`, 'Force deploy to staging')
|
|
5287
|
-
* .action(({ args, flags }) => { ... });
|
|
5288
|
-
*
|
|
5289
|
-
* // $ mycli deploy --help
|
|
5290
|
-
* // ...
|
|
5291
|
-
* // Examples:
|
|
5292
|
-
* // deploy production Deploy to production
|
|
5293
|
-
* // mycli deploy staging -f Force deploy to staging
|
|
5294
|
-
* ```
|
|
5139
|
+
* Request a process exit code without emitting error-shaped output.
|
|
5295
5140
|
*
|
|
5296
|
-
*
|
|
5141
|
+
* Use this for check/status commands that should print normal output but
|
|
5142
|
+
* still signal a non-zero status to scripts. This does not stop execution;
|
|
5143
|
+
* later calls overwrite earlier calls, and thrown errors still win.
|
|
5297
5144
|
*/
|
|
5298
|
-
|
|
5145
|
+
setExitCode(code: number): void;
|
|
5299
5146
|
/**
|
|
5300
|
-
*
|
|
5301
|
-
*
|
|
5302
|
-
* The flag name is added to the type-level `F` map. Duplicate flag names
|
|
5303
|
-
* are prevented at the type level via the `Exclude` constraint.
|
|
5147
|
+
* Emit a structured JSON value to stdout.
|
|
5304
5148
|
*
|
|
5305
|
-
*
|
|
5306
|
-
*
|
|
5149
|
+
* Always serialises `value` as JSON to stdout regardless of output
|
|
5150
|
+
* mode. Prefer this over `log(JSON.stringify(...))` so the output
|
|
5151
|
+
* channel can enforce consistent formatting and future features
|
|
5152
|
+
* (pretty-print in TTY, streaming JSON, etc.).
|
|
5153
|
+
*/
|
|
5154
|
+
json(value: unknown): void;
|
|
5155
|
+
/**
|
|
5156
|
+
* Whether the output channel is in JSON mode (`--json` flag active).
|
|
5307
5157
|
*
|
|
5308
|
-
*
|
|
5309
|
-
*
|
|
5310
|
-
*
|
|
5311
|
-
|
|
5312
|
-
|
|
5158
|
+
* Handlers can check this to skip decorative output (spinners,
|
|
5159
|
+
* progress bars, ANSI formatting) when machine-readable output is
|
|
5160
|
+
* expected.
|
|
5161
|
+
*/
|
|
5162
|
+
readonly jsonMode: boolean;
|
|
5163
|
+
/**
|
|
5164
|
+
* Active output verbosity for this command execution.
|
|
5313
5165
|
*
|
|
5314
|
-
*
|
|
5315
|
-
*
|
|
5316
|
-
*
|
|
5317
|
-
*
|
|
5318
|
-
*
|
|
5319
|
-
*
|
|
5320
|
-
|
|
5321
|
-
|
|
5322
|
-
|
|
5323
|
-
*
|
|
5324
|
-
* .default('localhost')
|
|
5325
|
-
* .describe('Bind address'))
|
|
5326
|
-
* .flag('verbose', flag.boolean()
|
|
5327
|
-
* .alias('v')
|
|
5328
|
-
* .describe('Enable verbose logging'))
|
|
5329
|
-
* .action(({ flags, out }) => {
|
|
5330
|
-
* flags.port; // number
|
|
5331
|
-
* flags.host; // string
|
|
5332
|
-
* flags.verbose; // boolean
|
|
5333
|
-
* out.log(`Listening on ${flags.host}:${flags.port}`);
|
|
5334
|
-
* });
|
|
5166
|
+
* Root `--quiet`/`-q` resolves to `'quiet'`. Most handlers should emit
|
|
5167
|
+
* informational output through {@linkcode Out.info | info()},
|
|
5168
|
+
* {@linkcode Out.status | status()}, {@linkcode Out.spinner | spinner()},
|
|
5169
|
+
* or {@linkcode Out.progress | progress()} and let the channel suppress it
|
|
5170
|
+
* automatically. Read this property only when custom rendering or expensive
|
|
5171
|
+
* optional work genuinely depends on the active verbosity.
|
|
5172
|
+
*/
|
|
5173
|
+
readonly verbosity: Verbosity;
|
|
5174
|
+
/**
|
|
5175
|
+
* Whether stdout is connected to a TTY (terminal).
|
|
5335
5176
|
*
|
|
5336
|
-
*
|
|
5337
|
-
*
|
|
5338
|
-
*
|
|
5177
|
+
* Handlers can check this to decide whether to emit decorative output
|
|
5178
|
+
* (spinners, progress bars, ANSI color codes). When `false`, the output
|
|
5179
|
+
* is being piped or redirected — skip interactive decorations.
|
|
5339
5180
|
*
|
|
5340
|
-
*
|
|
5341
|
-
*
|
|
5342
|
-
* which a plain record cannot carry.
|
|
5343
|
-
* @throws {@link CLIError} `FLAG_NAME_COLLISION` when the command already
|
|
5344
|
-
* declares this name, or the new flag's spellings collide with another
|
|
5345
|
-
* flag's.
|
|
5346
|
-
* @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling
|
|
5347
|
-
* collides with one propagated to a registered subcommand.
|
|
5181
|
+
* Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
|
|
5182
|
+
* decorative output should be suppressed regardless of `isTTY`.
|
|
5348
5183
|
*/
|
|
5349
|
-
|
|
5184
|
+
readonly isTTY: boolean;
|
|
5185
|
+
/** Terminal dimensions captured when the output channel was created, if available. */
|
|
5186
|
+
readonly terminalSize: TerminalSize | undefined;
|
|
5350
5187
|
/**
|
|
5351
|
-
*
|
|
5352
|
-
*
|
|
5353
|
-
* Names and aliases must not collide with existing flags or other entries.
|
|
5354
|
-
* Literal names are checked by the compiler. Generated names are checked
|
|
5355
|
-
* at runtime, and their values include the registered flag value types.
|
|
5356
|
-
* Adding flags clears any previously registered action, like `.flag()`.
|
|
5188
|
+
* Context-aware ANSI color palette (powered by `ansispeck`).
|
|
5357
5189
|
*
|
|
5358
|
-
*
|
|
5359
|
-
*
|
|
5190
|
+
* Colors are enabled only when stdout is a TTY, JSON mode is off, and the
|
|
5191
|
+
* environment supports color (`NO_COLOR`, `FORCE_COLOR`, `--no-color`,
|
|
5192
|
+
* `--color`, `CI` are respected). When disabled, every formatter is an
|
|
5193
|
+
* identity function — `out.color.red('x')` returns `'x'` — so handlers can
|
|
5194
|
+
* style unconditionally without gating on `isTTY`/`jsonMode` themselves.
|
|
5360
5195
|
*
|
|
5361
5196
|
* @example
|
|
5362
5197
|
* ```ts
|
|
5363
|
-
*
|
|
5364
|
-
* .
|
|
5365
|
-
*
|
|
5198
|
+
* .action(({ out }) => {
|
|
5199
|
+
* out.log(`${out.color.green('✔')} deployed ${out.color.bold('api')}`);
|
|
5200
|
+
* });
|
|
5366
5201
|
* ```
|
|
5367
5202
|
*/
|
|
5368
|
-
|
|
5203
|
+
readonly color: Colors;
|
|
5369
5204
|
/**
|
|
5370
|
-
*
|
|
5205
|
+
* Whether OSC 8 terminal hyperlinks should be emitted.
|
|
5371
5206
|
*
|
|
5372
|
-
*
|
|
5373
|
-
*
|
|
5374
|
-
*
|
|
5375
|
-
*
|
|
5207
|
+
* Honors explicit `--no-hyperlinks`/`--hyperlinks` argv flags first, then
|
|
5208
|
+
* `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, falling back to `isTTY`.
|
|
5209
|
+
* Handlers rendering their own `out.color.link(...)` output can gate on
|
|
5210
|
+
* this to keep OSC 8 escapes out of piped or opted-out contexts.
|
|
5211
|
+
*/
|
|
5212
|
+
readonly isHyperlinkSupported: boolean;
|
|
5213
|
+
/**
|
|
5214
|
+
* Render tabular data.
|
|
5376
5215
|
*
|
|
5377
|
-
*
|
|
5378
|
-
*
|
|
5216
|
+
* - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
|
|
5217
|
+
* - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
|
|
5218
|
+
* - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
|
|
5219
|
+
* (useful for `grep`, `awk`, etc.).
|
|
5220
|
+
* - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
|
|
5221
|
+
* side channel while `json()` writes machine output to stdout.
|
|
5379
5222
|
*
|
|
5380
|
-
*
|
|
5381
|
-
*
|
|
5382
|
-
* or `arg.custom()`.
|
|
5223
|
+
* When `columns` is omitted, columns are auto-inferred from the keys
|
|
5224
|
+
* of the first row. Column headers default to the key name.
|
|
5383
5225
|
*
|
|
5384
|
-
*
|
|
5385
|
-
*
|
|
5386
|
-
* command('deploy')
|
|
5387
|
-
* // Required string arg — first positional
|
|
5388
|
-
* .arg('target', arg.string()
|
|
5389
|
-
* .env('DEPLOY_TARGET')
|
|
5390
|
-
* .describe('Deploy target'))
|
|
5391
|
-
* // Optional number arg — second positional
|
|
5392
|
-
* .arg('port', arg.number()
|
|
5393
|
-
* .env('PORT')
|
|
5394
|
-
* .default(3000)
|
|
5395
|
-
* .describe('Port number'))
|
|
5396
|
-
* .action(({ args }) => {
|
|
5397
|
-
* args.target; // string
|
|
5398
|
-
* args.port; // number
|
|
5399
|
-
* });
|
|
5226
|
+
* When `columns` is provided, both text and JSON output are projected to
|
|
5227
|
+
* only the listed keys.
|
|
5400
5228
|
*
|
|
5401
|
-
*
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5229
|
+
* @param rows - Array of row objects.
|
|
5230
|
+
*/
|
|
5231
|
+
table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
|
|
5232
|
+
/**
|
|
5233
|
+
* Render tabular data with explicit column selection.
|
|
5405
5234
|
*
|
|
5406
|
-
* @
|
|
5407
|
-
* @
|
|
5408
|
-
*
|
|
5409
|
-
* @throws {@link CLIError} `INVALID_BUILDER_STATE` when an earlier arg on this
|
|
5410
|
-
* command is variadic, so this one could never be filled.
|
|
5411
|
-
* @throws {@link CLIError} `DUPLICATE_STDIN_INPUT` when another input on this
|
|
5412
|
-
* command already consumes stdin exclusively.
|
|
5235
|
+
* @param rows - Array of row objects.
|
|
5236
|
+
* @param columns - Column descriptors controlling which keys are shown and header labels.
|
|
5237
|
+
* @param options - Per-call rendering options (format, stream).
|
|
5413
5238
|
*/
|
|
5414
|
-
|
|
5239
|
+
table<T extends Record<string, unknown>>(rows: readonly T[], columns?: readonly TableColumn<T>[], options?: TableOptions): void;
|
|
5415
5240
|
/**
|
|
5416
|
-
*
|
|
5241
|
+
* Create a spinner for indeterminate progress feedback.
|
|
5417
5242
|
*
|
|
5418
|
-
*
|
|
5419
|
-
*
|
|
5420
|
-
* subcommand's `CommandSchema` is also appended to `schema.commands` for
|
|
5421
|
-
* help rendering and completion generation.
|
|
5243
|
+
* Returns a no-op handle in quiet or JSON mode. Otherwise, non-TTY output
|
|
5244
|
+
* uses a no-op handle or the configured static fallback.
|
|
5422
5245
|
*
|
|
5423
|
-
*
|
|
5424
|
-
*
|
|
5425
|
-
*
|
|
5246
|
+
* @param text - Initial spinner text.
|
|
5247
|
+
* @param options - Fallback strategy for non-TTY environments.
|
|
5248
|
+
* @returns A {@link SpinnerHandle} for lifecycle control.
|
|
5249
|
+
*/
|
|
5250
|
+
spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
|
|
5251
|
+
/**
|
|
5252
|
+
* Create a progress bar for measured work.
|
|
5426
5253
|
*
|
|
5427
|
-
*
|
|
5428
|
-
*
|
|
5429
|
-
* const db = group('db')
|
|
5430
|
-
* .description('Database operations')
|
|
5431
|
-
* .command(migrateCmd)
|
|
5432
|
-
* .command(seedCmd);
|
|
5433
|
-
* ```
|
|
5254
|
+
* Returns a no-op handle in quiet or JSON mode. Otherwise, pass `total` for
|
|
5255
|
+
* determinate mode (percentage bar); omit for indeterminate (pulsing).
|
|
5434
5256
|
*
|
|
5435
|
-
* @param
|
|
5436
|
-
* @returns
|
|
5437
|
-
* @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling this
|
|
5438
|
-
* command propagates collides with one the subcommand, or any of its own
|
|
5439
|
-
* descendants, declares.
|
|
5257
|
+
* @param options - Progress configuration (total, label, fallback).
|
|
5258
|
+
* @returns A {@link ProgressHandle} for updating progress.
|
|
5440
5259
|
*/
|
|
5441
|
-
|
|
5260
|
+
progress(options: ProgressOptions): ProgressHandle;
|
|
5442
5261
|
/**
|
|
5443
|
-
*
|
|
5444
|
-
*
|
|
5445
|
-
* The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
|
|
5446
|
-
* from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
|
|
5447
|
-
* definitions.
|
|
5262
|
+
* Stop the currently active spinner or progress handle, if any.
|
|
5448
5263
|
*
|
|
5449
|
-
*
|
|
5450
|
-
*
|
|
5264
|
+
* TTY spinner and progress handles start `setInterval` timers that
|
|
5265
|
+
* prevent the process from exiting until a terminal method (`stop`,
|
|
5266
|
+
* `succeed`, `fail`, `done`) is called. If a handler throws before
|
|
5267
|
+
* reaching that call, the timer leaks and the process hangs.
|
|
5451
5268
|
*
|
|
5452
|
-
*
|
|
5269
|
+
* Call `stopActive()` in a `finally` block after handler execution
|
|
5270
|
+
* to guarantee cleanup. It is idempotent — safe to call when no
|
|
5271
|
+
* handle is active, or when the handle was already stopped.
|
|
5453
5272
|
*
|
|
5454
|
-
*
|
|
5455
|
-
*
|
|
5456
|
-
*
|
|
5457
|
-
* command('greet')
|
|
5458
|
-
* .arg('name', arg.string())
|
|
5459
|
-
* .action(({ args, out }) => {
|
|
5460
|
-
* out.log(`Hello, ${args.name}!`);
|
|
5461
|
-
* });
|
|
5462
|
-
* ```
|
|
5273
|
+
* The framework calls this automatically in `runCommand()` and
|
|
5274
|
+
* `cli().run()`. Direct users of `createOutput()` should call it
|
|
5275
|
+
* themselves after the handler returns or throws.
|
|
5463
5276
|
*
|
|
5464
5277
|
* @example
|
|
5465
5278
|
* ```ts
|
|
5466
|
-
*
|
|
5467
|
-
*
|
|
5468
|
-
*
|
|
5469
|
-
*
|
|
5470
|
-
* .
|
|
5471
|
-
*
|
|
5472
|
-
* .action(async ({ args, flags, ctx, out, meta }) => {
|
|
5473
|
-
* args.target; // string
|
|
5474
|
-
* flags.force; // boolean
|
|
5475
|
-
* flags.region; // 'us' | 'eu' | 'ap' | undefined
|
|
5476
|
-
* ctx.user; // User (from auth middleware)
|
|
5477
|
-
* meta.command; // string
|
|
5478
|
-
*
|
|
5479
|
-
* const spinner = out.spinner('Deploying...');
|
|
5480
|
-
* await deploy(args.target, { force: flags.force });
|
|
5481
|
-
* spinner.stop();
|
|
5482
|
-
* out.log('Done');
|
|
5483
|
-
* });
|
|
5279
|
+
* const out = createOutput({ isTTY: true });
|
|
5280
|
+
* try {
|
|
5281
|
+
* await handler({ out });
|
|
5282
|
+
* } finally {
|
|
5283
|
+
* out.stopActive();
|
|
5284
|
+
* }
|
|
5484
5285
|
* ```
|
|
5485
|
-
*
|
|
5486
|
-
* @returns The builder (for chaining).
|
|
5487
5286
|
*/
|
|
5488
|
-
|
|
5287
|
+
stopActive(): void;
|
|
5489
5288
|
}
|
|
5490
5289
|
/**
|
|
5491
|
-
*
|
|
5290
|
+
* Runtime metadata about the CLI program and current command execution.
|
|
5492
5291
|
*
|
|
5493
|
-
*
|
|
5292
|
+
* Available to action handlers and middleware.
|
|
5494
5293
|
*
|
|
5495
|
-
* @
|
|
5496
|
-
*
|
|
5497
|
-
*
|
|
5294
|
+
* Populated by the CLI dispatch layer from {@link CLISchema} and
|
|
5295
|
+
* {@link CommandSchema}. For standalone `runCommand()` calls without
|
|
5296
|
+
* a CLI wrapper, a minimal meta is constructed from the command's own schema.
|
|
5297
|
+
*/
|
|
5298
|
+
interface CommandMeta {
|
|
5299
|
+
/** CLI program name (from `cli('name')` or package.json inference). */
|
|
5300
|
+
readonly name: string;
|
|
5301
|
+
/** Binary display name used in help/usage (may differ from `name`). */
|
|
5302
|
+
readonly bin: string;
|
|
5303
|
+
/** Program version, if set via `.version()` or discovered from package.json. */
|
|
5304
|
+
readonly version: string | undefined;
|
|
5305
|
+
/** The leaf command name currently being executed. */
|
|
5306
|
+
readonly command: string;
|
|
5307
|
+
}
|
|
5308
|
+
/**
|
|
5309
|
+
* The bag of values received by an action handler.
|
|
5498
5310
|
*
|
|
5499
|
-
*
|
|
5500
|
-
*
|
|
5501
|
-
*
|
|
5502
|
-
*
|
|
5503
|
-
*
|
|
5504
|
-
*
|
|
5505
|
-
* });
|
|
5506
|
-
* ```
|
|
5311
|
+
* - `args`: fully resolved positional arguments
|
|
5312
|
+
* - `flags`: fully resolved flags
|
|
5313
|
+
* - `sources`: which stage produced each of those values
|
|
5314
|
+
* - `ctx`: derive/middleware-provided context
|
|
5315
|
+
* - `out`: output channel
|
|
5316
|
+
* - `meta`: CLI program metadata (name, bin, version, command)
|
|
5507
5317
|
*
|
|
5508
|
-
*
|
|
5318
|
+
* The `C` parameter defaults to `Record<string, never>`, making `ctx`
|
|
5319
|
+
* property access a type error until derive or middleware extends it.
|
|
5509
5320
|
*/
|
|
5510
|
-
|
|
5321
|
+
interface ActionParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> {
|
|
5322
|
+
/** Fully resolved positional argument values, typed from `.arg()` definitions. */
|
|
5323
|
+
readonly args: Readonly<InferArgs<A>>;
|
|
5324
|
+
/** Fully resolved flag values, typed from `.flag()` definitions. */
|
|
5325
|
+
readonly flags: Readonly<InferFlags<F>>;
|
|
5326
|
+
/**
|
|
5327
|
+
* Where each resolved value came from, keyed like `flags` and `args`.
|
|
5328
|
+
*
|
|
5329
|
+
* An input that resolved no value has no record. {@link wasExplicit} answers
|
|
5330
|
+
* the explicit-versus-defaulted question; read `stage` for the rest.
|
|
5331
|
+
*/
|
|
5332
|
+
readonly sources: InputSources<F, A>;
|
|
5333
|
+
/** Middleware/derive-provided context, typed from `.middleware()` and `.derive()` chains. */
|
|
5334
|
+
readonly ctx: Readonly<C>;
|
|
5335
|
+
/** Structured output channel for stdout, stderr, JSON, tables, and spinners. */
|
|
5336
|
+
readonly out: Out;
|
|
5337
|
+
/** Ask a typed question after selecting the operation or receiving a server challenge. */
|
|
5338
|
+
readonly ask: Ask;
|
|
5339
|
+
/** Runtime metadata about the CLI program and current command. */
|
|
5340
|
+
readonly meta: CommandMeta;
|
|
5341
|
+
}
|
|
5511
5342
|
/**
|
|
5512
|
-
*
|
|
5343
|
+
* Action handler function signature.
|
|
5513
5344
|
*
|
|
5514
|
-
*
|
|
5515
|
-
*
|
|
5516
|
-
*
|
|
5345
|
+
* May be sync or async — the framework will `await` the return value
|
|
5346
|
+
* regardless. The `C` parameter carries the accumulated middleware
|
|
5347
|
+
* context type (defaults to empty).
|
|
5348
|
+
*/
|
|
5349
|
+
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>;
|
|
5350
|
+
/**
|
|
5351
|
+
* Type-erased action handler stored on {@linkcode CommandBuilder}.
|
|
5517
5352
|
*
|
|
5518
|
-
*
|
|
5519
|
-
*
|
|
5353
|
+
* The typed {@linkcode ActionHandler} from `.action()` is cast to this
|
|
5354
|
+
* erased form at the type-erasure boundary, keeping {@linkcode CommandBuilder}
|
|
5355
|
+
* covariant in its generic parameters. This enables structural
|
|
5356
|
+
* compatibility across TypeScript declaration-file boundaries where
|
|
5357
|
+
* generic inference may fall back to constraint types.
|
|
5520
5358
|
*
|
|
5521
|
-
*
|
|
5359
|
+
* Follows the same erasure pattern as {@link ErasedDeriveHandler} and
|
|
5360
|
+
* {@link ErasedMiddlewareHandler}.
|
|
5361
|
+
*/
|
|
5362
|
+
type ErasedActionHandler = (params: {
|
|
5363
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
5364
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
5365
|
+
readonly sources: ErasedInputSources;
|
|
5366
|
+
readonly ctx: Readonly<Record<string, unknown>>;
|
|
5367
|
+
readonly out: Out;
|
|
5368
|
+
/** Ask a typed question after selecting the operation or receiving a server challenge. */
|
|
5369
|
+
readonly ask: Ask;
|
|
5370
|
+
readonly meta: CommandMeta;
|
|
5371
|
+
}) => void | Promise<void>;
|
|
5372
|
+
/**
|
|
5373
|
+
* The provenance bag as the execution seam carries it, before a handler's own
|
|
5374
|
+
* flag and arg names type it.
|
|
5375
|
+
*/
|
|
5376
|
+
type ErasedInputSources = InputSources<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>;
|
|
5377
|
+
/**
|
|
5378
|
+
* The bag of values received by a derive handler.
|
|
5522
5379
|
*
|
|
5523
|
-
* @
|
|
5524
|
-
*
|
|
5525
|
-
*
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
*
|
|
5380
|
+
* Identical to {@link ActionParams}: derives run after full resolution and
|
|
5381
|
+
* before the action handler, with typed args, flags, provenance, and current
|
|
5382
|
+
* context plus `out` and `meta`.
|
|
5383
|
+
*/
|
|
5384
|
+
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>;
|
|
5385
|
+
/**
|
|
5386
|
+
* Command-scoped typed pre-action handler.
|
|
5530
5387
|
*
|
|
5531
|
-
*
|
|
5388
|
+
* Derive handlers may:
|
|
5389
|
+
* - validate resolved input and throw {@linkcode CLIError}
|
|
5390
|
+
* - return nothing (or `undefined`) to continue without changing context
|
|
5391
|
+
* - return an object whose properties merge into `ctx` downstream
|
|
5392
|
+
*
|
|
5393
|
+
* Handlers may be async; the resolved value follows the same rules.
|
|
5394
|
+
* They cannot wrap downstream execution; use {@linkcode middleware} for that.
|
|
5532
5395
|
*/
|
|
5533
|
-
|
|
5396
|
+
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> | void | Promise<void>;
|
|
5397
|
+
/**
|
|
5398
|
+
* Type-erased derive handler stored on the command builder.
|
|
5399
|
+
*/
|
|
5400
|
+
type ErasedDeriveHandler = (params: {
|
|
5401
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
5402
|
+
readonly flags: Readonly<Record<string, unknown>>;
|
|
5403
|
+
readonly sources: ErasedInputSources;
|
|
5404
|
+
readonly ctx: Readonly<Record<string, unknown>>;
|
|
5405
|
+
readonly out: Out;
|
|
5406
|
+
/** Ask a typed question after selecting the operation or receiving a server challenge. */
|
|
5407
|
+
readonly ask: Ask;
|
|
5408
|
+
readonly meta: CommandMeta;
|
|
5409
|
+
}) => undefined | Readonly<Record<string, unknown>> | Promise<undefined | Readonly<Record<string, unknown>>>;
|
|
5410
|
+
/**
|
|
5411
|
+
* Internal execution step union preserving registration order across
|
|
5412
|
+
* {@linkcode CommandBuilder.derive | derive()} and {@linkcode CommandBuilder.middleware | middleware()}.
|
|
5413
|
+
*/
|
|
5414
|
+
type ExecutionStep = {
|
|
5415
|
+
readonly kind: 'derive';
|
|
5416
|
+
readonly handler: ErasedDeriveHandler;
|
|
5417
|
+
} | {
|
|
5418
|
+
readonly kind: 'middleware';
|
|
5419
|
+
readonly handler: ErasedMiddlewareHandler;
|
|
5420
|
+
};
|
|
5421
|
+
/**
|
|
5422
|
+
* Program metadata passed to a function-form example, resolved at render time.
|
|
5423
|
+
*
|
|
5424
|
+
* `name` is the actually-invoked program name (`options.help.binName`, falling
|
|
5425
|
+
* back to the command name) so examples stay truthful under symlinks,
|
|
5426
|
+
* `inheritName`, and `npx x` vs a global install. `version` is the program
|
|
5427
|
+
* version, or `undefined` when none is configured.
|
|
5428
|
+
*/
|
|
5429
|
+
interface ExampleMeta {
|
|
5430
|
+
readonly name: string;
|
|
5431
|
+
readonly version: string | undefined;
|
|
5432
|
+
}
|
|
5433
|
+
/**
|
|
5434
|
+
* An example command line: a literal string, or a function resolved at render
|
|
5435
|
+
* time with the program {@link ExampleMeta} (so the program name need not be
|
|
5436
|
+
* hardcoded).
|
|
5437
|
+
*/
|
|
5438
|
+
type ExampleCommand = string | ((meta: ExampleMeta) => string);
|
|
5439
|
+
/** A single usage example shown in help text. */
|
|
5440
|
+
interface CommandExample {
|
|
5441
|
+
/** The command invocation (e.g. `'deploy production --force'`). */
|
|
5442
|
+
readonly command: ExampleCommand;
|
|
5443
|
+
/** Optional description of what this example does. */
|
|
5444
|
+
readonly description?: string;
|
|
5445
|
+
}
|
|
5446
|
+
/** Resolve an {@link ExampleCommand} to its string form for the given meta. */
|
|
5447
|
+
declare function resolveExampleCommand(command: ExampleCommand, meta: ExampleMeta): string;
|
|
5448
|
+
/**
|
|
5449
|
+
* Runtime descriptor produced by {@link CommandBuilder}.
|
|
5450
|
+
*
|
|
5451
|
+
* Consumers (parser, help generator, CLI dispatcher) read this to
|
|
5452
|
+
* understand the command's shape — flags, args, aliases, subcommands,
|
|
5453
|
+
* and interactive resolver.
|
|
5454
|
+
*/
|
|
5455
|
+
interface CommandSchema {
|
|
5456
|
+
/** Type-only seal produced by {@link createCommandSchema}. */
|
|
5457
|
+
readonly [schemaBrand]: 'command';
|
|
5458
|
+
/** The command name (used for dispatch, e.g. `'deploy'`). */
|
|
5459
|
+
readonly name: string;
|
|
5460
|
+
/** Human-readable description for help text. */
|
|
5461
|
+
readonly description: string | undefined;
|
|
5462
|
+
/** Longer explanation shown only in this command's help, with paragraphs wrapped to its width. */
|
|
5463
|
+
readonly details?: HelpDescription | undefined;
|
|
5464
|
+
/** Alternative names for this command. */
|
|
5465
|
+
readonly aliases: readonly string[];
|
|
5466
|
+
/** Whether this command is hidden from help listings. */
|
|
5467
|
+
readonly hidden: boolean;
|
|
5468
|
+
/** Usage examples for help text. */
|
|
5469
|
+
readonly examples: readonly CommandExample[];
|
|
5470
|
+
/** Named flag schemas, keyed by flag name. */
|
|
5471
|
+
readonly flags: Readonly<Record<string, FlagSchema>>;
|
|
5472
|
+
/** Flag declaration order when it differs from the flag record's key order. */
|
|
5473
|
+
readonly flagDeclarationOrder?: readonly string[] | undefined;
|
|
5474
|
+
/** Ordered positional arg entries (name + schema). */
|
|
5475
|
+
readonly args: readonly CommandArgEntry[];
|
|
5476
|
+
/** Relationships checked after input resolution. */
|
|
5477
|
+
readonly constraints?: readonly CommandConstraint[] | undefined;
|
|
5478
|
+
/** Object validators run after resolution. @internal */
|
|
5479
|
+
readonly validators?: readonly CommandValidator[] | undefined;
|
|
5480
|
+
/** Whether an action handler has been registered. */
|
|
5481
|
+
readonly hasAction: boolean;
|
|
5482
|
+
/**
|
|
5483
|
+
* Command-level interactive resolver for schema-driven prompt control.
|
|
5484
|
+
*
|
|
5485
|
+
* When set, called after CLI/env/config resolution with partially resolved
|
|
5486
|
+
* flag values. Returns prompt configs for flags that need interactive input.
|
|
5487
|
+
* Takes precedence over per-flag `.prompt()` configs for flags it returns
|
|
5488
|
+
* configs for; flags not mentioned fall back to their per-flag configs.
|
|
5489
|
+
*
|
|
5490
|
+
* @see InteractiveResolver
|
|
5491
|
+
*/
|
|
5492
|
+
readonly interactive: ErasedInteractiveResolver | undefined;
|
|
5493
|
+
/**
|
|
5494
|
+
* Nested subcommand schemas (for help rendering and completion).
|
|
5495
|
+
*
|
|
5496
|
+
* Pure data — no execution closures. Populated by `.command()` on
|
|
5497
|
+
* `CommandBuilder`. Empty for leaf commands.
|
|
5498
|
+
*/
|
|
5499
|
+
readonly commands: readonly CommandSchema[];
|
|
5500
|
+
}
|
|
5534
5501
|
/**
|
|
5535
|
-
* A
|
|
5502
|
+
* A named positional argument entry in the command schema.
|
|
5536
5503
|
*
|
|
5537
|
-
*
|
|
5538
|
-
*
|
|
5504
|
+
* Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
|
|
5505
|
+
* The array ordering in {@link CommandSchema.args} determines CLI position.
|
|
5539
5506
|
*/
|
|
5540
|
-
interface
|
|
5541
|
-
/**
|
|
5542
|
-
readonly
|
|
5543
|
-
/**
|
|
5544
|
-
readonly
|
|
5545
|
-
/** Non-empty list of selectable options (populated from flag enum values when omitted). */
|
|
5546
|
-
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
5507
|
+
interface CommandArgEntry {
|
|
5508
|
+
/** User-facing argument name (shown in help as `<name>`). */
|
|
5509
|
+
readonly name: string;
|
|
5510
|
+
/** Runtime descriptor controlling parsing, presence, and coercion. */
|
|
5511
|
+
readonly schema: ArgSchema;
|
|
5547
5512
|
}
|
|
5548
5513
|
/**
|
|
5549
|
-
* A
|
|
5514
|
+
* A named positional argument entry accepted by {@link createCommandSchema}.
|
|
5550
5515
|
*
|
|
5551
|
-
*
|
|
5552
|
-
* present and non-empty.
|
|
5516
|
+
* The schema may be an {@link ArgDefinition} or an already-built {@link ArgSchema}.
|
|
5553
5517
|
*/
|
|
5554
|
-
interface
|
|
5555
|
-
/**
|
|
5556
|
-
readonly
|
|
5557
|
-
/**
|
|
5558
|
-
readonly
|
|
5559
|
-
/** Non-empty list of selectable options (populated from flag enum values when omitted). */
|
|
5560
|
-
readonly choices: readonly [SelectChoice, ...SelectChoice[]];
|
|
5561
|
-
/** Minimum number of selections required (validated after input). */
|
|
5562
|
-
readonly min?: number;
|
|
5563
|
-
/** Maximum number of selections allowed (validated after input). */
|
|
5564
|
-
readonly max?: number;
|
|
5518
|
+
interface CommandArgEntryDefinition {
|
|
5519
|
+
/** User-facing argument name (shown in help as `<name>`). */
|
|
5520
|
+
readonly name: string;
|
|
5521
|
+
/** Arg definition or an already-built schema. */
|
|
5522
|
+
readonly schema: ArgDefinition | ArgSchema;
|
|
5565
5523
|
}
|
|
5566
5524
|
/**
|
|
5567
|
-
*
|
|
5568
|
-
* present. The prompt engine receives this (not raw {@linkcode PromptConfig}),
|
|
5569
|
-
* so it never needs to merge enum values from `FlagSchema`.
|
|
5525
|
+
* Input shape accepted by {@link createCommandSchema}.
|
|
5570
5526
|
*
|
|
5571
|
-
*
|
|
5527
|
+
* Every field except `name` is optional. Flags, args, and subcommands accept
|
|
5528
|
+
* either definitions or already-built schemas.
|
|
5572
5529
|
*/
|
|
5573
|
-
|
|
5530
|
+
interface CommandDefinition {
|
|
5531
|
+
/** The command name used for dispatch. */
|
|
5532
|
+
readonly name: string;
|
|
5533
|
+
/**
|
|
5534
|
+
* Human-readable description for help text.
|
|
5535
|
+
* @defaultValue `undefined`
|
|
5536
|
+
*/
|
|
5537
|
+
readonly description?: string | undefined;
|
|
5538
|
+
/** Longer explanation shown only in this command's help. */
|
|
5539
|
+
readonly details?: HelpDescription | undefined;
|
|
5540
|
+
/**
|
|
5541
|
+
* Alternative names for this command.
|
|
5542
|
+
* @defaultValue `[]`
|
|
5543
|
+
*/
|
|
5544
|
+
readonly aliases?: readonly string[] | undefined;
|
|
5545
|
+
/**
|
|
5546
|
+
* Whether this command is hidden from help listings.
|
|
5547
|
+
* @defaultValue `false`
|
|
5548
|
+
*/
|
|
5549
|
+
readonly hidden?: boolean | undefined;
|
|
5550
|
+
/**
|
|
5551
|
+
* Usage examples for help text.
|
|
5552
|
+
* @defaultValue `[]`
|
|
5553
|
+
*/
|
|
5554
|
+
readonly examples?: readonly CommandExample[] | undefined;
|
|
5555
|
+
/**
|
|
5556
|
+
* Flag definitions or built schemas, keyed by flag name.
|
|
5557
|
+
* @defaultValue `{}`
|
|
5558
|
+
*/
|
|
5559
|
+
readonly flags?: Readonly<Record<string, FlagDefinition | FlagSchema>> | undefined;
|
|
5560
|
+
/** Explicit declaration order for named flags. Unlisted flags follow in record order. */
|
|
5561
|
+
readonly flagDeclarationOrder?: readonly string[] | undefined;
|
|
5562
|
+
/**
|
|
5563
|
+
* Ordered positional arg entries.
|
|
5564
|
+
* @defaultValue `[]`
|
|
5565
|
+
*/
|
|
5566
|
+
readonly args?: readonly CommandArgEntryDefinition[] | undefined;
|
|
5567
|
+
/** Relationships checked after input resolution. */
|
|
5568
|
+
readonly constraints?: readonly CommandConstraint[] | undefined;
|
|
5569
|
+
/** Object validators run after resolution. @internal */
|
|
5570
|
+
readonly validators?: readonly CommandValidator[] | undefined;
|
|
5571
|
+
/**
|
|
5572
|
+
* Whether an action handler has been registered.
|
|
5573
|
+
* @defaultValue `false`
|
|
5574
|
+
*/
|
|
5575
|
+
readonly hasAction?: boolean | undefined;
|
|
5576
|
+
/**
|
|
5577
|
+
* Command-level interactive resolver.
|
|
5578
|
+
* @defaultValue `undefined`
|
|
5579
|
+
*/
|
|
5580
|
+
readonly interactive?: ErasedInteractiveResolver | undefined;
|
|
5581
|
+
/**
|
|
5582
|
+
* Nested subcommand definitions or built schemas.
|
|
5583
|
+
* @defaultValue `[]`
|
|
5584
|
+
*/
|
|
5585
|
+
readonly commands?: readonly (CommandDefinition | CommandSchema)[] | undefined;
|
|
5586
|
+
}
|
|
5574
5587
|
/**
|
|
5575
|
-
*
|
|
5588
|
+
* Create a {@link CommandSchema} from a plain definition object.
|
|
5576
5589
|
*
|
|
5577
|
-
*
|
|
5578
|
-
*
|
|
5590
|
+
* Most consumers should prefer {@link command | command()}, which returns a
|
|
5591
|
+
* {@link CommandBuilder} with type inference. `createCommandSchema()` is the
|
|
5592
|
+
* low-level escape hatch for tooling that composes schemas as data.
|
|
5579
5593
|
*
|
|
5580
|
-
*
|
|
5581
|
-
*
|
|
5582
|
-
*
|
|
5594
|
+
* Flags, args, and subcommands are normalized recursively, so an already-built
|
|
5595
|
+
* schema fed back in produces a deep-equal schema.
|
|
5596
|
+
*
|
|
5597
|
+
* Flag spellings are checked across the whole tree, so a definition whose names,
|
|
5598
|
+
* aliases, or negated spellings collide with each other or with a propagated
|
|
5599
|
+
* ancestor flag is rejected here. Both flags still parse under their canonical
|
|
5600
|
+
* names, so what a collision costs is the shared spelling. Help advertises it on
|
|
5601
|
+
* both flags and the parser answers it with one of them.
|
|
5602
|
+
* Args go through the same invariants {@link CommandBuilder.arg} enforces.
|
|
5603
|
+
* These are the checks the {@link CommandBuilder} applies as flags, args, and
|
|
5604
|
+
* subcommands are registered.
|
|
5605
|
+
*
|
|
5606
|
+
* @param definition - Command name plus optional flags, args, and subcommands.
|
|
5607
|
+
* @returns A fully populated {@link CommandSchema}.
|
|
5608
|
+
* @throws {CLIError} With code `'INVALID_SCHEMA'` when a name at any depth is
|
|
5609
|
+
* empty or contains whitespace, a flag or arg at any depth is named
|
|
5610
|
+
* `__proto__`, which JavaScript cannot carry as a plain record key, or a flag
|
|
5611
|
+
* record at any depth has a
|
|
5612
|
+
* replaced prototype, which hides the entries a name check would read.
|
|
5613
|
+
* @throws {CLIError} With code `'FLAG_NAME_COLLISION'` when two flags on one
|
|
5614
|
+
* command share a spelling.
|
|
5615
|
+
* @throws {CLIError} With code `'PROPAGATED_FLAG_COLLISION'` when a flag shadows
|
|
5616
|
+
* a spelling propagated from an ancestor command.
|
|
5617
|
+
* @throws {CLIError} With code `'INVALID_BUILDER_STATE'` when a positional comes
|
|
5618
|
+
* after a variadic one, or `'DUPLICATE_STDIN_INPUT'` when two inputs on one
|
|
5619
|
+
* command consume stdin and either is exclusive.
|
|
5583
5620
|
*
|
|
5584
5621
|
* @example
|
|
5585
5622
|
* ```ts
|
|
5586
|
-
*
|
|
5587
|
-
*
|
|
5588
|
-
*
|
|
5589
|
-
*
|
|
5590
|
-
*
|
|
5591
|
-
*
|
|
5592
|
-
* };
|
|
5623
|
+
* const schema = createCommandSchema({
|
|
5624
|
+
* name: 'deploy',
|
|
5625
|
+
* description: 'Ship the build',
|
|
5626
|
+
* flags: { force: { kind: 'boolean' } },
|
|
5627
|
+
* args: [{ name: 'target', schema: { kind: 'string' } }],
|
|
5628
|
+
* });
|
|
5593
5629
|
* ```
|
|
5594
5630
|
*/
|
|
5595
|
-
|
|
5596
|
-
/**
|
|
5597
|
-
* Present a single prompt and return the user's response.
|
|
5598
|
-
*
|
|
5599
|
-
* @param config - The resolved prompt configuration (choices guaranteed
|
|
5600
|
-
* for select/multiselect).
|
|
5601
|
-
* @returns The user's answer, `{ answered: false }` if cancelled, or
|
|
5602
|
-
* `{ answered: false, reason: 'invalid' }` when invalid attempts are exhausted.
|
|
5603
|
-
*/
|
|
5604
|
-
promptOne(config: ResolvedPromptConfig): Promise<PromptResult>;
|
|
5605
|
-
}
|
|
5606
|
-
/**
|
|
5607
|
-
* A function that reads a single line of user input.
|
|
5608
|
-
*
|
|
5609
|
-
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
5610
|
-
* indicating the user closed the input stream (treated as cancel).
|
|
5611
|
-
*
|
|
5612
|
-
* The terminal prompter uses this as its sole input seam. The
|
|
5613
|
-
* resolution chain (prompt-adapter-1) will wire this to the
|
|
5614
|
-
* runtime adapter's stdin.
|
|
5615
|
-
*/
|
|
5616
|
-
type ReadFn = () => Promise<string | null>;
|
|
5631
|
+
declare function createCommandSchema(definition: CommandDefinition): CommandSchema;
|
|
5617
5632
|
/**
|
|
5618
|
-
*
|
|
5619
|
-
* enum values from the flag schema.
|
|
5633
|
+
* Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
|
|
5620
5634
|
*
|
|
5621
|
-
*
|
|
5622
|
-
*
|
|
5623
|
-
* are available.
|
|
5635
|
+
* Advanced helper alias: useful only when working on DreamCLI internals or
|
|
5636
|
+
* custom tooling that mirrors the framework's type-erasure boundary.
|
|
5624
5637
|
*
|
|
5625
|
-
*
|
|
5626
|
-
*
|
|
5638
|
+
* Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
|
|
5639
|
+
* assignable. The CLI layer's `compileCommand()` traverses these to build
|
|
5640
|
+
* the execution graph.
|
|
5627
5641
|
*
|
|
5628
|
-
* @param config - Raw prompt config from `FlagSchema.prompt`
|
|
5629
|
-
* @param enumValues - Optional enum values from `FlagSchema.enumValues`
|
|
5630
|
-
* @returns Resolved config with choices guaranteed for select kinds
|
|
5631
|
-
* @throws Error if select/multiselect has no choices and no enum values
|
|
5632
5642
|
*/
|
|
5633
|
-
|
|
5643
|
+
type AnyCommandBuilder = CommandBuilder<Record<string, FlagBuilder<FlagConfig>>, Record<string, ArgBuilder<ArgConfig>>, Record<string, unknown>>;
|
|
5644
|
+
/** Retain declared flag names for duplicate checks alongside an index signature. */
|
|
5645
|
+
type KnownFlags<F> = { [K in keyof F as string extends K ? never : number extends K ? never : K]: F[K]; };
|
|
5646
|
+
/** Generated names can carry any registered builder, while declared names keep their types. */
|
|
5647
|
+
type MergeFlags<F extends Record<string, FlagBuilder<FlagConfig>>, R extends Record<string, FlagBuilder<FlagConfig>>> = string extends keyof F | keyof R ? KnownFlags<F> & KnownFlags<R> & Record<string, F[keyof F] | R[keyof R]> : F & R;
|
|
5634
5648
|
/**
|
|
5635
|
-
*
|
|
5649
|
+
* Immutable command schema builder.
|
|
5636
5650
|
*
|
|
5637
|
-
*
|
|
5638
|
-
*
|
|
5639
|
-
*
|
|
5640
|
-
*
|
|
5651
|
+
* The type parameters `F` (flags), `A` (args), and `C` (context) are
|
|
5652
|
+
* phantom types that accumulate builder types as `.flag()`, `.arg()`,
|
|
5653
|
+
* `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
|
|
5654
|
+
* fully typed `ActionParams<F, A, C>`.
|
|
5641
5655
|
*
|
|
5642
|
-
*
|
|
5643
|
-
*
|
|
5644
|
-
* - **Minimal:** only the operations the framework actually needs
|
|
5645
|
-
* - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
|
|
5656
|
+
* `C` defaults to `Record<string, never>`, making `ctx` property
|
|
5657
|
+
* access a type error until derive or middleware extends it.
|
|
5646
5658
|
*
|
|
5647
5659
|
* @example
|
|
5648
5660
|
* ```ts
|
|
5649
|
-
*
|
|
5650
|
-
*
|
|
5651
|
-
*
|
|
5652
|
-
*
|
|
5653
|
-
*
|
|
5661
|
+
* const deploy = command('deploy')
|
|
5662
|
+
* .description('Deploy to an environment')
|
|
5663
|
+
* .arg('target', arg.string().describe('Deploy target'))
|
|
5664
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
5665
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
5666
|
+
* .action(async ({ args, flags, out }) => {
|
|
5667
|
+
* // args.target: string
|
|
5668
|
+
* // flags.force: boolean
|
|
5669
|
+
* // flags.region: 'us' | 'eu' | 'ap' | undefined
|
|
5670
|
+
* out.log(`Deploying ${args.target}...`);
|
|
5671
|
+
* });
|
|
5654
5672
|
* ```
|
|
5655
5673
|
*/
|
|
5656
|
-
|
|
5657
|
-
/**
|
|
5658
|
-
readonly
|
|
5659
|
-
/**
|
|
5660
|
-
|
|
5661
|
-
* Values are `string | undefined` — mirrors Node's `process.env` semantics.
|
|
5662
|
-
*/
|
|
5663
|
-
readonly env: Readonly<Record<string, string | undefined>>;
|
|
5664
|
-
/** Current working directory (absolute path). */
|
|
5665
|
-
readonly cwd: string;
|
|
5666
|
-
/** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
|
|
5667
|
-
readonly stdout: WriteFn;
|
|
5668
|
-
/** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
|
|
5669
|
-
readonly stderr: WriteFn;
|
|
5670
|
-
/** Wait for pending output writes to settle, rejecting with a recorded output failure. */
|
|
5671
|
-
readonly flush?: () => Promise<void>;
|
|
5674
|
+
declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> = {}, A extends Record<string, ArgBuilder<ArgConfig>> = {}, C extends Record<string, unknown> = Record<string, never>> {
|
|
5675
|
+
/** @internal Runtime schema descriptor. */
|
|
5676
|
+
readonly schema: CommandSchema;
|
|
5677
|
+
/** @internal The action handler, if registered (type-erased for covariance). */
|
|
5678
|
+
readonly handler: ErasedActionHandler | undefined;
|
|
5672
5679
|
/**
|
|
5673
|
-
*
|
|
5680
|
+
* @internal Nested sub-command builders (type-erased for heterogeneous storage).
|
|
5674
5681
|
*
|
|
5675
|
-
*
|
|
5676
|
-
*
|
|
5682
|
+
* Stored separately from `schema.commands` because builders carry action
|
|
5683
|
+
* handlers and phantom types needed by `compileCommand()` in the CLI layer.
|
|
5684
|
+
* `schema.commands` holds pure `CommandSchema[]` for help/completion.
|
|
5677
5685
|
*/
|
|
5678
|
-
readonly
|
|
5679
|
-
/** Hidden terminal input. Absent when echo suppression is unsupported. */
|
|
5680
|
-
readonly readSecret?: ReadFn;
|
|
5686
|
+
readonly _subcommands: readonly AnyCommandBuilder[];
|
|
5681
5687
|
/**
|
|
5682
|
-
*
|
|
5683
|
-
*
|
|
5684
|
-
* Returns the full stdin contents when data is piped (`stdinIsTTY` is
|
|
5685
|
-
* false), or `null` when stdin is a TTY (no piped data available).
|
|
5688
|
+
* @internal Derive and middleware steps in registration order.
|
|
5686
5689
|
*
|
|
5687
|
-
*
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
+
* The executor builds the handler chain from this list.
|
|
5691
|
+
*/
|
|
5692
|
+
readonly _executionSteps: readonly ExecutionStep[];
|
|
5693
|
+
/** @internal Phantom brand for accumulated flag builder types. No runtime value. */
|
|
5694
|
+
readonly _flags: F;
|
|
5695
|
+
/** @internal Phantom brand for accumulated arg builder types. No runtime value. */
|
|
5696
|
+
readonly _args: A;
|
|
5697
|
+
/** @internal Phantom brand for accumulated context type. No runtime value. */
|
|
5698
|
+
readonly _ctx: C;
|
|
5699
|
+
/**
|
|
5700
|
+
* Create a command builder from a pre-built schema descriptor.
|
|
5690
5701
|
*
|
|
5691
|
-
* @
|
|
5702
|
+
* @param schema - Runtime command descriptor.
|
|
5703
|
+
* @param handler - Action handler, if registered.
|
|
5704
|
+
* @param subcommands - Nested sub-command builders (type-erased).
|
|
5705
|
+
* @param executionSteps - Derive/middleware steps in registration order.
|
|
5692
5706
|
*/
|
|
5693
|
-
|
|
5694
|
-
/** Whether stdout is connected to a TTY. */
|
|
5695
|
-
readonly isTTY: boolean;
|
|
5696
|
-
/** Whether stdin is connected to a TTY (used for prompt gating). */
|
|
5697
|
-
readonly stdinIsTTY: boolean;
|
|
5698
|
-
/** Read current terminal dimensions for stdout, if available. */
|
|
5699
|
-
readonly getTerminalSize: () => TerminalSize | undefined;
|
|
5700
|
-
/** Subscribe to terminal resize events when the runtime supports them. */
|
|
5701
|
-
readonly onTerminalResize: (listener: () => void) => (() => void) | undefined;
|
|
5707
|
+
constructor(schema: CommandSchema, handler?: ErasedActionHandler, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);
|
|
5702
5708
|
/**
|
|
5703
|
-
*
|
|
5704
|
-
*
|
|
5709
|
+
* Declare typed relationships between already-resolved flags and arguments.
|
|
5710
|
+
* A bare name selects a flag when both kinds use the same name.
|
|
5705
5711
|
*/
|
|
5706
|
-
|
|
5712
|
+
constrain(build: (builder: ConstraintBuilder<Extract<keyof F, string>, Extract<keyof A, string>>) => readonly CommandConstraint[]): CommandBuilder<F, A, C>;
|
|
5707
5713
|
/**
|
|
5708
|
-
*
|
|
5709
|
-
*
|
|
5710
|
-
*
|
|
5711
|
-
* (ENOENT/NotFound). Throws on other I/O errors (permission denied,
|
|
5712
|
-
* is-directory, etc.) — those indicate unexpected failures, not
|
|
5713
|
-
* "try the next path".
|
|
5714
|
-
*
|
|
5715
|
-
* Used by config file discovery to probe multiple candidate paths.
|
|
5714
|
+
* Validate the resolved flags using Standard Schema. Pass `{ input: 'resolved' }`
|
|
5715
|
+
* to validate an object containing flags, arguments, and their provenance.
|
|
5716
|
+
* The validator's output is discarded.
|
|
5716
5717
|
*/
|
|
5717
|
-
|
|
5718
|
+
validate(validator: StandardSchemaV1, options?: CommandValidationOptions): CommandBuilder<F, A, C>;
|
|
5718
5719
|
/**
|
|
5719
|
-
*
|
|
5720
|
+
* Register a command-level interactive resolver for schema-driven prompts.
|
|
5720
5721
|
*
|
|
5721
|
-
*
|
|
5722
|
-
*
|
|
5722
|
+
* The resolver is called after CLI/env/config resolution with partially
|
|
5723
|
+
* resolved flag values. It returns a prompt schema for flags that need
|
|
5724
|
+
* interactive input based on the current state.
|
|
5723
5725
|
*
|
|
5724
|
-
*
|
|
5725
|
-
|
|
5726
|
-
|
|
5727
|
-
/**
|
|
5728
|
-
* Create a directory, including missing parents.
|
|
5726
|
+
* For flags the resolver returns a {@linkcode PromptConfig}, that config is used
|
|
5727
|
+
* instead of any per-flag `.prompt()` config. For flags returned as falsy
|
|
5728
|
+
* (or not mentioned), per-flag `.prompt()` configs are used as fallback.
|
|
5729
5729
|
*
|
|
5730
|
-
*
|
|
5731
|
-
* (permission denied, existing file at the path, etc.).
|
|
5730
|
+
* Commands without `.interactive()` use per-flag prompt configs directly.
|
|
5732
5731
|
*
|
|
5733
|
-
*
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
*
|
|
5732
|
+
* @example
|
|
5733
|
+
* ```ts
|
|
5734
|
+
* const deploy = command('deploy')
|
|
5735
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']))
|
|
5736
|
+
* .flag('force', flag.boolean())
|
|
5737
|
+
* .interactive(({ flags }) => ({
|
|
5738
|
+
* region: !flags.region && {
|
|
5739
|
+
* kind: 'select',
|
|
5740
|
+
* message: 'Select region',
|
|
5741
|
+
* },
|
|
5742
|
+
* }))
|
|
5743
|
+
* .action(({ flags }) => { ... });
|
|
5744
|
+
* ```
|
|
5738
5745
|
*
|
|
5739
|
-
* -
|
|
5740
|
-
*
|
|
5746
|
+
* @param resolver - Function receiving partially resolved flags and returning prompt configs.
|
|
5747
|
+
* @returns The builder (for chaining).
|
|
5741
5748
|
*/
|
|
5742
|
-
|
|
5749
|
+
interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;
|
|
5743
5750
|
/**
|
|
5744
|
-
*
|
|
5751
|
+
* Register a command-scoped typed pre-action handler.
|
|
5745
5752
|
*
|
|
5746
|
-
*
|
|
5747
|
-
*
|
|
5753
|
+
* Derive runs after full resolution and before the action handler.
|
|
5754
|
+
* It receives typed `{ args, flags, ctx, out, meta }` and may either:
|
|
5748
5755
|
*
|
|
5749
|
-
*
|
|
5756
|
+
* - return nothing (or `undefined`) for validation-only behavior
|
|
5757
|
+
* - return an object to merge additional properties into `ctx`
|
|
5758
|
+
*
|
|
5759
|
+
* Handlers may be async — the runtime awaits them before continuing.
|
|
5760
|
+
*
|
|
5761
|
+
* Unlike middleware, derive cannot wrap downstream execution and does not
|
|
5762
|
+
* use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
|
|
5763
|
+
* or error-boundary patterns.
|
|
5764
|
+
*
|
|
5765
|
+
* Adding derive drops the current handler (like `.flag()`, `.arg()`, and
|
|
5766
|
+
* `.middleware()`) because the action handler's `ctx` type may change.
|
|
5767
|
+
*
|
|
5768
|
+
* @example
|
|
5769
|
+
* ```ts
|
|
5770
|
+
* command('deploy')
|
|
5771
|
+
* .flag('token', flag.string().env('AUTH_TOKEN'))
|
|
5772
|
+
* .derive(({ flags }) => {
|
|
5773
|
+
* if (!flags.token) {
|
|
5774
|
+
* throw new CLIError('Not authenticated', {
|
|
5775
|
+
* code: 'AUTH_REQUIRED',
|
|
5776
|
+
* suggest: 'Run `mycli login` or set AUTH_TOKEN',
|
|
5777
|
+
* });
|
|
5778
|
+
* }
|
|
5779
|
+
* return { token: flags.token };
|
|
5780
|
+
* })
|
|
5781
|
+
* .action(({ ctx }) => {
|
|
5782
|
+
* ctx.token; // string
|
|
5783
|
+
* });
|
|
5784
|
+
* ```
|
|
5785
|
+
*
|
|
5786
|
+
* @param handler - Derive function receiving typed args/flags/ctx.
|
|
5787
|
+
* @returns The builder (for chaining).
|
|
5750
5788
|
*/
|
|
5751
|
-
|
|
5789
|
+
derive<Output extends Record<string, unknown> | undefined = undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;
|
|
5752
5790
|
/**
|
|
5753
|
-
*
|
|
5791
|
+
* Register middleware to run before the action handler.
|
|
5754
5792
|
*
|
|
5755
|
-
*
|
|
5756
|
-
*
|
|
5757
|
-
*
|
|
5793
|
+
* Middleware executes in registration order. Each middleware receives
|
|
5794
|
+
* `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
|
|
5795
|
+
* to continue the chain. Context additions are merged and become
|
|
5796
|
+
* typed downstream.
|
|
5758
5797
|
*
|
|
5759
|
-
*
|
|
5798
|
+
* Adding middleware widens `C` via intersection and drops the current
|
|
5799
|
+
* handler (like `.flag()` / `.arg()` — the handler's type signature
|
|
5800
|
+
* changes when context changes).
|
|
5801
|
+
*
|
|
5802
|
+
* @example
|
|
5803
|
+
* ```ts
|
|
5804
|
+
* import { CLIError, command, middleware } from '@kjanat/dreamcli';
|
|
5805
|
+
*
|
|
5806
|
+
* interface User {
|
|
5807
|
+
* id: string;
|
|
5808
|
+
* email: string;
|
|
5809
|
+
* }
|
|
5810
|
+
*
|
|
5811
|
+
* async function getCurrentUser(): Promise<User | null> {
|
|
5812
|
+
* return { id: 'u_123', email: 'dev@example.com' };
|
|
5813
|
+
* }
|
|
5814
|
+
*
|
|
5815
|
+
* function startTrace(name: string): string {
|
|
5816
|
+
* return `trace:${name}`;
|
|
5817
|
+
* }
|
|
5818
|
+
*
|
|
5819
|
+
* // Resolve the current user and expose it as `ctx.user` downstream.
|
|
5820
|
+
* const auth = middleware<{ user: User }>(async ({ next }) => {
|
|
5821
|
+
* const user = await getCurrentUser();
|
|
5822
|
+
* if (!user) {
|
|
5823
|
+
* throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
5824
|
+
* }
|
|
5825
|
+
* await next({ user });
|
|
5826
|
+
* });
|
|
5827
|
+
*
|
|
5828
|
+
* // Create a trace id for this command run and expose it as `ctx.traceId`.
|
|
5829
|
+
* const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
|
|
5830
|
+
* const traceId = startTrace(`${meta.name}.${meta.command}`);
|
|
5831
|
+
* await next({ traceId });
|
|
5832
|
+
* });
|
|
5833
|
+
*
|
|
5834
|
+
* command('deploy')
|
|
5835
|
+
* .middleware(auth) // C becomes { user: User }
|
|
5836
|
+
* .middleware(telemetry) // C becomes { user: User } & { traceId: string }
|
|
5837
|
+
* .action(({ ctx }) => {
|
|
5838
|
+
* ctx.user; // User — typed
|
|
5839
|
+
* ctx.traceId; // string — typed
|
|
5840
|
+
* });
|
|
5841
|
+
* ```
|
|
5842
|
+
*
|
|
5843
|
+
* @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
|
|
5844
|
+
* Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
|
|
5845
|
+
* @returns The builder (for chaining).
|
|
5760
5846
|
*/
|
|
5761
|
-
|
|
5847
|
+
middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;
|
|
5762
5848
|
/**
|
|
5763
|
-
*
|
|
5764
|
-
*
|
|
5849
|
+
* Set the command's description for help text.
|
|
5850
|
+
*
|
|
5851
|
+
* Displayed below the usage line in `--help` output and next to the
|
|
5852
|
+
* command name in parent command/group help listings.
|
|
5853
|
+
*
|
|
5854
|
+
* @param text - One-line description of what the command does.
|
|
5855
|
+
*
|
|
5856
|
+
* @example
|
|
5857
|
+
* ```ts
|
|
5858
|
+
* command('deploy')
|
|
5859
|
+
* .description('Deploy the application to a target environment')
|
|
5860
|
+
* .action(({ out }) => { out.log('deploying...'); });
|
|
5861
|
+
*
|
|
5862
|
+
* // $ mycli deploy --help
|
|
5863
|
+
* // Usage: deploy [flags]
|
|
5864
|
+
* //
|
|
5865
|
+
* // Deploy the application to a target environment
|
|
5866
|
+
* ```
|
|
5867
|
+
*
|
|
5868
|
+
* @returns The builder (for chaining).
|
|
5765
5869
|
*/
|
|
5766
|
-
|
|
5767
|
-
}
|
|
5768
|
-
/** Current terminal dimensions in columns and rows. */
|
|
5769
|
-
interface TerminalSize {
|
|
5770
|
-
/** Terminal width in columns. */
|
|
5771
|
-
readonly columns: number;
|
|
5772
|
-
/** Terminal height in rows. */
|
|
5773
|
-
readonly rows: number;
|
|
5774
|
-
}
|
|
5775
|
-
/**
|
|
5776
|
-
* Options for creating a test adapter.
|
|
5777
|
-
*
|
|
5778
|
-
* All fields are optional — sensible defaults are applied for testing
|
|
5779
|
-
* scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
|
|
5780
|
-
* throws instead of killing the process).
|
|
5781
|
-
*/
|
|
5782
|
-
interface TestAdapterOptions {
|
|
5783
|
-
/** Raw argv (defaults to `['node', 'test']`). */
|
|
5784
|
-
readonly argv?: readonly string[];
|
|
5785
|
-
/** Environment variables (defaults to `{}`). */
|
|
5786
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
5787
|
-
/** Working directory (defaults to `'/test'`). */
|
|
5788
|
-
readonly cwd?: string;
|
|
5789
|
-
/** Stdout writer (defaults to noop). */
|
|
5790
|
-
readonly stdout?: WriteFn;
|
|
5791
|
-
/** Stderr writer (defaults to noop). */
|
|
5792
|
-
readonly stderr?: WriteFn;
|
|
5870
|
+
description(text: string): CommandBuilder<F, A, C>;
|
|
5793
5871
|
/**
|
|
5794
|
-
*
|
|
5872
|
+
* Add a longer explanation to this command's help.
|
|
5873
|
+
*
|
|
5874
|
+
* Paragraphs wrap to the help width. Parent command listings use only
|
|
5875
|
+
* `.description()`. A function receives the current help description theme.
|
|
5795
5876
|
*
|
|
5796
|
-
*
|
|
5877
|
+
* @param text - Literal text or a function that styles the explanation.
|
|
5878
|
+
* @returns A new builder with the explanation.
|
|
5797
5879
|
*/
|
|
5798
|
-
|
|
5799
|
-
/** Hidden reader stub; omitted adapters report unsupported hidden input. */
|
|
5800
|
-
readonly readSecret?: ReadFn;
|
|
5880
|
+
details(text: HelpDescription): CommandBuilder<F, A, C>;
|
|
5801
5881
|
/**
|
|
5802
|
-
*
|
|
5882
|
+
* Add an alternative name for this command.
|
|
5803
5883
|
*
|
|
5804
|
-
*
|
|
5805
|
-
*
|
|
5806
|
-
*
|
|
5884
|
+
* Aliases are accepted during dispatch alongside the primary name.
|
|
5885
|
+
* Multiple aliases can be chained. Aliases are shown in help output.
|
|
5886
|
+
*
|
|
5887
|
+
* @param name - Alternative command name (e.g. `'d'` for `deploy`).
|
|
5807
5888
|
*
|
|
5808
5889
|
* @example
|
|
5809
5890
|
* ```ts
|
|
5810
|
-
*
|
|
5811
|
-
*
|
|
5812
|
-
*
|
|
5891
|
+
* command('deploy')
|
|
5892
|
+
* .alias('d')
|
|
5893
|
+
* .alias('push')
|
|
5894
|
+
* .action(({ out }) => { out.log('deploying...'); });
|
|
5895
|
+
*
|
|
5896
|
+
* // All equivalent:
|
|
5897
|
+
* // $ mycli deploy
|
|
5898
|
+
* // $ mycli d
|
|
5899
|
+
* // $ mycli push
|
|
5813
5900
|
* ```
|
|
5901
|
+
*
|
|
5902
|
+
* @returns The builder (for chaining).
|
|
5814
5903
|
*/
|
|
5815
|
-
|
|
5816
|
-
/** TTY flag for stdout (defaults to `false`). */
|
|
5817
|
-
readonly isTTY?: boolean;
|
|
5818
|
-
/** TTY flag for stdin (defaults to `false`). */
|
|
5819
|
-
readonly stdinIsTTY?: boolean;
|
|
5820
|
-
/** Terminal dimensions returned by `getTerminalSize()`. */
|
|
5821
|
-
readonly terminalSize?: TerminalSize;
|
|
5822
|
-
/** Resize subscription hook returned by `onTerminalResize()`. */
|
|
5823
|
-
readonly onTerminalResize?: (listener: () => void) => (() => void) | undefined;
|
|
5824
|
-
/**
|
|
5825
|
-
* Exit function (defaults to throwing {@linkcode ExitError}).
|
|
5826
|
-
* The default throw-based exit allows tests to catch the exit code.
|
|
5827
|
-
*/
|
|
5828
|
-
readonly exit?: (code: number) => never;
|
|
5904
|
+
alias(name: string): CommandBuilder<F, A, C>;
|
|
5829
5905
|
/**
|
|
5830
|
-
*
|
|
5906
|
+
* Hide this command from help listings.
|
|
5831
5907
|
*
|
|
5832
|
-
*
|
|
5908
|
+
* The command remains fully functional and dispatchable — it just
|
|
5909
|
+
* won't appear in `--help` output or shell completions. Useful for
|
|
5910
|
+
* internal/debug commands.
|
|
5911
|
+
*
|
|
5912
|
+
* @example
|
|
5833
5913
|
* ```ts
|
|
5834
|
-
*
|
|
5835
|
-
*
|
|
5836
|
-
*
|
|
5837
|
-
*
|
|
5838
|
-
*
|
|
5839
|
-
*
|
|
5840
|
-
* })
|
|
5914
|
+
* command('debug-dump')
|
|
5915
|
+
* .hidden()
|
|
5916
|
+
* .action(({ out }) => { out.log(JSON.stringify(internalState)); });
|
|
5917
|
+
*
|
|
5918
|
+
* // $ mycli --help → 'debug-dump' is not listed
|
|
5919
|
+
* // $ mycli debug-dump → still works
|
|
5841
5920
|
* ```
|
|
5921
|
+
*
|
|
5922
|
+
* @returns The builder (for chaining).
|
|
5842
5923
|
*/
|
|
5843
|
-
|
|
5924
|
+
hidden(): CommandBuilder<F, A, C>;
|
|
5844
5925
|
/**
|
|
5845
|
-
*
|
|
5846
|
-
* `null` — nothing exists).
|
|
5926
|
+
* Add a usage example to help text.
|
|
5847
5927
|
*
|
|
5848
|
-
*
|
|
5928
|
+
* Examples are rendered in the "Examples:" section of `--help` output.
|
|
5929
|
+
* Call multiple times to add several examples. Each example shows a
|
|
5930
|
+
* shell invocation, optionally with a description.
|
|
5931
|
+
*
|
|
5932
|
+
* `cmd` may be a literal string or a function receiving the program
|
|
5933
|
+
* {@link ExampleMeta} (`name`, `version`), resolved at render time. Use the
|
|
5934
|
+
* function form to reference the invoked program name instead of hardcoding
|
|
5935
|
+
* it, so examples stay truthful under symlinks, `inheritName`, and
|
|
5936
|
+
* `npx x` vs a global install.
|
|
5937
|
+
*
|
|
5938
|
+
* @param cmd - The example command line, or a `(meta) => string` builder.
|
|
5939
|
+
* @param description - Optional one-line explanation of what the example does.
|
|
5940
|
+
*
|
|
5941
|
+
* @example
|
|
5849
5942
|
* ```ts
|
|
5850
|
-
*
|
|
5851
|
-
*
|
|
5852
|
-
*
|
|
5943
|
+
* command('deploy')
|
|
5944
|
+
* .arg('target', arg.string())
|
|
5945
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
5946
|
+
* .example('deploy production', 'Deploy to production')
|
|
5947
|
+
* .example((m) => `${m.name} deploy staging -f`, 'Force deploy to staging')
|
|
5948
|
+
* .action(({ args, flags }) => { ... });
|
|
5949
|
+
*
|
|
5950
|
+
* // $ mycli deploy --help
|
|
5951
|
+
* // ...
|
|
5952
|
+
* // Examples:
|
|
5953
|
+
* // deploy production Deploy to production
|
|
5954
|
+
* // mycli deploy staging -f Force deploy to staging
|
|
5853
5955
|
* ```
|
|
5956
|
+
*
|
|
5957
|
+
* @returns The builder (for chaining).
|
|
5854
5958
|
*/
|
|
5855
|
-
|
|
5856
|
-
/**
|
|
5857
|
-
* Directory creation stub for `flag.path()` `create` checks (defaults to
|
|
5858
|
-
* a noop that resolves without creating anything).
|
|
5859
|
-
*/
|
|
5860
|
-
readonly mkdir?: (path: string) => Promise<void>;
|
|
5861
|
-
/** Home directory (defaults to `'/home/test'`). */
|
|
5862
|
-
readonly homedir?: string;
|
|
5863
|
-
/** Config directory (defaults to `'/home/test/.config'`). */
|
|
5864
|
-
readonly configDir?: string;
|
|
5865
|
-
/** User-scope config roots for discovery (defaults to `[configDir]`). */
|
|
5866
|
-
readonly userConfigDirs?: readonly string[];
|
|
5867
|
-
/** System-scope config roots for discovery (defaults to `[]`). */
|
|
5868
|
-
readonly systemConfigDirs?: readonly string[];
|
|
5869
|
-
}
|
|
5870
|
-
/**
|
|
5871
|
-
* Error thrown by adapter implementations that model process exit as an
|
|
5872
|
-
* exception instead of terminating immediately.
|
|
5873
|
-
*
|
|
5874
|
-
* Runtime and CLI dispatch layers can catch this to perform real process
|
|
5875
|
-
* termination, while tests can assert on exit codes without killing the
|
|
5876
|
-
* runner:
|
|
5877
|
-
*
|
|
5878
|
-
* ```ts
|
|
5879
|
-
* try {
|
|
5880
|
-
* await cli.run({ adapter: createTestAdapter() });
|
|
5881
|
-
* } catch (e) {
|
|
5882
|
-
* if (e instanceof ExitError) expect(e.code).toBe(0);
|
|
5883
|
-
* }
|
|
5884
|
-
* ```
|
|
5885
|
-
*/
|
|
5886
|
-
declare class ExitError extends Error {
|
|
5887
|
-
/** Error name — always `'ExitError'` for `instanceof` checks. */
|
|
5888
|
-
readonly name = "ExitError";
|
|
5889
|
-
/** The exit code passed to `exit()`. */
|
|
5890
|
-
readonly code: number;
|
|
5891
|
-
/** Create an ExitError for the given process exit code. */
|
|
5892
|
-
constructor(code: number);
|
|
5893
|
-
}
|
|
5894
|
-
/**
|
|
5895
|
-
* Create a test runtime adapter with injectable process state.
|
|
5896
|
-
*
|
|
5897
|
-
* Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
|
|
5898
|
-
* environment variables, TTY state, stdin, or config-file reads without
|
|
5899
|
-
* touching the host process.
|
|
5900
|
-
*
|
|
5901
|
-
* @param options - Optional overrides for any adapter field.
|
|
5902
|
-
* @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
|
|
5903
|
-
*
|
|
5904
|
-
* @example
|
|
5905
|
-
* ```ts
|
|
5906
|
-
* const adapter = createTestAdapter({
|
|
5907
|
-
* argv: ['node', 'cli.js', 'deploy', '--force'],
|
|
5908
|
-
* env: { DEPLOY_REGION: 'us' },
|
|
5909
|
-
* });
|
|
5910
|
-
*
|
|
5911
|
-
* const result = await cli('mycli').run({ adapter });
|
|
5912
|
-
* ```
|
|
5913
|
-
*/
|
|
5914
|
-
declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
|
|
5915
|
-
/**
|
|
5916
|
-
* Minimal I/O seam — the only write primitive the output module depends on.
|
|
5917
|
-
*
|
|
5918
|
-
* Extracted to its own file so that both `index.ts` (OutputChannel) and
|
|
5919
|
-
* `activity.ts` (handle classes) can import it without a circular dependency.
|
|
5920
|
-
*
|
|
5921
|
-
* @module dreamcli/core/output/writer
|
|
5922
|
-
*/
|
|
5923
|
-
/**
|
|
5924
|
-
* A function that writes a string somewhere.
|
|
5925
|
-
*
|
|
5926
|
-
* This is the only write primitive the output layer depends on.
|
|
5927
|
-
* In production it usually wraps `process.stdout.write` or
|
|
5928
|
-
* `process.stderr.write`; in tests it is often a simple string accumulator.
|
|
5929
|
-
*
|
|
5930
|
-
* The contract is intentionally tiny:
|
|
5931
|
-
* - writes are synchronous fire-and-forget
|
|
5932
|
-
* - callers decide whether to append a trailing newline
|
|
5933
|
-
* - there is no backpressure or flush signal
|
|
5934
|
-
*
|
|
5935
|
-
* @example
|
|
5936
|
-
* ```ts
|
|
5937
|
-
* const lines: string[] = [];
|
|
5938
|
-
* const write: WriteFn = (data) => {
|
|
5939
|
-
* lines.push(data);
|
|
5940
|
-
* };
|
|
5941
|
-
* ```
|
|
5942
|
-
*/
|
|
5943
|
-
type WriteFn = (data: string) => void;
|
|
5944
|
-
/**
|
|
5945
|
-
* Configuration for creating an output channel.
|
|
5946
|
-
*
|
|
5947
|
-
* Every field is optional — sensible defaults are applied when omitted.
|
|
5948
|
-
*/
|
|
5949
|
-
interface OutputOptions {
|
|
5950
|
-
/**
|
|
5951
|
-
* Writer for stdout-bound messages (`log`, `info`, `json`).
|
|
5952
|
-
* Defaults to `process.stdout.write` when running in Node/Bun.
|
|
5953
|
-
*/
|
|
5954
|
-
readonly stdout?: WriteFn;
|
|
5955
|
-
/**
|
|
5956
|
-
* Writer for stderr-bound messages (`warn`, `error`).
|
|
5957
|
-
* In JSON mode, `log` and `info` are also redirected here so that
|
|
5958
|
-
* stdout contains only structured JSON output.
|
|
5959
|
-
* Defaults to `process.stderr.write` when running in Node/Bun.
|
|
5960
|
-
*/
|
|
5961
|
-
readonly stderr?: WriteFn;
|
|
5962
|
-
/**
|
|
5963
|
-
* Whether stdout is connected to a TTY.
|
|
5964
|
-
* When `false`, output may omit ANSI codes and decorations.
|
|
5965
|
-
* Defaults to `false` (safe default — non-TTY until proven otherwise).
|
|
5966
|
-
*/
|
|
5967
|
-
readonly isTTY?: boolean;
|
|
5959
|
+
example(cmd: ExampleCommand, description?: string): CommandBuilder<F, A, C>;
|
|
5968
5960
|
/**
|
|
5969
|
-
*
|
|
5970
|
-
*
|
|
5971
|
-
*
|
|
5961
|
+
* Register a named flag on this command.
|
|
5962
|
+
*
|
|
5963
|
+
* The flag name is added to the type-level `F` map. Duplicate flag names
|
|
5964
|
+
* are prevented at the type level via the `Exclude` constraint.
|
|
5965
|
+
*
|
|
5966
|
+
* The builder controls the flag's type, presence, aliases, env/config
|
|
5967
|
+
* bindings, and description. See {@link FlagBuilder} for available modifiers.
|
|
5968
|
+
*
|
|
5969
|
+
* @param name - Flag name: the `--name` CLI token and the matching key on `flags`
|
|
5970
|
+
* in the handler. The name is preserved as-is (no camelCasing); read non-identifier
|
|
5971
|
+
* names such as `'dry-run'` with bracket access (`flags['dry-run']`).
|
|
5972
|
+
* @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
|
|
5973
|
+
* `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
|
|
5974
|
+
*
|
|
5975
|
+
* @example
|
|
5976
|
+
* ```ts
|
|
5977
|
+
* command('serve')
|
|
5978
|
+
* .flag('port', flag.number()
|
|
5979
|
+
* .alias('p')
|
|
5980
|
+
* .env('PORT')
|
|
5981
|
+
* .default(3000)
|
|
5982
|
+
* .describe('Port to listen on'))
|
|
5983
|
+
* .flag('host', flag.string()
|
|
5984
|
+
* .env('HOST')
|
|
5985
|
+
* .default('localhost')
|
|
5986
|
+
* .describe('Bind address'))
|
|
5987
|
+
* .flag('verbose', flag.boolean()
|
|
5988
|
+
* .alias('v')
|
|
5989
|
+
* .describe('Enable verbose logging'))
|
|
5990
|
+
* .action(({ flags, out }) => {
|
|
5991
|
+
* flags.port; // number
|
|
5992
|
+
* flags.host; // string
|
|
5993
|
+
* flags.verbose; // boolean
|
|
5994
|
+
* out.log(`Listening on ${flags.host}:${flags.port}`);
|
|
5995
|
+
* });
|
|
5996
|
+
*
|
|
5997
|
+
* // $ mycli serve --port 8080 -v
|
|
5998
|
+
* // $ PORT=9090 mycli serve
|
|
5999
|
+
* ```
|
|
6000
|
+
*
|
|
6001
|
+
* @returns The builder (for chaining).
|
|
6002
|
+
* @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
|
|
6003
|
+
* which a plain record cannot carry.
|
|
6004
|
+
* @throws {@link CLIError} `FLAG_NAME_COLLISION` when the command already
|
|
6005
|
+
* declares this name, or the new flag's spellings collide with another
|
|
6006
|
+
* flag's.
|
|
6007
|
+
* @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling
|
|
6008
|
+
* collides with one propagated to a registered subcommand.
|
|
5972
6009
|
*/
|
|
5973
|
-
|
|
6010
|
+
flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof KnownFlags<F>>, builder: B): CommandBuilder<MergeFlags<F, Record<N, B>>, A, C>;
|
|
5974
6011
|
/**
|
|
5975
|
-
*
|
|
5976
|
-
*
|
|
5977
|
-
*
|
|
6012
|
+
* Register a record of flags, preserving each own string key and inferred value type.
|
|
6013
|
+
*
|
|
6014
|
+
* Names and aliases must not collide with existing flags or other entries.
|
|
6015
|
+
* Literal names are checked by the compiler. Generated names are checked
|
|
6016
|
+
* at runtime, and their values include the registered flag value types.
|
|
6017
|
+
* Adding flags clears any previously registered action, like `.flag()`.
|
|
6018
|
+
*
|
|
6019
|
+
* @param record - Named flag builders to add to this command.
|
|
6020
|
+
* @returns A new builder with the added flags.
|
|
6021
|
+
*
|
|
6022
|
+
* @example
|
|
6023
|
+
* ```ts
|
|
6024
|
+
* command('serve')
|
|
6025
|
+
* .flags({ port: flag.number().default(3000), host: flag.string() })
|
|
6026
|
+
* .action(({ flags }) => { flags.port; flags.host; });
|
|
6027
|
+
* ```
|
|
5978
6028
|
*/
|
|
5979
|
-
|
|
6029
|
+
flags<const R extends Record<string, FlagBuilder<FlagConfig>>>(record: R & { [K in (keyof KnownFlags<R> & keyof KnownFlags<F>) | Extract<keyof R, symbol>]: never; }): CommandBuilder<MergeFlags<F, R>, A, C>;
|
|
5980
6030
|
/**
|
|
5981
|
-
*
|
|
6031
|
+
* Register a named positional argument on this command.
|
|
5982
6032
|
*
|
|
5983
|
-
*
|
|
5984
|
-
*
|
|
5985
|
-
*
|
|
6033
|
+
* Args are ordered by registration — position on the CLI matches the
|
|
6034
|
+
* order of `.arg()` calls. The arg name is added to the type-level `A`
|
|
6035
|
+
* map. Duplicate arg names are prevented at the type level via the
|
|
6036
|
+
* `Exclude` constraint.
|
|
5986
6037
|
*
|
|
5987
|
-
*
|
|
6038
|
+
* The builder controls the arg's type, presence, env binding, and
|
|
6039
|
+
* description. See {@link ArgBuilder} for available modifiers.
|
|
6040
|
+
*
|
|
6041
|
+
* @param name - Positional arg name (used in help text and `args.*`).
|
|
6042
|
+
* @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
|
|
6043
|
+
* or `arg.custom()`.
|
|
6044
|
+
*
|
|
6045
|
+
* @example
|
|
6046
|
+
* ```ts
|
|
6047
|
+
* command('deploy')
|
|
6048
|
+
* // Required string arg — first positional
|
|
6049
|
+
* .arg('target', arg.string()
|
|
6050
|
+
* .env('DEPLOY_TARGET')
|
|
6051
|
+
* .describe('Deploy target'))
|
|
6052
|
+
* // Optional number arg — second positional
|
|
6053
|
+
* .arg('port', arg.number()
|
|
6054
|
+
* .env('PORT')
|
|
6055
|
+
* .default(3000)
|
|
6056
|
+
* .describe('Port number'))
|
|
6057
|
+
* .action(({ args }) => {
|
|
6058
|
+
* args.target; // string
|
|
6059
|
+
* args.port; // number
|
|
6060
|
+
* });
|
|
6061
|
+
*
|
|
6062
|
+
* // Usage: deploy [flags] <target> [port]
|
|
6063
|
+
* // $ mycli deploy production 8080
|
|
6064
|
+
* // $ DEPLOY_TARGET=staging mycli deploy
|
|
6065
|
+
* ```
|
|
6066
|
+
*
|
|
6067
|
+
* @returns The builder (for chaining).
|
|
6068
|
+
* @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
|
|
6069
|
+
* which a plain record cannot carry.
|
|
6070
|
+
* @throws {@link CLIError} `INVALID_BUILDER_STATE` when an earlier arg on this
|
|
6071
|
+
* command is variadic, so this one could never be filled.
|
|
6072
|
+
* @throws {@link CLIError} `DUPLICATE_STDIN_INPUT` when another input on this
|
|
6073
|
+
* command already consumes stdin exclusively.
|
|
5988
6074
|
*/
|
|
5989
|
-
|
|
6075
|
+
arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
|
|
5990
6076
|
/**
|
|
5991
|
-
*
|
|
6077
|
+
* Register a nested subcommand on this command.
|
|
5992
6078
|
*
|
|
5993
|
-
*
|
|
5994
|
-
*
|
|
5995
|
-
*
|
|
6079
|
+
* The subcommand's builder is stored in `_subcommands` for the CLI layer's
|
|
6080
|
+
* `compileCommand()` to traverse when building the execution graph. The
|
|
6081
|
+
* subcommand's `CommandSchema` is also appended to `schema.commands` for
|
|
6082
|
+
* help rendering and completion generation.
|
|
5996
6083
|
*
|
|
5997
|
-
*
|
|
5998
|
-
*
|
|
5999
|
-
*
|
|
6084
|
+
* Does not change `F`, `A`, or `C` — subcommands are type-erased at the
|
|
6085
|
+
* parent level (same semantics as `CLIBuilder.command()`). The handler is
|
|
6086
|
+
* preserved.
|
|
6087
|
+
*
|
|
6088
|
+
* @example
|
|
6089
|
+
* ```ts
|
|
6090
|
+
* const db = group('db')
|
|
6091
|
+
* .description('Database operations')
|
|
6092
|
+
* .command(migrateCmd)
|
|
6093
|
+
* .command(seedCmd);
|
|
6094
|
+
* ```
|
|
6095
|
+
*
|
|
6096
|
+
* @param sub - Child {@link CommandBuilder} to nest under this command.
|
|
6097
|
+
* @returns The builder (for chaining).
|
|
6098
|
+
* @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling this
|
|
6099
|
+
* command propagates collides with one the subcommand, or any of its own
|
|
6100
|
+
* descendants, declares.
|
|
6000
6101
|
*/
|
|
6001
|
-
|
|
6102
|
+
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>;
|
|
6002
6103
|
/**
|
|
6003
|
-
*
|
|
6104
|
+
* Register the action handler for this command.
|
|
6004
6105
|
*
|
|
6005
|
-
*
|
|
6006
|
-
*
|
|
6007
|
-
*
|
|
6008
|
-
* access out of the output layer.
|
|
6106
|
+
* The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
|
|
6107
|
+
* from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
|
|
6108
|
+
* definitions.
|
|
6009
6109
|
*
|
|
6010
|
-
*
|
|
6110
|
+
* May be synchronous or async. Return values are ignored; command handlers
|
|
6111
|
+
* communicate through `out`, thrown errors, and side effects.
|
|
6112
|
+
*
|
|
6113
|
+
* @param handler - Function receiving `ActionParams<F, A, C>`.
|
|
6114
|
+
*
|
|
6115
|
+
* @example
|
|
6116
|
+
* ```ts
|
|
6117
|
+
* // Minimal
|
|
6118
|
+
* command('greet')
|
|
6119
|
+
* .arg('name', arg.string())
|
|
6120
|
+
* .action(({ args, out }) => {
|
|
6121
|
+
* out.log(`Hello, ${args.name}!`);
|
|
6122
|
+
* });
|
|
6123
|
+
* ```
|
|
6124
|
+
*
|
|
6125
|
+
* @example
|
|
6126
|
+
* ```ts
|
|
6127
|
+
* // Full params — flags, args, context, output, metadata
|
|
6128
|
+
* command('deploy')
|
|
6129
|
+
* .arg('target', arg.string().env('DEPLOY_TARGET'))
|
|
6130
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
6131
|
+
* .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
|
|
6132
|
+
* .middleware(auth)
|
|
6133
|
+
* .action(async ({ args, flags, ctx, out, meta }) => {
|
|
6134
|
+
* args.target; // string
|
|
6135
|
+
* flags.force; // boolean
|
|
6136
|
+
* flags.region; // 'us' | 'eu' | 'ap' | undefined
|
|
6137
|
+
* ctx.user; // User (from auth middleware)
|
|
6138
|
+
* meta.command; // string
|
|
6139
|
+
*
|
|
6140
|
+
* const spinner = out.spinner('Deploying...');
|
|
6141
|
+
* await deploy(args.target, { force: flags.force });
|
|
6142
|
+
* spinner.stop();
|
|
6143
|
+
* out.log('Done');
|
|
6144
|
+
* });
|
|
6145
|
+
* ```
|
|
6146
|
+
*
|
|
6147
|
+
* @returns The builder (for chaining).
|
|
6011
6148
|
*/
|
|
6012
|
-
|
|
6149
|
+
action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
|
|
6013
6150
|
}
|
|
6014
6151
|
/**
|
|
6015
|
-
* Create
|
|
6016
|
-
*
|
|
6017
|
-
* Low-level factory: action handlers already receive `out` automatically from
|
|
6018
|
-
* `cli()`, `.execute()`, and `runCommand()`. Call `createOutput()` when you
|
|
6019
|
-
* are embedding DreamCLI primitives into a custom runtime or need a standalone
|
|
6020
|
-
* output implementation outside the normal command pipeline.
|
|
6021
|
-
*
|
|
6022
|
-
* @param options - Optional configuration. When omitted, output is
|
|
6023
|
-
* discarded (useful for silent test runs). Pass `stdout`/`stderr`
|
|
6024
|
-
* writers to direct output somewhere useful.
|
|
6152
|
+
* Create a new command builder.
|
|
6025
6153
|
*
|
|
6026
|
-
* @
|
|
6154
|
+
* @param name - The command name used for dispatch (e.g. `'deploy'`).
|
|
6027
6155
|
*
|
|
6028
6156
|
* @example
|
|
6029
6157
|
* ```ts
|
|
6030
|
-
*
|
|
6031
|
-
* const out = createOutput({
|
|
6032
|
-
* stdout: (s) => process.stdout.write(s),
|
|
6033
|
-
* stderr: (s) => process.stderr.write(s),
|
|
6034
|
-
* isTTY: process.stdout.isTTY === true,
|
|
6035
|
-
* });
|
|
6158
|
+
* import { arg, command, flag } from '@kjanat/dreamcli';
|
|
6036
6159
|
*
|
|
6037
|
-
*
|
|
6038
|
-
*
|
|
6039
|
-
*
|
|
6040
|
-
*
|
|
6041
|
-
*
|
|
6042
|
-
*
|
|
6160
|
+
* const greet = command('greet')
|
|
6161
|
+
* .arg('name', arg.string())
|
|
6162
|
+
* .flag('loud', flag.boolean())
|
|
6163
|
+
* .action(({ args, flags, out }) => {
|
|
6164
|
+
* const msg = `Hello, ${args.name}!`;
|
|
6165
|
+
* out.log(flags.loud ? msg.toUpperCase() : msg);
|
|
6166
|
+
* });
|
|
6043
6167
|
* ```
|
|
6168
|
+
*
|
|
6169
|
+
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
6044
6170
|
*/
|
|
6045
|
-
declare function
|
|
6046
|
-
/** Captured output from a `createCaptureOutput` instance. */
|
|
6047
|
-
interface CapturedOutput {
|
|
6048
|
-
/**
|
|
6049
|
-
* Lines written to stdout.
|
|
6050
|
-
*
|
|
6051
|
-
* In normal mode: `log`, `info`, and `json` output.
|
|
6052
|
-
* In JSON mode: only `json` output (log/info redirected to stderr).
|
|
6053
|
-
*/
|
|
6054
|
-
readonly stdout: string[];
|
|
6055
|
-
/**
|
|
6056
|
-
* Lines written to stderr.
|
|
6057
|
-
*
|
|
6058
|
-
* In normal mode: `warn` and `error` output.
|
|
6059
|
-
* In JSON mode: `warn`, `error`, `log`, and `info` output.
|
|
6060
|
-
*/
|
|
6061
|
-
readonly stderr: string[];
|
|
6062
|
-
/**
|
|
6063
|
-
* Activity events from spinner and progress handles.
|
|
6064
|
-
*
|
|
6065
|
-
* Captured separately from stdout/stderr to allow targeted assertions
|
|
6066
|
-
* on activity lifecycle without parsing text output. Events are
|
|
6067
|
-
* recorded in chronological order.
|
|
6068
|
-
*/
|
|
6069
|
-
readonly activity: ActivityEvent[];
|
|
6070
|
-
}
|
|
6171
|
+
declare function command(name: string): CommandBuilder;
|
|
6071
6172
|
/**
|
|
6072
|
-
* Create
|
|
6173
|
+
* Create a command builder intended for use as a command group.
|
|
6073
6174
|
*
|
|
6074
|
-
*
|
|
6075
|
-
*
|
|
6175
|
+
* Semantically identical to {@linkcode command | command()} — a group is simply a command that
|
|
6176
|
+
* has subcommands registered via `.command()`. The separate factory
|
|
6177
|
+
* communicates intent: groups organise subcommands, leaf commands have actions.
|
|
6076
6178
|
*
|
|
6077
|
-
*
|
|
6078
|
-
*
|
|
6179
|
+
* A group may also have its own `.action()` (e.g. `git remote` lists remotes
|
|
6180
|
+
* when invoked without a subcommand, but dispatches to `git remote add`, etc.).
|
|
6079
6181
|
*
|
|
6080
|
-
* @
|
|
6081
|
-
* {@link CapturedOutput} buffers.
|
|
6182
|
+
* @param name - The group name used for dispatch (e.g. `'db'`).
|
|
6082
6183
|
*
|
|
6083
6184
|
* @example
|
|
6084
6185
|
* ```ts
|
|
6085
|
-
* const
|
|
6086
|
-
*
|
|
6087
|
-
*
|
|
6088
|
-
*
|
|
6089
|
-
* expect(captured.stderr).toEqual(['danger\n']);
|
|
6186
|
+
* const db = group('db')
|
|
6187
|
+
* .description('Database operations')
|
|
6188
|
+
* .command(migrateCmd)
|
|
6189
|
+
* .command(seedCmd);
|
|
6090
6190
|
* ```
|
|
6191
|
+
*
|
|
6192
|
+
* @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
|
|
6091
6193
|
*/
|
|
6092
|
-
declare function
|
|
6093
|
-
export {
|
|
6194
|
+
declare function group(name: string): CommandBuilder;
|
|
6195
|
+
export { InferPrompt as $, CompletionHandler as $n, FlagNegation as $t, MiddlewareParams as A, StandardSchemaV1Options as An, DuplicateKeys as At, createTestAdapter as B, PromptConfig as Bn, CountFlagDefinition as Bt, resolveExampleCommand as C, StdinOptions as Cn, StringArgElementConfig as Ct, wasExplicit as D, StandardSchemaV1 as Dn, arg as Dt, SourcesOf as E, InferStandardOutput as En, WithoutArgElementEligibility as Et, ConstraintInput as F, StandardSchemaV1Types as Fn, SplitOptions as Ft, ResolvedSelectPromptConfig as G, SelectPromptConfig as Gn, FlagBuilder as Gt, ReadFn as H, PromptKind as Hn, DefaultValueOptions as Ht, ExitError as I, ConfirmPromptConfig as In, SplitPolicy as It, OutputOptions as J, EnvOptions as Jn, FlagDefinitionBase as Jt, resolvePromptConfig as K, NumberConstraintViolation as Kn, FlagConfig as Kt, RuntimeAdapter as L, InputPromptConfig as Ln, SplitSetting as Lt, CommandConstraint as M, StandardSchemaV1Props as Mn, SourceSplitBinding as Mt, CommandValidationOptions as N, StandardSchemaV1Result as Nn, SplitBinding as Nt, Middleware as O, StandardSchemaV1FailureResult as On, createArgSchema as Ot, ConstraintBuilder as P, StandardSchemaV1SuccessResult as Pn, SplitFormat as Pt, Ask as Q, CompletionContext as Qn, FlagKind as Qt, TerminalSize as R, MultiselectPromptConfig as Rn, ArrayFlagDefinition as Rt, group as S, StdinConsume as Sn, StringArgDefinition as St, ResolutionProvenance as T, InferStandardInput as Tn, WithVariadic as Tt, ResolvedMultiselectPromptConfig as U, PromptResult as Un, DuplicatePolicy as Ut, PromptEngine as V, PromptConfigBase as Vn, CustomFlagDefinition as Vt, ResolvedPromptConfig as W, SelectChoice as Wn, EnumFlagDefinition as Wt, createOutput as X, IndexedRecordEnvBinding as Xn, FlagDefinitionOverrides as Xt, createCaptureOutput as Y, IndexedEnvBinding as Yn, FlagDefinitionByKind as Yt, WriteFn as Z, IndexedValueEnvBinding as Zn, FlagFactory as Zt, InteractiveResolver as _, PathFlagOptions as _n, InferArg as _t, CommandBuilder as a, KeyValueFlagDefinition as an, ProgressHandle as ar, ArgDefinition as at, command as b, StringConstraints as bn, NumberArgDefinition as bt, CommandMeta as c, StringElementConfig as cn, SpinnerOptions as cr, ArgDefinitionOverrides as ct, DeriveParams as d, WithoutElementEligibility as dn, TableOptions as dr, ArgParseFn as dt, FlagParseFn as en, HelpDescription as er, prompt as et, ErasedActionHandler as f, createFlagSchema as fn, TableStream as fr, ArgPresence as ft, InteractiveParams as g, PathChecks as gn, EnumArgDefinition as gt, ExecutionStep as h, DateFlagOptions as hn, CustomArgDefinition as ht, CommandArgEntryDefinition as i, InferFlags as in, Fallback as ir, ArgDefaultValue as it, middleware as j, StandardSchemaV1PathSegment as jn, SPLIT_FORMATS as jt, MiddlewareHandler as k, StandardSchemaV1Issue as kn, DUPLICATE_KEYS as kt, CommandSchema as l, StringFlagDefinition as ln, TableColumn as lr, ArgFactory as lt, ExampleMeta as m, getFlagNegatedName as mn, BooleanArgDefinition as mt, ActionParams as n, FlagSchema as nn, HelpThemeFactory as nr, ArgBuilder as nt, CommandDefinition as o, NumberFlagDefinition as on, ProgressOptions as or, ArgDefinitionBase as ot, ExampleCommand as p, flag as pn, schemaBrand as pr, ArgSchema as pt, CapturedOutput as q, NumberConstraints as qn, FlagDefinition as qt, CommandArgEntry as r, InferFlag as rn, ActivityEvent as rr, ArgConfig as rt, CommandExample as s, ResolvedValue as sn, SpinnerHandle as sr, ArgDefinitionByKind as st, ActionHandler as t, FlagPresence as tn, HelpTheme as tr, Verbosity as tt, DeriveHandler as u, WithPresence as un, TableFormat as ur, ArgKind as ut, InteractiveResult as v, UrlFlagOptions as vn, InferArgs as vt, InputSources as w, StdinWhen as wn, WithArgPresence as wt, createCommandSchema as x, StdinBinding as xn, ResolvedArgValue as xt, Out as y, StringConstraintViolation as yn, KeyValueArgDefinition as yt, TestAdapterOptions as z, PasswordPromptConfig as zn, BooleanFlagDefinition as zt };
|