@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

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 (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -1,487 +0,0 @@
1
- /**
2
- * Internal planner contract for CLI dispatch outcomes.
3
- *
4
- * Captures the stable seam between CLI-facing invocation planning and the
5
- * lower-level execution pipeline. This module is now the explicit invocation
6
- * planner seam: it owns root interception, command dispatch, default-command
7
- * fallback, propagated-flag merging, and match handoff shaping.
8
- *
9
- * @module dreamcli/core/cli/planner
10
- * @internal
11
- */
12
-
13
- import { CLIError, ParseError } from '#internals/core/errors/index.ts';
14
- import type { HelpOptions } from '#internals/core/help/index.ts';
15
- import type { OutputPolicy } from '#internals/core/output/contracts.ts';
16
- import {
17
- buildFlagLookup,
18
- flagExpectsValue,
19
- includesBeforeSeparator,
20
- } from '#internals/core/parse/index.ts';
21
- import type { CommandMeta, CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
22
- import { dispatch, findClosestCommand } from './dispatch.ts';
23
- import type { CLIPlugin } from './plugin.ts';
24
- import { collectPropagatedFlags } from './propagate.ts';
25
-
26
- /**
27
- * Structural subset of CLISchema used by the planner.
28
- *
29
- * Decouples invocation planning from the full CLIBuilder surface so the
30
- * planner can be tested and reasoned about without constructing a real CLI.
31
- * @internal
32
- */
33
- interface PlannerSchemaLike {
34
- /** CLI program name used in help text and error messages. */
35
- readonly name: string;
36
- /** Declared version string; `undefined` disables `--version` interception. */
37
- readonly version: string | undefined;
38
- /** Registered top-level commands available for dispatch. */
39
- readonly commands: readonly ErasedCommand[];
40
- /** Fallback command when no subcommand token matches. */
41
- readonly defaultCommand: ErasedCommand | undefined;
42
- /** Plugins forwarded into every matched execution plan. */
43
- readonly plugins: readonly CLIPlugin[];
44
- }
45
-
46
- /** Root-level help interception outcome. */
47
- interface RootHelpOutcome {
48
- /** Discriminant — argv matched `--help` / `-h` before any command. */
49
- readonly kind: 'root-help';
50
- /** Help options to render root-level usage. */
51
- readonly help: HelpOptions;
52
- }
53
-
54
- /** Root-level version interception outcome. */
55
- interface RootVersionOutcome {
56
- /** Discriminant — argv matched `--version` / `-V` and schema declares a version. */
57
- readonly kind: 'root-version';
58
- /** Resolved version string to render. */
59
- readonly version: string;
60
- }
61
-
62
- /** CLI-level dispatch failure before command execution starts. */
63
- interface DispatchErrorOutcome {
64
- /** Discriminant — dispatch could not resolve a command from argv. */
65
- readonly kind: 'dispatch-error';
66
- /** Structured error with suggestion text for the caller to render. */
67
- readonly error: CLIError;
68
- }
69
-
70
- /** Successful planner handoff to the shared command execution path. */
71
- interface PlannerMatchOutcome {
72
- /** Discriminant — dispatch found a matching command for argv. */
73
- readonly kind: 'match';
74
- /** Fully resolved execution plan ready for the executor pipeline. */
75
- readonly plan: CommandExecutionPlan;
76
- }
77
-
78
- /**
79
- * Stable planner result union for the re-foundation workstream.
80
- *
81
- * `CLIBuilder.execute()` still renders and executes these outcomes, but
82
- * planning itself is intentionally bounded to this union.
83
- */
84
- type DispatchOutcome =
85
- | RootHelpOutcome
86
- | RootVersionOutcome
87
- | DispatchErrorOutcome
88
- | PlannerMatchOutcome;
89
-
90
- /**
91
- * Concrete execution handoff produced by a successful planner match.
92
- *
93
- * `mergedSchema` is the exact command schema the executor sees after
94
- * propagated ancestor flags are collected and child definitions shadow them.
95
- */
96
- interface CommandExecutionPlan {
97
- /** Type-erased command instance that owns the handler. */
98
- readonly command: ErasedCommand;
99
- /** Command schema with propagated ancestor flags merged in. */
100
- readonly mergedSchema: CommandSchema;
101
- /** Remaining argv tokens after command dispatch consumed the command path. */
102
- readonly argv: readonly string[];
103
- /** CLI-level metadata (program name, bin, version) for the handler context. */
104
- readonly meta: CommandMeta;
105
- /** Plugins to run through the execution lifecycle. */
106
- readonly plugins: readonly CLIPlugin[];
107
- /** Output policy (json mode, TTY, verbosity) governing handler rendering. */
108
- readonly output: OutputPolicy;
109
- /** Help options for rendering per-command help; `undefined` when unavailable. */
110
- readonly help: HelpOptions | undefined;
111
- }
112
-
113
- interface BuildCommandExecutionPlanOptions {
114
- readonly command: ErasedCommand;
115
- readonly commandPath: readonly CommandSchema[];
116
- readonly argv: readonly string[];
117
- readonly meta: CommandMeta;
118
- readonly plugins: readonly CLIPlugin[];
119
- readonly output: OutputPolicy;
120
- readonly help: HelpOptions | undefined;
121
- }
122
-
123
- /**
124
- * Dispatch resolved a group command that requires a subcommand selection.
125
- *
126
- * The caller should render subcommand-level help for the matched group.
127
- * @internal
128
- */
129
- interface NeedsSubcommandOutcome {
130
- /** Discriminant — group command matched but no leaf subcommand was selected. */
131
- readonly kind: 'needs-subcommand';
132
- /** The group command that was matched. */
133
- readonly command: ErasedCommand;
134
- /** Full ancestor path from root to this group, used for propagated flag collection. */
135
- readonly commandPath: readonly CommandSchema[];
136
- /** Help options scoped to the group command's bin path. */
137
- readonly help: HelpOptions;
138
- }
139
-
140
- /** Full planner result including the `needs-subcommand` variant used by CLIBuilder. @internal */
141
- type InvocationPlan = DispatchOutcome | NeedsSubcommandOutcome;
142
-
143
- /** Options bag for {@linkcode planInvocation}. @internal */
144
- interface PlanInvocationOptions {
145
- /** CLI schema subset driving dispatch decisions. */
146
- readonly schema: PlannerSchemaLike;
147
- /** Raw argv tokens (typically `adapter.argv.slice(2)`). */
148
- readonly argv: readonly string[];
149
- /** Root-level help configuration for rendering. */
150
- readonly help: HelpOptions;
151
- /** Output policy propagated into matched execution plans. */
152
- readonly output: OutputPolicy;
153
- }
154
-
155
- function buildMeta(
156
- schema: PlannerSchemaLike,
157
- helpOptions: HelpOptions,
158
- commandName: string,
159
- ): CommandMeta {
160
- return {
161
- name: schema.name,
162
- bin: helpOptions.binName ?? schema.name,
163
- version: schema.version,
164
- command: commandName,
165
- };
166
- }
167
-
168
- /** Build a name+alias lookup map for top-level commands. @internal */
169
- function buildRootCommandMap(
170
- commands: readonly ErasedCommand[],
171
- ): ReadonlyMap<string, ErasedCommand> {
172
- const rootCommands = new Map<string, ErasedCommand>();
173
-
174
- const addRoute = (route: string, command: ErasedCommand): void => {
175
- const existing = rootCommands.get(route);
176
- if (existing !== undefined) {
177
- throw new CLIError(
178
- `Duplicate root command route '${route}' (${existing.schema.name} and ${command.schema.name})`,
179
- {
180
- code: 'DUPLICATE_COMMAND',
181
- suggest: 'Ensure root command names and aliases are unique',
182
- },
183
- );
184
- }
185
-
186
- rootCommands.set(route, command);
187
- };
188
-
189
- for (const cmd of commands) {
190
- addRoute(cmd.schema.name, cmd);
191
- for (const alias of cmd.schema.aliases) {
192
- addRoute(alias, cmd);
193
- }
194
- }
195
- return rootCommands;
196
- }
197
-
198
- /**
199
- * Merge propagated ancestor flags into the matched command schema.
200
- *
201
- * Child flag definitions win when names collide, matching current CLI
202
- * dispatch semantics and the future planner contract.
203
- */
204
- function mergeCommandSchema(
205
- command: ErasedCommand,
206
- commandPath: readonly CommandSchema[],
207
- ): CommandSchema {
208
- const propagated = collectPropagatedFlags(commandPath);
209
- if (Object.keys(propagated).length === 0) {
210
- return command.schema;
211
- }
212
-
213
- return {
214
- ...command.schema,
215
- flags: { ...propagated, ...command.schema.flags },
216
- };
217
- }
218
-
219
- /** Build the planner handoff for a matched command invocation. */
220
- function buildCommandExecutionPlan(
221
- options: BuildCommandExecutionPlanOptions,
222
- ): CommandExecutionPlan {
223
- return {
224
- command: options.command,
225
- mergedSchema: mergeCommandSchema(options.command, options.commandPath),
226
- argv: options.argv,
227
- meta: options.meta,
228
- plugins: options.plugins,
229
- output: options.output,
230
- help: options.help,
231
- };
232
- }
233
-
234
- function buildPlannerMatchOutcome(
235
- schema: PlannerSchemaLike,
236
- command: ErasedCommand,
237
- commandPath: readonly CommandSchema[],
238
- argv: readonly string[],
239
- help: HelpOptions,
240
- output: OutputPolicy,
241
- ): PlannerMatchOutcome {
242
- return {
243
- kind: 'match',
244
- plan: buildCommandExecutionPlan({
245
- command,
246
- commandPath,
247
- argv,
248
- meta: buildMeta(schema, help, command.schema.name),
249
- plugins: schema.plugins,
250
- output,
251
- help,
252
- }),
253
- };
254
- }
255
-
256
- function canDelegateUnknownRootToDefault(command: ErasedCommand, input: string): boolean {
257
- return input === '' || command.schema.args.length > 0;
258
- }
259
-
260
- function findUnknownFlagBeforePositional(
261
- argv: readonly string[],
262
- flags: CommandSchema['flags'],
263
- ): string | undefined {
264
- const lookup = buildFlagLookup(flags);
265
-
266
- for (let index = 0; index < argv.length; index++) {
267
- const token = argv[index];
268
- if (token === undefined || token === '--') return undefined;
269
- if (token === '-' || !token.startsWith('-')) return undefined;
270
-
271
- if (token.startsWith('--')) {
272
- const equalsIndex = token.indexOf('=');
273
- const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
274
- const entry = lookup.get(name);
275
- if (entry === undefined) return equalsIndex === -1 ? token : `--${name}`;
276
- if (equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
277
- continue;
278
- }
279
-
280
- const chars = token.slice(1);
281
- for (let charIndex = 0; charIndex < chars.length; charIndex++) {
282
- const char = chars.charAt(charIndex);
283
- const entry = lookup.get(char);
284
- if (entry === undefined) return `-${char}`;
285
- if (!flagExpectsValue(entry[1])) continue;
286
- if (charIndex === chars.length - 1) index++;
287
- break;
288
- }
289
- }
290
-
291
- return undefined;
292
- }
293
-
294
- /**
295
- * Decide what to do with an argv invocation before any command executes.
296
- *
297
- * Handles root interception (`--help`, `--version`, bare `help` token),
298
- * dispatches into the command tree, falls back to the default command, and
299
- * produces structured errors for unknown commands/flags.
300
- * @internal
301
- */
302
- function planInvocation(options: PlanInvocationOptions): InvocationPlan {
303
- // `--json` is a root-level flag, not part of any command schema, so it is
304
- // stripped before dispatch/parse — but only before the `--` separator, so a
305
- // literal `--json` positional (after `--`) survives and reaches the command
306
- // (#28). The `--json` *output mode* is detected separately in `.execute()`.
307
- const separatorIndex = options.argv.indexOf('--');
308
- const head = separatorIndex === -1 ? options.argv : options.argv.slice(0, separatorIndex);
309
- const tail = separatorIndex === -1 ? [] : options.argv.slice(separatorIndex);
310
- const filteredHead = head.includes('--json') ? head.filter((arg) => arg !== '--json') : head;
311
- const filteredArgv = separatorIndex === -1 ? filteredHead : [...filteredHead, ...tail];
312
-
313
- if (
314
- options.schema.version !== undefined &&
315
- (includesBeforeSeparator(options.argv, '--version') ||
316
- includesBeforeSeparator(options.argv, '-V'))
317
- ) {
318
- return {
319
- kind: 'root-version',
320
- version: options.schema.version,
321
- };
322
- }
323
-
324
- const firstArg = filteredArgv[0];
325
- if (firstArg === '--help' || firstArg === '-h') {
326
- return {
327
- kind: 'root-help',
328
- help: options.help,
329
- };
330
- }
331
-
332
- if (firstArg === 'help') {
333
- const hasRealHelpCommand = options.schema.commands.some(
334
- (command) => command.schema.name === 'help' || command.schema.aliases.includes('help'),
335
- );
336
- if (!hasRealHelpCommand) {
337
- const rest = filteredArgv.slice(1);
338
- if (rest.length === 0) {
339
- return {
340
- kind: 'root-help',
341
- help: options.help,
342
- };
343
- }
344
-
345
- return planInvocation({
346
- ...options,
347
- argv: [...rest, '--help'],
348
- });
349
- }
350
- }
351
-
352
- if (firstArg === undefined && options.schema.defaultCommand === undefined) {
353
- return {
354
- kind: 'root-help',
355
- help: options.help,
356
- };
357
- }
358
-
359
- if (options.schema.commands.length === 0) {
360
- return {
361
- kind: 'dispatch-error',
362
- error: new CLIError('No commands registered', {
363
- code: 'NO_ACTION',
364
- suggest: 'Add commands via .command() before calling .run()',
365
- }),
366
- };
367
- }
368
-
369
- const defaultCommand = options.schema.defaultCommand;
370
- // At the root, a default command's flags govern value-flag arity so a
371
- // space-separated value (`mycli --region eu`) is not misread as a command
372
- // name and stolen from the default-command fallback (see #25).
373
- const rootValueFlags =
374
- defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
375
- const result = dispatch(
376
- filteredArgv,
377
- buildRootCommandMap(options.schema.commands),
378
- [],
379
- rootValueFlags,
380
- );
381
-
382
- switch (result.kind) {
383
- case 'unknown': {
384
- if (defaultCommand !== undefined && result.parentPath.length === 0) {
385
- const suggestion =
386
- result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
387
- if (suggestion === undefined && canDelegateUnknownRootToDefault(defaultCommand, result.input)) {
388
- return buildPlannerMatchOutcome(
389
- options.schema,
390
- defaultCommand,
391
- [defaultCommand.schema],
392
- filteredArgv,
393
- options.help,
394
- options.output,
395
- );
396
- }
397
-
398
- const unknownFlag = findUnknownFlagBeforePositional(
399
- filteredArgv,
400
- defaultCommand.schema.flags,
401
- );
402
- if (unknownFlag !== undefined) {
403
- return {
404
- kind: 'dispatch-error',
405
- error: new ParseError(`Unknown flag ${unknownFlag}`, {
406
- code: 'UNKNOWN_FLAG',
407
- suggest: `Run '${options.schema.name} --help' for available commands`,
408
- }),
409
- };
410
- }
411
- }
412
-
413
- if (result.input === '') {
414
- const unknownFlag = filteredArgv.find((token) => token.startsWith('-'));
415
- if (unknownFlag === undefined) {
416
- return {
417
- kind: 'root-help',
418
- help: options.help,
419
- };
420
- }
421
-
422
- return {
423
- kind: 'dispatch-error',
424
- error: new ParseError(`Unknown flag ${unknownFlag}`, {
425
- code: 'UNKNOWN_FLAG',
426
- suggest: `Run '${options.schema.name} --help' for available commands`,
427
- }),
428
- };
429
- }
430
-
431
- const suggestion = findClosestCommand(result.input, result.candidates);
432
- const scopePath =
433
- result.parentPath.length > 0
434
- ? `${options.schema.name} ${result.parentPath.map((schema) => schema.name).join(' ')}`
435
- : options.schema.name;
436
-
437
- return {
438
- kind: 'dispatch-error',
439
- error: new ParseError(`Unknown command: ${result.input}`, {
440
- code: 'UNKNOWN_COMMAND',
441
- suggest:
442
- suggestion !== undefined
443
- ? `Did you mean '${suggestion}'?`
444
- : `Run '${scopePath} --help' for available commands`,
445
- }),
446
- };
447
- }
448
-
449
- case 'needs-subcommand': {
450
- const ancestorNames = result.commandPath.slice(0, -1).map((schema) => schema.name);
451
- return {
452
- kind: 'needs-subcommand',
453
- command: result.command,
454
- commandPath: result.commandPath,
455
- help: {
456
- ...options.help,
457
- binName: [options.schema.name, ...ancestorNames].join(' '),
458
- },
459
- };
460
- }
461
-
462
- case 'match':
463
- return buildPlannerMatchOutcome(
464
- options.schema,
465
- result.command,
466
- result.commandPath,
467
- result.remainingArgv,
468
- options.help,
469
- options.output,
470
- );
471
- }
472
- }
473
-
474
- export type {
475
- CommandExecutionPlan,
476
- DispatchErrorOutcome,
477
- DispatchOutcome,
478
- InvocationPlan,
479
- NeedsSubcommandOutcome,
480
- OutputPolicy,
481
- PlanInvocationOptions,
482
- PlannerMatchOutcome,
483
- PlannerSchemaLike,
484
- RootHelpOutcome,
485
- RootVersionOutcome,
486
- };
487
- export { buildCommandExecutionPlan, buildRootCommandMap, mergeCommandSchema, planInvocation };
@@ -1,117 +0,0 @@
1
- /**
2
- * CLI plugin lifecycle hooks.
3
- *
4
- * Plugins attach to `CLIBuilder` and observe command execution at stable
5
- * points: before parse, after resolve, before action, and after action.
6
- *
7
- * @module dreamcli/core/cli/plugin
8
- */
9
-
10
- import type { DeprecationWarning } from '#internals/core/resolve/index.ts';
11
- import type { CommandMeta, CommandSchema, Out } from '#internals/core/schema/command.ts';
12
-
13
- /** Shared hook payload for a concrete command execution. */
14
- interface PluginCommandContext {
15
- /** Runtime command schema being executed. */
16
- readonly command: CommandSchema;
17
- /** CLI metadata for this execution. */
18
- readonly meta: CommandMeta;
19
- /** Output channel for this execution. */
20
- readonly out: Out;
21
- }
22
-
23
- /** Payload for `beforeParse`. */
24
- interface BeforeParseParams extends PluginCommandContext {
25
- /** Raw argv that will be parsed for the leaf command. */
26
- readonly argv: readonly string[];
27
- }
28
-
29
- /** Payload for hooks that observe resolved inputs. */
30
- interface ResolvedCommandParams extends PluginCommandContext {
31
- /** Fully resolved flag values. */
32
- readonly flags: Readonly<Record<string, unknown>>;
33
- /** Fully resolved argument values. */
34
- readonly args: Readonly<Record<string, unknown>>;
35
- /** Structured deprecation warnings collected during resolution. */
36
- readonly deprecations: readonly DeprecationWarning[];
37
- }
38
-
39
- /**
40
- * Individual lifecycle hooks that a plugin may implement.
41
- *
42
- * Hook order for a successful command run is:
43
- * `beforeParse` → `afterResolve` → `beforeAction` → middleware/action → `afterAction`.
44
- *
45
- * Hooks are awaited serially and run in plugin registration order at each
46
- * stage. Throwing from any hook aborts the command just like throwing from
47
- * middleware or the action handler. `afterAction` runs only after the
48
- * middleware chain and action complete successfully.
49
- */
50
- interface CLIPluginHooks {
51
- /** Called immediately before leaf-command argv is parsed. */
52
- readonly beforeParse?: (params: BeforeParseParams) => void | Promise<void>;
53
- /** Called after parse + resolve, before middleware or action execution. */
54
- readonly afterResolve?: (params: ResolvedCommandParams) => void | Promise<void>;
55
- /** Called immediately before the middleware chain and action handler run. */
56
- readonly beforeAction?: (params: ResolvedCommandParams) => void | Promise<void>;
57
- /** Called after the middleware chain and action handler complete successfully. */
58
- readonly afterAction?: (params: ResolvedCommandParams) => void | Promise<void>;
59
- }
60
-
61
- /**
62
- * Immutable plugin definition registered via `CLIBuilder.plugin()`.
63
- *
64
- * Use {@link plugin} to construct values of this shape instead of manually
65
- * assembling the object.
66
- */
67
- interface CLIPlugin {
68
- /** Optional label for diagnostics and debugging. */
69
- readonly name: string | undefined;
70
- /** Lifecycle hooks implemented by the plugin. */
71
- readonly hooks: CLIPluginHooks;
72
- }
73
-
74
- /**
75
- * Create a CLI plugin from lifecycle hooks.
76
- *
77
- * @param hooks - Lifecycle hooks to register.
78
- * @param name - Optional plugin name for diagnostics.
79
- *
80
- * @example
81
- * ```ts
82
- * import { cli, command, plugin } from '@kjanat/dreamcli';
83
- *
84
- * const deploy = command('deploy').action(({ out }) => {
85
- * out.log('deploying');
86
- * });
87
- *
88
- * const trace = plugin(
89
- * {
90
- * beforeParse: ({ argv, out }) => {
91
- * out.info(`argv: ${argv.join(' ')}`);
92
- * },
93
- * afterResolve: ({ flags, args }) => {
94
- * console.log({ flags, args });
95
- * },
96
- * },
97
- * 'trace',
98
- * );
99
- *
100
- * cli('mycli').plugin(trace).command(deploy).run();
101
- * ```
102
- *
103
- * @returns A frozen {@link CLIPlugin} definition.
104
- */
105
- function plugin(hooks: CLIPluginHooks, name?: string): CLIPlugin {
106
- const frozenHooks = Object.freeze({ ...hooks });
107
- return Object.freeze({ hooks: frozenHooks, name });
108
- }
109
-
110
- export type {
111
- BeforeParseParams,
112
- CLIPlugin,
113
- CLIPluginHooks,
114
- PluginCommandContext,
115
- ResolvedCommandParams,
116
- };
117
- export { plugin };
@@ -1,97 +0,0 @@
1
- /**
2
- * Propagated flag collection for nested command dispatch.
3
- *
4
- * Walks a command path (root ancestor to target) and collects flags marked
5
- * `propagate: true`. Child commands that define a flag with the same name
6
- * as a propagated ancestor flag "shadow" the ancestor's flag — the child's
7
- * definition wins.
8
- *
9
- * @module dreamcli/core/cli/propagate
10
- */
11
-
12
- import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
13
-
14
- // --- Propagated flag collection
15
-
16
- /**
17
- * Collect propagated flags from a command path.
18
- *
19
- * The command path is an ordered array of {@linkcode CommandSchema} from the root
20
- * ancestor to the target command that will actually execute. Each ancestor's
21
- * flags marked `propagate: true` are accumulated. If a descendant (including
22
- * the target) defines a flag with the same name — regardless of whether the
23
- * descendant's flag has `propagate: true` — it shadows the ancestor's flag.
24
- *
25
- * The target command's own flags are **not** included in the result. This
26
- * function returns only the *inherited* propagated flags that should be merged
27
- * into the target command's flag set before resolution.
28
- *
29
- * @param commandPath - Ordered schemas from root ancestor to target (inclusive).
30
- * Must contain at least one element (the target itself). When the path has
31
- * only one element, no ancestors exist and the result is empty.
32
- *
33
- * @returns A record of propagated flag schemas keyed by flag name. Empty when
34
- * the path has no ancestors or no ancestor flags have `propagate: true`.
35
- *
36
- * @example
37
- * ```ts
38
- * // Given: root (--verbose [propagate]) → db → migrate
39
- * // Where migrate does NOT define --verbose
40
- * const inherited = collectPropagatedFlags([rootSchema, dbSchema, migrateSchema]);
41
- * // inherited = { verbose: <FlagSchema from root> }
42
- *
43
- * // If db also defines --verbose (shadowing root):
44
- * const inherited2 = collectPropagatedFlags([rootSchema, dbSchemaWithVerbose, migrateSchema]);
45
- * // inherited2 = { verbose: <FlagSchema from db> }
46
- * ```
47
- */
48
- function collectPropagatedFlags(
49
- commandPath: readonly CommandSchema[],
50
- ): Readonly<Record<string, FlagSchema>> {
51
- if (commandPath.length <= 1) return {};
52
-
53
- // Ancestors = all elements except the last (target).
54
- // Walk root → ... → parent, accumulating propagated flags.
55
- // Later ancestors shadow earlier ones (natural overwrite order).
56
- const accumulated: Record<string, FlagSchema> = {};
57
-
58
- for (let i = 0; i < commandPath.length - 1; i++) {
59
- const ancestor = commandPath[i];
60
- if (ancestor === undefined) continue;
61
-
62
- for (const [name, flagSchema] of Object.entries(ancestor.flags)) {
63
- if (flagSchema.propagate) {
64
- // Check if any descendant (between this ancestor and the target)
65
- // defines a flag with the same name — if so, skip the ancestor's
66
- // flag entirely. This ensures a child that redefines a flag
67
- // (even without propagate) masks the ancestor's propagated flag.
68
- let shadowedByDescendant = false;
69
- for (let j = i + 1; j < commandPath.length - 1; j++) {
70
- const descendant = commandPath[j];
71
- if (descendant !== undefined && name in descendant.flags) {
72
- shadowedByDescendant = true;
73
- break;
74
- }
75
- }
76
- if (!shadowedByDescendant) {
77
- accumulated[name] = flagSchema;
78
- }
79
- }
80
- }
81
- }
82
-
83
- // Remove any flag names that the target command defines directly.
84
- // A target's own flag — propagated or not — shadows inherited flags.
85
- const target = commandPath[commandPath.length - 1];
86
- if (target !== undefined) {
87
- for (const name of Object.keys(target.flags)) {
88
- delete accumulated[name];
89
- }
90
- }
91
-
92
- return accumulated;
93
- }
94
-
95
- // --- Exports
96
-
97
- export { collectPropagatedFlags };