@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3

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 (137) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.d.mts +7 -3
  66. package/dist/version.mjs +7 -1
  67. package/package.json +21 -26
  68. package/src/core/cli/dispatch.ts +0 -355
  69. package/src/core/cli/help-links.ts +0 -82
  70. package/src/core/cli/index.ts +0 -1614
  71. package/src/core/cli/planner.ts +0 -656
  72. package/src/core/cli/plugin.ts +0 -117
  73. package/src/core/cli/propagate.ts +0 -97
  74. package/src/core/cli/root-help.ts +0 -342
  75. package/src/core/cli/root-surface.ts +0 -87
  76. package/src/core/cli/runtime-preflight.ts +0 -456
  77. package/src/core/completion/index.ts +0 -138
  78. package/src/core/completion/shells/bash.ts +0 -459
  79. package/src/core/completion/shells/fish.ts +0 -259
  80. package/src/core/completion/shells/powershell.ts +0 -439
  81. package/src/core/completion/shells/shared.ts +0 -310
  82. package/src/core/completion/shells/zsh.ts +0 -381
  83. package/src/core/config/index.ts +0 -417
  84. package/src/core/config/package-json.ts +0 -560
  85. package/src/core/errors/index.ts +0 -193
  86. package/src/core/execution/index.ts +0 -265
  87. package/src/core/help/ansi.ts +0 -144
  88. package/src/core/help/index.ts +0 -563
  89. package/src/core/json-schema/index.ts +0 -910
  90. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  91. package/src/core/output/activity.ts +0 -575
  92. package/src/core/output/bind.ts +0 -59
  93. package/src/core/output/contracts.ts +0 -194
  94. package/src/core/output/display-value.ts +0 -48
  95. package/src/core/output/index.ts +0 -704
  96. package/src/core/output/renderers.ts +0 -125
  97. package/src/core/output/writer.ts +0 -46
  98. package/src/core/parse/index.ts +0 -742
  99. package/src/core/prompt/index.ts +0 -623
  100. package/src/core/resolve/args.ts +0 -144
  101. package/src/core/resolve/coerce.ts +0 -500
  102. package/src/core/resolve/config.ts +0 -26
  103. package/src/core/resolve/contracts.ts +0 -135
  104. package/src/core/resolve/errors.ts +0 -227
  105. package/src/core/resolve/flags.ts +0 -269
  106. package/src/core/resolve/index.ts +0 -108
  107. package/src/core/resolve/property.ts +0 -99
  108. package/src/core/schema/activity.ts +0 -240
  109. package/src/core/schema/arg.ts +0 -841
  110. package/src/core/schema/command.ts +0 -1500
  111. package/src/core/schema/flag.ts +0 -917
  112. package/src/core/schema/index.ts +0 -96
  113. package/src/core/schema/middleware.ts +0 -171
  114. package/src/core/schema/number-constraints.ts +0 -153
  115. package/src/core/schema/prompt.ts +0 -171
  116. package/src/core/schema/run.ts +0 -198
  117. package/src/core/schema-dsl/index.ts +0 -109
  118. package/src/core/schema-dsl/parse.ts +0 -262
  119. package/src/core/schema-dsl/runtime.ts +0 -609
  120. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  121. package/src/core/testkit/index.ts +0 -147
  122. package/src/index.ts +0 -181
  123. package/src/runtime/adapter.ts +0 -303
  124. package/src/runtime/auto.ts +0 -86
  125. package/src/runtime/bun.ts +0 -48
  126. package/src/runtime/deno.ts +0 -367
  127. package/src/runtime/detect.ts +0 -105
  128. package/src/runtime/index.ts +0 -21
  129. package/src/runtime/node-builtins.d.ts +0 -27
  130. package/src/runtime/node.ts +0 -289
  131. package/src/runtime/paths.ts +0 -64
  132. package/src/runtime/support.ts +0 -77
  133. package/src/runtime.ts +0 -31
  134. package/src/schema.ts +0 -16
  135. package/src/strings.ts +0 -34
  136. package/src/testkit.ts +0 -25
  137. package/src/version.ts +0 -20
@@ -1 +1,712 @@
1
- import{CLIError as e}from"../errors/index.mjs";function t(t,n,r){if(n.stdinMode&&n.variadic)throw new e(`Argument <${t}> cannot be both variadic and stdin-backed`,{code:`INVALID_BUILDER_STATE`,details:{arg:t,stdinMode:!0,variadic:!0},suggest:`Remove .stdin() or .variadic() from this argument`});if(!n.stdinMode)return;let i=r.find(e=>e.schema.stdinMode);if(i!==void 0)throw new e(`Only one stdin argument is allowed; <${i.name}> is already stdin-backed`,{code:`DUPLICATE_STDIN_ARG`,details:{arg:t,existingArg:i.name},suggest:`Keep .stdin() on a single argument per command`})}function n(e,t){return t===`alias`&&e.length===1?`-${e}`:`--${e}`}function r(e){if(e.kind===`canonical`)return`canonical flag ${n(e.name,e.kind)}`;let t=e.name.length===1?`short alias`:`long alias`;return`${e.hidden?`hidden `:``}${t} ${n(e.name,e.kind)}`}function i(e,t){return[{owner:e,name:e,kind:`canonical`,hidden:!1},...t.aliases.map(t=>({owner:e,name:t.name,kind:`alias`,hidden:t.hidden}))]}function a(t,i,a,o){let s=o?.inherited??!1,c=`flag ${n(a.owner,`canonical`)}`,l=`Command '${t}' ${c}`;throw new e(s?`${l} propagates ${r(a)}, which collides with ${r(i)} on flag ${n(i.owner,`canonical`)}`:`Command '${t}' flag ${n(i.owner,`canonical`)} ${r(i)} collides with ${r(a)} on ${c}`,{code:s?`PROPAGATED_FLAG_COLLISION`:`FLAG_NAME_COLLISION`,details:{command:t,flag:i.owner,surface:i.name,surfaceKind:i.kind,hidden:i.hidden,existingFlag:a.owner,existingSurface:a.name,existingSurfaceKind:a.kind,existingHidden:a.hidden,inherited:s}})}function o(e,t){let n=new Map;for(let[r,o]of Object.entries(t))for(let t of i(r,o)){let r=n.get(t.name);r!==void 0&&a(e,t,r),n.set(t.name,t)}}function s(e,t,n){let r=new Map;for(let[e,n]of Object.entries(t))for(let t of i(e,n))r.set(t.name,t);for(let[t,o]of Object.entries(n))for(let n of i(t,o)){let t=r.get(n.name);t!==void 0&&a(e,n,t,{inherited:!0})}}function c(e,t){let n={...e};for(let e of Object.keys(t))delete n[e];for(let[e,r]of Object.entries(t))r.propagate&&(n[e]=r);return n}function l(e,t={}){o(e.name,e.flags);let n={...t};for(let t of Object.keys(e.flags))delete n[t];s(e.name,n,e.flags);let r=c(t,e.flags);for(let t of e.commands)l(t,r)}function u(e){return e}var d=class n{schema;handler;_subcommands;_executionSteps;constructor(e,t,n,r){this.schema=e,this.handler=t,this._subcommands=n??[],this._executionSteps=r??[]}interactive(e){let t=e;return new n({...this.schema,interactive:t},this.handler,this._subcommands,this._executionSteps)}derive(e){let t=e;return new n({...this.schema,hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`derive`,handler:t}])}middleware(e){return new n({...this.schema,middleware:[...this.schema.middleware,e._handler],hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`middleware`,handler:e._handler}])}description(e){return new n({...this.schema,description:e},this.handler,this._subcommands,this._executionSteps)}alias(e){return new n({...this.schema,aliases:[...this.schema.aliases,e]},this.handler,this._subcommands,this._executionSteps)}hidden(){return new n({...this.schema,hidden:!0},this.handler,this._subcommands,this._executionSteps)}example(e,t){let r=t===void 0?{command:e}:{command:e,description:t};return new n({...this.schema,examples:[...this.schema.examples,r]},this.handler,this._subcommands,this._executionSteps)}flag(t,r){if(t in this.schema.flags)throw new e(`Command '${this.schema.name}' already defines flag --${t}`,{code:`FLAG_NAME_COLLISION`,details:{command:this.schema.name,flag:t,surface:t,surfaceKind:`canonical`}});let i={...this.schema.flags,[t]:r.schema},a={...this.schema,flags:i,hasAction:!1};return l(a),new n(a,void 0,this._subcommands,this._executionSteps)}arg(e,r){t(e,r.schema,this.schema.args);let i={name:e,schema:r.schema},a=[...this.schema.args,i];return new n({...this.schema,args:a,hasAction:!1},void 0,this._subcommands,this._executionSteps)}command(e){let t={...this.schema,commands:[...this.schema.commands,e.schema]};return l(t),new n(t,this.handler,[...this._subcommands,u(e)],this._executionSteps)}action(e){return new n({...this.schema,hasAction:!0},e,this._subcommands,this._executionSteps)}};function f(e){return new d({name:e,description:void 0,aliases:[],hidden:!1,examples:[],flags:{},args:[],hasAction:!1,interactive:void 0,middleware:[],commands:[]})}function p(e){return f(e)}export{d as CommandBuilder,f as command,p as group};
1
+ import { CLIError } from "../errors/index.mjs";
2
+ //#region src/core/schema/command.ts
3
+ /**
4
+ * Validate a new arg entry against invariants before adding it to the command.
5
+ *
6
+ * @param name - Arg name being registered.
7
+ * @param schema - Runtime descriptor of the arg.
8
+ * @param args - Already-registered arg entries on this command.
9
+ *
10
+ * @throws {@link CLIError} `INVALID_BUILDER_STATE` if both `.stdin()` and `.variadic()` are set.
11
+ * @throws {@link CLIError} `DUPLICATE_STDIN_ARG` if another arg already uses `.stdin()`.
12
+ *
13
+ * @internal
14
+ */
15
+ function validateArgEntry(name, schema, args) {
16
+ if (schema.stdinMode && schema.variadic) throw new CLIError(`Argument <${name}> cannot be both variadic and stdin-backed`, {
17
+ code: "INVALID_BUILDER_STATE",
18
+ details: {
19
+ arg: name,
20
+ stdinMode: true,
21
+ variadic: true
22
+ },
23
+ suggest: "Remove .stdin() or .variadic() from this argument"
24
+ });
25
+ if (!schema.stdinMode) return;
26
+ const existing = args.find((entry) => entry.schema.stdinMode);
27
+ if (existing === void 0) return;
28
+ throw new CLIError(`Only one stdin argument is allowed; <${existing.name}> is already stdin-backed`, {
29
+ code: "DUPLICATE_STDIN_ARG",
30
+ details: {
31
+ arg: name,
32
+ existingArg: existing.name
33
+ },
34
+ suggest: "Keep .stdin() on a single argument per command"
35
+ });
36
+ }
37
+ function formatFlagToken(name, kind) {
38
+ return kind === "alias" && name.length === 1 ? `-${name}` : `--${name}`;
39
+ }
40
+ function describeFlagForm(form) {
41
+ if (form.kind === "canonical") return `canonical flag ${formatFlagToken(form.name, form.kind)}`;
42
+ const aliasType = form.name.length === 1 ? "short alias" : "long alias";
43
+ return `${form.hidden ? "hidden " : ""}${aliasType} ${formatFlagToken(form.name, form.kind)}`;
44
+ }
45
+ function listFlagForms(name, schema) {
46
+ return [{
47
+ owner: name,
48
+ name,
49
+ kind: "canonical",
50
+ hidden: false
51
+ }, ...schema.aliases.map((alias) => ({
52
+ owner: name,
53
+ name: alias.name,
54
+ kind: "alias",
55
+ hidden: alias.hidden
56
+ }))];
57
+ }
58
+ function throwFlagCollisionError(commandName, form, existing, options) {
59
+ const inherited = options?.inherited ?? false;
60
+ const existingOwner = `flag ${formatFlagToken(existing.owner, "canonical")}`;
61
+ const subject = `Command '${commandName}' ${existingOwner}`;
62
+ throw new CLIError(inherited ? `${subject} propagates ${describeFlagForm(existing)}, which collides with ${describeFlagForm(form)} on flag ${formatFlagToken(form.owner, "canonical")}` : `Command '${commandName}' flag ${formatFlagToken(form.owner, "canonical")} ${describeFlagForm(form)} collides with ${describeFlagForm(existing)} on ${existingOwner}`, {
63
+ code: inherited ? "PROPAGATED_FLAG_COLLISION" : "FLAG_NAME_COLLISION",
64
+ details: {
65
+ command: commandName,
66
+ flag: form.owner,
67
+ surface: form.name,
68
+ surfaceKind: form.kind,
69
+ hidden: form.hidden,
70
+ existingFlag: existing.owner,
71
+ existingSurface: existing.name,
72
+ existingSurfaceKind: existing.kind,
73
+ existingHidden: existing.hidden,
74
+ inherited
75
+ }
76
+ });
77
+ }
78
+ function validateLocalFlagCollisions(commandName, flags) {
79
+ const seen = /* @__PURE__ */ new Map();
80
+ for (const [name, schema] of Object.entries(flags)) for (const form of listFlagForms(name, schema)) {
81
+ const existing = seen.get(form.name);
82
+ if (existing !== void 0) throwFlagCollisionError(commandName, form, existing);
83
+ seen.set(form.name, form);
84
+ }
85
+ }
86
+ function validateInheritedFlagCollisions(commandName, inherited, local) {
87
+ const inheritedForms = /* @__PURE__ */ new Map();
88
+ for (const [name, schema] of Object.entries(inherited)) for (const form of listFlagForms(name, schema)) inheritedForms.set(form.name, form);
89
+ for (const [name, schema] of Object.entries(local)) for (const form of listFlagForms(name, schema)) {
90
+ const existing = inheritedForms.get(form.name);
91
+ if (existing !== void 0) throwFlagCollisionError(commandName, form, existing, { inherited: true });
92
+ }
93
+ }
94
+ function buildInheritedFlagsForChildren(inherited, local) {
95
+ const next = { ...inherited };
96
+ for (const name of Object.keys(local)) delete next[name];
97
+ for (const [name, schema] of Object.entries(local)) if (schema.propagate) next[name] = schema;
98
+ return next;
99
+ }
100
+ function validateCommandFlagTree(command, inheritedFlags = {}) {
101
+ validateLocalFlagCollisions(command.name, command.flags);
102
+ const visibleInherited = { ...inheritedFlags };
103
+ for (const name of Object.keys(command.flags)) delete visibleInherited[name];
104
+ validateInheritedFlagCollisions(command.name, visibleInherited, command.flags);
105
+ const inheritedForChildren = buildInheritedFlagsForChildren(inheritedFlags, command.flags);
106
+ for (const child of command.commands) validateCommandFlagTree(child, inheritedForChildren);
107
+ }
108
+ /**
109
+ * Erase a typed `CommandBuilder<F, A, C>` to `AnyCommandBuilder` for
110
+ * heterogeneous storage. Centralises the `as unknown as` double-cast
111
+ * required at the type-erasure boundary.
112
+ *
113
+ * @internal
114
+ */
115
+ function eraseBuilder(builder) {
116
+ return builder;
117
+ }
118
+ /**
119
+ * Immutable command schema builder.
120
+ *
121
+ * The type parameters `F` (flags), `A` (args), and `C` (context) are
122
+ * phantom types that accumulate builder types as `.flag()`, `.arg()`,
123
+ * `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
124
+ * fully typed `ActionParams<F, A, C>`.
125
+ *
126
+ * `C` defaults to `Record<string, never>`, making `ctx` property
127
+ * access a type error until derive or middleware extends it.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const deploy = command('deploy')
132
+ * .description('Deploy to an environment')
133
+ * .arg('target', arg.string().describe('Deploy target'))
134
+ * .flag('force', flag.boolean().alias('f'))
135
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
136
+ * .action(async ({ args, flags, out }) => {
137
+ * // args.target: string
138
+ * // flags.force: boolean
139
+ * // flags.region: 'us' | 'eu' | 'ap' | undefined
140
+ * out.log(`Deploying ${args.target}...`);
141
+ * });
142
+ * ```
143
+ */
144
+ var CommandBuilder = class CommandBuilder {
145
+ /** @internal Runtime schema descriptor. */
146
+ schema;
147
+ /** @internal The action handler, if registered (type-erased for covariance). */
148
+ handler;
149
+ /**
150
+ * @internal Nested sub-command builders (type-erased for heterogeneous storage).
151
+ *
152
+ * Stored separately from `schema.commands` because builders carry action
153
+ * handlers and phantom types needed by `eraseCommand()` in the CLI layer.
154
+ * `schema.commands` holds pure `CommandSchema[]` for help/completion.
155
+ */
156
+ _subcommands;
157
+ /**
158
+ * @internal Execution steps in registration order.
159
+ *
160
+ * Distinct from `schema.middleware`: middleware handlers remain in schema
161
+ * for backward compatibility, while derives stay command-local and builder-
162
+ * scoped so future shared/global middleware can compose cleanly.
163
+ */
164
+ _executionSteps;
165
+ /**
166
+ * Create a command builder from a pre-built schema descriptor.
167
+ *
168
+ * @param schema - Runtime command descriptor.
169
+ * @param handler - Action handler, if registered.
170
+ * @param subcommands - Nested sub-command builders (type-erased).
171
+ * @param executionSteps - Derive/middleware steps in registration order.
172
+ */
173
+ constructor(schema, handler, subcommands, executionSteps) {
174
+ this.schema = schema;
175
+ this.handler = handler;
176
+ this._subcommands = subcommands ?? [];
177
+ this._executionSteps = executionSteps ?? [];
178
+ }
179
+ /**
180
+ * Register a command-level interactive resolver for schema-driven prompts.
181
+ *
182
+ * The resolver is called after CLI/env/config resolution with partially
183
+ * resolved flag values. It returns a prompt schema for flags that need
184
+ * interactive input based on the current state.
185
+ *
186
+ * For flags the resolver returns a {@linkcode PromptConfig}, that config is used
187
+ * instead of any per-flag `.prompt()` config. For flags returned as falsy
188
+ * (or not mentioned), per-flag `.prompt()` configs are used as fallback.
189
+ *
190
+ * Commands without `.interactive()` use per-flag prompt configs directly.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * const deploy = command('deploy')
195
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
196
+ * .flag('force', flag.boolean())
197
+ * .interactive(({ flags }) => ({
198
+ * region: !flags.region && {
199
+ * kind: 'select',
200
+ * message: 'Select region',
201
+ * },
202
+ * }))
203
+ * .action(({ flags }) => { ... });
204
+ * ```
205
+ *
206
+ * @param resolver - Function receiving partially resolved flags and returning prompt configs.
207
+ * @returns The builder (for chaining).
208
+ */
209
+ interactive(resolver) {
210
+ const erased = resolver;
211
+ return new CommandBuilder({
212
+ ...this.schema,
213
+ interactive: erased
214
+ }, this.handler, this._subcommands, this._executionSteps);
215
+ }
216
+ /**
217
+ * Register a command-scoped typed pre-action handler.
218
+ *
219
+ * Derive runs after full resolution and before the action handler.
220
+ * It receives typed `{ args, flags, ctx, out, meta }` and may either:
221
+ *
222
+ * - return `undefined` for validation-only behavior
223
+ * - return an object to merge additional properties into `ctx`
224
+ *
225
+ * Unlike middleware, derive cannot wrap downstream execution and does not
226
+ * use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
227
+ * or error-boundary patterns.
228
+ *
229
+ * Adding derive drops the current handler (like `.flag()`, `.arg()`, and
230
+ * `.middleware()`) because the action handler's `ctx` type may change.
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * command('deploy')
235
+ * .flag('token', flag.string().env('AUTH_TOKEN'))
236
+ * .derive(({ flags }) => {
237
+ * if (!flags.token) {
238
+ * throw new CLIError('Not authenticated', {
239
+ * code: 'AUTH_REQUIRED',
240
+ * suggest: 'Run `mycli login` or set AUTH_TOKEN',
241
+ * });
242
+ * }
243
+ * return { token: flags.token };
244
+ * })
245
+ * .action(({ ctx }) => {
246
+ * ctx.token; // string
247
+ * });
248
+ * ```
249
+ *
250
+ * @param handler - Derive function receiving typed args/flags/ctx.
251
+ * @returns The builder (for chaining).
252
+ */
253
+ derive(handler) {
254
+ const erased = handler;
255
+ return new CommandBuilder({
256
+ ...this.schema,
257
+ hasAction: false
258
+ }, void 0, this._subcommands, [...this._executionSteps, {
259
+ kind: "derive",
260
+ handler: erased
261
+ }]);
262
+ }
263
+ /**
264
+ * Register middleware to run before the action handler.
265
+ *
266
+ * Middleware executes in registration order. Each middleware receives
267
+ * `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
268
+ * to continue the chain. Context additions are merged and become
269
+ * typed downstream.
270
+ *
271
+ * Adding middleware widens `C` via intersection and drops the current
272
+ * handler (like `.flag()` / `.arg()` — the handler's type signature
273
+ * changes when context changes).
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * import { CLIError, command, middleware } from '@kjanat/dreamcli';
278
+ *
279
+ * interface User {
280
+ * id: string;
281
+ * email: string;
282
+ * }
283
+ *
284
+ * async function getCurrentUser(): Promise<User | null> {
285
+ * return { id: 'u_123', email: 'dev@example.com' };
286
+ * }
287
+ *
288
+ * function startTrace(name: string): string {
289
+ * return `trace:${name}`;
290
+ * }
291
+ *
292
+ * // Resolve the current user and expose it as `ctx.user` downstream.
293
+ * const auth = middleware<{ user: User }>(async ({ next }) => {
294
+ * const user = await getCurrentUser();
295
+ * if (!user) {
296
+ * throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
297
+ * }
298
+ * await next({ user });
299
+ * });
300
+ *
301
+ * // Create a trace id for this command run and expose it as `ctx.traceId`.
302
+ * const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
303
+ * const traceId = startTrace(`${meta.name}.${meta.command}`);
304
+ * await next({ traceId });
305
+ * });
306
+ *
307
+ * command('deploy')
308
+ * .middleware(auth) // C becomes { user: User }
309
+ * .middleware(telemetry) // C becomes { user: User } & { traceId: string }
310
+ * .action(({ ctx }) => {
311
+ * ctx.user; // User — typed
312
+ * ctx.traceId; // string — typed
313
+ * });
314
+ * ```
315
+ *
316
+ * @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
317
+ * Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
318
+ * @returns The builder (for chaining).
319
+ */
320
+ middleware(m) {
321
+ return new CommandBuilder({
322
+ ...this.schema,
323
+ middleware: [...this.schema.middleware, m._handler],
324
+ hasAction: false
325
+ }, void 0, this._subcommands, [...this._executionSteps, {
326
+ kind: "middleware",
327
+ handler: m._handler
328
+ }]);
329
+ }
330
+ /**
331
+ * Set the command's description for help text.
332
+ *
333
+ * Displayed below the usage line in `--help` output and next to the
334
+ * command name in parent command/group help listings.
335
+ *
336
+ * @param text - One-line description of what the command does.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * command('deploy')
341
+ * .description('Deploy the application to a target environment')
342
+ * .action(({ out }) => { out.log('deploying...'); });
343
+ *
344
+ * // $ mycli deploy --help
345
+ * // Usage: deploy [flags]
346
+ * //
347
+ * // Deploy the application to a target environment
348
+ * ```
349
+ *
350
+ * @returns The builder (for chaining).
351
+ */
352
+ description(text) {
353
+ return new CommandBuilder({
354
+ ...this.schema,
355
+ description: text
356
+ }, this.handler, this._subcommands, this._executionSteps);
357
+ }
358
+ /**
359
+ * Add an alternative name for this command.
360
+ *
361
+ * Aliases are accepted during dispatch alongside the primary name.
362
+ * Multiple aliases can be chained. Aliases are shown in help output.
363
+ *
364
+ * @param name - Alternative command name (e.g. `'d'` for `deploy`).
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * command('deploy')
369
+ * .alias('d')
370
+ * .alias('push')
371
+ * .action(({ out }) => { out.log('deploying...'); });
372
+ *
373
+ * // All equivalent:
374
+ * // $ mycli deploy
375
+ * // $ mycli d
376
+ * // $ mycli push
377
+ * ```
378
+ *
379
+ * @returns The builder (for chaining).
380
+ */
381
+ alias(name) {
382
+ return new CommandBuilder({
383
+ ...this.schema,
384
+ aliases: [...this.schema.aliases, name]
385
+ }, this.handler, this._subcommands, this._executionSteps);
386
+ }
387
+ /**
388
+ * Hide this command from help listings.
389
+ *
390
+ * The command remains fully functional and dispatchable — it just
391
+ * won't appear in `--help` output or shell completions. Useful for
392
+ * internal/debug commands.
393
+ *
394
+ * @example
395
+ * ```ts
396
+ * command('debug-dump')
397
+ * .hidden()
398
+ * .action(({ out }) => { out.log(JSON.stringify(internalState)); });
399
+ *
400
+ * // $ mycli --help → 'debug-dump' is not listed
401
+ * // $ mycli debug-dump → still works
402
+ * ```
403
+ *
404
+ * @returns The builder (for chaining).
405
+ */
406
+ hidden() {
407
+ return new CommandBuilder({
408
+ ...this.schema,
409
+ hidden: true
410
+ }, this.handler, this._subcommands, this._executionSteps);
411
+ }
412
+ /**
413
+ * Add a usage example to help text.
414
+ *
415
+ * Examples are rendered in the "Examples:" section of `--help` output.
416
+ * Call multiple times to add several examples. Each example shows a
417
+ * shell invocation, optionally with a description.
418
+ *
419
+ * @param cmd - The example command line (without the program name prefix).
420
+ * @param description - Optional one-line explanation of what the example does.
421
+ *
422
+ * @example
423
+ * ```ts
424
+ * command('deploy')
425
+ * .arg('target', arg.string())
426
+ * .flag('force', flag.boolean().alias('f'))
427
+ * .example('deploy production', 'Deploy to production')
428
+ * .example('deploy staging -f', 'Force deploy to staging')
429
+ * .action(({ args, flags }) => { ... });
430
+ *
431
+ * // $ mycli deploy --help
432
+ * // ...
433
+ * // Examples:
434
+ * // deploy production Deploy to production
435
+ * // deploy staging -f Force deploy to staging
436
+ * ```
437
+ *
438
+ * @returns The builder (for chaining).
439
+ */
440
+ example(cmd, description) {
441
+ const entry = description !== void 0 ? {
442
+ command: cmd,
443
+ description
444
+ } : { command: cmd };
445
+ return new CommandBuilder({
446
+ ...this.schema,
447
+ examples: [...this.schema.examples, entry]
448
+ }, this.handler, this._subcommands, this._executionSteps);
449
+ }
450
+ /**
451
+ * Register a named flag on this command.
452
+ *
453
+ * The flag name is added to the type-level `F` map. Duplicate flag names
454
+ * are prevented at the type level via the `Exclude` constraint.
455
+ *
456
+ * The builder controls the flag's type, presence, aliases, env/config
457
+ * bindings, and description. See {@link FlagBuilder} for available modifiers.
458
+ *
459
+ * @param name - Flag name: the `--name` CLI token and the matching key on `flags`
460
+ * in the handler. The name is preserved as-is (no camelCasing); read non-identifier
461
+ * names such as `'dry-run'` with bracket access (`flags['dry-run']`).
462
+ * @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
463
+ * `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
464
+ *
465
+ * @example
466
+ * ```ts
467
+ * command('serve')
468
+ * .flag('port', flag.number()
469
+ * .alias('p')
470
+ * .env('PORT')
471
+ * .default(3000)
472
+ * .describe('Port to listen on'))
473
+ * .flag('host', flag.string()
474
+ * .env('HOST')
475
+ * .default('localhost')
476
+ * .describe('Bind address'))
477
+ * .flag('verbose', flag.boolean()
478
+ * .alias('v')
479
+ * .describe('Enable verbose logging'))
480
+ * .action(({ flags, out }) => {
481
+ * flags.port; // number
482
+ * flags.host; // string
483
+ * flags.verbose; // boolean
484
+ * out.log(`Listening on ${flags.host}:${flags.port}`);
485
+ * });
486
+ *
487
+ * // $ mycli serve --port 8080 -v
488
+ * // $ PORT=9090 mycli serve
489
+ * ```
490
+ *
491
+ * @returns The builder (for chaining).
492
+ */
493
+ flag(name, builder) {
494
+ if (name in this.schema.flags) throw new CLIError(`Command '${this.schema.name}' already defines flag --${name}`, {
495
+ code: "FLAG_NAME_COLLISION",
496
+ details: {
497
+ command: this.schema.name,
498
+ flag: name,
499
+ surface: name,
500
+ surfaceKind: "canonical"
501
+ }
502
+ });
503
+ const nextFlags = {
504
+ ...this.schema.flags,
505
+ [name]: builder.schema
506
+ };
507
+ const nextSchema = {
508
+ ...this.schema,
509
+ flags: nextFlags,
510
+ hasAction: false
511
+ };
512
+ validateCommandFlagTree(nextSchema);
513
+ return new CommandBuilder(nextSchema, void 0, this._subcommands, this._executionSteps);
514
+ }
515
+ /**
516
+ * Register a named positional argument on this command.
517
+ *
518
+ * Args are ordered by registration — position on the CLI matches the
519
+ * order of `.arg()` calls. The arg name is added to the type-level `A`
520
+ * map. Duplicate arg names are prevented at the type level via the
521
+ * `Exclude` constraint.
522
+ *
523
+ * The builder controls the arg's type, presence, env binding, and
524
+ * description. See {@link ArgBuilder} for available modifiers.
525
+ *
526
+ * @param name - Positional arg name (used in help text and `args.*`).
527
+ * @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
528
+ * or `arg.custom()`.
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * command('deploy')
533
+ * // Required string arg — first positional
534
+ * .arg('target', arg.string()
535
+ * .env('DEPLOY_TARGET')
536
+ * .describe('Deploy target'))
537
+ * // Optional number arg — second positional
538
+ * .arg('port', arg.number()
539
+ * .env('PORT')
540
+ * .default(3000)
541
+ * .describe('Port number'))
542
+ * .action(({ args }) => {
543
+ * args.target; // string
544
+ * args.port; // number
545
+ * });
546
+ *
547
+ * // Usage: deploy [flags] <target> [port]
548
+ * // $ mycli deploy production 8080
549
+ * // $ DEPLOY_TARGET=staging mycli deploy
550
+ * ```
551
+ *
552
+ * @returns The builder (for chaining).
553
+ */
554
+ arg(name, builder) {
555
+ validateArgEntry(name, builder.schema, this.schema.args);
556
+ const entry = {
557
+ name,
558
+ schema: builder.schema
559
+ };
560
+ const nextArgs = [...this.schema.args, entry];
561
+ return new CommandBuilder({
562
+ ...this.schema,
563
+ args: nextArgs,
564
+ hasAction: false
565
+ }, void 0, this._subcommands, this._executionSteps);
566
+ }
567
+ /**
568
+ * Register a nested subcommand on this command.
569
+ *
570
+ * The subcommand's builder is stored in `_subcommands` for the CLI layer's
571
+ * `eraseCommand()` to traverse when building the execution tree. The
572
+ * subcommand's `CommandSchema` is also appended to `schema.commands` for
573
+ * help rendering and completion generation.
574
+ *
575
+ * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
576
+ * parent level (same semantics as `CLIBuilder.command()`). The handler is
577
+ * preserved.
578
+ *
579
+ * @example
580
+ * ```ts
581
+ * const db = group('db')
582
+ * .description('Database operations')
583
+ * .command(migrateCmd)
584
+ * .command(seedCmd);
585
+ * ```
586
+ *
587
+ * @param sub - Child {@link CommandBuilder} to nest under this command.
588
+ * @returns The builder (for chaining).
589
+ */
590
+ command(sub) {
591
+ const nextSchema = {
592
+ ...this.schema,
593
+ commands: [...this.schema.commands, sub.schema]
594
+ };
595
+ validateCommandFlagTree(nextSchema);
596
+ return new CommandBuilder(nextSchema, this.handler, [...this._subcommands, eraseBuilder(sub)], this._executionSteps);
597
+ }
598
+ /**
599
+ * Register the action handler for this command.
600
+ *
601
+ * The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
602
+ * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
603
+ * definitions.
604
+ *
605
+ * May be synchronous or async. Return values are ignored; command handlers
606
+ * communicate through `out`, thrown errors, and side effects.
607
+ *
608
+ * @param handler - Function receiving `ActionParams<F, A, C>`.
609
+ *
610
+ * @example
611
+ * ```ts
612
+ * // Minimal
613
+ * command('greet')
614
+ * .arg('name', arg.string())
615
+ * .action(({ args, out }) => {
616
+ * out.log(`Hello, ${args.name}!`);
617
+ * });
618
+ * ```
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * // Full params — flags, args, context, output, metadata
623
+ * command('deploy')
624
+ * .arg('target', arg.string().env('DEPLOY_TARGET'))
625
+ * .flag('force', flag.boolean().alias('f'))
626
+ * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
627
+ * .middleware(auth)
628
+ * .action(async ({ args, flags, ctx, out, meta }) => {
629
+ * args.target; // string
630
+ * flags.force; // boolean
631
+ * flags.region; // 'us' | 'eu' | 'ap' | undefined
632
+ * ctx.user; // User (from auth middleware)
633
+ * meta.command; // string
634
+ *
635
+ * const spinner = out.spinner('Deploying...');
636
+ * await deploy(args.target, { force: flags.force });
637
+ * spinner.stop();
638
+ * out.log('Done');
639
+ * });
640
+ * ```
641
+ *
642
+ * @returns The builder (for chaining).
643
+ */
644
+ action(handler) {
645
+ return new CommandBuilder({
646
+ ...this.schema,
647
+ hasAction: true
648
+ }, handler, this._subcommands, this._executionSteps);
649
+ }
650
+ };
651
+ /**
652
+ * Create a new command builder.
653
+ *
654
+ * @param name - The command name used for dispatch (e.g. `'deploy'`).
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * import { arg, command, flag } from '@kjanat/dreamcli';
659
+ *
660
+ * const greet = command('greet')
661
+ * .arg('name', arg.string())
662
+ * .flag('loud', flag.boolean())
663
+ * .action(({ args, flags, out }) => {
664
+ * const msg = `Hello, ${args.name}!`;
665
+ * out.log(flags.loud ? msg.toUpperCase() : msg);
666
+ * });
667
+ * ```
668
+ *
669
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
670
+ */
671
+ function command(name) {
672
+ return new CommandBuilder({
673
+ name,
674
+ description: void 0,
675
+ aliases: [],
676
+ hidden: false,
677
+ examples: [],
678
+ flags: {},
679
+ args: [],
680
+ hasAction: false,
681
+ interactive: void 0,
682
+ middleware: [],
683
+ commands: []
684
+ });
685
+ }
686
+ /**
687
+ * Create a command builder intended for use as a command group.
688
+ *
689
+ * Semantically identical to {@linkcode command | command()} — a group is simply a command that
690
+ * has subcommands registered via `.command()`. The separate factory
691
+ * communicates intent: groups organise subcommands, leaf commands have actions.
692
+ *
693
+ * A group may also have its own `.action()` (e.g. `git remote` lists remotes
694
+ * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
695
+ *
696
+ * @param name - The group name used for dispatch (e.g. `'db'`).
697
+ *
698
+ * @example
699
+ * ```ts
700
+ * const db = group('db')
701
+ * .description('Database operations')
702
+ * .command(migrateCmd)
703
+ * .command(seedCmd);
704
+ * ```
705
+ *
706
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
707
+ */
708
+ function group(name) {
709
+ return command(name);
710
+ }
711
+ //#endregion
712
+ export { CommandBuilder, command, group };