@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,409 @@
1
+ /**
2
+ * Runtime preflight helpers for CLIBuilder.run().
3
+ *
4
+ * Separates adapter-driven sourcing work from planner and executor logic:
5
+ * config discovery, package metadata discovery, invocation-scoped stdin reads,
6
+ * prompt auto-wiring, and runtime-derived schema overrides.
7
+ *
8
+ * @module dreamcli/core/cli/runtime-preflight
9
+ * @internal
10
+ */
11
+
12
+ import type { FormatLoader } from '#internals/core/config/index.ts';
13
+ import { discoverConfig } from '#internals/core/config/index.ts';
14
+ import { discoverPackageJson, inferCliName } from '#internals/core/config/package-json.ts';
15
+ import { CLIError, ParseError } from '#internals/core/errors/index.ts';
16
+ import type { Verbosity } from '#internals/core/output/index.ts';
17
+ import { parse } from '#internals/core/parse/index.ts';
18
+ import type { PromptEngine } from '#internals/core/prompt/index.ts';
19
+ import { createTerminalPrompter } from '#internals/core/prompt/index.ts';
20
+ import type { CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
21
+ import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
22
+ import { planInvocation } from './planner.ts';
23
+ import type { CLIPlugin } from './plugin.ts';
24
+
25
+ /** Config discovery settings extracted from CLISchema for preflight use. @internal */
26
+ interface RuntimeConfigSettings {
27
+ /** Application name used to locate config files (e.g. `~/.config/<appName>/`). */
28
+ readonly appName: string;
29
+ /** Optional format loaders (JSON/YAML/TOML); `undefined` uses built-in JSON. */
30
+ readonly loaders: readonly FormatLoader[] | undefined;
31
+ }
32
+
33
+ /** Package.json discovery settings extracted from CLISchema. @internal */
34
+ interface RuntimePackageJsonSettings {
35
+ /** Whether to infer the CLI binary name from `package.json` `bin` field. */
36
+ readonly inferName: boolean;
37
+ }
38
+
39
+ /**
40
+ * Structural subset of CLISchema used by runtime preflight.
41
+ *
42
+ * Decouples adapter-driven sourcing (config, package.json, stdin) from the
43
+ * full CLIBuilder surface so preflight can be tested independently.
44
+ * @internal
45
+ */
46
+ interface RuntimePreflightSchemaLike {
47
+ /** CLI program name; may be overridden by package.json discovery or inheritance. */
48
+ readonly name: string;
49
+ /** Whether this CLI inherits its name from a parent (nested CLI embedding). */
50
+ readonly inheritName: boolean;
51
+ /** Declared version; `undefined` means version will be inferred from package.json if available. */
52
+ readonly version: string | undefined;
53
+ /** Declared description; `undefined` allows package.json inference. */
54
+ readonly description: string | undefined;
55
+ /** Registered top-level commands for dispatch planning during stdin detection. */
56
+ readonly commands: readonly ErasedCommand[];
57
+ /** Fallback command when no subcommand token matches. */
58
+ readonly defaultCommand: ErasedCommand | undefined;
59
+ /** Config file discovery settings; `undefined` disables config loading. */
60
+ readonly configSettings: RuntimeConfigSettings | undefined;
61
+ /** Package.json discovery settings; `undefined` disables package.json inference. */
62
+ readonly packageJsonSettings: RuntimePackageJsonSettings | undefined;
63
+ /** Whether `.completions()` registered the built-in completions command. */
64
+ readonly hasBuiltInCompletions: boolean;
65
+ /** Plugins forwarded into the execution pipeline. */
66
+ readonly plugins: readonly CLIPlugin[];
67
+ }
68
+
69
+ /**
70
+ * Caller-supplied overrides for runtime preflight.
71
+ *
72
+ * When provided, these bypass adapter auto-detection (useful for testing
73
+ * and the `CLIRunOptions` public surface).
74
+ * @internal
75
+ */
76
+ interface RuntimePreflightOptions {
77
+ /** Environment variables override; bypasses adapter env when set. */
78
+ readonly env?: Readonly<Record<string, string | undefined>>;
79
+ /** Pre-loaded config object; skips config file discovery when set. */
80
+ readonly config?: Readonly<Record<string, unknown>>;
81
+ /** Pre-read stdin data; `null` means stdin was explicitly empty. */
82
+ readonly stdinData?: string | null;
83
+ /** Custom prompt engine; bypasses terminal prompter auto-creation. */
84
+ readonly prompter?: PromptEngine;
85
+ /** Output verbosity level override. */
86
+ readonly verbosity?: Verbosity;
87
+ /** Force JSON output mode regardless of `--json` flag presence. */
88
+ readonly jsonMode?: boolean;
89
+ /** TTY detection override; bypasses adapter TTY check. */
90
+ readonly isTTY?: boolean;
91
+ }
92
+
93
+ /**
94
+ * Fully resolved runtime inputs ready for the execution pipeline.
95
+ *
96
+ * All adapter vs. caller-override decisions are settled by the time this
97
+ * is constructed; the executor treats these as final truth.
98
+ * @internal
99
+ */
100
+ interface RuntimeExecutionInputs {
101
+ /** Resolved environment variables (from adapter or caller override). */
102
+ readonly env: Readonly<Record<string, string | undefined>>;
103
+ /** Whether stdout is a TTY (controls color, spinners, interactive prompts). */
104
+ readonly isTTY: boolean;
105
+ /** Whether structured JSON output mode is active. */
106
+ readonly jsonMode: boolean;
107
+ /** Output verbosity level. */
108
+ readonly verbosity: Verbosity;
109
+ /** Pre-read stdin data if the invocation declared stdin-mode args. */
110
+ readonly stdinData?: string | null;
111
+ /** Prompt engine for interactive flag resolution; absent in non-TTY. */
112
+ readonly prompter?: PromptEngine;
113
+ /** Loaded config data for the config resolution step. */
114
+ readonly config?: Readonly<Record<string, unknown>>;
115
+ }
116
+
117
+ /** Preflight succeeded — all runtime inputs are resolved and ready for execution. @internal */
118
+ interface ReadyRuntimePreflight {
119
+ /** Discriminant — preflight completed without errors. */
120
+ readonly kind: 'ready';
121
+ /** Schema after package.json discovery and name inheritance applied. */
122
+ readonly schema: RuntimePreflightSchemaLike;
123
+ /** Argv with valid runtime `--config` tokens stripped out. */
124
+ readonly filteredArgv: readonly string[];
125
+ /** Fully resolved runtime inputs for the execution pipeline. */
126
+ readonly inputs: RuntimeExecutionInputs;
127
+ }
128
+
129
+ /** Preflight failed during config file discovery/loading. @internal */
130
+ interface RuntimeConfigErrorPreflight {
131
+ /** Discriminant — config loading produced a structured error. */
132
+ readonly kind: 'config-error';
133
+ /** The config discovery/parse error to render. */
134
+ readonly error: CLIError;
135
+ /** Whether JSON output was requested (needed to choose error rendering). */
136
+ readonly jsonMode: boolean;
137
+ }
138
+
139
+ /** Discriminated union of preflight outcomes — either ready or config-error. @internal */
140
+ type RuntimePreflightResult = ReadyRuntimePreflight | RuntimeConfigErrorPreflight;
141
+
142
+ /** Options bag for {@linkcode prepareRuntimePreflight}. @internal */
143
+ interface PrepareRuntimePreflightOptions {
144
+ /** CLI schema subset driving preflight decisions. */
145
+ readonly schema: RuntimePreflightSchemaLike;
146
+ /** Runtime adapter providing argv, env, stdin, and filesystem access. */
147
+ readonly adapter: RuntimeAdapter;
148
+ /** Caller-supplied overrides; `undefined` means auto-detect everything. */
149
+ readonly options: RuntimePreflightOptions | undefined;
150
+ /** Name inherited from a parent CLI (nested embedding); `undefined` for standalone. */
151
+ readonly inheritedName: string | undefined;
152
+ }
153
+
154
+ const PRECHECK_OUTPUT = {
155
+ jsonMode: false,
156
+ isTTY: false,
157
+ verbosity: 'normal' as const,
158
+ };
159
+
160
+ /** Extract and strip valid runtime `--config` forms from argv, returning path + filtered tokens. @internal */
161
+ function extractConfigFlag(argv: readonly string[]): {
162
+ readonly configPath: string | undefined;
163
+ readonly filteredArgv: readonly string[];
164
+ } {
165
+ const filteredArgv: string[] = [];
166
+ let configPath: string | undefined;
167
+
168
+ for (let i = 0; i < argv.length; i += 1) {
169
+ const arg = argv[i];
170
+ if (arg === undefined) {
171
+ continue;
172
+ }
173
+
174
+ if (arg === '--') {
175
+ filteredArgv.push(...argv.slice(i));
176
+ break;
177
+ }
178
+
179
+ if (configPath === undefined && arg.startsWith('--config=')) {
180
+ const value = arg.slice('--config='.length);
181
+ if (value.length > 0) {
182
+ configPath = value;
183
+ continue;
184
+ }
185
+
186
+ filteredArgv.push(arg);
187
+ continue;
188
+ }
189
+
190
+ if (configPath === undefined && arg === '--config') {
191
+ const nextArg = argv[i + 1];
192
+ if (nextArg !== undefined && !nextArg.startsWith('-') && nextArg !== '--') {
193
+ configPath = nextArg;
194
+ i += 1;
195
+ continue;
196
+ }
197
+
198
+ filteredArgv.push(arg);
199
+ continue;
200
+ }
201
+
202
+ filteredArgv.push(arg);
203
+ }
204
+
205
+ return { configPath, filteredArgv };
206
+ }
207
+
208
+ /** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
209
+ function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean {
210
+ if (argv.includes('--help') || argv.includes('-h')) {
211
+ return false;
212
+ }
213
+
214
+ try {
215
+ const parsed = parse(schema, argv);
216
+ return schema.args.some(({ name, schema: argSchema }) => {
217
+ const parsedValue = parsed.args[name];
218
+ return argSchema.stdinMode && (parsedValue === undefined || parsedValue === '-');
219
+ });
220
+ } catch (error: unknown) {
221
+ if (error instanceof ParseError) {
222
+ return false;
223
+ }
224
+ throw error;
225
+ }
226
+ }
227
+
228
+ /** Plan the invocation and check whether the matched command needs stdin data. @internal */
229
+ function invocationNeedsStdin(
230
+ schema: RuntimePreflightSchemaLike,
231
+ argv: readonly string[],
232
+ ): boolean {
233
+ const plan = planInvocation({
234
+ schema,
235
+ argv,
236
+ help: { binName: schema.name },
237
+ output: PRECHECK_OUTPUT,
238
+ });
239
+
240
+ switch (plan.kind) {
241
+ case 'match':
242
+ return commandInvocationNeedsStdin(plan.plan.mergedSchema, plan.plan.argv);
243
+ case 'dispatch-error':
244
+ case 'needs-subcommand':
245
+ case 'root-help':
246
+ case 'root-version':
247
+ return false;
248
+ }
249
+ }
250
+
251
+ function isCompletionsInvocation(
252
+ schema: RuntimePreflightSchemaLike,
253
+ argv: readonly string[],
254
+ ): boolean {
255
+ if (!schema.hasBuiltInCompletions) {
256
+ return false;
257
+ }
258
+
259
+ const plan = planInvocation({
260
+ schema,
261
+ argv,
262
+ help: { binName: schema.name },
263
+ output: PRECHECK_OUTPUT,
264
+ });
265
+
266
+ return plan.kind === 'match' && plan.plan.command.schema.name === 'completions';
267
+ }
268
+
269
+ async function applyPackageJsonDiscovery(
270
+ schema: RuntimePreflightSchemaLike,
271
+ adapter: RuntimeAdapter,
272
+ inheritedName: string | undefined,
273
+ isCompletions: boolean,
274
+ ): Promise<RuntimePreflightSchemaLike> {
275
+ const packageJsonSettings = schema.packageJsonSettings;
276
+ const packageSchema =
277
+ packageJsonSettings !== undefined && !isCompletions
278
+ ? await (async (): Promise<RuntimePreflightSchemaLike> => {
279
+ const pkg = await discoverPackageJson(adapter);
280
+ if (pkg === null) return schema;
281
+
282
+ const inferredName = packageJsonSettings.inferName ? inferCliName(pkg) : undefined;
283
+ return {
284
+ ...schema,
285
+ ...(schema.version === undefined && pkg.version !== undefined
286
+ ? { version: pkg.version }
287
+ : {}),
288
+ ...(schema.description === undefined && pkg.description !== undefined
289
+ ? { description: pkg.description }
290
+ : {}),
291
+ ...(inferredName !== undefined ? { name: inferredName } : {}),
292
+ };
293
+ })()
294
+ : schema;
295
+
296
+ return inheritedName !== undefined ? { ...packageSchema, name: inheritedName } : packageSchema;
297
+ }
298
+
299
+ async function loadRuntimeConfig(
300
+ schema: RuntimePreflightSchemaLike,
301
+ adapter: RuntimeAdapter,
302
+ configPath: string | undefined,
303
+ isCompletions: boolean,
304
+ existingConfig: Readonly<Record<string, unknown>> | undefined,
305
+ ): Promise<Readonly<Record<string, unknown>> | CLIError | undefined> {
306
+ if (schema.configSettings === undefined || isCompletions || existingConfig !== undefined) {
307
+ return existingConfig;
308
+ }
309
+
310
+ try {
311
+ const result = await discoverConfig(schema.configSettings.appName, adapter, {
312
+ ...(configPath !== undefined ? { configPath } : {}),
313
+ ...(schema.configSettings.loaders !== undefined
314
+ ? { loaders: schema.configSettings.loaders }
315
+ : {}),
316
+ });
317
+ return result.found ? result.data : undefined;
318
+ } catch (error: unknown) {
319
+ if (error instanceof CLIError) {
320
+ return error;
321
+ }
322
+ throw error;
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Run all adapter-driven sourcing work before command execution.
328
+ *
329
+ * Discovers config files, reads package.json metadata, detects stdin needs,
330
+ * wires up the prompt engine, and resolves output policy overrides into a
331
+ * single {@linkcode RuntimePreflightResult}.
332
+ * @internal
333
+ */
334
+ async function prepareRuntimePreflight(
335
+ options: PrepareRuntimePreflightOptions,
336
+ ): Promise<RuntimePreflightResult> {
337
+ const rawArgv = options.adapter.argv.slice(2);
338
+ const { configPath, filteredArgv } =
339
+ options.schema.configSettings !== undefined
340
+ ? extractConfigFlag(rawArgv)
341
+ : { configPath: undefined, filteredArgv: rawArgv };
342
+ const hasJsonFlag = filteredArgv.includes('--json');
343
+ const jsonMode = hasJsonFlag || options.options?.jsonMode === true;
344
+ const isCompletions = isCompletionsInvocation(options.schema, filteredArgv);
345
+ const schema = await applyPackageJsonDiscovery(
346
+ options.schema,
347
+ options.adapter,
348
+ options.inheritedName,
349
+ isCompletions,
350
+ );
351
+ const loadedConfig = await loadRuntimeConfig(
352
+ schema,
353
+ options.adapter,
354
+ configPath,
355
+ isCompletions,
356
+ options.options?.config,
357
+ );
358
+
359
+ if (loadedConfig instanceof CLIError) {
360
+ return {
361
+ kind: 'config-error',
362
+ error: loadedConfig,
363
+ jsonMode,
364
+ };
365
+ }
366
+
367
+ const autoPrompter =
368
+ options.options?.prompter === undefined && options.adapter.stdinIsTTY
369
+ ? createTerminalPrompter(options.adapter.stdin, options.adapter.stderr)
370
+ : undefined;
371
+ const stdinData =
372
+ options.options?.stdinData === undefined && invocationNeedsStdin(schema, filteredArgv)
373
+ ? await options.adapter.readStdin()
374
+ : options.options?.stdinData;
375
+
376
+ return {
377
+ kind: 'ready',
378
+ schema,
379
+ filteredArgv,
380
+ inputs: {
381
+ env: options.options?.env ?? options.adapter.env,
382
+ isTTY: options.options?.isTTY ?? options.adapter.isTTY,
383
+ jsonMode,
384
+ verbosity: options.options?.verbosity ?? 'normal',
385
+ ...(stdinData !== undefined ? { stdinData } : {}),
386
+ ...(options.options?.prompter !== undefined
387
+ ? { prompter: options.options.prompter }
388
+ : autoPrompter !== undefined
389
+ ? { prompter: autoPrompter }
390
+ : {}),
391
+ ...(loadedConfig !== undefined ? { config: loadedConfig } : {}),
392
+ },
393
+ };
394
+ }
395
+
396
+ export type {
397
+ PrepareRuntimePreflightOptions,
398
+ ReadyRuntimePreflight,
399
+ RuntimeExecutionInputs,
400
+ RuntimePreflightOptions,
401
+ RuntimePreflightResult,
402
+ RuntimePreflightSchemaLike,
403
+ };
404
+ export {
405
+ commandInvocationNeedsStdin,
406
+ extractConfigFlag,
407
+ invocationNeedsStdin,
408
+ prepareRuntimePreflight,
409
+ };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Shell completion script generation from command schemas.
3
+ *
4
+ * Each shell has a dedicated generator in `shells/` that takes a
5
+ * {@link CLISchema} and returns a complete shell-specific completion
6
+ * script as a string. Generators walk the full command tree depth,
7
+ * including propagated flags from ancestor commands at each nesting level.
8
+ *
9
+ * @module dreamcli/core/completion
10
+ */
11
+
12
+ import type { CLISchema } from '#internals/core/cli/index.ts';
13
+ import { generateBashCompletion } from './shells/bash.ts';
14
+ import { generateFishCompletion } from './shells/fish.ts';
15
+ import { generatePowerShellCompletion } from './shells/powershell.ts';
16
+ import type { CompletionOptions } from './shells/shared.ts';
17
+ import { generateZshCompletion } from './shells/zsh.ts';
18
+
19
+ // --- Shell type — supported completion targets
20
+
21
+ /**
22
+ * Supported shell targets for completion script generation.
23
+ *
24
+ * `bash`, `zsh`, `fish`, and `powershell` are implemented today.
25
+ */
26
+ type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
27
+
28
+ /**
29
+ * Implemented shell values as a frozen readonly non-empty tuple.
30
+ *
31
+ * Use this tuple for user-facing validation and shell selection UIs.
32
+ * It intentionally matches the shipped {@link Shell} union exactly so docs,
33
+ * help output, and completion generation advertise the same support surface.
34
+ *
35
+ * @see {@link Shell} for the union type matching these entries.
36
+ */
37
+ const SHELLS: Readonly<readonly ['bash', 'zsh', 'fish', 'powershell']> = Object.freeze([
38
+ 'bash',
39
+ 'zsh',
40
+ 'fish',
41
+ 'powershell',
42
+ ] as const satisfies readonly ['bash', 'zsh', 'fish', 'powershell']);
43
+
44
+ // --- Shell-agnostic dispatch
45
+
46
+ /**
47
+ * Generate a completion script for the given shell.
48
+ *
49
+ * This is the primary completion entrypoint for most consumers. Pass a CLI
50
+ * schema and target shell, then write the returned script to a file or source
51
+ * it directly from the command line.
52
+ *
53
+ * @param schema - The CLI schema describing commands, flags, and args.
54
+ * @param shell - Target shell.
55
+ * @param options - Optional generator configuration such as function naming
56
+ * and root default-command completion behavior.
57
+ * @returns A complete shell completion script as a string.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * const script = generateCompletion(app.schema, 'bash');
62
+ * // e.g. source <(mycli completions bash)
63
+ * ```
64
+ */
65
+ function generateCompletion(schema: CLISchema, shell: Shell, options?: CompletionOptions): string {
66
+ switch (shell) {
67
+ case 'bash':
68
+ return generateBashCompletion(schema, options);
69
+ case 'zsh':
70
+ return generateZshCompletion(schema, options);
71
+ case 'fish':
72
+ return generateFishCompletion(schema, options);
73
+ case 'powershell':
74
+ return generatePowerShellCompletion(schema, options);
75
+ }
76
+ }
77
+
78
+ // --- Exports
79
+
80
+ export type { CompletionOptions, Shell };
81
+ export {
82
+ generateBashCompletion,
83
+ generateCompletion,
84
+ generateFishCompletion,
85
+ generatePowerShellCompletion,
86
+ generateZshCompletion,
87
+ SHELLS,
88
+ };