@kjanat/dreamcli 0.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 (205) hide show
  1. package/CHANGELOG.md +706 -0
  2. package/LICENSE +22 -0
  3. package/README.md +502 -0
  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 -0
  96. package/dist/index.mjs +1 -0
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/runtime/adapter.mjs +1 -0
  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 +7 -0
  115. package/dist/runtime.mjs +1 -0
  116. package/dist/testkit.d.mts +6 -0
  117. package/dist/testkit.mjs +1 -0
  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 +33 -0
  122. package/examples/gh/package.json +44 -0
  123. package/examples/gh/src/commands/auth.ts +66 -0
  124. package/examples/gh/src/commands/issue.ts +120 -0
  125. package/examples/gh/src/commands/pr.ts +125 -0
  126. package/examples/gh/src/data/issues.yaml +5 -0
  127. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  128. package/examples/gh/src/data/pull-requests.yaml +7 -0
  129. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  130. package/examples/gh/src/docs.ts +11 -0
  131. package/examples/gh/src/lib/auth.ts +37 -0
  132. package/examples/gh/src/lib/utils.ts +17 -0
  133. package/examples/gh/src/main.test.ts +307 -0
  134. package/examples/gh/src/main.ts +40 -0
  135. package/examples/interactive.ts +66 -0
  136. package/examples/json-mode.ts +91 -0
  137. package/examples/middleware.ts +71 -0
  138. package/examples/multi-command.ts +66 -0
  139. package/examples/spinner-progress.ts +49 -0
  140. package/examples/testing.ts +147 -0
  141. package/package.json +149 -2
  142. package/src/core/cli/dispatch.ts +286 -0
  143. package/src/core/cli/index.ts +978 -0
  144. package/src/core/cli/planner.ts +413 -0
  145. package/src/core/cli/plugin.ts +117 -0
  146. package/src/core/cli/propagate.ts +97 -0
  147. package/src/core/cli/root-help.ts +269 -0
  148. package/src/core/cli/root-surface.ts +74 -0
  149. package/src/core/cli/runtime-preflight.ts +409 -0
  150. package/src/core/completion/index.ts +88 -0
  151. package/src/core/completion/shells/bash.ts +459 -0
  152. package/src/core/completion/shells/fish.ts +259 -0
  153. package/src/core/completion/shells/powershell.ts +405 -0
  154. package/src/core/completion/shells/shared.ts +283 -0
  155. package/src/core/completion/shells/zsh.ts +381 -0
  156. package/src/core/config/index.ts +407 -0
  157. package/src/core/config/package-json.ts +220 -0
  158. package/src/core/errors/index.ts +193 -0
  159. package/src/core/execution/index.ts +270 -0
  160. package/src/core/help/index.ts +557 -0
  161. package/src/core/json-schema/index.ts +891 -0
  162. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  163. package/src/core/output/activity.ts +568 -0
  164. package/src/core/output/contracts.ts +194 -0
  165. package/src/core/output/display-value.ts +48 -0
  166. package/src/core/output/index.ts +669 -0
  167. package/src/core/output/renderers.ts +125 -0
  168. package/src/core/output/writer.ts +46 -0
  169. package/src/core/parse/index.ts +661 -0
  170. package/src/core/prompt/index.ts +583 -0
  171. package/src/core/resolve/args.ts +144 -0
  172. package/src/core/resolve/coerce.ts +432 -0
  173. package/src/core/resolve/config.ts +26 -0
  174. package/src/core/resolve/contracts.ts +135 -0
  175. package/src/core/resolve/errors.ts +227 -0
  176. package/src/core/resolve/flags.ts +205 -0
  177. package/src/core/resolve/index.ts +108 -0
  178. package/src/core/resolve/property.ts +99 -0
  179. package/src/core/schema/activity.ts +240 -0
  180. package/src/core/schema/arg.ts +719 -0
  181. package/src/core/schema/command.ts +1490 -0
  182. package/src/core/schema/flag.ts +756 -0
  183. package/src/core/schema/index.ts +91 -0
  184. package/src/core/schema/middleware.ts +171 -0
  185. package/src/core/schema/prompt.ts +156 -0
  186. package/src/core/schema/run.ts +195 -0
  187. package/src/core/schema-dsl/index.ts +109 -0
  188. package/src/core/schema-dsl/parse.ts +262 -0
  189. package/src/core/schema-dsl/runtime.ts +609 -0
  190. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  191. package/src/core/testkit/index.ts +123 -0
  192. package/src/index.ts +170 -0
  193. package/src/runtime/adapter.ts +303 -0
  194. package/src/runtime/auto.ts +110 -0
  195. package/src/runtime/bun.ts +55 -0
  196. package/src/runtime/deno.ts +369 -0
  197. package/src/runtime/detect.ts +105 -0
  198. package/src/runtime/index.ts +21 -0
  199. package/src/runtime/node-builtins.d.ts +23 -0
  200. package/src/runtime/node.ts +300 -0
  201. package/src/runtime/paths.ts +62 -0
  202. package/src/runtime/support.ts +135 -0
  203. package/src/runtime.ts +31 -0
  204. package/src/testkit.ts +25 -0
  205. package/src/version.ts +20 -0
@@ -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 };
@@ -0,0 +1,8 @@
1
+ import{getFlagAliasNames as e}from"../schema/flag.mjs";import{formatDisplayValue as t}from"../output/display-value.mjs";function n(e){return{width:e?.width??80,binName:e?.binName,isDefaultHelp:e?.isDefaultHelp??!1}}function r(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function i(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
2
+ `)}function a(e){return typeof e==`string`?`[deprecated: ${e}]`:`[deprecated]`}function o(e){return e===void 0?`undefined`:e===null?`null`:t(e)}function s(t,n){let r=e(n,{kind:`short`}),i=e(n,{kind:`long`}),a=[...r.map(e=>`-${e}`),`--${t}`,...i.map(e=>`--${e}`)];return n.kind===`boolean`?a.join(`, `):`${a.join(`, `)} ${c(n)}`}function c(e){switch(e.kind){case`string`:return`<string>`;case`number`:return`<number>`;case`enum`:return`<${(e.enumValues??[]).join(`|`)}>`;case`array`:return`<${e.elementSchema===void 0?`value`:c(e.elementSchema).slice(1,-1)}>...`;case`boolean`:return``;case`custom`:return`<value>`}}function l(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.configPath!==void 0&&t.push(`[config: ${e.configPath}]`),e.prompt!==void 0&&t.push(`[prompt]`),e.presence===`required`?t.push(`[required]`):e.presence===`defaulted`&&e.kind!==`boolean`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function u(t){let n=Object.keys(t);if(n.length===0)return[];let r=[...n].sort((n,r)=>{let i=t[n],a=t[r];if(i===void 0||a===void 0)return 0;let o=e(i,{kind:`short`}).length>0,s=e(a,{kind:`short`}).length>0;return o&&!s?-1:!o&&s?1:n.localeCompare(r)}),i=[];for(let e of r){let n=t[e];n!==void 0&&i.push({left:s(e,n),description:l(n)})}return i}function d(e){let{name:t,schema:n}=e,r=n.kind===`enum`&&n.enumValues!==void 0?n.enumValues.join(`|`):t,i=n.variadic?`...`:``;return n.presence===`required`?`<${r}>${i}`:`[${r}]${i}`}function f(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.presence===`defaulted`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function p(e,t){let r=n(t),i=[];i.push(h(e,r)),e.description!==void 0&&i.push(e.description);let a=e.commands.filter(e=>!e.hidden);return a.length>0&&i.push(v(a,r)),e.args.length>0&&i.push(g(e.args,r)),Object.keys(e.flags).length>0&&i.push(_(e.flags,r)),e.examples.length>0&&i.push(y(e.examples)),i}function m(e,t){return`${p(e,t).join(`
3
+
4
+ `)}\n`}function h(e,t){let n=[`Usage:`],r=t.binName===void 0||t.isDefaultHelp&&t.binName===e.name?e.name:`${t.binName} ${e.name}`;n.push(r),e.commands.length>0&&n.push(`<command>`),Object.keys(e.flags).length>0&&n.push(`[flags]`);for(let t of e.args)n.push(d(t));return n.join(` `)}function g(e,t){let n=[`Arguments:`],a=0,o=[];for(let t of e){let e=` ${d(t)}`,n=f(t.schema);o.push({left:e,desc:n}),e.length>a&&(a=e.length)}let s=a+2;for(let{left:e,desc:a}of o)if(a.length===0)n.push(e);else{let o=r(e,s),c=i(a,t.width,s);n.push(`${o}${c}`)}return n.join(`
5
+ `)}function _(e,t){let n=[`Flags:`],a=u(e);if(a.length===0)return``;let o=0;for(let e of a){let t=` ${e.left}`;t.length>o&&(o=t.length)}let s=o+2;for(let e of a){let a=` ${e.left}`;if(e.description.length===0)n.push(a);else{let o=r(a,s),c=i(e.description,t.width,s);n.push(`${o}${c}`)}}return n.join(`
6
+ `)}function v(e,t){let n=[`Commands:`],a=0;for(let t of e)t.name.length>a&&(a=t.name.length);let o=2+a+2;for(let a of e){let e=` ${a.name}`,s=a.description??``;if(s.length===0)n.push(e);else{let a=r(e,o),c=i(s,t.width,o);n.push(`${a}${c}`)}}return n.join(`
7
+ `)}function y(e){let t=[`Examples:`];for(let n of e)n.description===void 0?t.push(` $ ${n.command}`):(t.push(` ${n.description}:`),t.push(` $ ${n.command}`));return t.join(`
8
+ `)}export{m as formatHelp,p as formatHelpSections};
@@ -0,0 +1,109 @@
1
+ import { CommandSchema } from "../schema/command.mjs";
2
+ import { CLISchema } from "../cli/index.mjs";
3
+
4
+ //#region src/core/json-schema/index.d.ts
5
+ /**
6
+ * Options for JSON Schema generation.
7
+ *
8
+ * Both {@link generateSchema} and {@link generateInputSchema} accept these
9
+ * options to control which parts of the CLI schema are included in the output.
10
+ */
11
+ interface JsonSchemaOptions {
12
+ /**
13
+ * Include commands marked as hidden.
14
+ *
15
+ * When `true` (default), hidden commands appear in the output with
16
+ * `hidden: true` (definition schema) or as valid branches (input schema).
17
+ * When `false`, hidden commands and their entire subtrees are excluded.
18
+ *
19
+ * @defaultValue `true`
20
+ */
21
+ readonly includeHidden?: boolean;
22
+ /**
23
+ * Include prompt configuration on flags.
24
+ *
25
+ * When `false`, prompt configs are omitted even if defined on flags.
26
+ * Useful for producing a schema focused on the non-interactive CLI
27
+ * surface only.
28
+ *
29
+ * Only affects {@link generateSchema} output — prompt configs are never
30
+ * included in {@link generateInputSchema} output.
31
+ *
32
+ * @defaultValue `true`
33
+ */
34
+ readonly includePrompts?: boolean;
35
+ }
36
+ /**
37
+ * Generate a definition metadata document describing the CLI's structure.
38
+ *
39
+ * Walks the full command tree and produces a plain JSON-serializable object
40
+ * representing all commands, subcommands, flags, args, and metadata.
41
+ * Non-serializable runtime values (parse functions, middleware handlers,
42
+ * interactive resolvers) are omitted.
43
+ *
44
+ * @param schema - The CLI schema from `CLIBuilder.schema`.
45
+ * @param options - Generation options.
46
+ * @returns A plain object suitable for `JSON.stringify()`.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const app = cli('myapp').version('1.0.0').command(deploy);
51
+ * const definition = generateSchema(app.schema);
52
+ * writeFileSync('cli-schema.json', JSON.stringify(definition, null, 2));
53
+ * ```
54
+ */
55
+ declare function generateSchema(schema: CLISchema, options?: JsonSchemaOptions): Record<string, unknown>;
56
+ /**
57
+ * Generate a JSON Schema (draft 2020-12) for validating CLI input as JSON.
58
+ *
59
+ * Accepts either a full {@link CLISchema} (producing a discriminated union
60
+ * across all commands) or a single {@link CommandSchema} (producing a flat
61
+ * object schema for that command's flags and args).
62
+ *
63
+ * **Single command** — produces an object schema where flag/arg names are
64
+ * properties with appropriate JSON Schema types.
65
+ *
66
+ * **Multi-command CLI** — produces a `oneOf` discriminated union with a
67
+ * `command` property identifying each branch. Nested subcommands use
68
+ * dot-delimited paths (e.g. `"deploy.rollback"`).
69
+ *
70
+ * Only commands with action handlers are included (group commands without
71
+ * actions are not directly invocable and are skipped).
72
+ *
73
+ * @param schema - A CLI schema or a single command schema.
74
+ * @param options - Generation options.
75
+ * @returns A JSON Schema object suitable for `JSON.stringify()`.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * // Validate a config file against the CLI's input shape
80
+ * const inputSchema = generateInputSchema(app.schema);
81
+ * writeFileSync('input-schema.json', JSON.stringify(inputSchema, null, 2));
82
+ * ```
83
+ */
84
+ declare function generateInputSchema(schema: CLISchema | CommandSchema, options?: JsonSchemaOptions): Record<string, unknown>;
85
+ /**
86
+ * JSON Schema (draft 2020-12) that validates the output of {@link generateSchema}.
87
+ *
88
+ * Each `$defs` entry is defined once as a schema DSL string — the DSL
89
+ * parser produces a runtime AST, and {@link nodeToJsonSchema} converts
90
+ * that AST to a JSON Schema fragment. No probe fixtures, no override
91
+ * maps, no manually maintained type definitions.
92
+ *
93
+ * Hosted at {@link DEFINITION_SCHEMA_URL} for `$schema` resolution. Also
94
+ * exported so tooling can validate definition documents without a network
95
+ * round-trip.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * import Ajv from 'ajv/dist/2020';
100
+ * import { definitionMetaSchema, generateSchema } from '@kjanat/dreamcli';
101
+ *
102
+ * const ajv = new Ajv();
103
+ * const validate = ajv.compile(definitionMetaSchema);
104
+ * const valid = validate(generateSchema(myCli.schema));
105
+ * ```
106
+ */
107
+ declare const definitionMetaSchema: Record<string, unknown>;
108
+ //#endregion
109
+ export { type JsonSchemaOptions, definitionMetaSchema, generateInputSchema, generateSchema };