@kjanat/dreamcli 5.0.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.
Files changed (42) hide show
  1. package/dist/{index-BIMjOsR6.d.mts → command-Cq6YZjEH.d.mts} +1183 -691
  2. package/dist/completion-DCWRvQjQ.mjs +59 -0
  3. package/dist/completion.d.mts +11 -1
  4. package/dist/completion.mjs +1 -1
  5. package/dist/config-CANc4lsA.mjs +1 -0
  6. package/dist/config.d.mts +12 -2
  7. package/dist/config.mjs +1 -1
  8. package/dist/core-CPh0FcFg.mjs +25 -0
  9. package/dist/dynamic-xPNS3_vL.mjs +1 -0
  10. package/dist/{index-jq_FJRKt.d.mts → index-8EiEDJfX.d.mts} +33 -7
  11. package/dist/{index-DpslpOVV.d.mts → index-BZ3jYjyh.d.mts} +18 -3
  12. package/dist/{index-hzYPRc_O.d.mts → index-Bkk86gFg.d.mts} +18 -13
  13. package/dist/{index-AIC5Gler.d.mts → index-CLg6j-KJ.d.mts} +1 -1
  14. package/dist/{index-BidVVmln.d.mts → index-DBepo8jX.d.mts} +28 -6
  15. package/dist/index.d.mts +33 -10
  16. package/dist/index.mjs +1 -1
  17. package/dist/json-schema-DmFJR8c6.mjs +59 -0
  18. package/dist/json-schema.d.mts +9 -1
  19. package/dist/json-schema.mjs +1 -1
  20. package/dist/{package-json-fYhxDdWD.mjs → package-json-hqUWeazy.mjs} +1 -1
  21. package/dist/prompt.d.mts +12 -1
  22. package/dist/prompt.mjs +1 -1
  23. package/dist/rolldown-runtime-DOYBPklu.mjs +1 -0
  24. package/dist/runtime.d.mts +20 -2
  25. package/dist/runtime.mjs +1 -1
  26. package/dist/session-BBRg9p2u.mjs +1 -0
  27. package/dist/{terminal-DRsRn4sc.mjs → terminal-mINn5p7B.mjs} +1 -1
  28. package/dist/test-prompter-BI9sA9n7.mjs +1 -0
  29. package/dist/testkit.d.mts +17 -4
  30. package/dist/testkit.mjs +1 -1
  31. package/dist/version.mjs +1 -1
  32. package/dreamcli.schema.json +186 -0
  33. package/package.json +13 -14
  34. package/skills/cli-creation/SKILL.md +1 -1
  35. package/dist/adapter-DBeedKmD.d.mts +0 -283
  36. package/dist/completion-Bh-qywmB.mjs +0 -6
  37. package/dist/config-DruA8aFV.mjs +0 -1
  38. package/dist/core-B9YNSJeA.mjs +0 -19
  39. package/dist/json-schema-DF5fXdKQ.mjs +0 -59
  40. package/dist/rolldown-runtime-G4Kt5YOX.mjs +0 -1
  41. package/dist/session-Crtzt7LY.mjs +0 -1
  42. package/dist/test-prompter-BLNGCOA_.mjs +0 -1
@@ -30,6 +30,8 @@ declare const schemaBrand: unique symbol;
30
30
  type Fallback = 'silent' | 'static';
31
31
  /** Options for {@link Out.spinner}. */
32
32
  interface SpinnerOptions {
33
+ /** Render alongside other concurrent activities instead of replacing them. */
34
+ readonly concurrent?: boolean;
33
35
  /**
34
36
  * Fallback strategy when `!isTTY` or `jsonMode`.
35
37
  * @defaultValue `'silent'`
@@ -57,12 +59,14 @@ interface SpinnerHandle {
57
59
  * @returns The resolved value of the wrapped promise.
58
60
  */
59
61
  wrap<T>(promise: Promise<T>, options?: {
60
- readonly succeed?: string;
61
- readonly fail?: string;
62
+ readonly succeed?: string | ((value: T) => string);
63
+ readonly fail?: string | ((error: unknown) => string);
62
64
  }): Promise<T>;
63
65
  }
64
66
  /** Options for {@link Out.progress}. */
65
67
  interface ProgressOptions {
68
+ /** Render alongside other concurrent activities instead of replacing them. */
69
+ readonly concurrent?: boolean;
66
70
  /**
67
71
  * Total units of work. When provided, the bar shows a determinate
68
72
  * percentage. When omitted, the bar pulses in indeterminate mode.
@@ -246,6 +250,29 @@ type HelpDescription = string | ((theme: HelpTheme) => string);
246
250
  * unconditionally, gating is the framework's job.
247
251
  */
248
252
  type HelpThemeFactory = (colors: Colors) => Partial<HelpTheme>;
253
+ /**
254
+ * Runtime value completion callbacks.
255
+ *
256
+ * @module dreamcli/core/schema/completion
257
+ */
258
+ /** The input and partial command line being completed. */
259
+ interface CompletionContext {
260
+ /** The value prefix typed before the cursor. */
261
+ readonly prefix: string;
262
+ /** Canonical command names, excluding the executable. Empty for a default command. */
263
+ readonly commandPath: readonly string[];
264
+ /** The input whose value is being completed. */
265
+ readonly input: {
266
+ readonly kind: 'flag' | 'arg';
267
+ readonly name: string;
268
+ };
269
+ /** Arguments before the cursor, including the current partial token. */
270
+ readonly argv: readonly string[];
271
+ /** Environment supplied to this execution. */
272
+ readonly env: Readonly<Record<string, string | undefined>>;
273
+ }
274
+ /** Return complete candidate values. DreamCLI filters them by prefix. */
275
+ type CompletionHandler = (context: CompletionContext) => readonly string[] | Promise<readonly string[]>;
249
276
  /**
250
277
  * An indexed env family whose entries are single values.
251
278
  *
@@ -643,6 +670,8 @@ declare const STDIN_CONSUMES: readonly ["exclusive", "broadcast"];
643
670
  type StdinConsume = (typeof STDIN_CONSUMES)[number];
644
671
  /** The normalized stdin axis of a flag or an arg. */
645
672
  interface StdinBinding {
673
+ /** False when this input has no command-line form. Omitted means true. */
674
+ readonly argv?: false;
646
675
  /** When this input reads the stdin stream. */
647
676
  readonly when: StdinWhen;
648
677
  /** Whether this input consumes the stream alone. */
@@ -652,6 +681,13 @@ interface StdinBinding {
652
681
  }
653
682
  /** Stdin settings accepted by `.stdin()` and by the schema definitions. */
654
683
  interface StdinOptions {
684
+ /**
685
+ * Accept this input on the command line. Set false to omit its flag spellings
686
+ * or positional slot from parsing, help, and completion. Other sources still apply.
687
+ * Cannot be combined with `when: 'dash'`.
688
+ * @defaultValue `true`
689
+ */
690
+ readonly argv?: boolean | undefined;
655
691
  /**
656
692
  * When this input reads the stdin stream.
657
693
  * @defaultValue `'dash-or-missing'`
@@ -1013,6 +1049,8 @@ type DuplicatePolicy = 'last' | 'first' | 'error';
1013
1049
  interface FlagSchema<K extends FlagKind = FlagKind> {
1014
1050
  /** Type-only seal produced by {@link createFlagSchema}. */
1015
1051
  readonly [schemaBrand]: 'flag';
1052
+ /** Callback used to complete this input's values. */
1053
+ readonly completion?: CompletionHandler | undefined;
1016
1054
  /** What kind of value this flag accepts. */
1017
1055
  readonly kind: K;
1018
1056
  /** Current presence state. */
@@ -1059,6 +1097,10 @@ interface FlagSchema<K extends FlagKind = FlagKind> {
1059
1097
  readonly configPath: string | undefined;
1060
1098
  /** Human-readable description for help text. */
1061
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;
1062
1104
  /** Allowed literal values when `kind === 'enum'`. */
1063
1105
  readonly enumValues: readonly string[] | undefined;
1064
1106
  /**
@@ -1175,6 +1217,8 @@ interface FlagSchema<K extends FlagKind = FlagKind> {
1175
1217
  }
1176
1218
  /** Definition fields accepted by every flag kind. */
1177
1219
  interface FlagDefinitionBase {
1220
+ /** Callback used to complete this input's values. */
1221
+ readonly completion?: CompletionHandler | undefined;
1178
1222
  /**
1179
1223
  * Presence state.
1180
1224
  * @defaultValue `'optional'`
@@ -1238,6 +1282,10 @@ interface FlagDefinitionBase {
1238
1282
  * @defaultValue `undefined`
1239
1283
  */
1240
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;
1241
1289
  /**
1242
1290
  * Help placeholder label (`'url'` renders as `<url>`).
1243
1291
  * @defaultValue `undefined`
@@ -1500,6 +1548,17 @@ declare class FlagBuilder<C extends FlagConfig> {
1500
1548
  * @param schema - Runtime descriptor seeding this builder's state.
1501
1549
  */
1502
1550
  constructor(schema: FlagSchema);
1551
+ /**
1552
+ * Compute value candidates when the user requests shell completion.
1553
+ *
1554
+ * The callback runs without the command action, middleware, prompts, or
1555
+ * config discovery. Return complete values; DreamCLI filters by prefix.
1556
+ * Candidates containing control characters are omitted.
1557
+ *
1558
+ * @param handler - Callback receiving the input and partial command line.
1559
+ * @returns A new builder with the completion callback.
1560
+ */
1561
+ complete(handler: CompletionHandler): FlagBuilder<WithoutElementEligibility<C>>;
1503
1562
  /**
1504
1563
  * Provide a default value. The flag becomes "always present" — handlers
1505
1564
  * will never see `undefined`.
@@ -1714,6 +1773,10 @@ declare class FlagBuilder<C extends FlagConfig> {
1714
1773
  * @returns The builder (for chaining).
1715
1774
  */
1716
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>>;
1717
1780
  /**
1718
1781
  * Attach interactive prompt configuration for v0.3+ resolution.
1719
1782
  *
@@ -2641,6 +2704,8 @@ type ArgParseFn<T> = (raw: string) => T;
2641
2704
  interface ArgSchema<K extends ArgKind = ArgKind> {
2642
2705
  /** Type-only seal produced by {@link createArgSchema}. */
2643
2706
  readonly [schemaBrand]: 'arg';
2707
+ /** Callback used to complete this input's values. */
2708
+ readonly completion?: CompletionHandler | undefined;
2644
2709
  /** What kind of value this arg accepts. */
2645
2710
  readonly kind: K;
2646
2711
  /** Current presence state. */
@@ -2663,6 +2728,8 @@ interface ArgSchema<K extends ArgKind = ArgKind> {
2663
2728
  readonly sensitive: boolean;
2664
2729
  /** Human-readable description for help text. */
2665
2730
  readonly description: HelpDescription | undefined;
2731
+ /** Named section in command help. */
2732
+ readonly group: string | undefined;
2666
2733
  /**
2667
2734
  * Environment variable name for env resolution.
2668
2735
  *
@@ -2805,6 +2872,8 @@ interface ArgSchema<K extends ArgKind = ArgKind> {
2805
2872
  }
2806
2873
  /** Definition fields accepted by every arg kind. */
2807
2874
  interface ArgDefinitionBase {
2875
+ /** Callback used to complete this input's values. */
2876
+ readonly completion?: CompletionHandler | undefined;
2808
2877
  /**
2809
2878
  * Presence state.
2810
2879
  * @defaultValue `'required'`
@@ -2841,6 +2910,8 @@ interface ArgDefinitionBase {
2841
2910
  * @defaultValue `undefined`
2842
2911
  */
2843
2912
  readonly description?: HelpDescription | undefined;
2913
+ /** Named section in command help. */
2914
+ readonly group?: string | undefined;
2844
2915
  /**
2845
2916
  * Environment variable name for env resolution.
2846
2917
  * @defaultValue `undefined`
@@ -3100,6 +3171,17 @@ declare class ArgBuilder<C extends ArgConfig> {
3100
3171
  * @param schema - Runtime descriptor for this positional argument.
3101
3172
  */
3102
3173
  constructor(schema: ArgSchema);
3174
+ /**
3175
+ * Compute value candidates when the user requests shell completion.
3176
+ *
3177
+ * The callback runs without the command action, middleware, prompts, or
3178
+ * config discovery. Return complete values; DreamCLI filters by prefix.
3179
+ * Candidates containing control characters are omitted.
3180
+ *
3181
+ * @param handler - Callback receiving the input and partial command line.
3182
+ * @returns A new builder with the completion callback.
3183
+ */
3184
+ complete(handler: CompletionHandler): ArgBuilder<WithoutArgElementEligibility<C>>;
3103
3185
  /**
3104
3186
  * Mark the arg as required (this is the default for positional args).
3105
3187
  * Produces an error if no value resolves from any configured source
@@ -3481,6 +3563,8 @@ declare class ArgBuilder<C extends ArgConfig> {
3481
3563
  * ```
3482
3564
  */
3483
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>>;
3484
3568
  /**
3485
3569
  * Mark this arg as deprecated.
3486
3570
  *
@@ -4081,350 +4165,968 @@ declare const prompt: {
4081
4165
  };
4082
4166
  };
4083
4167
  /**
4084
- * Parameters received by a middleware function at runtime.
4168
+ * Minimal I/O seam — the only write primitive the output module depends on.
4085
4169
  *
4086
- * Middleware receives erased args, flags, and provenance (since it's defined
4087
- * independently of commands) plus the accumulated context from prior middleware
4088
- * and a `next` function to continue the chain.
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
4089
4174
  */
4090
- interface MiddlewareParams {
4091
- /** Fully resolved positional arguments (type-erased). */
4092
- readonly args: Readonly<Record<string, unknown>>;
4093
- /** Fully resolved flags (type-erased). */
4094
- readonly flags: Readonly<Record<string, unknown>>;
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 {
4095
4202
  /**
4096
- * Where each resolved value came from, keyed like `flags` and `args`.
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.
4097
4236
  *
4098
- * Erased alongside them, so any key reads as `ResolutionProvenance |
4099
- * undefined`. A key the bound command never declared, and one an input
4100
- * resolved no value for, both read `undefined`.
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`
4101
4242
  */
4102
- readonly sources: ErasedInputSources;
4103
- /** Context accumulated from previous middleware in the chain. */
4104
- readonly ctx: Readonly<Record<string, unknown>>;
4105
- /** Output channel. */
4106
- readonly out: Out;
4107
- /** Invocation-scoped interactive questions. */
4108
- readonly ask: Ask;
4109
- /** CLI program metadata (name, bin, version, command). */
4110
- readonly meta: CommandMeta;
4243
+ readonly jsonMode?: boolean;
4111
4244
  /**
4112
- * Continue to the next middleware or action handler.
4245
+ * Explicitly enable or disable ANSI colors on `out.color`.
4113
4246
  *
4114
- * Call with context additions that merge into `ctx` for downstream.
4115
- * Returns when the entire downstream chain completes — enabling
4116
- * wrap-around patterns (timing, try/catch, cleanup).
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).
4117
4254
  */
4118
- readonly next: (additions: Record<string, unknown>) => Promise<void>;
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;
4119
4267
  }
4120
4268
  /**
4121
- * Type-erased middleware handler stored on the command builder.
4122
- *
4123
- * At runtime, all middleware handlers have this signature. The phantom
4124
- * `Output` type on {@linkcode Middleware} is erased.
4125
- */
4126
- type ErasedMiddlewareHandler = (params: MiddlewareParams) => void | Promise<void>;
4127
- /**
4128
- * Middleware handler function with typed `next()` parameter.
4269
+ * Create an output channel.
4129
4270
  *
4130
- * The `Output` generic constrains what properties must be passed to
4131
- * {@linkcode MiddlewareParams.next | next()}, ensuring type-safe context additions at the call site.
4132
- */
4133
- type MiddlewareHandler<Output extends Record<string, unknown>> = (params: {
4134
- readonly args: Readonly<Record<string, unknown>>;
4135
- readonly flags: Readonly<Record<string, unknown>>;
4136
- readonly sources: ErasedInputSources;
4137
- readonly ctx: Readonly<Record<string, unknown>>;
4138
- readonly out: Out;
4139
- /** Invocation-scoped interactive questions. */
4140
- readonly ask: Ask;
4141
- readonly meta: CommandMeta;
4142
- /** Pass context additions downstream. Must include all `Output` properties. */
4143
- readonly next: (additions: Output) => Promise<void>;
4144
- }) => void | Promise<void>;
4145
- /**
4146
- * Internal runtime representation of middleware.
4147
- */
4148
- interface MiddlewareImpl {
4149
- readonly _handler: ErasedMiddlewareHandler;
4150
- }
4151
- /**
4152
- * 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.
4153
4275
  *
4154
- * The `Output` parameter tracks what this middleware adds to context at
4155
- * compile time. The `_output` brand is phantom — it exists only in the
4156
- * type system for inference, not at runtime.
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.
4157
4279
  *
4158
- * Created via the {@linkcode middleware} factory. Attached to commands via
4159
- * `CommandBuilder.middleware()`.
4280
+ * @returns An {@link Out} instance backed by an {@link OutputChannel}.
4160
4281
  *
4161
4282
  * @example
4162
4283
  * ```ts
4163
- * interface User { id: string; name: string }
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
+ * });
4164
4290
  *
4165
- * const auth = middleware<{ user: User }>(async ({ next }) => {
4166
- * const user = await getUser();
4167
- * if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
4168
- * return next({ user });
4291
+ * // Test (capture output)
4292
+ * const lines: string[] = [];
4293
+ * const out = createOutput({
4294
+ * stdout: (s) => lines.push(s),
4295
+ * stderr: (s) => lines.push(s),
4169
4296
  * });
4170
4297
  * ```
4171
4298
  */
4172
- type Middleware<Output extends Record<string, unknown>> = MiddlewareImpl & {
4173
- /** @internal Phantom type brand — compile-time only. */
4174
- readonly _output: Output;
4175
- };
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
+ }
4176
4325
  /**
4177
- * Create a middleware definition.
4326
+ * Create an output channel that captures all output into arrays.
4178
4327
  *
4179
- * Middleware runs before the action handler and can add typed context,
4180
- * short-circuit execution, or wrap downstream processing.
4328
+ * Useful in tests to assert on what a handler wrote without touching
4329
+ * real I/O.
4181
4330
  *
4182
- * @param handler - Function receiving `{ args, flags, ctx, out, meta, next }`.
4183
- * Call `next(additions)` to continue the chain with added context.
4184
- * Omitting the `next()` call short-circuits (e.g., for auth guards).
4185
- * @returns {@linkcode Middleware} to attach via `CommandBuilder.middleware()`.
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.
4186
4336
  *
4187
4337
  * @example
4188
4338
  * ```ts
4189
- * // Auth guard — adds user to context or throws
4190
- * const auth = middleware(async ({ next }) => {
4191
- * const user = await getUser();
4192
- * if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
4193
- * return next({ user });
4194
- * });
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']);
4344
+ * ```
4345
+ */
4346
+ declare function createCaptureOutput(options?: Omit<OutputOptions, 'stdout' | 'stderr'>): [out: Out, captured: CapturedOutput];
4347
+ /**
4348
+ * A select prompt config with choices guaranteed non-empty.
4195
4349
  *
4196
- * // Timing wrapper — measures downstream execution
4197
- * const timing = middleware(async ({ out, next }) => {
4198
- * const start = Date.now();
4199
- * await next({});
4200
- * out.info(`Done in ${Date.now() - start}ms`);
4201
- * });
4202
- *
4203
- * command('deploy')
4204
- * .middleware(timing)
4205
- * .middleware(auth)
4206
- * .action(({ ctx }) => {
4207
- * console.log(ctx.user.name); // typed!
4208
- * });
4209
- * ```
4350
+ * The resolution chain populates choices from `FlagSchema.enumValues`
4351
+ * when the user's {@linkcode PromptConfig} omits them.
4210
4352
  */
4211
- declare function middleware<Output extends Record<string, unknown>>(handler: MiddlewareHandler<Output>): Middleware<Output>;
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
+ }
4212
4361
  /**
4213
- * Where a resolved value came from.
4362
+ * A multiselect prompt config with choices guaranteed non-empty.
4214
4363
  *
4215
- * Resolution records one {@link ResolutionProvenance} per input that produced a
4216
- * value, and the same record reaches a handler through `sources` and a
4217
- * `resolve()` caller through `ResolveResult.provenance`. {@link wasExplicit}
4218
- * derives the explicit-versus-defaulted question from it.
4364
+ * Same guarantee as {@linkcode ResolvedSelectPromptConfig} — choices are always
4365
+ * present and non-empty.
4366
+ */
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
+ }
4379
+ /**
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`.
4219
4383
  *
4220
- * @module dreamcli/core/schema/provenance
4384
+ * confirm and input configs pass through unchanged.
4221
4385
  */
4386
+ type ResolvedPromptConfig = ConfirmPromptConfig | InputPromptConfig | PasswordPromptConfig | ResolvedSelectPromptConfig | ResolvedMultiselectPromptConfig;
4222
4387
  /**
4223
- * Which stage produced a resolved value, and how.
4388
+ * Prompt engine interface.
4224
4389
  *
4225
- * `via` and `trigger` distinguish the two ways stdin delivers bytes. An explicit
4226
- * `-` keeps CLI precedence and reports `{ stage: 'cli', via: 'stdin', trigger:
4227
- * 'dash' }`; an absent input takes the fallback stage between CLI and env and
4228
- * reports `{ stage: 'stdin', via: 'stdin', trigger: 'fallback' }`.
4390
+ * Implementations present one prompt per `promptOne()` call and return
4391
+ * the result. Engines may retain state across calls, such as an answer queue.
4229
4392
  *
4230
- * The `'env'` stage is two records the same way. A variable bound by name
4231
- * reports `{ stage: 'env', envVar }`, the one concrete variable that supplied
4232
- * the value. An indexed family bound with an `IndexedEnvBinding` reports
4233
- * `{ stage: 'env', via: 'indexed', count, envVars }`: the count variable that
4234
- * claimed the input and every member variable read, in entry order and, within
4235
- * an entry, in field order. `envVars` is empty when the count is `0`. Test
4236
- * `'envVar' in source` (or `source.via`) before reading either shape's fields.
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.
4237
4396
  *
4238
4397
  * @example
4239
4398
  * ```ts
4240
- * command('deploy')
4241
- * .flag('region', flag.string().env('REGION').default('us'))
4242
- * .action(({ sources }) => {
4243
- * const region = sources.flags.region;
4244
- * if (region?.stage === 'env' && 'envVar' in region) console.log(`from ${region.envVar}`);
4245
- * });
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
+ * };
4246
4406
  * ```
4247
4407
  */
4248
- type ResolutionProvenance = {
4249
- readonly stage: 'cli';
4250
- } | {
4251
- readonly stage: 'cli';
4252
- readonly via: 'stdin';
4253
- readonly trigger: 'dash';
4254
- } | {
4255
- readonly stage: 'stdin';
4256
- readonly via: 'stdin';
4257
- readonly trigger: 'fallback';
4258
- } | {
4259
- readonly stage: 'env';
4260
- readonly envVar: string;
4261
- } | {
4262
- readonly stage: 'env';
4263
- readonly via: 'indexed';
4264
- readonly count: string;
4265
- readonly envVars: readonly string[];
4266
- } | {
4267
- readonly stage: 'config';
4268
- readonly configPath: string;
4269
- } | {
4270
- readonly stage: 'prompt';
4271
- } | {
4272
- readonly stage: 'default';
4273
- };
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
+ }
4274
4419
  /**
4275
- * Provenance of every input of one surface, keyed by input name.
4420
+ * A function that reads a single line of user input.
4276
4421
  *
4277
- * An input that resolved no value has no record, so every member is optional in
4278
- * value even though the key set is the surface's own.
4422
+ * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
4423
+ * indicating the user closed the input stream (treated as cancel).
4279
4424
  *
4280
- * @typeParam T - The record of flag or arg builders whose keys this mirrors.
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.
4281
4428
  */
4282
- type SourcesOf<T> = { readonly [K in keyof T]: ResolutionProvenance | undefined; };
4429
+ type ReadFn = () => Promise<string | null>;
4283
4430
  /**
4284
- * Where each of a command's resolved values came from.
4431
+ * Prepare a {@linkcode ResolvedPromptConfig} from a raw {@linkcode PromptConfig} and optional
4432
+ * enum values from the flag schema.
4285
4433
  *
4286
- * Handed to an action, derive, or middleware handler as `sources`, keyed by the
4287
- * same names as `flags` and `args`.
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.
4288
4437
  *
4289
- * @typeParam F - The command's flag builders.
4290
- * @typeParam A - The command's arg builders.
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.
4440
+ *
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
4291
4445
  */
4292
- interface InputSources<F, A> {
4293
- /** Provenance of every declared flag, keyed by flag name. */
4294
- readonly flags: SourcesOf<F>;
4295
- /** Provenance of every declared arg, keyed by arg name. */
4296
- readonly args: SourcesOf<A>;
4297
- }
4446
+ declare function resolvePromptConfig(config: PromptConfig, enumValues: readonly string[] | undefined): ResolvedPromptConfig;
4298
4447
  /**
4299
- * Whether a value came from somewhere other than its declared default.
4448
+ * Runtime adapter interface.
4300
4449
  *
4301
- * Every stage but `'default'` means the value was supplied: typed on the command
4302
- * line, piped, exported, written in a config file, or answered at a prompt. An
4303
- * input that resolved no value at all has no record and is not explicit.
4304
- *
4305
- * Read `stage` directly for a narrower question, such as `stage === 'cli'` for
4306
- * "the user typed it on this command line".
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.
4307
4454
  *
4308
- * @param source - The provenance record of one input, or `undefined`.
4309
- * @returns `true` when a source other than the default produced the value.
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()}
4310
4459
  *
4311
4460
  * @example
4312
4461
  * ```ts
4313
- * command('build')
4314
- * .flag('out', flag.string().default('dist'))
4315
- * .action(({ sources, out }) => {
4316
- * if (wasExplicit(sources.flags.out)) out.info('using an overridden output');
4317
- * });
4462
+ * // Production: auto-detected
4463
+ * cli('mycli').run(); // uses Node/Bun/Deno adapter
4464
+ *
4465
+ * // Test: explicit adapter
4466
+ * cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
4318
4467
  * ```
4319
4468
  */
4320
- declare function wasExplicit(source: ResolutionProvenance | undefined): boolean;
4469
+ interface RuntimeAdapter {
4470
+ /** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
4471
+ readonly argv: readonly string[];
4472
+ /**
4473
+ * Environment variables.
4474
+ * Values are `string | undefined` — mirrors Node's `process.env` semantics.
4475
+ */
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>;
4485
+ /**
4486
+ * Line reader for stdin. Used by the prompt engine for interactive input.
4487
+ *
4488
+ * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
4489
+ * indicating the user closed the input stream (treated as cancel).
4490
+ */
4491
+ readonly stdin: ReadFn;
4492
+ /** Hidden terminal input. Absent when echo suppression is unsupported. */
4493
+ readonly readSecret?: ReadFn;
4494
+ /**
4495
+ * Read all of stdin as a single string (for piped data).
4496
+ *
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.
4505
+ */
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;
4515
+ /**
4516
+ * Exit the process with the given code.
4517
+ * Must not return (divergent function).
4518
+ */
4519
+ readonly exit: (code: number) => never;
4520
+ /**
4521
+ * Read a file as UTF-8 text.
4522
+ *
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.
4529
+ */
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>;
4533
+ /**
4534
+ * Probe what exists at a filesystem path.
4535
+ *
4536
+ * Returns `'file'` or `'directory'` for existing paths (other kinds such
4537
+ * as sockets report `'file'`), or `null` when nothing exists there.
4538
+ *
4539
+ * Used by `flag.path()` existence/type checks after resolution.
4540
+ */
4541
+ readonly stat: (path: string) => Promise<'file' | 'directory' | null>;
4542
+ /**
4543
+ * Create a directory, including missing parents.
4544
+ *
4545
+ * Succeeds when the directory already exists. Throws on other I/O errors
4546
+ * (permission denied, existing file at the path, etc.).
4547
+ *
4548
+ * Used by `flag.path()` `create` checks after resolution.
4549
+ */
4550
+ readonly mkdir: (path: string) => Promise<void>;
4551
+ /**
4552
+ * User home directory (absolute path).
4553
+ *
4554
+ * - Node/Bun: derived from `HOME` / `USERPROFILE` env
4555
+ * - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
4556
+ */
4557
+ readonly homedir: string;
4558
+ /**
4559
+ * Platform-specific user configuration directory (absolute path).
4560
+ *
4561
+ * - Unix: `$XDG_CONFIG_HOME` or `~/.config`
4562
+ * - Windows: `%APPDATA%` or `~\AppData\Roaming`
4563
+ *
4564
+ * Config discovery appends the app-specific subdirectory.
4565
+ */
4566
+ readonly configDir: string;
4567
+ /**
4568
+ * User-scope config roots for discovery, highest priority first.
4569
+ *
4570
+ * - Unix: `[configDir]`
4571
+ * - macOS: `[configDir, ~/Library/Application Support]`
4572
+ * - Windows: `[configDir]`
4573
+ *
4574
+ * When absent, discovery falls back to `[configDir]`.
4575
+ */
4576
+ readonly userConfigDirs?: readonly string[];
4577
+ /**
4578
+ * System-scope config roots for discovery (`['/etc']` on Linux and
4579
+ * macOS, `[]` on Windows). When absent, discovery probes none.
4580
+ */
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
+ }
4321
4590
  /**
4322
- * Widen the context type when adding middleware.
4591
+ * Options for creating a test adapter.
4323
4592
  *
4324
- * The default `C = Record<string, never>` uses an index signature where
4325
- * every key maps to `never` — making property access a type error until
4326
- * middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
4327
- * collapses all properties to `never` because `never & T = never`.
4328
- *
4329
- * This utility replaces `Record<string, never>` entirely on the first
4330
- * `.middleware()` call. Subsequent calls use plain intersection.
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).
4331
4596
  */
4332
- type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
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;
4608
+ /**
4609
+ * Stdin line reader (defaults to returning `null` — immediate EOF).
4610
+ *
4611
+ * Use a custom {@linkcode ReadFn} to simulate user input in tests.
4612
+ */
4613
+ readonly stdin?: ReadFn;
4614
+ /** Hidden reader stub; omitted adapters report unsupported hidden input. */
4615
+ readonly readSecret?: ReadFn;
4616
+ /**
4617
+ * Piped stdin data for testing args with `.stdin()` configured.
4618
+ *
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`.
4622
+ *
4623
+ * @example
4624
+ * ```ts
4625
+ * createTestAdapter({
4626
+ * stdinData: '{"key": "value"}',
4627
+ * })
4628
+ * ```
4629
+ */
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[];
4686
+ }
4333
4687
  /**
4334
- * Widen the context type when adding command-scoped derived context.
4688
+ * Error thrown by adapter implementations that model process exit as an
4689
+ * exception instead of terminating immediately.
4335
4690
  *
4336
- * Validation-only derive handlers return `undefined` (or nothing), preserving `C`.
4337
- * Context-producing derive handlers return an object that merges into `C`
4338
- * using the same first-call replacement rules as middleware.
4339
- */
4340
- type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
4341
- /**
4342
- * Parameters received by the interactive resolver function.
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:
4343
4694
  *
4344
- * `flags` contains partially resolved values — present for flags resolved
4345
- * via CLI, env, or config, `undefined` for unresolved flags. The resolver
4346
- * uses this to decide which prompts to show based on current state.
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
+ * ```
4347
4702
  */
4348
- interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
4349
- /** Partially resolved flag values (after CLI/env/config, before prompts). */
4350
- readonly flags: Readonly<Partial<InferFlags<F>>>;
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);
4351
4710
  }
4352
4711
  /**
4353
- * A record mapping flag names to prompt configs or falsy values.
4712
+ * Create a test runtime adapter with injectable process state.
4354
4713
  *
4355
- * - `PromptConfig` — show this prompt for the flag
4356
- * - `false | undefined | null | 0 | ''` — skip prompting for this flag
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.
4357
4717
  *
4358
- * Only flag names that need prompting should have truthy values.
4359
- * Flags not mentioned are handled by their per-flag `.prompt()` config.
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
+ * ```
4360
4730
  */
4361
- type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
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
+ }
4362
4785
  /**
4363
- * Interactive resolver function for command-level prompt control.
4786
+ * Parameters received by a middleware function at runtime.
4364
4787
  *
4365
- * Called after CLI/env/config resolution but before per-flag prompts fire.
4366
- * Receives partially resolved values and returns a prompt schema for
4367
- * flags that should be prompted. Commands without `.interactive()` use
4368
- * per-flag prompt configs directly.
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.
4791
+ */
4792
+ interface MiddlewareParams {
4793
+ /** Fully resolved positional arguments (type-erased). */
4794
+ readonly args: Readonly<Record<string, unknown>>;
4795
+ /** Fully resolved flags (type-erased). */
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
+ */
4804
+ readonly sources: ErasedInputSources;
4805
+ /** Context accumulated from previous middleware in the chain. */
4806
+ readonly ctx: Readonly<Record<string, unknown>>;
4807
+ /** Output channel. */
4808
+ readonly out: Out;
4809
+ /** Invocation-scoped interactive questions. */
4810
+ readonly ask: Ask;
4811
+ /** CLI program metadata (name, bin, version, command). */
4812
+ readonly meta: CommandMeta;
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
+ }
4822
+ /**
4823
+ * Type-erased middleware handler stored on the command builder.
4824
+ *
4825
+ * At runtime, all middleware handlers have this signature. The phantom
4826
+ * `Output` type on {@linkcode Middleware} is erased.
4827
+ */
4828
+ type ErasedMiddlewareHandler = (params: MiddlewareParams) => void | Promise<void>;
4829
+ /**
4830
+ * Middleware handler function with typed `next()` parameter.
4831
+ *
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.
4834
+ */
4835
+ type MiddlewareHandler<Output extends Record<string, unknown>> = (params: {
4836
+ readonly args: Readonly<Record<string, unknown>>;
4837
+ readonly flags: Readonly<Record<string, unknown>>;
4838
+ readonly sources: ErasedInputSources;
4839
+ readonly ctx: Readonly<Record<string, unknown>>;
4840
+ readonly out: Out;
4841
+ /** Invocation-scoped interactive questions. */
4842
+ readonly ask: Ask;
4843
+ readonly meta: CommandMeta;
4844
+ /** Pass context additions downstream. Must include all `Output` properties. */
4845
+ readonly next: (additions: Output) => Promise<void>;
4846
+ }) => void | Promise<void>;
4847
+ /**
4848
+ * Internal runtime representation of middleware.
4849
+ */
4850
+ interface MiddlewareImpl {
4851
+ readonly _handler: ErasedMiddlewareHandler;
4852
+ }
4853
+ /**
4854
+ * Middleware with phantom output type.
4855
+ *
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()`.
4369
4862
  *
4370
4863
  * @example
4371
4864
  * ```ts
4372
- * import { command, flag } from '@kjanat/dreamcli';
4865
+ * interface User { id: string; name: string }
4373
4866
  *
4374
- * const deploy = command('deploy')
4375
- * .flag('region', flag.enum(['us', 'eu', 'ap']))
4376
- * .interactive(({ flags }) => ({
4377
- * region: !flags.region && {
4378
- * kind: 'select',
4379
- * message: 'Select region',
4380
- * },
4381
- * }))
4382
- * .action(({ flags, out }) => {
4383
- * out.log(`Deploying to ${flags.region}`);
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
+ * ```
4873
+ */
4874
+ type Middleware<Output extends Record<string, unknown>> = MiddlewareImpl & {
4875
+ /** @internal Phantom type brand — compile-time only. */
4876
+ readonly _output: Output;
4877
+ };
4878
+ /**
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!
4384
4910
  * });
4385
4911
  * ```
4386
4912
  */
4387
- type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (params: InteractiveParams<F>) => InteractiveResult;
4913
+ declare function middleware<Output extends Record<string, unknown>>(handler: MiddlewareHandler<Output>): Middleware<Output>;
4388
4914
  /**
4389
- * Type-erased interactive resolver stored on {@linkcode CommandSchema}.
4915
+ * Where a resolved value came from.
4390
4916
  *
4391
- * Advanced bridge type: most consumers should use {@link InteractiveResolver}
4392
- * via {@linkcode command | command().interactive()} and never reference this alias directly.
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.
4393
4921
  *
4394
- * At runtime, the resolver receives `{ flags: Record<string, unknown> }`
4395
- * and returns `Record<string, PromptConfig | falsy>`. The phantom types
4396
- * from `CommandBuilder<F, A>` are erased.
4922
+ * @module dreamcli/core/schema/provenance
4397
4923
  */
4398
- type ErasedInteractiveResolver = (params: {
4399
- readonly flags: Readonly<Record<string, unknown>>;
4400
- }) => InteractiveResult;
4401
4924
  /**
4402
- * Seals {@linkcode Out} against structural construction outside the framework.
4925
+ * Which stage produced a resolved value, and how.
4403
4926
  *
4404
- * @internal
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
+ * ```
4405
4949
  */
4406
- declare const outBrand: unique symbol;
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
+ };
4407
4976
  /**
4408
- * Output channel available inside action handlers.
4977
+ * Provenance of every input of one surface, keyed by input name.
4409
4978
  *
4410
- * Provides structured methods for stdout/stderr, JSON output,
4411
- * spinners, progress bars, and tables. The real implementation lives in
4412
- * `src/core/output/`; this interface defines the shape that handlers consume.
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.
4413
4981
  *
4414
- * `Out` is a framework-created, non-exhaustive value: obtain instances from
4415
- * action parameters, `createOutput()`, or `createCaptureOutput()` — do not
4416
- * implement it. New readonly members may be added in minor releases.
4982
+ * @typeParam T - The record of flag or arg builders whose keys this mirrors.
4417
4983
  */
4418
- interface Out {
4419
- /** Framework-construction seal. Obtain `Out` values from DreamCLI; do not implement this interface. */
4420
- readonly [outBrand]: never;
4421
- /** Write to stdout (normal output). */
4422
- log(message: string): void;
4423
- /** Informational (may be suppressed in quiet mode). */
4424
- info(message: string): void;
4425
- /**
4426
- * Status line to stderr, suppressed in quiet mode.
4427
- *
4984
+ type SourcesOf<T> = { readonly [K in keyof T]: ResolutionProvenance | undefined; };
4985
+ /**
4986
+ * Where each of a command's resolved values came from.
4987
+ *
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.
4993
+ */
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>;
4999
+ }
5000
+ /**
5001
+ * Whether a value came from somewhere other than its declared default.
5002
+ *
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.
5006
+ *
5007
+ * Read `stage` directly for a narrower question, such as `stage === 'cli'` for
5008
+ * "the user typed it on this command line".
5009
+ *
5010
+ * @param source - The provenance record of one input, or `undefined`.
5011
+ * @returns `true` when a source other than the default produced the value.
5012
+ *
5013
+ * @example
5014
+ * ```ts
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
+ * });
5020
+ * ```
5021
+ */
5022
+ declare function wasExplicit(source: ResolutionProvenance | undefined): boolean;
5023
+ /**
5024
+ * Widen the context type when adding middleware.
5025
+ *
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`.
5030
+ *
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.
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.
5041
+ */
5042
+ type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
5043
+ /**
5044
+ * Parameters received by the interactive resolver function.
5045
+ *
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.
5056
+ *
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.
5071
+ *
5072
+ * @example
5073
+ * ```ts
5074
+ * import { command, flag } from '@kjanat/dreamcli';
5075
+ *
5076
+ * const deploy = command('deploy')
5077
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
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}`);
5086
+ * });
5087
+ * ```
5088
+ */
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;
5127
+ /**
5128
+ * Status line to stderr, suppressed in quiet mode.
5129
+ *
4428
5130
  * Keeps stdout clean for piping; for success and progress notes like
4429
5131
  * `Wrote <path>` that scripts silence with `--quiet`.
4430
5132
  */
@@ -4480,6 +5182,8 @@ interface Out {
4480
5182
  * decorative output should be suppressed regardless of `isTTY`.
4481
5183
  */
4482
5184
  readonly isTTY: boolean;
5185
+ /** Terminal dimensions captured when the output channel was created, if available. */
5186
+ readonly terminalSize: TerminalSize | undefined;
4483
5187
  /**
4484
5188
  * Context-aware ANSI color palette (powered by `ansispeck`).
4485
5189
  *
@@ -4755,6 +5459,8 @@ interface CommandSchema {
4755
5459
  readonly name: string;
4756
5460
  /** Human-readable description for help text. */
4757
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;
4758
5464
  /** Alternative names for this command. */
4759
5465
  readonly aliases: readonly string[];
4760
5466
  /** Whether this command is hidden from help listings. */
@@ -4763,8 +5469,14 @@ interface CommandSchema {
4763
5469
  readonly examples: readonly CommandExample[];
4764
5470
  /** Named flag schemas, keyed by flag name. */
4765
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;
4766
5474
  /** Ordered positional arg entries (name + schema). */
4767
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;
4768
5480
  /** Whether an action handler has been registered. */
4769
5481
  readonly hasAction: boolean;
4770
5482
  /**
@@ -4823,6 +5535,8 @@ interface CommandDefinition {
4823
5535
  * @defaultValue `undefined`
4824
5536
  */
4825
5537
  readonly description?: string | undefined;
5538
+ /** Longer explanation shown only in this command's help. */
5539
+ readonly details?: HelpDescription | undefined;
4826
5540
  /**
4827
5541
  * Alternative names for this command.
4828
5542
  * @defaultValue `[]`
@@ -4843,11 +5557,17 @@ interface CommandDefinition {
4843
5557
  * @defaultValue `{}`
4844
5558
  */
4845
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;
4846
5562
  /**
4847
5563
  * Ordered positional arg entries.
4848
5564
  * @defaultValue `[]`
4849
5565
  */
4850
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;
4851
5571
  /**
4852
5572
  * Whether an action handler has been registered.
4853
5573
  * @defaultValue `false`
@@ -4921,6 +5641,10 @@ declare function createCommandSchema(definition: CommandDefinition): CommandSche
4921
5641
  *
4922
5642
  */
4923
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;
4924
5648
  /**
4925
5649
  * Immutable command schema builder.
4926
5650
  *
@@ -4981,6 +5705,17 @@ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> =
4981
5705
  * @param executionSteps - Derive/middleware steps in registration order.
4982
5706
  */
4983
5707
  constructor(schema: CommandSchema, handler?: ErasedActionHandler, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);
5708
+ /**
5709
+ * Declare typed relationships between already-resolved flags and arguments.
5710
+ * A bare name selects a flag when both kinds use the same name.
5711
+ */
5712
+ constrain(build: (builder: ConstraintBuilder<Extract<keyof F, string>, Extract<keyof A, string>>) => readonly CommandConstraint[]): CommandBuilder<F, A, C>;
5713
+ /**
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.
5717
+ */
5718
+ validate(validator: StandardSchemaV1, options?: CommandValidationOptions): CommandBuilder<F, A, C>;
4984
5719
  /**
4985
5720
  * Register a command-level interactive resolver for schema-driven prompts.
4986
5721
  *
@@ -5133,6 +5868,16 @@ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> =
5133
5868
  * @returns The builder (for chaining).
5134
5869
  */
5135
5870
  description(text: string): CommandBuilder<F, A, C>;
5871
+ /**
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.
5876
+ *
5877
+ * @param text - Literal text or a function that styles the explanation.
5878
+ * @returns A new builder with the explanation.
5879
+ */
5880
+ details(text: HelpDescription): CommandBuilder<F, A, C>;
5136
5881
  /**
5137
5882
  * Add an alternative name for this command.
5138
5883
  *
@@ -5235,469 +5980,216 @@ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> =
5235
5980
  * .env('PORT')
5236
5981
  * .default(3000)
5237
5982
  * .describe('Port to listen on'))
5238
- * .flag('host', flag.string()
5239
- * .env('HOST')
5240
- * .default('localhost')
5241
- * .describe('Bind address'))
5242
- * .flag('verbose', flag.boolean()
5243
- * .alias('v')
5244
- * .describe('Enable verbose logging'))
5245
- * .action(({ flags, out }) => {
5246
- * flags.port; // number
5247
- * flags.host; // string
5248
- * flags.verbose; // boolean
5249
- * out.log(`Listening on ${flags.host}:${flags.port}`);
5250
- * });
5251
- *
5252
- * // $ mycli serve --port 8080 -v
5253
- * // $ PORT=9090 mycli serve
5254
- * ```
5255
- *
5256
- * @returns The builder (for chaining).
5257
- * @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
5258
- * which a plain record cannot carry.
5259
- * @throws {@link CLIError} `FLAG_NAME_COLLISION` when the command already
5260
- * declares this name, or the new flag's spellings collide with another
5261
- * flag's.
5262
- * @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling
5263
- * collides with one propagated to a registered subcommand.
5264
- */
5265
- flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof F>, builder: B): CommandBuilder<F & Record<N, B>, A, C>;
5266
- /**
5267
- * Register a named positional argument on this command.
5268
- *
5269
- * Args are ordered by registration — position on the CLI matches the
5270
- * order of `.arg()` calls. The arg name is added to the type-level `A`
5271
- * map. Duplicate arg names are prevented at the type level via the
5272
- * `Exclude` constraint.
5273
- *
5274
- * The builder controls the arg's type, presence, env binding, and
5275
- * description. See {@link ArgBuilder} for available modifiers.
5276
- *
5277
- * @param name - Positional arg name (used in help text and `args.*`).
5278
- * @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
5279
- * or `arg.custom()`.
5280
- *
5281
- * @example
5282
- * ```ts
5283
- * command('deploy')
5284
- * // Required string arg — first positional
5285
- * .arg('target', arg.string()
5286
- * .env('DEPLOY_TARGET')
5287
- * .describe('Deploy target'))
5288
- * // Optional number arg — second positional
5289
- * .arg('port', arg.number()
5290
- * .env('PORT')
5291
- * .default(3000)
5292
- * .describe('Port number'))
5293
- * .action(({ args }) => {
5294
- * args.target; // string
5295
- * args.port; // number
5296
- * });
5297
- *
5298
- * // Usage: deploy [flags] <target> [port]
5299
- * // $ mycli deploy production 8080
5300
- * // $ DEPLOY_TARGET=staging mycli deploy
5301
- * ```
5302
- *
5303
- * @returns The builder (for chaining).
5304
- * @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
5305
- * which a plain record cannot carry.
5306
- * @throws {@link CLIError} `INVALID_BUILDER_STATE` when an earlier arg on this
5307
- * command is variadic, so this one could never be filled.
5308
- * @throws {@link CLIError} `DUPLICATE_STDIN_INPUT` when another input on this
5309
- * command already consumes stdin exclusively.
5310
- */
5311
- arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
5312
- /**
5313
- * Register a nested subcommand on this command.
5314
- *
5315
- * The subcommand's builder is stored in `_subcommands` for the CLI layer's
5316
- * `compileCommand()` to traverse when building the execution graph. The
5317
- * subcommand's `CommandSchema` is also appended to `schema.commands` for
5318
- * help rendering and completion generation.
5319
- *
5320
- * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
5321
- * parent level (same semantics as `CLIBuilder.command()`). The handler is
5322
- * preserved.
5323
- *
5324
- * @example
5325
- * ```ts
5326
- * const db = group('db')
5327
- * .description('Database operations')
5328
- * .command(migrateCmd)
5329
- * .command(seedCmd);
5330
- * ```
5331
- *
5332
- * @param sub - Child {@link CommandBuilder} to nest under this command.
5333
- * @returns The builder (for chaining).
5334
- * @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling this
5335
- * command propagates collides with one the subcommand, or any of its own
5336
- * descendants, declares.
5337
- */
5338
- 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>;
5339
- /**
5340
- * Register the action handler for this command.
5341
- *
5342
- * The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
5343
- * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
5344
- * definitions.
5345
- *
5346
- * May be synchronous or async. Return values are ignored; command handlers
5347
- * communicate through `out`, thrown errors, and side effects.
5348
- *
5349
- * @param handler - Function receiving `ActionParams<F, A, C>`.
5350
- *
5351
- * @example
5352
- * ```ts
5353
- * // Minimal
5354
- * command('greet')
5355
- * .arg('name', arg.string())
5356
- * .action(({ args, out }) => {
5357
- * out.log(`Hello, ${args.name}!`);
5358
- * });
5359
- * ```
5360
- *
5361
- * @example
5362
- * ```ts
5363
- * // Full params — flags, args, context, output, metadata
5364
- * command('deploy')
5365
- * .arg('target', arg.string().env('DEPLOY_TARGET'))
5366
- * .flag('force', flag.boolean().alias('f'))
5367
- * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
5368
- * .middleware(auth)
5369
- * .action(async ({ args, flags, ctx, out, meta }) => {
5370
- * args.target; // string
5371
- * flags.force; // boolean
5372
- * flags.region; // 'us' | 'eu' | 'ap' | undefined
5373
- * ctx.user; // User (from auth middleware)
5374
- * meta.command; // string
5375
- *
5376
- * const spinner = out.spinner('Deploying...');
5377
- * await deploy(args.target, { force: flags.force });
5378
- * spinner.stop();
5379
- * out.log('Done');
5380
- * });
5381
- * ```
5382
- *
5383
- * @returns The builder (for chaining).
5384
- */
5385
- action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
5386
- }
5387
- /**
5388
- * Create a new command builder.
5389
- *
5390
- * @param name - The command name used for dispatch (e.g. `'deploy'`).
5391
- *
5392
- * @example
5393
- * ```ts
5394
- * import { arg, command, flag } from '@kjanat/dreamcli';
5395
- *
5396
- * const greet = command('greet')
5397
- * .arg('name', arg.string())
5398
- * .flag('loud', flag.boolean())
5399
- * .action(({ args, flags, out }) => {
5400
- * const msg = `Hello, ${args.name}!`;
5401
- * out.log(flags.loud ? msg.toUpperCase() : msg);
5402
- * });
5403
- * ```
5404
- *
5405
- * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
5406
- */
5407
- declare function command(name: string): CommandBuilder;
5408
- /**
5409
- * Create a command builder intended for use as a command group.
5410
- *
5411
- * Semantically identical to {@linkcode command | command()} — a group is simply a command that
5412
- * has subcommands registered via `.command()`. The separate factory
5413
- * communicates intent: groups organise subcommands, leaf commands have actions.
5414
- *
5415
- * A group may also have its own `.action()` (e.g. `git remote` lists remotes
5416
- * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
5417
- *
5418
- * @param name - The group name used for dispatch (e.g. `'db'`).
5419
- *
5420
- * @example
5421
- * ```ts
5422
- * const db = group('db')
5423
- * .description('Database operations')
5424
- * .command(migrateCmd)
5425
- * .command(seedCmd);
5426
- * ```
5427
- *
5428
- * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
5429
- */
5430
- declare function group(name: string): CommandBuilder;
5431
- /**
5432
- * A select prompt config with choices guaranteed non-empty.
5433
- *
5434
- * The resolution chain populates choices from `FlagSchema.enumValues`
5435
- * when the user's {@linkcode PromptConfig} omits them.
5436
- */
5437
- interface ResolvedSelectPromptConfig extends PromptConfigBase {
5438
- /** Discriminant — single-choice selection prompt. */
5439
- readonly kind: 'select';
5440
- /** User-facing question text. */
5441
- readonly message: string;
5442
- /** Non-empty list of selectable options (populated from flag enum values when omitted). */
5443
- readonly choices: readonly [SelectChoice, ...SelectChoice[]];
5444
- }
5445
- /**
5446
- * A multiselect prompt config with choices guaranteed non-empty.
5447
- *
5448
- * Same guarantee as {@linkcode ResolvedSelectPromptConfig} — choices are always
5449
- * present and non-empty.
5450
- */
5451
- interface ResolvedMultiselectPromptConfig extends PromptConfigBase {
5452
- /** Discriminant — multiple-choice selection prompt. */
5453
- readonly kind: 'multiselect';
5454
- /** User-facing question text. */
5455
- readonly message: string;
5456
- /** Non-empty list of selectable options (populated from flag enum values when omitted). */
5457
- readonly choices: readonly [SelectChoice, ...SelectChoice[]];
5458
- /** Minimum number of selections required (validated after input). */
5459
- readonly min?: number;
5460
- /** Maximum number of selections allowed (validated after input). */
5461
- readonly max?: number;
5462
- }
5463
- /**
5464
- * Prompt config variant where select/multiselect choices are guaranteed
5465
- * present. The prompt engine receives this (not raw {@linkcode PromptConfig}),
5466
- * so it never needs to merge enum values from `FlagSchema`.
5467
- *
5468
- * confirm and input configs pass through unchanged.
5469
- */
5470
- type ResolvedPromptConfig = ConfirmPromptConfig | InputPromptConfig | PasswordPromptConfig | ResolvedSelectPromptConfig | ResolvedMultiselectPromptConfig;
5471
- /**
5472
- * Prompt engine interface.
5473
- *
5474
- * Implementations present one prompt per `promptOne()` call and return
5475
- * the result. Engines may retain state across calls, such as an answer queue.
5476
- *
5477
- * The resolution chain calls `promptOne` for each flag that needs
5478
- * interactive input. Engines do not need schema knowledge — all
5479
- * relevant context (message, choices, validation) is in the config.
5480
- *
5481
- * @example
5482
- * ```ts
5483
- * // Custom engine (e.g. wrapping @clack/prompts)
5484
- * const engine: PromptEngine = {
5485
- * async promptOne(config) {
5486
- * // ... render with your library
5487
- * return { answered: true, value: userInput };
5488
- * }
5489
- * };
5490
- * ```
5491
- */
5492
- interface PromptEngine {
5493
- /**
5494
- * Present a single prompt and return the user's response.
5495
- *
5496
- * @param config - The resolved prompt configuration (choices guaranteed
5497
- * for select/multiselect).
5498
- * @returns The user's answer, `{ answered: false }` if cancelled, or
5499
- * `{ answered: false, reason: 'invalid' }` when invalid attempts are exhausted.
5500
- */
5501
- promptOne(config: ResolvedPromptConfig): Promise<PromptResult>;
5502
- }
5503
- /**
5504
- * A function that reads a single line of user input.
5505
- *
5506
- * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
5507
- * indicating the user closed the input stream (treated as cancel).
5508
- *
5509
- * The terminal prompter uses this as its sole input seam. The
5510
- * resolution chain (prompt-adapter-1) will wire this to the
5511
- * runtime adapter's stdin.
5512
- */
5513
- type ReadFn = () => Promise<string | null>;
5514
- /**
5515
- * Prepare a {@linkcode ResolvedPromptConfig} from a raw {@linkcode PromptConfig} and optional
5516
- * enum values from the flag schema.
5517
- *
5518
- * For select/multiselect prompts without explicit choices, this merges
5519
- * the flag's enum values into the choices list. Throws if no choices
5520
- * are available.
5521
- *
5522
- * This function is called by the resolution chain (prompt-resolve-1),
5523
- * not by the engine itself — keeping the engine free of schema knowledge.
5524
- *
5525
- * @param config - Raw prompt config from `FlagSchema.prompt`
5526
- * @param enumValues - Optional enum values from `FlagSchema.enumValues`
5527
- * @returns Resolved config with choices guaranteed for select kinds
5528
- * @throws Error if select/multiselect has no choices and no enum values
5529
- */
5530
- declare function resolvePromptConfig(config: PromptConfig, enumValues: readonly string[] | undefined): ResolvedPromptConfig;
5531
- /**
5532
- * Minimal I/O seam — the only write primitive the output module depends on.
5533
- *
5534
- * Extracted to its own file so that both `index.ts` (OutputChannel) and
5535
- * `activity.ts` (handle classes) can import it without a circular dependency.
5536
- *
5537
- * @module dreamcli/core/output/writer
5538
- */
5539
- /**
5540
- * A function that writes a string somewhere.
5541
- *
5542
- * This is the only write primitive the output layer depends on.
5543
- * In production it usually wraps `process.stdout.write` or
5544
- * `process.stderr.write`; in tests it is often a simple string accumulator.
5545
- *
5546
- * The contract is intentionally tiny:
5547
- * - writes are synchronous fire-and-forget
5548
- * - callers decide whether to append a trailing newline
5549
- * - there is no backpressure or flush signal
5550
- *
5551
- * @example
5552
- * ```ts
5553
- * const lines: string[] = [];
5554
- * const write: WriteFn = (data) => {
5555
- * lines.push(data);
5556
- * };
5557
- * ```
5558
- */
5559
- type WriteFn = (data: string) => void;
5560
- /**
5561
- * Configuration for creating an output channel.
5562
- *
5563
- * Every field is optional — sensible defaults are applied when omitted.
5564
- */
5565
- interface OutputOptions {
5566
- /**
5567
- * Writer for stdout-bound messages (`log`, `info`, `json`).
5568
- * Defaults to `process.stdout.write` when running in Node/Bun.
5569
- */
5570
- readonly stdout?: WriteFn;
5571
- /**
5572
- * Writer for stderr-bound messages (`warn`, `error`).
5573
- * In JSON mode, `log` and `info` are also redirected here so that
5574
- * stdout contains only structured JSON output.
5575
- * Defaults to `process.stderr.write` when running in Node/Bun.
5576
- */
5577
- readonly stderr?: WriteFn;
5578
- /**
5579
- * Whether stdout is connected to a TTY.
5580
- * When `false`, output may omit ANSI codes and decorations.
5581
- * Defaults to `false` (safe default — non-TTY until proven otherwise).
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.
5582
6009
  */
5583
- readonly isTTY?: boolean;
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>;
5584
6011
  /**
5585
- * Verbosity level.
5586
- * - `'normal'` (default) — emit all messages
5587
- * - `'quiet'` — suppress `info` messages
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
+ * ```
5588
6028
  */
5589
- readonly verbosity?: Verbosity;
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>;
5590
6030
  /**
5591
- * Enable JSON output mode.
6031
+ * Register a named positional argument on this command.
5592
6032
  *
5593
- * When `true`, `log` and `info` messages are redirected to stderr
5594
- * so that stdout is reserved exclusively for structured `json()` output.
5595
- * `warn` and `error` continue to write to stderr as normal.
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.
5596
6037
  *
5597
- * @defaultValue `false`
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.
5598
6074
  */
5599
- readonly jsonMode?: boolean;
6075
+ arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
5600
6076
  /**
5601
- * Explicitly enable or disable ANSI colors on `out.color`.
6077
+ * Register a nested subcommand on this command.
5602
6078
  *
5603
- * When set, this wins over the auto-gate — use it to force colors in
5604
- * captured test output or when embedding into a host that manages its
5605
- * own color policy.
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.
5606
6083
  *
5607
- * @defaultValue auto — enabled when `isTTY` is `true`, `jsonMode` is
5608
- * `false`, and the environment supports color (`NO_COLOR`,
5609
- * `FORCE_COLOR`, `--no-color`, `--color`, `CI` are respected).
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.
5610
6101
  */
5611
- readonly color?: boolean;
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>;
5612
6103
  /**
5613
- * Resolved OSC 8 hyperlink support for `out.isHyperlinkSupported`.
6104
+ * Register the action handler for this command.
5614
6105
  *
5615
- * When set, this wins over the `isTTY` fallback. Callers pass the
5616
- * `NO_HYPERLINKS`/`FORCE_HYPERLINKS` (and `--no-hyperlinks`/`--hyperlinks`)
5617
- * decision here via {@linkcode resolveHyperlinkOverride}, keeping `process`
5618
- * 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.
5619
6109
  *
5620
- * @defaultValue `isTTY`
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).
5621
6148
  */
5622
- readonly hyperlinks?: boolean;
6149
+ action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
5623
6150
  }
5624
6151
  /**
5625
- * Create an output channel.
5626
- *
5627
- * Low-level factory: action handlers already receive `out` automatically from
5628
- * `cli()`, `.execute()`, and `runCommand()`. Call `createOutput()` when you
5629
- * are embedding DreamCLI primitives into a custom runtime or need a standalone
5630
- * output implementation outside the normal command pipeline.
5631
- *
5632
- * @param options - Optional configuration. When omitted, output is
5633
- * discarded (useful for silent test runs). Pass `stdout`/`stderr`
5634
- * writers to direct output somewhere useful.
6152
+ * Create a new command builder.
5635
6153
  *
5636
- * @returns An {@link Out} instance backed by an {@link OutputChannel}.
6154
+ * @param name - The command name used for dispatch (e.g. `'deploy'`).
5637
6155
  *
5638
6156
  * @example
5639
6157
  * ```ts
5640
- * // Production (wired by the runtime adapter)
5641
- * const out = createOutput({
5642
- * stdout: (s) => process.stdout.write(s),
5643
- * stderr: (s) => process.stderr.write(s),
5644
- * isTTY: process.stdout.isTTY === true,
5645
- * });
6158
+ * import { arg, command, flag } from '@kjanat/dreamcli';
5646
6159
  *
5647
- * // Test (capture output)
5648
- * const lines: string[] = [];
5649
- * const out = createOutput({
5650
- * stdout: (s) => lines.push(s),
5651
- * stderr: (s) => lines.push(s),
5652
- * });
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
+ * });
5653
6167
  * ```
6168
+ *
6169
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
5654
6170
  */
5655
- declare function createOutput(options?: OutputOptions): Out;
5656
- /** Captured output from a `createCaptureOutput` instance. */
5657
- interface CapturedOutput {
5658
- /**
5659
- * Lines written to stdout.
5660
- *
5661
- * In normal mode: `log`, `info`, and `json` output.
5662
- * In JSON mode: only `json` output (log/info redirected to stderr).
5663
- */
5664
- readonly stdout: string[];
5665
- /**
5666
- * Lines written to stderr.
5667
- *
5668
- * In normal mode: `warn` and `error` output.
5669
- * In JSON mode: `warn`, `error`, `log`, and `info` output.
5670
- */
5671
- readonly stderr: string[];
5672
- /**
5673
- * Activity events from spinner and progress handles.
5674
- *
5675
- * Captured separately from stdout/stderr to allow targeted assertions
5676
- * on activity lifecycle without parsing text output. Events are
5677
- * recorded in chronological order.
5678
- */
5679
- readonly activity: ActivityEvent[];
5680
- }
6171
+ declare function command(name: string): CommandBuilder;
5681
6172
  /**
5682
- * Create an output channel that captures all output into arrays.
6173
+ * Create a command builder intended for use as a command group.
5683
6174
  *
5684
- * Useful in tests to assert on what a handler wrote without touching
5685
- * real I/O.
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.
5686
6178
  *
5687
- * @param options - Optional {@link OutputOptions} (minus `stdout`/`stderr`,
5688
- * which are wired to the capture buffers automatically).
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.).
5689
6181
  *
5690
- * @returns A tuple of `[out, captured]` — the {@link Out} channel and the
5691
- * {@link CapturedOutput} buffers.
6182
+ * @param name - The group name used for dispatch (e.g. `'db'`).
5692
6183
  *
5693
6184
  * @example
5694
6185
  * ```ts
5695
- * const [out, captured] = createCaptureOutput();
5696
- * out.log('hello');
5697
- * out.warn('danger');
5698
- * expect(captured.stdout).toEqual(['hello\n']);
5699
- * expect(captured.stderr).toEqual(['danger\n']);
6186
+ * const db = group('db')
6187
+ * .description('Database operations')
6188
+ * .command(migrateCmd)
6189
+ * .command(seedCmd);
5700
6190
  * ```
6191
+ *
6192
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
5701
6193
  */
5702
- declare function createCaptureOutput(options?: Omit<OutputOptions, 'stdout' | 'stderr'>): [out: Out, captured: CapturedOutput];
5703
- export { ArgDefinitionOverrides as $, TableFormat as $n, StringElementConfig as $t, Out as A, PasswordPromptConfig as An, BooleanFlagDefinition as At, MiddlewareHandler as B, IndexedEnvBinding as Bn, FlagDefinitionByKind as Bt, ErasedActionHandler as C, StandardSchemaV1Props as Cn, SourceSplitBinding as Ct, InteractiveParams as D, ConfirmPromptConfig as Dn, SplitPolicy as Dt, ExecutionStep as E, StandardSchemaV1Types as En, SplitOptions as Et, InputSources as F, SelectChoice as Fn, EnumFlagDefinition as Ft, prompt as G, HelpThemeFactory as Gn, FlagParseFn as Gt, middleware as H, IndexedValueEnvBinding as Hn, FlagFactory as Ht, ResolutionProvenance as I, SelectPromptConfig as In, FlagBuilder as It, ArgConfig as J, ProgressHandle as Jn, InferFlag as Jt, Verbosity as K, ActivityEvent as Kn, FlagPresence as Kt, SourcesOf as L, NumberConstraintViolation as Ln, FlagConfig as Lt, createCommandSchema as M, PromptConfigBase as Mn, CustomFlagDefinition as Mt, group as N, PromptKind as Nn, DefaultValueOptions as Nt, InteractiveResolver as O, InputPromptConfig as On, SplitSetting as Ot, resolveExampleCommand as P, PromptResult as Pn, DuplicatePolicy as Pt, ArgDefinitionByKind as Q, TableColumn as Qn, ResolvedValue as Qt, wasExplicit as R, NumberConstraints as Rn, FlagDefinition as Rt, DeriveParams as S, StandardSchemaV1PathSegment as Sn, SPLIT_FORMATS as St, ExampleMeta as T, StandardSchemaV1SuccessResult as Tn, SplitFormat as Tt, Ask as U, HelpDescription as Un, FlagKind as Ut, MiddlewareParams as V, IndexedRecordEnvBinding as Vn, FlagDefinitionOverrides as Vt, InferPrompt as W, HelpTheme as Wn, FlagNegation as Wt, ArgDefinition as X, SpinnerHandle as Xn, KeyValueFlagDefinition as Xt, ArgDefaultValue as Y, ProgressOptions as Yn, InferFlags as Yt, ArgDefinitionBase as Z, SpinnerOptions as Zn, NumberFlagDefinition as Zt, CommandDefinition as _, InferStandardOutput as _n, WithoutArgElementEligibility as _t, WriteFn as a, getFlagNegatedName as an, BooleanArgDefinition as at, CommandSchema as b, StandardSchemaV1Issue as bn, DUPLICATE_KEYS as bt, ResolvedMultiselectPromptConfig as c, PathFlagOptions as cn, InferArg as ct, resolvePromptConfig as d, StringConstraints as dn, NumberArgDefinition as dt, StringFlagDefinition as en, TableOptions as er, ArgFactory as et, ActionHandler as f, StdinBinding as fn, ResolvedArgValue as ft, CommandBuilder as g, InferStandardInput as gn, WithVariadic as gt, CommandArgEntryDefinition as h, StdinWhen as hn, WithArgPresence as ht, createOutput as i, flag as in, ArgSchema as it, command as j, PromptConfig as jn, CountFlagDefinition as jt, InteractiveResult as k, MultiselectPromptConfig as kn, ArrayFlagDefinition as kt, ResolvedPromptConfig as l, UrlFlagOptions as ln, InferArgs as lt, CommandArgEntry as m, StdinOptions as mn, StringArgElementConfig as mt, OutputOptions as n, WithoutElementEligibility as nn, schemaBrand as nr, ArgParseFn as nt, PromptEngine as o, DateFlagOptions as on, CustomArgDefinition as ot, ActionParams as p, StdinConsume as pn, StringArgDefinition as pt, ArgBuilder as q, Fallback as qn, FlagSchema as qt, createCaptureOutput as r, createFlagSchema as rn, ArgPresence as rt, ReadFn as s, PathChecks as sn, EnumArgDefinition as st, CapturedOutput as t, WithPresence as tn, TableStream as tr, ArgKind as tt, ResolvedSelectPromptConfig as u, StringConstraintViolation as un, KeyValueArgDefinition as ut, CommandExample as v, StandardSchemaV1 as vn, arg as vt, ExampleCommand as w, StandardSchemaV1Result as wn, SplitBinding as wt, DeriveHandler as x, StandardSchemaV1Options as xn, DuplicateKeys as xt, CommandMeta as y, StandardSchemaV1FailureResult as yn, createArgSchema as yt, Middleware as z, EnvOptions as zn, FlagDefinitionBase as zt };
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 };