@kjanat/dreamcli 1.0.0 → 2.0.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 (217) hide show
  1. package/CHANGELOG.md +45 -6
  2. package/LICENSE +1 -1
  3. package/README.md +296 -164
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -920
  96. package/dist/index.mjs +1 -10
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +6 -252
  115. package/dist/runtime.mjs +1 -1
  116. package/dist/testkit.d.mts +5 -24
  117. package/dist/testkit.mjs +1 -1
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +2 -2
  122. package/examples/gh/package.json +7 -11
  123. package/examples/gh/src/commands/auth.ts +2 -2
  124. package/examples/gh/src/commands/issue.ts +4 -4
  125. package/examples/gh/src/commands/pr.ts +4 -4
  126. package/examples/gh/src/docs.ts +11 -0
  127. package/examples/gh/src/lib/auth.ts +1 -1
  128. package/examples/gh/src/main.test.ts +6 -5
  129. package/examples/gh/src/main.ts +8 -6
  130. package/examples/interactive.ts +3 -3
  131. package/examples/json-mode.ts +4 -6
  132. package/examples/middleware.ts +3 -3
  133. package/examples/multi-command.ts +3 -3
  134. package/examples/spinner-progress.ts +5 -5
  135. package/examples/testing.ts +8 -6
  136. package/package.json +70 -44
  137. package/src/core/cli/dispatch.ts +4 -0
  138. package/src/core/cli/index.ts +185 -632
  139. package/src/core/cli/planner.ts +413 -0
  140. package/src/core/cli/plugin.ts +7 -1
  141. package/src/core/cli/propagate.ts +1 -1
  142. package/src/core/cli/runtime-preflight.ts +409 -0
  143. package/src/core/completion/index.ts +15 -9
  144. package/src/core/completion/shells/bash.ts +6 -3
  145. package/src/core/completion/shells/fish.ts +245 -10
  146. package/src/core/completion/shells/powershell.ts +390 -9
  147. package/src/core/completion/shells/shared.ts +4 -4
  148. package/src/core/completion/shells/zsh.ts +12 -7
  149. package/src/core/config/index.ts +7 -4
  150. package/src/core/config/package-json.ts +6 -2
  151. package/src/core/errors/index.ts +23 -8
  152. package/src/core/execution/index.ts +270 -0
  153. package/src/core/help/index.ts +13 -15
  154. package/src/core/json-schema/index.ts +193 -7
  155. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  156. package/src/core/output/contracts.ts +194 -0
  157. package/src/core/output/index.ts +47 -82
  158. package/src/core/output/renderers.ts +125 -0
  159. package/src/core/parse/index.ts +39 -21
  160. package/src/core/prompt/index.ts +44 -27
  161. package/src/core/resolve/args.ts +144 -0
  162. package/src/core/resolve/coerce.ts +432 -0
  163. package/src/core/resolve/config.ts +26 -0
  164. package/src/core/resolve/contracts.ts +135 -0
  165. package/src/core/resolve/errors.ts +227 -0
  166. package/src/core/resolve/flags.ts +205 -0
  167. package/src/core/resolve/index.ts +41 -1264
  168. package/src/core/resolve/property.ts +99 -0
  169. package/src/core/schema/activity.ts +3 -0
  170. package/src/core/schema/arg.ts +26 -14
  171. package/src/core/schema/command.ts +265 -38
  172. package/src/core/schema/flag.ts +120 -15
  173. package/src/core/schema/index.ts +11 -2
  174. package/src/core/schema/middleware.ts +6 -6
  175. package/src/core/schema/prompt.ts +9 -1
  176. package/src/core/schema/run.ts +25 -17
  177. package/src/core/schema-dsl/index.ts +109 -0
  178. package/src/core/schema-dsl/parse.ts +262 -0
  179. package/src/core/schema-dsl/runtime.ts +609 -0
  180. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  181. package/src/core/testkit/index.ts +55 -297
  182. package/src/index.ts +10 -4
  183. package/src/runtime/adapter.ts +13 -10
  184. package/src/runtime/auto.ts +3 -3
  185. package/src/runtime/bun.ts +4 -4
  186. package/src/runtime/deno.ts +43 -29
  187. package/src/runtime/detect.ts +4 -1
  188. package/src/runtime/index.ts +1 -1
  189. package/src/runtime/node.ts +43 -21
  190. package/src/runtime/paths.ts +9 -3
  191. package/src/runtime/support.ts +20 -4
  192. package/src/runtime.ts +1 -1
  193. package/src/testkit.ts +10 -8
  194. package/dist/adapter-CCSh5juX.cjs +0 -1
  195. package/dist/adapter-DIwO-q7K.d.mts +0 -3447
  196. package/dist/adapter-DQnxxLiE.d.cts +0 -3447
  197. package/dist/auto-5cjZaF9V.mjs +0 -3
  198. package/dist/auto-B0eSgoDw.cjs +0 -3
  199. package/dist/index.cjs +0 -10
  200. package/dist/index.d.cts +0 -920
  201. package/dist/runtime.cjs +0 -1
  202. package/dist/runtime.d.cts +0 -253
  203. package/dist/testkit-CEDYPvhF.mjs +0 -14
  204. package/dist/testkit-ClIKijxC.cjs +0 -14
  205. package/dist/testkit.cjs +0 -1
  206. package/dist/testkit.d.cts +0 -25
  207. package/examples/gh/tsconfig.json +0 -37
  208. package/examples/tsconfig.json +0 -17
  209. package/src/core/cli/AGENTS.md +0 -72
  210. package/src/core/completion/AGENTS.md +0 -72
  211. package/src/core/completion/completion-test-helpers.ts +0 -48
  212. package/src/core/output/AGENTS.md +0 -69
  213. package/src/core/resolve/AGENTS.md +0 -69
  214. package/src/core/schema/AGENTS.md +0 -61
  215. package/src/core/testkit/AGENTS.md +0 -55
  216. package/src/runtime/AGENTS.md +0 -74
  217. package/src/runtime/test-helpers.ts +0 -40
@@ -19,15 +19,15 @@ import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '#internals/version.ts';
19
19
  /**
20
20
  * Format a version tag for generated completion script headers.
21
21
  *
22
- * Produces e.g. `"dreamcli v0.9.1 (f9b5f1a)"` when built, or
23
- * `"dreamcli"` when running unbundled in development.
22
+ * Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
23
+ * `"@kjanat/dreamcli"` when running unbundled in development.
24
24
  *
25
25
  * @internal
26
26
  */
27
27
  function versionTag(): string {
28
- if (DREAMCLI_VERSION === 'dev') return 'dreamcli';
28
+ if (DREAMCLI_VERSION === 'dev') return '@kjanat/dreamcli';
29
29
  const rev = DREAMCLI_REVISION !== 'dev' ? ` (${DREAMCLI_REVISION})` : '';
30
- return `dreamcli v${DREAMCLI_VERSION}${rev}`;
30
+ return `@kjanat/dreamcli v${DREAMCLI_VERSION}${rev}`;
31
31
  }
32
32
 
33
33
  // --- CompletionOptions — generator configuration
@@ -15,6 +15,7 @@
15
15
 
16
16
  import type { CLISchema } from '#internals/core/cli/index.ts';
17
17
  import { CLIError } from '#internals/core/errors/index.ts';
18
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
18
19
  import type { FlagSchema } from '#internals/core/schema/index.ts';
19
20
  import type { CommandNode, CompletionOptions } from './shared.ts';
20
21
  import {
@@ -162,7 +163,9 @@ function generateZshCompletion(schema: CLISchema, options?: CompletionOptions):
162
163
 
163
164
  lines.push('}');
164
165
  lines.push('');
165
- lines.push(`${funcName} "$@"`);
166
+ // Register with compdef for `source <(cmd completions zsh)` usage.
167
+ // fpath-based autoloading is handled by the `#compdef` directive above.
168
+ lines.push(`compdef ${funcName} ${quoteShellArg(schema.name)}`);
166
169
  lines.push('');
167
170
 
168
171
  return lines.join('\n');
@@ -314,7 +317,8 @@ function escapeZshDescription(value: string): string {
314
317
  * Each flag produces one or more spec strings in zsh `_arguments` format:
315
318
  * - `'--name[description]'` for simple flags
316
319
  * - `'--name[description]:value:(v1 v2 v3)'` for enum flags
317
- * - `'(-s --name)'{-s,--name}'[description]'` for flags with short aliases
320
+ * - `'(-s --name --alias)'{-s,--name,--alias}'[description]'` for flags with
321
+ * visible aliases
318
322
  *
319
323
  * @internal
320
324
  */
@@ -325,7 +329,9 @@ function buildZshFlagSpecsFromFlags(
325
329
  for (const [name, schema] of Object.entries(flags)) {
326
330
  const desc = escapeZshDescription(schema.description ?? name);
327
331
  const longFlag = `--${name}`;
328
- const shortFlags = schema.aliases.filter((a) => a.length === 1).map((a) => `-${a}`);
332
+ const shortFlags = getFlagAliasNames(schema, { kind: 'short' }).map((alias) => `-${alias}`);
333
+ const longAliases = getFlagAliasNames(schema, { kind: 'long' }).map((alias) => `--${alias}`);
334
+ const allForms = [...shortFlags, longFlag, ...longAliases];
329
335
 
330
336
  let valuePart = '';
331
337
  if (schema.kind === 'boolean') {
@@ -337,10 +343,9 @@ function buildZshFlagSpecsFromFlags(
337
343
  valuePart = ':value:';
338
344
  }
339
345
 
340
- if (shortFlags.length > 0) {
341
- // Mutual exclusion group with ALL short aliases + long flag
342
- // Format: '(-v -V --verbose)'{-v,-V,--verbose}'[desc]:value'
343
- const allForms = [...shortFlags, longFlag];
346
+ if (allForms.length > 1) {
347
+ // Mutual exclusion group with all visible forms for the same flag.
348
+ // Format: '(-v --verbose --verb)'{-v,--verbose,--verb}'[desc]:value'
344
349
  const escapedForms = allForms.map(escapeZshCasePatternValue).join(',');
345
350
  specs.push(
346
351
  `${quoteShellArg(`(${allForms.join(' ')})`)}{${escapedForms}}${quoteShellArg(
@@ -75,6 +75,7 @@ interface ConfigDiscoveryOptions {
75
75
 
76
76
  /** Successful config discovery — file found and parsed. */
77
77
  interface ConfigFound {
78
+ /** Discriminant — `true` indicates a config file was found and parsed successfully. */
78
79
  readonly found: true;
79
80
  /** Absolute path to the config file that was loaded. */
80
81
  readonly path: string;
@@ -86,6 +87,7 @@ interface ConfigFound {
86
87
 
87
88
  /** No config file found at any candidate path (not an error). */
88
89
  interface ConfigNotFound {
90
+ /** Discriminant — `false` indicates no config file exists at any candidate path. */
89
91
  readonly found: false;
90
92
  }
91
93
 
@@ -265,7 +267,7 @@ type ConfigAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd' | 'configDir'>;
265
267
  *
266
268
  * Low-level discovery helper behind `CLIBuilder.config()`. Most apps should
267
269
  * let the CLI runtime call this automatically; call it directly when testing
268
- * config behavior or building custom bootstrapping around `RuntimeAdapter`.
270
+ * config behavior or building custom bootstrapping around {@linkcode RuntimeAdapter}.
269
271
  *
270
272
  * Pure function — all filesystem I/O flows through `adapter.readFile`.
271
273
  * Returns a discriminated union: `{ found: true, ... }` when a config
@@ -366,14 +368,15 @@ async function discoverConfig(
366
368
  *
367
369
  * @example
368
370
  * ```ts
369
- * import { configFormat } from 'dreamcli';
371
+ * import { cli, configFormat } from '@kjanat/dreamcli';
370
372
  * import { parse as parseYaml } from 'yaml';
371
373
  * import { parse as parseTOML } from '@iarna/toml';
372
374
  *
373
- * const yamlLoader = configFormat(['yaml', 'yml'], Bun.YAML.parse);
374
375
  * const yamlPackageLoader = configFormat(['yaml', 'yml'], parseYaml);
375
- * const tomlLoader = configFormat(['toml'], Bun.TOML.parse);
376
376
  * const tomlPackageLoader = configFormat(['toml'], parseTOML);
377
+ * // Or with Bun's built-in parsers:
378
+ * // const yamlLoader = configFormat(['yaml', 'yml'], Bun.YAML.parse);
379
+ * // const tomlLoader = configFormat(['toml'], Bun.TOML.parse);
377
380
  *
378
381
  * cli('myapp')
379
382
  * .config('myapp')
@@ -25,9 +25,13 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
25
25
  * All fields are optional — a valid package.json may omit any of them.
26
26
  */
27
27
  interface PackageJsonData {
28
+ /** Package name (e.g. `@scope/mycli`). */
28
29
  readonly name?: string;
30
+ /** Semver version string from `package.json`. */
29
31
  readonly version?: string;
32
+ /** One-line package description. */
30
33
  readonly description?: string;
34
+ /** Binary entry point(s) — string for single-bin, object for multi-bin. */
31
35
  readonly bin?: string | Readonly<Record<string, string>>;
32
36
  }
33
37
 
@@ -94,7 +98,7 @@ function joinPath(base: string, segment: string): string {
94
98
  *
95
99
  * @example
96
100
  * ```ts
97
- * import { discoverPackageJson } from 'dreamcli';
101
+ * import { discoverPackageJson } from '@kjanat/dreamcli';
98
102
  *
99
103
  * const pkg = await discoverPackageJson(adapter);
100
104
  * if (pkg !== null) {
@@ -188,7 +192,7 @@ function parseBinField(value: unknown): string | Readonly<Record<string, string>
188
192
  *
189
193
  * @example
190
194
  * ```ts
191
- * import { inferCliName } from 'dreamcli';
195
+ * import { inferCliName } from '@kjanat/dreamcli';
192
196
  *
193
197
  * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
194
198
  * inferCliName({ name: '@scope/mycli' }); // 'mycli'
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Structured error types for DreamCLI.
3
3
  *
4
- * Base `CLIError` carries stable code, exit code, suggestion, and structured
5
- * details. `ParseError` and `ValidationError` derive from it with
4
+ * Base {@linkcode CLIError} carries stable code, exit code, suggestion, and structured
5
+ * details. {@linkcode ParseError} and {@linkcode ValidationError} derive from it with
6
6
  * category-appropriate defaults.
7
7
  *
8
8
  * @module dreamcli/core/errors
@@ -59,7 +59,7 @@ export interface CLIErrorOptions {
59
59
  * consistent shape for rendering (TTY pretty-print, `--json`, test assertions).
60
60
  */
61
61
  export class CLIError extends Error {
62
- /** @override */
62
+ /** Error class name, always `'CLIError'` for the base class. @override */
63
63
  override readonly name: string = 'CLIError';
64
64
 
65
65
  /** Stable machine-readable identifier. */
@@ -74,6 +74,7 @@ export class CLIError extends Error {
74
74
  /** Structured payload for machine output. */
75
75
  readonly details: Readonly<Record<string, unknown>> | undefined;
76
76
 
77
+ /** Create a structured CLI error from a human message and machine-readable options. */
77
78
  constructor(message: string, options: CLIErrorOptions) {
78
79
  super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
79
80
  this.code = options.code;
@@ -98,22 +99,30 @@ export class CLIError extends Error {
98
99
  }
99
100
  }
100
101
 
101
- /** Shape returned by `CLIError.toJSON()`. */
102
+ /** Shape returned by {@linkcode CLIError}.toJSON(). */
102
103
  export interface CLIErrorJSON {
104
+ /** Error class name (e.g. `'CLIError'`, `'ParseError'`). */
103
105
  readonly name: string;
106
+ /** Stable machine-readable identifier for programmatic matching. */
104
107
  readonly code: ErrorCode;
108
+ /** Human-readable description of what went wrong. */
105
109
  readonly message: string;
110
+ /** Process exit code associated with this error. */
106
111
  readonly exitCode: number;
112
+ /** Actionable hint shown to the user, when available. */
107
113
  readonly suggest?: string;
114
+ /** Structured payload for machine consumers, when available. */
108
115
  readonly details?: Readonly<Record<string, unknown>>;
109
116
  }
110
117
 
111
118
  // --- ParseError — argv parsing failures
112
119
 
113
- /** Options for `ParseError`. Code is narrowed to parse-specific codes. */
120
+ /** Options for {@linkcode ParseError}. Code is narrowed to parse-specific codes. */
114
121
  export interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
122
+ /** Parse-category error code (e.g. `'UNKNOWN_FLAG'`, `'MISSING_VALUE'`). */
115
123
  readonly code: ParseErrorCode;
116
124
  /**
125
+ * Process exit code for parse failures.
117
126
  * @defaultValue `2`
118
127
  */
119
128
  readonly exitCode?: number;
@@ -125,10 +134,12 @@ export interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitC
125
134
  * Exit code defaults to `2` (standard for CLI usage errors).
126
135
  */
127
136
  export class ParseError extends CLIError {
128
- /** @override */
137
+ /** Always `'ParseError'`. @override */
129
138
  override readonly name = 'ParseError' as const;
139
+ /** Narrowed to parse-category codes. */
130
140
  declare readonly code: ParseErrorCode;
131
141
 
142
+ /** Create a parse error with exit code defaulting to `2`. */
132
143
  constructor(message: string, options: ParseErrorOptions) {
133
144
  super(message, { ...options, exitCode: options.exitCode ?? 2 });
134
145
  }
@@ -136,10 +147,12 @@ export class ParseError extends CLIError {
136
147
 
137
148
  // --- ValidationError — post-parse validation / resolution failures
138
149
 
139
- /** Options for `ValidationError`. Code is narrowed to validation-specific codes. */
150
+ /** Options for {@linkcode ValidationError}. Code is narrowed to validation-specific codes. */
140
151
  export interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
152
+ /** Validation-category error code (e.g. `'REQUIRED_FLAG'`, `'INVALID_ENUM'`). */
141
153
  readonly code: ValidationErrorCode;
142
154
  /**
155
+ * Process exit code for validation failures.
143
156
  * @defaultValue `2`
144
157
  */
145
158
  readonly exitCode?: number;
@@ -151,10 +164,12 @@ export interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | '
151
164
  * Exit code defaults to `2` (standard for CLI usage errors).
152
165
  */
153
166
  export class ValidationError extends CLIError {
154
- /** @override */
167
+ /** Always `'ValidationError'`. @override */
155
168
  override readonly name = 'ValidationError' as const;
169
+ /** Narrowed to validation-category codes. */
156
170
  declare readonly code: ValidationErrorCode;
157
171
 
172
+ /** Create a validation error with exit code defaulting to `2`. */
158
173
  constructor(message: string, options: ValidationErrorOptions) {
159
174
  super(message, { ...options, exitCode: options.exitCode ?? 2 });
160
175
  }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Shared command execution seam.
3
+ *
4
+ * Centralizes the parse -> resolve -> plugin -> handler pipeline so CLI and
5
+ * testkit can converge on one owned execution path during the re-foundation.
6
+ *
7
+ * @module dreamcli/core/execution
8
+ * @internal
9
+ */
10
+
11
+ import type {
12
+ BeforeParseParams,
13
+ CLIPlugin,
14
+ ResolvedCommandParams,
15
+ } from '#internals/core/cli/plugin.ts';
16
+ import { CLIError } from '#internals/core/errors/index.ts';
17
+ import { formatHelp } from '#internals/core/help/index.ts';
18
+ import type { CapturedOutput } from '#internals/core/output/index.ts';
19
+ import { parse } from '#internals/core/parse/index.ts';
20
+ import { createTestPrompter } from '#internals/core/prompt/index.ts';
21
+ import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
22
+ import { resolve } from '#internals/core/resolve/index.ts';
23
+ import type {
24
+ CommandMeta,
25
+ CommandSchema,
26
+ Out,
27
+ RunnableCommand,
28
+ } from '#internals/core/schema/command.ts';
29
+ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
30
+
31
+ /**
32
+ * Explicit executor input for a single command invocation.
33
+ * @internal
34
+ */
35
+ interface CommandExecutionRequest {
36
+ /** The command instance whose handler will be invoked. */
37
+ readonly command: RunnableCommand;
38
+ /** Raw argument tokens to parse (excluding the program name). */
39
+ readonly argv: readonly string[];
40
+ /** Output channel for handler and error rendering. */
41
+ readonly out: Out;
42
+ /** Frozen schema definition (flags, args, metadata) for parsing and resolution. */
43
+ readonly schema: CommandSchema;
44
+ /** Runtime metadata (binary name, version) propagated to the handler. */
45
+ readonly meta: CommandMeta;
46
+ /** Optional overrides for env, config, prompter, plugins, and JSON mode. */
47
+ readonly options?: RunOptions;
48
+ }
49
+
50
+ /**
51
+ * Minimal executor result before output buffers are assembled into `RunResult`.
52
+ * @internal
53
+ */
54
+ interface CommandExecutionResult {
55
+ /** Process exit code (`0` on success, error-specific otherwise). */
56
+ readonly exitCode: number;
57
+ /** The structured error if the command failed, `undefined` on success. */
58
+ readonly error: CLIError | undefined;
59
+ }
60
+
61
+ /**
62
+ * Run the full parse -> resolve -> plugin -> handler pipeline for one command.
63
+ *
64
+ * Handles `--help` short-circuit, plugin lifecycle hooks, deprecation warnings,
65
+ * and error wrapping. Both CLI dispatch and testkit `runCommand` converge here.
66
+ * @internal
67
+ */
68
+ async function executeCommand(request: CommandExecutionRequest): Promise<CommandExecutionResult> {
69
+ const { argv, command, meta, options, out, schema } = request;
70
+
71
+ try {
72
+ if (includesBeforeSeparator(argv, '--help') || includesBeforeSeparator(argv, '-h')) {
73
+ const helpText = formatHelp(schema, options?.help);
74
+ out.log(helpText);
75
+ return { exitCode: 0, error: undefined };
76
+ }
77
+
78
+ const handler = command.handler;
79
+ if (handler === undefined) {
80
+ const error = new CLIError(`Command '${command.schema.name}' has no action handler`, {
81
+ code: 'NO_ACTION',
82
+ suggest: `Add an .action() handler to the '${command.schema.name}' command`,
83
+ });
84
+ out.error(error.message);
85
+ return { exitCode: 1, error };
86
+ }
87
+
88
+ await runBeforeParseHooks(options?.plugins, {
89
+ argv,
90
+ command: schema,
91
+ meta,
92
+ out,
93
+ });
94
+
95
+ const parsed = parse(schema, argv);
96
+
97
+ const effectivePrompter =
98
+ options?.prompter ??
99
+ (options?.answers !== undefined ? createTestPrompter(options.answers) : undefined);
100
+ const resolveOptions: ResolveOptions = {
101
+ ...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
102
+ ...(options?.env !== undefined ? { env: options.env } : {}),
103
+ ...(options?.config !== undefined ? { config: options.config } : {}),
104
+ ...(effectivePrompter !== undefined ? { prompter: effectivePrompter } : {}),
105
+ };
106
+ const resolved = await resolve(schema, parsed, resolveOptions);
107
+ const resolvedParams: ResolvedCommandParams = {
108
+ args: resolved.args,
109
+ flags: resolved.flags,
110
+ deprecations: resolved.deprecations,
111
+ command: schema,
112
+ meta,
113
+ out,
114
+ };
115
+
116
+ await runResolvedHooks(options?.plugins, 'afterResolve', resolvedParams);
117
+
118
+ for (const deprecation of resolved.deprecations) {
119
+ out.warn(formatDeprecation(deprecation));
120
+ }
121
+
122
+ await runResolvedHooks(options?.plugins, 'beforeAction', resolvedParams);
123
+ await executeWithExecutionSteps(command, handler, resolved.flags, resolved.args, out, meta);
124
+ await runResolvedHooks(options?.plugins, 'afterAction', resolvedParams);
125
+
126
+ return { exitCode: 0, error: undefined };
127
+ } catch (error: unknown) {
128
+ if (error instanceof CLIError) {
129
+ if (options?.jsonMode === true) {
130
+ out.json({ error: error.toJSON() });
131
+ } else {
132
+ out.error(error.message);
133
+ if (error.suggest !== undefined) {
134
+ out.error(`Suggestion: ${error.suggest}`);
135
+ }
136
+ }
137
+ return { exitCode: error.exitCode, error };
138
+ }
139
+
140
+ const message = error instanceof Error ? error.message : String(error);
141
+ const wrapped = new CLIError(`Unexpected error: ${message}`, {
142
+ code: 'UNEXPECTED_ERROR',
143
+ cause: error,
144
+ });
145
+ if (options?.jsonMode === true) {
146
+ out.json({ error: wrapped.toJSON() });
147
+ } else {
148
+ out.error(wrapped.message);
149
+ }
150
+ return { exitCode: 1, error: wrapped };
151
+ } finally {
152
+ out.stopActive();
153
+ }
154
+ }
155
+
156
+ type ResolvedHookName = Exclude<keyof CLIPlugin['hooks'], 'beforeParse'>;
157
+
158
+ async function runBeforeParseHooks(
159
+ plugins: readonly CLIPlugin[] | undefined,
160
+ params: BeforeParseParams,
161
+ ): Promise<void> {
162
+ if (plugins === undefined) return;
163
+ for (const current of plugins) {
164
+ const hook = current.hooks.beforeParse;
165
+ if (hook !== undefined) await hook(params);
166
+ }
167
+ }
168
+
169
+ async function runResolvedHooks(
170
+ plugins: readonly CLIPlugin[] | undefined,
171
+ hookName: ResolvedHookName,
172
+ params: ResolvedCommandParams,
173
+ ): Promise<void> {
174
+ if (plugins === undefined) return;
175
+ for (const current of plugins) {
176
+ const hook = current.hooks[hookName];
177
+ if (hook !== undefined) await hook(params);
178
+ }
179
+ }
180
+
181
+ async function executeWithExecutionSteps(
182
+ command: RunnableCommand,
183
+ handler: NonNullable<RunnableCommand['handler']>,
184
+ flags: Readonly<Record<string, unknown>>,
185
+ args: Readonly<Record<string, unknown>>,
186
+ out: Out,
187
+ meta: CommandMeta,
188
+ ): Promise<void> {
189
+ const steps = command._executionSteps;
190
+
191
+ type ChainFn = (ctx: Readonly<Record<string, unknown>>) => Promise<void>;
192
+
193
+ let chain: ChainFn = async (ctx) => {
194
+ await handler({ flags, args, ctx, out, meta });
195
+ };
196
+
197
+ for (let i = steps.length - 1; i >= 0; i--) {
198
+ const step = steps[i];
199
+ if (step === undefined) continue;
200
+ const downstream = chain;
201
+ switch (step.kind) {
202
+ case 'derive':
203
+ chain = async (ctx) => {
204
+ const additions = await step.handler({ args, flags, ctx, out, meta });
205
+ if (additions === undefined) {
206
+ await downstream(ctx);
207
+ return;
208
+ }
209
+ if (typeof additions !== 'object' || additions === null || Array.isArray(additions)) {
210
+ throw new CLIError('derive() must return an object or undefined', {
211
+ code: 'INVALID_BUILDER_STATE',
212
+ suggest:
213
+ 'Return an object to add context, or return nothing for validation-only derive handlers',
214
+ });
215
+ }
216
+ await downstream({ ...ctx, ...additions });
217
+ };
218
+ break;
219
+ case 'middleware':
220
+ chain = async (ctx) => {
221
+ await step.handler({
222
+ args,
223
+ flags,
224
+ ctx,
225
+ out,
226
+ meta,
227
+ next: async (additions) => {
228
+ await downstream({ ...ctx, ...additions });
229
+ },
230
+ });
231
+ };
232
+ break;
233
+ }
234
+ }
235
+
236
+ await chain({});
237
+ }
238
+
239
+ /**
240
+ * Assemble a {@linkcode CommandExecutionResult} and captured output buffers into a public `RunResult`.
241
+ * @internal
242
+ */
243
+ function buildRunResult(result: CommandExecutionResult, captured: CapturedOutput): RunResult {
244
+ return {
245
+ exitCode: result.exitCode,
246
+ stdout: captured.stdout,
247
+ stderr: captured.stderr,
248
+ activity: captured.activity,
249
+ error: result.error,
250
+ };
251
+ }
252
+
253
+ function formatDeprecation(deprecation: DeprecationWarning): string {
254
+ const entity =
255
+ deprecation.kind === 'flag' ? `flag --${deprecation.name}` : `argument <${deprecation.name}>`;
256
+ return typeof deprecation.message === 'string'
257
+ ? `Warning: ${entity} is deprecated: ${deprecation.message}`
258
+ : `Warning: ${entity} is deprecated`;
259
+ }
260
+
261
+ function includesBeforeSeparator(argv: readonly string[], token: string): boolean {
262
+ for (const arg of argv) {
263
+ if (arg === '--') return false;
264
+ if (arg === token) return true;
265
+ }
266
+ return false;
267
+ }
268
+
269
+ export type { CommandExecutionRequest, CommandExecutionResult };
270
+ export { buildRunResult, executeCommand };
@@ -2,13 +2,14 @@
2
2
  * Auto-generated help text from command schemas.
3
3
  *
4
4
  * Renders usage line, description, positional args, flags table, and
5
- * examples from a `CommandSchema`. Designed for TTY output with
5
+ * examples from a {@linkcode CommandSchema}. Designed for TTY output with
6
6
  * configurable width.
7
7
  *
8
8
  * @module dreamcli/core/help
9
9
  */
10
10
 
11
11
  import { formatDisplayValue } from '#internals/core/output/display-value.ts';
12
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
12
13
  import type {
13
14
  ArgSchema,
14
15
  CommandArgEntry,
@@ -137,23 +138,20 @@ interface FlagEntry {
137
138
  * @returns Formatted left-column string for the flags table.
138
139
  */
139
140
  function formatFlagLeft(name: string, schema: FlagSchema): string {
140
- const parts: string[] = [];
141
-
142
- // Short alias first (single-char)
143
- const shortAlias = schema.aliases.find((a) => a.length === 1);
144
- if (shortAlias !== undefined) {
145
- parts.push(`-${shortAlias},`);
146
- }
147
-
148
- // Long flag name
149
- parts.push(`--${name}`);
141
+ const visibleShortAliases = getFlagAliasNames(schema, { kind: 'short' });
142
+ const visibleLongAliases = getFlagAliasNames(schema, { kind: 'long' });
143
+ const forms = [
144
+ ...visibleShortAliases.map((alias) => `-${alias}`),
145
+ `--${name}`,
146
+ ...visibleLongAliases.map((alias) => `--${alias}`),
147
+ ];
150
148
 
151
149
  // Value placeholder (skip for boolean)
152
150
  if (schema.kind !== 'boolean') {
153
- parts.push(formatValueHint(schema));
151
+ return `${forms.join(', ')} ${formatValueHint(schema)}`;
154
152
  }
155
153
 
156
- return parts.join(' ');
154
+ return forms.join(', ');
157
155
  }
158
156
 
159
157
  /**
@@ -240,8 +238,8 @@ function buildFlagEntries(flags: Readonly<Record<string, FlagSchema>>): readonly
240
238
  const aSchema = flags[a];
241
239
  const bSchema = flags[b];
242
240
  if (aSchema === undefined || bSchema === undefined) return 0;
243
- const aHasShort = aSchema.aliases.some((al) => al.length === 1);
244
- const bHasShort = bSchema.aliases.some((al) => al.length === 1);
241
+ const aHasShort = getFlagAliasNames(aSchema, { kind: 'short' }).length > 0;
242
+ const bHasShort = getFlagAliasNames(bSchema, { kind: 'short' }).length > 0;
245
243
  if (aHasShort && !bHasShort) return -1;
246
244
  if (!aHasShort && bHasShort) return 1;
247
245
  return a.localeCompare(b);