@kjanat/dreamcli 1.0.0 → 2.0.1

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 +63 -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
@@ -0,0 +1,139 @@
1
+ import { FlagSchema } from "../../schema/flag.mjs";
2
+ import { CommandSchema } from "../../schema/command.mjs";
3
+
4
+ //#region src/core/completion/shells/shared.d.ts
5
+ /**
6
+ * Format a version tag for generated completion script headers.
7
+ *
8
+ * Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
9
+ * `"@kjanat/dreamcli"` when running unbundled in development.
10
+ *
11
+ * @internal
12
+ */
13
+ declare function versionTag(): string;
14
+ /**
15
+ * Options for completion script generation.
16
+ *
17
+ * Passed to individual shell generators alongside the CLI schema.
18
+ *
19
+ * These options affect the generated script text, not runtime completion
20
+ * behavior after installation.
21
+ */
22
+ interface CompletionOptions {
23
+ /**
24
+ * Override the generated shell function name prefix.
25
+ *
26
+ * Defaults to the CLI name from the schema. This is mainly useful when
27
+ * embedding multiple generated scripts in the same environment and you want
28
+ * deterministic, collision-free helper names.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * generateCompletion(schema, 'bash', { functionPrefix: 'acme' });
33
+ * ```
34
+ */
35
+ readonly functionPrefix?: string;
36
+ /**
37
+ * Controls which root-level surface shell completion exposes when a
38
+ * default command exists.
39
+ *
40
+ * - `'subcommands'` keeps hybrid CLIs command-centric at the root while
41
+ * still exposing default-command flags for a single visible default
42
+ * command.
43
+ * - `'surface'` exposes the default command's root-usable flags at the
44
+ * root whenever a visible default command exists.
45
+ *
46
+ * @defaultValue `'subcommands'`
47
+ */
48
+ readonly rootMode?: 'subcommands' | 'surface';
49
+ }
50
+ /**
51
+ * Normalized root completion surface consumed by shell generators.
52
+ *
53
+ * @internal
54
+ */
55
+ interface RootCompletionSurface {
56
+ readonly visibleCommands: readonly CommandSchema[];
57
+ readonly visibleDefaultCommand: CommandSchema | undefined;
58
+ readonly rootFlags: Readonly<Record<string, FlagSchema>>;
59
+ readonly defaultFlags: Readonly<Record<string, FlagSchema>>;
60
+ readonly includeDefaultFlags: boolean;
61
+ }
62
+ /**
63
+ * Schema shape needed to compute the root completion surface.
64
+ *
65
+ * @internal
66
+ */
67
+ interface RootCompletionSchemaLike {
68
+ readonly commands: ReadonlyArray<{
69
+ readonly schema: CommandSchema;
70
+ }>;
71
+ readonly defaultCommand: {
72
+ readonly schema: CommandSchema;
73
+ } | undefined;
74
+ readonly version: string | undefined;
75
+ }
76
+ /**
77
+ * Resolve the root-level completion surface from the CLI schema and policy.
78
+ *
79
+ * @internal
80
+ */
81
+ declare function resolveRootCompletionSurface(schema: RootCompletionSchemaLike, rootMode?: CompletionOptions['rootMode']): RootCompletionSurface;
82
+ /**
83
+ * A flattened node from the command tree, carrying its ancestry context.
84
+ *
85
+ * Used by both bash and zsh generators to produce completions at every
86
+ * nesting level with correct propagated flag inheritance.
87
+ *
88
+ * @internal
89
+ */
90
+ interface CommandNode {
91
+ /** Name path from root: `['db', 'migrate']` */
92
+ readonly path: readonly string[];
93
+ /** The command schema at this node */
94
+ readonly schema: CommandSchema;
95
+ /** Propagated flags inherited from ancestors (excludes own flags) */
96
+ readonly propagatedFlags: Readonly<Record<string, FlagSchema>>;
97
+ /** Merged flags: propagated + own (own shadows propagated) */
98
+ readonly mergedFlags: Readonly<Record<string, FlagSchema>>;
99
+ /** Visible child command schemas (for subcommand completion) */
100
+ readonly children: readonly CommandSchema[];
101
+ }
102
+ /**
103
+ * Walk the command tree depth-first, producing a flat list of
104
+ * {@link CommandNode}s with propagated flag context.
105
+ *
106
+ * @param topLevel - Top-level visible command schemas.
107
+ * @param ancestorSchemas - Schema path from root (for propagation calculation).
108
+ * @returns Flat list of all visible nodes in the tree.
109
+ *
110
+ * @internal
111
+ */
112
+ declare function walkCommandTree(topLevel: readonly CommandSchema[], ancestorSchemas?: readonly CommandSchema[]): readonly CommandNode[];
113
+ /**
114
+ * Sanitize a string for use as a shell function identifier.
115
+ * Replaces non-alphanumeric/underscore characters with underscores.
116
+ * When sanitization changes the name, appends a short stable hash suffix so
117
+ * distinct originals cannot collide on the same helper identifier.
118
+ * Used by both bash and zsh generators.
119
+ *
120
+ * @internal
121
+ */
122
+ declare function sanitizeShellIdentifier(name: string): string;
123
+ /**
124
+ * Quote a string for safe interpolation into a shell script.
125
+ *
126
+ * Uses single-quote wrapping with the standard `'\''` idiom for
127
+ * embedded single quotes. This prevents shell injection from CLI
128
+ * names containing spaces, semicolons, backticks, or other
129
+ * special characters.
130
+ *
131
+ * Returns the input unquoted if it consists only of shell-safe
132
+ * characters (`[a-zA-Z0-9_\-.]`), avoiding unnecessary noise
133
+ * in generated scripts for common CLI names like `my-cli` or `app.v2`.
134
+ *
135
+ * @internal
136
+ */
137
+ declare function quoteShellArg(value: string): string;
138
+ //#endregion
139
+ export { type CommandNode, type CompletionOptions, type RootCompletionSurface, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
@@ -0,0 +1 @@
1
+ import{collectPropagatedFlags as e}from"../../cli/propagate.mjs";import{resolveRootSurface as t}from"../../cli/root-surface.mjs";import{DREAMCLI_REVISION as n,DREAMCLI_VERSION as r}from"../../../version.mjs";function i(){return`@kjanat/dreamcli v${r}${` (${n})`}`}function a(e,n=`subcommands`){let r=t(e),i=o(e.version!==void 0),a=r.visibleDefaultCommand?.flags??{},s=n===`surface`?r.visibleDefaultCommand!==void 0:r.hasSingleVisibleDefault;return{visibleCommands:r.visibleCommands,visibleDefaultCommand:r.visibleDefaultCommand,rootFlags:i,defaultFlags:a,includeDefaultFlags:s}}function o(e){return{help:s(`Show help text`),...e?{version:s(`Show version`)}:{}}}function s(e){return{kind:`boolean`,presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:e,enumValues:void 0,elementSchema:void 0,prompt:void 0,parseFn:void 0,deprecated:void 0,propagate:!1}}function c(t,n=[]){let r=[];for(let i of t){if(i.hidden)continue;let t=[...n,i],a=e(t),o={...a,...i.flags},s=i.commands.filter(e=>!e.hidden);r.push({path:t.map(e=>e.name),schema:i,propagatedFlags:a,mergedFlags:o,children:s}),s.length>0&&r.push(...c(s,t))}return r}function l(e){let t=e.replace(/[^a-zA-Z0-9_]/g,`_`);if(t===e)return t;let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return`${t}_${(n>>>0).toString(16).padStart(8,`0`)}`}function u(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}export{u as quoteShellArg,a as resolveRootCompletionSurface,l as sanitizeShellIdentifier,i as versionTag,c as walkCommandTree};
@@ -0,0 +1,24 @@
1
+ import { CompletionOptions } from "./shared.mjs";
2
+ import { CLISchema } from "../../cli/index.mjs";
3
+
4
+ //#region src/core/completion/shells/zsh.d.ts
5
+ /**
6
+ * Generate a zsh completion script for the CLI.
7
+ *
8
+ * Use this when you want a zsh-specific script directly rather than routing
9
+ * through {@link generateCompletion}. The generated script is compatible with
10
+ * zsh's normal `#compdef` / `fpath` loading flow.
11
+ *
12
+ * @param schema - The CLI schema.
13
+ * @param options - Optional generator configuration.
14
+ * @returns A complete zsh completion script.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const script = generateZshCompletion(app.schema);
19
+ * // install with: mycli completions zsh > "${fpath[1]}/_mycli"
20
+ * ```
21
+ */
22
+ declare function generateZshCompletion(schema: CLISchema, options?: CompletionOptions): string;
23
+ //#endregion
24
+ export { generateZshCompletion };
@@ -0,0 +1,2 @@
1
+ import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";import{CLIError as o}from"../../errors/index.mjs";function s(e,s){let f=`_${r(s?.functionPrefix??e.name)}`,m=n(e,s?.rootMode),h=m.visibleCommands,g=a(h),_=[];_.push(`#compdef ${t(e.name)}`),_.push(`# Zsh completion for ${e.name}`),_.push(`# Generated by ${i()}`),_.push(`#`),_.push(`# Usage: source <(${e.name} completions zsh)`),_.push(`#`),_.push(`# Install permanently:`),_.push(`# ${e.name} completions zsh > "\${fpath[1]}/_${e.name}"`),_.push(`# # Then restart your shell`),_.push(``);let v=g.filter(e=>e.children.length>0),y=g.filter(e=>e.children.length===0);for(let e of y)e.path.length<2||l(_,`${f}_${e.path.map(r).join(`_`)}`,e);let b=[...v].sort((e,t)=>t.path.length-e.path.length);for(let e of b)c(_,`${f}_${e.path.map(r).join(`_`)}`,f,e);if(_.push(`${f}() {`),h.length>0){_.push(` local -a subcmds`),_.push(` local line state`),_.push(``);let e=p({...m.rootFlags,...m.includeDefaultFlags?m.defaultFlags:{}});_.push(` _arguments -C \\`);for(let t of e)_.push(`\t\t${t} \\`);_.push(` '1: :->subcmd' \\`),_.push(` '*::arg:->args'`),_.push(``),_.push(` case "$state" in`),_.push(` subcmd)`),_.push(` subcmds=(`),u(_,h,` `),_.push(` )`),_.push(` _describe 'command' subcmds`),_.push(` ;;`),_.push(` args)`),_.push(` case "$line[1]" in`);for(let e of h){let t=[e.name,...e.aliases].map(d),n=e.commands.filter(e=>!e.hidden);if(_.push(`\t\t\t\t${t.join(`|`)})`),n.length>0){let t=`${f}_${r(e.name)}`;_.push(`\t\t\t\t\t${t}`)}else{let t=g.find(t=>t.path.length===1&&t.schema.name===e.name);if(t===void 0)throw new o(`Missing completion node for command '${e.name}'`,{code:`UNEXPECTED_ERROR`});let n=p(t.mergedFlags);if(n.length>0){_.push(` _arguments \\`);for(let e=0;e<n.length;e++){let t=e<n.length-1?` \\`:``;_.push(`\t\t\t\t\t\t${n[e]}${t}`)}}}_.push(` ;;`)}_.push(` esac`),_.push(` ;;`),_.push(` esac`)}else{let e=p(m.rootFlags);_.push(` _arguments \\`);for(let t=0;t<e.length;t++){let n=t<e.length-1?` \\`:``;_.push(`\t\t${e[t]}${n}`)}}return _.push(`}`),_.push(``),_.push(`compdef ${f} ${t(e.name)}`),_.push(``),_.join(`
2
+ `)}function c(e,t,n,i){e.push(`${t}() {`),e.push(` local -a subcmds`),e.push(` local line state`),e.push(``);let a=p(i.mergedFlags);e.push(` _arguments -C \\`);for(let t of a)e.push(`\t\t${t} \\`);e.push(` '1: :->subcmd' \\`),e.push(` '*::arg:->args'`),e.push(``),e.push(` case "$state" in`),e.push(` subcmd)`),e.push(` subcmds=(`),u(e,i.children,` `),e.push(` )`),e.push(` _describe 'command' subcmds`),e.push(` ;;`),e.push(` args)`),e.push(` case "$line[1]" in`);for(let t of i.children){let a=[t.name,...t.aliases].map(d),o=`${n}_${[...i.path,t.name].map(r).join(`_`)}`;e.push(`\t\t\t\t${a.join(`|`)})`),e.push(`\t\t\t\t\t${o}`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`),e.push(` esac`),e.push(`}`),e.push(``)}function l(e,t,n){let r=p(n.mergedFlags);if(e.push(`${t}() {`),r.length>0){e.push(` _arguments \\`);for(let t=0;t<r.length;t++){let n=t<r.length-1?` \\`:``;e.push(`\t\t${r[t]}${n}`)}}e.push(`}`),e.push(``)}function u(e,n,r){for(let i of n){let n=i.description??i.name;for(let a of[i.name,...i.aliases])e.push(`${r}${t(`${a}:${n}`)}`)}}function d(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function f(e){return e.replace(/\\/g,`\\\\`).replace(/\]/g,`\\]`)}function p(n){let r=[];for(let[i,a]of Object.entries(n)){let n=f(a.description??i),o=`--${i}`,s=e(a,{kind:`short`}).map(e=>`-${e}`),c=e(a,{kind:`long`}).map(e=>`--${e}`),l=[...s,o,...c],u=``;if(a.kind===`boolean`||(u=a.kind===`enum`&&a.enumValues!==void 0?`:value:(${a.enumValues.map(m).join(` `)})`:`:value:`),l.length>1){let e=l.map(d).join(`,`);r.push(`${t(`(${l.join(` `)})`)}{${e}}${t(`[${n}]${u}`)}`)}else r.push(t(`${o}[${n}]${u}`))}return r}function m(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/ /g,`\\ `).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)}export{s as generateZshCompletion};
@@ -0,0 +1,161 @@
1
+ import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
+ import { PackageJsonAdapter, PackageJsonData, discoverPackageJson, inferCliName } from "./package-json.mjs";
3
+
4
+ //#region src/core/config/index.d.ts
5
+ /**
6
+ * Format loader — parses file content into a config object.
7
+ *
8
+ * Register custom config formats by providing file extensions and a parser.
9
+ * Parsers may return any parsed value; {@link discoverConfig} validates that
10
+ * the result is a plain object before feeding it into the resolution chain.
11
+ *
12
+ * Implementations should throw on syntax or shape errors; the caller wraps
13
+ * those failures as {@link CLIError} with code `CONFIG_PARSE_ERROR`.
14
+ */
15
+ interface FormatLoader {
16
+ /** File extensions this loader handles (without leading dot, e.g. `'toml'`). */
17
+ readonly extensions: readonly string[];
18
+ /**
19
+ * Parse file content into a config value.
20
+ *
21
+ * Arrays, primitives, and `null` are allowed at this boundary so generic
22
+ * parsers like `Bun.YAML.parse` can be passed directly. Those values are
23
+ * still rejected by {@link discoverConfig}, which requires a plain object.
24
+ */
25
+ readonly parse: (content: string) => unknown;
26
+ }
27
+ /** Options for {@link discoverConfig}. */
28
+ interface ConfigDiscoveryOptions {
29
+ /**
30
+ * Explicit config file path (`--config` override).
31
+ * When provided, skips search — loads only this path.
32
+ */
33
+ readonly configPath?: string;
34
+ /**
35
+ * Additional format loaders (JSON is built-in).
36
+ * Later loaders for the same extension win (allows override).
37
+ */
38
+ readonly loaders?: readonly FormatLoader[];
39
+ /**
40
+ * Custom search paths (absolute).
41
+ * Replaces the default search paths when provided.
42
+ * Probed in order; first found wins.
43
+ */
44
+ readonly searchPaths?: readonly string[];
45
+ }
46
+ /** Successful config discovery — file found and parsed. */
47
+ interface ConfigFound {
48
+ /** Discriminant — `true` indicates a config file was found and parsed successfully. */
49
+ readonly found: true;
50
+ /** Absolute path to the config file that was loaded. */
51
+ readonly path: string;
52
+ /** Parsed config data. */
53
+ readonly data: Readonly<Record<string, unknown>>;
54
+ /** File extension that determined the loader (e.g. `'json'`). */
55
+ readonly format: string;
56
+ }
57
+ /** No config file found at any candidate path (not an error). */
58
+ interface ConfigNotFound {
59
+ /** Discriminant — `false` indicates no config file exists at any candidate path. */
60
+ readonly found: false;
61
+ }
62
+ /** Discriminated result of config discovery. */
63
+ type ConfigDiscoveryResult = ConfigFound | ConfigNotFound;
64
+ /**
65
+ * Build the default config search paths for an app.
66
+ *
67
+ * Advanced helper used by DreamCLI's config discovery. Most apps should call
68
+ * `.config()` or {@link discoverConfig} instead of constructing search paths
69
+ * manually. Exported for debugging, custom discovery flows, and help text.
70
+ *
71
+ * Search order (first match wins):
72
+ * 1. `$CWD/.{appName}.json` — dotfile in project root
73
+ * 2. `$CWD/{appName}.config.json` — explicit config in project root
74
+ * 3. `$CONFIG_DIR/{appName}/config.json` — XDG / AppData standard
75
+ * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
76
+ * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
77
+ *
78
+ * When custom {@link ConfigDiscoveryOptions.loaders | loaders} are registered,
79
+ * each path pattern is repeated per supported extension (JSON always first).
80
+ *
81
+ * @param appName - CLI application name used to derive config filenames.
82
+ * @param cwd - Current working directory (project-root search location).
83
+ * @param configDir - Platform config directory (XDG / AppData).
84
+ * @param loaders - Optional custom {@link FormatLoader}s whose extensions expand the search set.
85
+ * @returns Ordered list of candidate config file paths (first match wins).
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const paths = buildConfigSearchPaths('mycli', '/repo', '/home/me/.config');
90
+ * ```
91
+ */
92
+ declare function buildConfigSearchPaths(appName: string, cwd: string, configDir: string, loaders?: readonly FormatLoader[]): readonly string[];
93
+ /**
94
+ * The subset of {@link RuntimeAdapter} needed for config discovery.
95
+ *
96
+ * Exported so custom hosts and tests can type the minimal adapter required by
97
+ * {@link discoverConfig} without depending on the full runtime adapter shape.
98
+ */
99
+ type ConfigAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd' | 'configDir'>;
100
+ /**
101
+ * Discover and load a config file.
102
+ *
103
+ * Low-level discovery helper behind `CLIBuilder.config()`. Most apps should
104
+ * let the CLI runtime call this automatically; call it directly when testing
105
+ * config behavior or building custom bootstrapping around {@linkcode RuntimeAdapter}.
106
+ *
107
+ * Pure function — all filesystem I/O flows through `adapter.readFile`.
108
+ * Returns a discriminated union: `{ found: true, ... }` when a config
109
+ * file was found and parsed, `{ found: false }` when no file exists.
110
+ *
111
+ * @throws {CLIError} code `CONFIG_NOT_FOUND` — explicit `configPath` doesn't exist
112
+ * @throws {CLIError} code `CONFIG_PARSE_ERROR` — file exists but fails to parse
113
+ * @throws {CLIError} code `CONFIG_UNKNOWN_FORMAT` — no loader for the file extension
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const result = await discoverConfig('mycli', adapter, {
118
+ * loaders: [
119
+ * configFormat(['yaml', 'yml'], Bun.YAML.parse),
120
+ * configFormat(['toml'], Bun.TOML.parse),
121
+ * ],
122
+ * });
123
+ * ```
124
+ */
125
+ declare function discoverConfig(appName: string, adapter: ConfigAdapter, options?: ConfigDiscoveryOptions): Promise<ConfigDiscoveryResult>;
126
+ /**
127
+ * Create a {@link FormatLoader} from extensions and a parse function.
128
+ *
129
+ * Convenience factory for config loading. It avoids manually constructing the
130
+ * `{ extensions, parse }` object and makes intent clearer at call sites.
131
+ *
132
+ * Later loaders registered for the same extension override earlier ones. Any
133
+ * error thrown by `parse` is wrapped by {@link discoverConfig} as
134
+ * `CONFIG_PARSE_ERROR`.
135
+ *
136
+ * @param extensions - File extensions this loader handles (without dot, e.g. `'yaml'`).
137
+ * @param parse - Parse function: takes file content string and returns a parsed config value.
138
+ * @returns A {@link FormatLoader} ready to pass to {@link ConfigDiscoveryOptions.loaders}.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * import { cli, configFormat } from '@kjanat/dreamcli';
143
+ * import { parse as parseYaml } from 'yaml';
144
+ * import { parse as parseTOML } from '@iarna/toml';
145
+ *
146
+ * const yamlPackageLoader = configFormat(['yaml', 'yml'], parseYaml);
147
+ * const tomlPackageLoader = configFormat(['toml'], parseTOML);
148
+ * // Or with Bun's built-in parsers:
149
+ * // const yamlLoader = configFormat(['yaml', 'yml'], Bun.YAML.parse);
150
+ * // const tomlLoader = configFormat(['toml'], Bun.TOML.parse);
151
+ *
152
+ * cli('myapp')
153
+ * .config('myapp')
154
+ * .configLoader(yamlLoader)
155
+ * .configLoader(tomlLoader)
156
+ * .run();
157
+ * ```
158
+ */
159
+ declare function configFormat(extensions: readonly string[], parse: (content: string) => unknown): FormatLoader;
160
+ //#endregion
161
+ export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type PackageJsonAdapter, type PackageJsonData, buildConfigSearchPaths, configFormat, discoverConfig, discoverPackageJson, inferCliName };
@@ -0,0 +1 @@
1
+ import{CLIError as e}from"../errors/index.mjs";import"./package-json.mjs";function t(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const n={extensions:[`json`],parse:e=>{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Config must be a JSON object`);return t}};function r(e,...t){let n=e.includes(`\\`)?`\\`:`/`;return[e,...t].join(n)}function i(e){let t=e.lastIndexOf(`.`);return t<=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))?``:e.slice(t+1).toLowerCase()}function a(e,t,n,i){let a=o(i),s=[];for(let n of a)s.push(r(t,`.${e}.${n}`));for(let n of a)s.push(r(t,`${e}.config.${n}`));for(let t of a)s.push(r(n,e,`config.${t}`));return s}function o(e){let t=new Set,r=[];for(let e of n.extensions){let n=e.toLowerCase();t.has(n)||(t.add(n),r.push(n))}if(e!==void 0)for(let n of e)for(let e of n.extensions){let n=e.toLowerCase();t.has(n)||(t.add(n),r.push(n))}return r}function s(e){let t=new Map;for(let e of n.extensions)t.set(e.toLowerCase(),n);if(e!==void 0)for(let n of e)for(let e of n.extensions)t.set(e.toLowerCase(),n);return t}async function c(n,r,o){let c=s(o?.loaders),l=o?.configPath===void 0?o?.searchPaths??a(n,r.cwd,r.configDir,o?.loaders):[o.configPath];for(let n of l){let a=await r.readFile(n);if(a===null){if(o?.configPath!==void 0)throw new e(`Config file not found: ${n}`,{code:`CONFIG_NOT_FOUND`,details:{path:n},suggest:`Create the config file or remove the --config flag`});continue}let s=i(n),l=c.get(s);if(l===void 0)throw new e(`No loader registered for config format: .${s}`,{code:`CONFIG_UNKNOWN_FORMAT`,details:{path:n,extension:s},suggest:`Supported formats: ${[...c.keys()].join(`, `)}`});try{let e=l.parse(a);if(!t(e))throw Error(`Config loader must return a plain object`);return{found:!0,path:n,data:e,format:s}}catch(t){throw new e(`Failed to parse config file: ${n}`,{code:`CONFIG_PARSE_ERROR`,cause:t,details:{path:n,format:s,message:t instanceof Error?t.message:String(t)},suggest:`Check the config file for syntax errors`})}}return{found:!1}}function l(e,t){return{extensions:e,parse:t}}export{a as buildConfigSearchPaths,l as configFormat,c as discoverConfig};
@@ -0,0 +1,68 @@
1
+ import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
+
3
+ //#region src/core/config/package-json.d.ts
4
+ /**
5
+ * Subset of package.json fields relevant to CLI metadata.
6
+ *
7
+ * All fields are optional — a valid package.json may omit any of them.
8
+ */
9
+ interface PackageJsonData {
10
+ /** Package name (e.g. `@scope/mycli`). */
11
+ readonly name?: string;
12
+ /** Semver version string from `package.json`. */
13
+ readonly version?: string;
14
+ /** One-line package description. */
15
+ readonly description?: string;
16
+ /** Binary entry point(s) — string for single-bin, object for multi-bin. */
17
+ readonly bin?: string | Readonly<Record<string, string>>;
18
+ }
19
+ /**
20
+ * The subset of {@link RuntimeAdapter} needed for package.json discovery.
21
+ *
22
+ * Using a narrow pick keeps the function easy to test and makes the
23
+ * dependency explicit.
24
+ */
25
+ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
26
+ /**
27
+ * Discover the nearest `package.json` by walking up from `adapter.cwd`.
28
+ *
29
+ * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
30
+ * the CLI runtime discover package metadata automatically; call this directly
31
+ * when testing metadata inference or embedding the behavior in custom tooling.
32
+ *
33
+ * Returns the parsed metadata on success, `null` when no `package.json`
34
+ * is found (not an error). Malformed JSON and non-object roots also
35
+ * return `null` — the feature is a convenience, not a hard requirement.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { discoverPackageJson } from '@kjanat/dreamcli';
40
+ *
41
+ * const pkg = await discoverPackageJson(adapter);
42
+ * if (pkg !== null) {
43
+ * console.log(pkg.version); // '1.2.3'
44
+ * }
45
+ * ```
46
+ */
47
+ declare function discoverPackageJson(adapter: PackageJsonAdapter): Promise<PackageJsonData | null>;
48
+ /**
49
+ * Infer the CLI binary name from package.json data.
50
+ *
51
+ * Resolution order:
52
+ * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
53
+ * 2. Package `name` with scope stripped (e.g. `"@scope/mycli"` → `"mycli"`)
54
+ * 3. `undefined` if neither exists
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { inferCliName } from '@kjanat/dreamcli';
59
+ *
60
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
61
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
62
+ * inferCliName({ name: 'mycli' }); // 'mycli'
63
+ * inferCliName({}); // undefined
64
+ * ```
65
+ */
66
+ declare function inferCliName(pkg: PackageJsonData): string | undefined;
67
+ //#endregion
68
+ export { type PackageJsonAdapter, type PackageJsonData, discoverPackageJson, inferCliName };
@@ -0,0 +1 @@
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e){let r=e.cwd;for(;r!==void 0;){let a=null;try{a=await e.readFile(n(r,`package.json`))}catch{}if(a!==null){let e=i(a);if(e!==null)return e}r=t(r)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,o=typeof n.description==`string`?n.description:void 0,s=a(n.bin);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...o===void 0?{}:{description:o},...s===void 0?{}:{bin:s}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,o as inferCliName};
@@ -0,0 +1,126 @@
1
+ //#region src/core/errors/index.d.ts
2
+ /**
3
+ * Structured error types for DreamCLI.
4
+ *
5
+ * Base {@linkcode CLIError} carries stable code, exit code, suggestion, and structured
6
+ * details. {@linkcode ParseError} and {@linkcode ValidationError} derive from it with
7
+ * category-appropriate defaults.
8
+ *
9
+ * @module dreamcli/core/errors
10
+ */
11
+ /** Codes emitted during argv parsing. */
12
+ type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'UNEXPECTED_POSITIONAL';
13
+ /** Codes emitted during post-parse validation / resolution. */
14
+ type ValidationErrorCode = 'REQUIRED_FLAG' | 'REQUIRED_ARG' | 'INVALID_ENUM' | 'TYPE_MISMATCH' | 'CONSTRAINT_VIOLATED';
15
+ /** Any framework error code (extensible via `string & {}`). */
16
+ type ErrorCode = ParseErrorCode | ValidationErrorCode | (string & {});
17
+ /** Options accepted by the `CLIError` constructor. */
18
+ interface CLIErrorOptions {
19
+ /** Stable machine-readable identifier (e.g. `"UNKNOWN_FLAG"`). */
20
+ readonly code: ErrorCode;
21
+ /**
22
+ * Process exit code.
23
+ * @defaultValue `1`
24
+ */
25
+ readonly exitCode?: number;
26
+ /** One-liner actionable hint shown to the user. */
27
+ readonly suggest?: string;
28
+ /** Arbitrary structured payload (serialised in `--json` mode). */
29
+ readonly details?: Readonly<Record<string, unknown>>;
30
+ /** Original error, if this wraps another. */
31
+ readonly cause?: unknown;
32
+ }
33
+ /**
34
+ * Base structured error for DreamCLI.
35
+ *
36
+ * Every error surfaced by the framework extends this class, ensuring a
37
+ * consistent shape for rendering (TTY pretty-print, `--json`, test assertions).
38
+ */
39
+ declare class CLIError extends Error {
40
+ /** Error class name, always `'CLIError'` for the base class. @override */
41
+ readonly name: string;
42
+ /** Stable machine-readable identifier. */
43
+ readonly code: ErrorCode;
44
+ /** Process exit code (defaults to `1`). */
45
+ readonly exitCode: number;
46
+ /** One-liner actionable hint. */
47
+ readonly suggest: string | undefined;
48
+ /** Structured payload for machine output. */
49
+ readonly details: Readonly<Record<string, unknown>> | undefined;
50
+ /** Create a structured CLI error from a human message and machine-readable options. */
51
+ constructor(message: string, options: CLIErrorOptions);
52
+ /**
53
+ * Serialise to a plain object suitable for JSON output.
54
+ * @sealed
55
+ */
56
+ toJSON(): CLIErrorJSON;
57
+ }
58
+ /** Shape returned by {@linkcode CLIError}.toJSON(). */
59
+ interface CLIErrorJSON {
60
+ /** Error class name (e.g. `'CLIError'`, `'ParseError'`). */
61
+ readonly name: string;
62
+ /** Stable machine-readable identifier for programmatic matching. */
63
+ readonly code: ErrorCode;
64
+ /** Human-readable description of what went wrong. */
65
+ readonly message: string;
66
+ /** Process exit code associated with this error. */
67
+ readonly exitCode: number;
68
+ /** Actionable hint shown to the user, when available. */
69
+ readonly suggest?: string;
70
+ /** Structured payload for machine consumers, when available. */
71
+ readonly details?: Readonly<Record<string, unknown>>;
72
+ }
73
+ /** Options for {@linkcode ParseError}. Code is narrowed to parse-specific codes. */
74
+ interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
75
+ /** Parse-category error code (e.g. `'UNKNOWN_FLAG'`, `'MISSING_VALUE'`). */
76
+ readonly code: ParseErrorCode;
77
+ /**
78
+ * Process exit code for parse failures.
79
+ * @defaultValue `2`
80
+ */
81
+ readonly exitCode?: number;
82
+ }
83
+ /**
84
+ * Error thrown when argv tokenization / parsing fails.
85
+ *
86
+ * Exit code defaults to `2` (standard for CLI usage errors).
87
+ */
88
+ declare class ParseError extends CLIError {
89
+ /** Always `'ParseError'`. @override */
90
+ readonly name: 'ParseError';
91
+ /** Narrowed to parse-category codes. */
92
+ readonly code: ParseErrorCode;
93
+ /** Create a parse error with exit code defaulting to `2`. */
94
+ constructor(message: string, options: ParseErrorOptions);
95
+ }
96
+ /** Options for {@linkcode ValidationError}. Code is narrowed to validation-specific codes. */
97
+ interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
98
+ /** Validation-category error code (e.g. `'REQUIRED_FLAG'`, `'INVALID_ENUM'`). */
99
+ readonly code: ValidationErrorCode;
100
+ /**
101
+ * Process exit code for validation failures.
102
+ * @defaultValue `2`
103
+ */
104
+ readonly exitCode?: number;
105
+ }
106
+ /**
107
+ * Error thrown when resolved values fail validation constraints.
108
+ *
109
+ * Exit code defaults to `2` (standard for CLI usage errors).
110
+ */
111
+ declare class ValidationError extends CLIError {
112
+ /** Always `'ValidationError'`. @override */
113
+ readonly name: 'ValidationError';
114
+ /** Narrowed to validation-category codes. */
115
+ readonly code: ValidationErrorCode;
116
+ /** Create a validation error with exit code defaulting to `2`. */
117
+ constructor(message: string, options: ValidationErrorOptions);
118
+ }
119
+ /** Narrows an unknown value to `CLIError`. */
120
+ declare function isCLIError(value: unknown): value is CLIError;
121
+ /** Narrows an unknown value to `ParseError`. */
122
+ declare function isParseError(value: unknown): value is ParseError;
123
+ /** Narrows an unknown value to `ValidationError`. */
124
+ declare function isValidationError(value: unknown): value is ValidationError;
125
+ //#endregion
126
+ export { CLIError, CLIErrorJSON, CLIErrorOptions, ErrorCode, ParseError, ParseErrorCode, ParseErrorOptions, ValidationError, ValidationErrorCode, ValidationErrorOptions, isCLIError, isParseError, isValidationError };
@@ -0,0 +1 @@
1
+ var e=class extends Error{name=`CLIError`;code;exitCode;suggest;details;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.code=t.code,this.exitCode=t.exitCode??1,this.suggest=t.suggest,this.details=t.details}toJSON(){return{name:this.name,code:this.code,message:this.message,exitCode:this.exitCode,...this.suggest!==void 0&&{suggest:this.suggest},...this.details!==void 0&&{details:this.details}}}},t=class extends e{name=`ParseError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}},n=class extends e{name=`ValidationError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}};function r(t){return t instanceof e}function i(e){return e instanceof t}function a(e){return e instanceof n}export{e as CLIError,t as ParseError,n as ValidationError,r as isCLIError,i as isParseError,a as isValidationError};
@@ -0,0 +1,49 @@
1
+ import { CapturedOutput } from "../output/index.mjs";
2
+ import { CLIError } from "../errors/index.mjs";
3
+ import { RunOptions, RunResult } from "../schema/run.mjs";
4
+ import { CommandMeta, CommandSchema, Out, RunnableCommand } from "../schema/command.mjs";
5
+
6
+ //#region src/core/execution/index.d.ts
7
+ /**
8
+ * Explicit executor input for a single command invocation.
9
+ * @internal
10
+ */
11
+ interface CommandExecutionRequest {
12
+ /** The command instance whose handler will be invoked. */
13
+ readonly command: RunnableCommand;
14
+ /** Raw argument tokens to parse (excluding the program name). */
15
+ readonly argv: readonly string[];
16
+ /** Output channel for handler and error rendering. */
17
+ readonly out: Out;
18
+ /** Frozen schema definition (flags, args, metadata) for parsing and resolution. */
19
+ readonly schema: CommandSchema;
20
+ /** Runtime metadata (binary name, version) propagated to the handler. */
21
+ readonly meta: CommandMeta;
22
+ /** Optional overrides for env, config, prompter, plugins, and JSON mode. */
23
+ readonly options?: RunOptions;
24
+ }
25
+ /**
26
+ * Minimal executor result before output buffers are assembled into `RunResult`.
27
+ * @internal
28
+ */
29
+ interface CommandExecutionResult {
30
+ /** Process exit code (`0` on success, error-specific otherwise). */
31
+ readonly exitCode: number;
32
+ /** The structured error if the command failed, `undefined` on success. */
33
+ readonly error: CLIError | undefined;
34
+ }
35
+ /**
36
+ * Run the full parse -> resolve -> plugin -> handler pipeline for one command.
37
+ *
38
+ * Handles `--help` short-circuit, plugin lifecycle hooks, deprecation warnings,
39
+ * and error wrapping. Both CLI dispatch and testkit `runCommand` converge here.
40
+ * @internal
41
+ */
42
+ declare function executeCommand(request: CommandExecutionRequest): Promise<CommandExecutionResult>;
43
+ /**
44
+ * Assemble a {@linkcode CommandExecutionResult} and captured output buffers into a public `RunResult`.
45
+ * @internal
46
+ */
47
+ declare function buildRunResult(result: CommandExecutionResult, captured: CapturedOutput): RunResult;
48
+ //#endregion
49
+ export { type CommandExecutionRequest, type CommandExecutionResult, buildRunResult, executeCommand };
@@ -0,0 +1 @@
1
+ import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTestPrompter as r}from"../prompt/index.mjs";import{resolve as i}from"../resolve/index.mjs";async function a(a){let{argv:l,command:f,meta:p,options:m,out:h,schema:g}=a;try{if(d(l,`--help`)||d(l,`-h`)){let e=t(g,m?.help);return h.log(e),{exitCode:0,error:void 0}}let a=f.handler;if(a===void 0){let t=new e(`Command '${f.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${f.schema.name}' command`});return h.error(t.message),{exitCode:1,error:t}}await o(m?.plugins,{argv:l,command:g,meta:p,out:h});let _=n(g,l),v=m?.prompter??(m?.answers===void 0?void 0:r(m.answers)),y=await i(g,_,{...m?.stdinData===void 0?{}:{stdinData:m.stdinData},...m?.env===void 0?{}:{env:m.env},...m?.config===void 0?{}:{config:m.config},...v===void 0?{}:{prompter:v}}),b={args:y.args,flags:y.flags,deprecations:y.deprecations,command:g,meta:p,out:h};await s(m?.plugins,`afterResolve`,b);for(let e of y.deprecations)h.warn(u(e));return await s(m?.plugins,`beforeAction`,b),await c(f,a,y.flags,y.args,h,p),await s(m?.plugins,`afterAction`,b),{exitCode:0,error:void 0}}catch(t){if(t instanceof e)return m?.jsonMode===!0?h.json({error:t.toJSON()}):(h.error(t.message),t.suggest!==void 0&&h.error(`Suggestion: ${t.suggest}`)),{exitCode:t.exitCode,error:t};let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return m?.jsonMode===!0?h.json({error:n.toJSON()}):h.error(n.message),{exitCode:1,error:n}}finally{h.stopActive()}}async function o(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function s(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function c(t,n,r,i,a,o){let s=t._executionSteps,c=async e=>{await n({flags:r,args:i,ctx:e,out:a,meta:o})};for(let t=s.length-1;t>=0;t--){let n=s[t];if(n===void 0)continue;let l=c;switch(n.kind){case`derive`:c=async t=>{let s=await n.handler({args:i,flags:r,ctx:t,out:a,meta:o});if(s===void 0){await l(t);return}if(typeof s!=`object`||!s||Array.isArray(s))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...s})};break;case`middleware`:c=async e=>{await n.handler({args:i,flags:r,ctx:e,out:a,meta:o,next:async t=>{await l({...e,...t})}})};break}}await c({})}function l(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function u(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}function d(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}export{l as buildRunResult,a as executeCommand};
@@ -0,0 +1,49 @@
1
+ import { CommandSchema } from "../schema/command.mjs";
2
+
3
+ //#region src/core/help/index.d.ts
4
+ /** Options for customising help output. */
5
+ interface HelpOptions {
6
+ /** Maximum line width (columns). Defaults to 80. */
7
+ readonly width?: number;
8
+ /** Binary/program name shown in the usage line. Defaults to command name. */
9
+ readonly binName?: string;
10
+ /** @internal Whether this usage line is being rendered as merged root/default help. */
11
+ readonly isDefaultHelp?: boolean;
12
+ }
13
+ /**
14
+ * Build the ordered help sections without joining them.
15
+ *
16
+ * @internal
17
+ * @param schema - The {@link CommandSchema} to render.
18
+ * @param options - Optional {@link HelpOptions} for width/bin name.
19
+ * @returns Array of section strings (usage, description, commands, args, flags, examples).
20
+ */
21
+ declare function formatHelpSections(schema: CommandSchema, options?: HelpOptions): readonly string[];
22
+ /**
23
+ * Generate help text from a command schema.
24
+ *
25
+ * Low-level formatter: most applications reach this through `--help`,
26
+ * `help <command>`, or root help rendering in `CLIBuilder`. Call
27
+ * `formatHelp()` directly when embedding DreamCLI help text into custom UIs,
28
+ * tests, or generated docs.
29
+ *
30
+ * Sections rendered (in order):
31
+ * 1. **Usage** line — `program <command> [flags] <args>`
32
+ * 2. **Description** — the command's `.description()` text
33
+ * 3. **Commands** — subcommands table (if any, skips hidden)
34
+ * 4. **Arguments** — positional args table (if any)
35
+ * 5. **Flags** — flags table with type hints and defaults
36
+ * 6. **Examples** — usage examples (if any)
37
+ *
38
+ * @param schema - The command schema to render help for.
39
+ * @param options - Formatting options (width, binary name).
40
+ * @returns The formatted help string.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const text = formatHelp(deploy.schema, { binName: 'mycli' });
45
+ * ```
46
+ */
47
+ declare function formatHelp(schema: CommandSchema, options?: HelpOptions): string;
48
+ //#endregion
49
+ export { type HelpOptions, formatHelp, formatHelpSections };