@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -1,583 +0,0 @@
1
- /**
2
- * Prompt engine interface and implementations.
3
- *
4
- * The prompt engine is the pluggable rendering seam for interactive
5
- * flag resolution. The framework ships two implementations:
6
- *
7
- * - `createTerminalPrompter(read, write)` — line-based terminal I/O
8
- * - `createTestPrompter(answers)` — pre-configured answers for testing
9
- *
10
- * Custom engines implement the {@linkcode PromptEngine} interface to swap in
11
- * alternative UI (e.g. web-based, TUI library, etc.).
12
- *
13
- * The engine receives a {@linkcode ResolvedPromptConfig} — a variant of
14
- * {@linkcode PromptConfig} where select/multiselect choices are guaranteed
15
- * non-empty. The resolution chain handles merging enum values from
16
- * `FlagSchema` into choices before calling the engine.
17
- *
18
- * @module dreamcli/core/prompt
19
- */
20
-
21
- import type { WriteFn } from '#internals/core/output/index.ts';
22
- import type {
23
- ConfirmPromptConfig,
24
- InputPromptConfig,
25
- PromptConfig,
26
- PromptResult,
27
- SelectChoice,
28
- } from '#internals/core/schema/prompt.ts';
29
-
30
- // --- Resolved prompt config — choices guaranteed present for select kinds
31
-
32
- /**
33
- * A select prompt config with choices guaranteed non-empty.
34
- *
35
- * The resolution chain populates choices from `FlagSchema.enumValues`
36
- * when the user's {@linkcode PromptConfig} omits them.
37
- */
38
- interface ResolvedSelectPromptConfig {
39
- /** Discriminant — single-choice selection prompt. */
40
- readonly kind: 'select';
41
- /** User-facing question text. */
42
- readonly message: string;
43
- /** Non-empty list of selectable options (populated from flag enum values when omitted). */
44
- readonly choices: readonly [SelectChoice, ...SelectChoice[]];
45
- }
46
-
47
- /**
48
- * A multiselect prompt config with choices guaranteed non-empty.
49
- *
50
- * Same guarantee as {@linkcode ResolvedSelectPromptConfig} — choices are always
51
- * present and non-empty.
52
- */
53
- interface ResolvedMultiselectPromptConfig {
54
- /** Discriminant — multiple-choice selection prompt. */
55
- readonly kind: 'multiselect';
56
- /** User-facing question text. */
57
- readonly message: string;
58
- /** Non-empty list of selectable options (populated from flag enum values when omitted). */
59
- readonly choices: readonly [SelectChoice, ...SelectChoice[]];
60
- /** Minimum number of selections required (validated after input). */
61
- readonly min?: number;
62
- /** Maximum number of selections allowed (validated after input). */
63
- readonly max?: number;
64
- }
65
-
66
- /**
67
- * Prompt config variant where select/multiselect choices are guaranteed
68
- * present. The prompt engine receives this (not raw {@linkcode PromptConfig}),
69
- * so it never needs to merge enum values from `FlagSchema`.
70
- *
71
- * confirm and input configs pass through unchanged.
72
- */
73
- type ResolvedPromptConfig =
74
- | ConfirmPromptConfig
75
- | InputPromptConfig
76
- | ResolvedSelectPromptConfig
77
- | ResolvedMultiselectPromptConfig;
78
-
79
- // --- PromptEngine interface — the pluggable seam
80
-
81
- /**
82
- * Prompt engine interface.
83
- *
84
- * Implementations render a single prompt to the user and return the
85
- * result. The engine is stateless per call — each `promptOne` is
86
- * independent.
87
- *
88
- * The resolution chain calls `promptOne` for each flag that needs
89
- * interactive input. Engines do not need schema knowledge — all
90
- * relevant context (message, choices, validation) is in the config.
91
- *
92
- * @example
93
- * ```ts
94
- * // Custom engine (e.g. wrapping @clack/prompts)
95
- * const engine: PromptEngine = {
96
- * async promptOne(config) {
97
- * // ... render with your library
98
- * return { answered: true, value: userInput };
99
- * }
100
- * };
101
- * ```
102
- */
103
- interface PromptEngine {
104
- /**
105
- * Present a single prompt and return the user's response.
106
- *
107
- * @param config - The resolved prompt configuration (choices guaranteed
108
- * for select/multiselect).
109
- * @returns The user's answer, or `{ answered: false }` if cancelled.
110
- */
111
- promptOne(config: ResolvedPromptConfig): Promise<PromptResult>;
112
- }
113
-
114
- // --- ReadFn — the minimal stdin abstraction
115
-
116
- /**
117
- * A function that reads a single line of user input.
118
- *
119
- * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
120
- * indicating the user closed the input stream (treated as cancel).
121
- *
122
- * The terminal prompter uses this as its sole input seam. The
123
- * resolution chain (prompt-adapter-1) will wire this to the
124
- * runtime adapter's stdin.
125
- */
126
- type ReadFn = () => Promise<string | null>;
127
-
128
- // --- Sentinel for cancelled prompts in test prompter
129
-
130
- /**
131
- * Sentinel value representing a cancelled/aborted prompt in the test
132
- * prompter's answer queue.
133
- *
134
- * Uses `Symbol.for()` for cross-bundle safety — the same symbol is
135
- * returned regardless of which copy of the module is loaded.
136
- *
137
- * @example
138
- * ```ts
139
- * const prompter = createTestPrompter([
140
- * 'us', // first prompt answered 'us'
141
- * PROMPT_CANCEL, // second prompt cancelled
142
- * ]);
143
- * ```
144
- */
145
- const PROMPT_CANCEL: unique symbol = Symbol.for('dreamcli.prompt.cancel') as typeof PROMPT_CANCEL;
146
-
147
- /**
148
- * A queued answer consumed by {@link createTestPrompter}.
149
- *
150
- * The test prompter returns these values exactly as provided; it does not
151
- * coerce or validate them. The normal resolution pipeline performs any later
152
- * type coercion, so tests can supply values in the same shapes real prompts
153
- * would yield:
154
- *
155
- * - `string` for `input` and `select`
156
- * - `boolean` for `confirm`
157
- * - `string[]` for `multiselect`
158
- * - `PROMPT_CANCEL` to simulate user cancellation
159
- *
160
- * Because the type is intentionally `unknown`, tests may also inject malformed
161
- * answers to exercise downstream validation and error reporting.
162
- */
163
- type TestAnswer = unknown;
164
-
165
- // --- Test prompter
166
-
167
- /**
168
- * Options for `createTestPrompter`.
169
- */
170
- interface TestPrompterOptions {
171
- /**
172
- * Behavior when all answers have been consumed.
173
- *
174
- * - `'throw'` (default) — throws an error, making the test fail
175
- * loudly if more prompts fire than expected.
176
- * - `'cancel'` — returns `{ answered: false }`, simulating the
177
- * user cancelling all subsequent prompts.
178
- */
179
- readonly onExhausted?: 'throw' | 'cancel';
180
- }
181
-
182
- /**
183
- * Create a prompt engine that returns pre-configured answers.
184
- *
185
- * Each call to `promptOne` consumes the next answer from the queue.
186
- * Pass `PROMPT_CANCEL` as an answer to simulate the user cancelling
187
- * that prompt.
188
- *
189
- * @param answers - Ordered queue of answers. Use `PROMPT_CANCEL` for
190
- * cancellation.
191
- * @param options - Controls behavior when the queue is exhausted.
192
- * @returns A {@linkcode PromptEngine} suitable for testing.
193
- *
194
- * @example
195
- * ```ts
196
- * const prompter = createTestPrompter(['eu', true, PROMPT_CANCEL]);
197
- *
198
- * // First promptOne → { answered: true, value: 'eu' }
199
- * // Second promptOne → { answered: true, value: true }
200
- * // Third promptOne → { answered: false }
201
- * ```
202
- */
203
- function createTestPrompter(
204
- answers: readonly TestAnswer[],
205
- options?: TestPrompterOptions,
206
- ): PromptEngine {
207
- let index = 0;
208
- return {
209
- promptOne(): Promise<PromptResult> {
210
- if (index >= answers.length) {
211
- if (options?.onExhausted === 'cancel') {
212
- return Promise.resolve({ answered: false });
213
- }
214
- return Promise.reject(
215
- new Error(
216
- `Test prompter exhausted: expected at most ${answers.length} prompts, got prompt #${index + 1}`,
217
- ),
218
- );
219
- }
220
- const answer = answers[index];
221
- index += 1;
222
- if (answer === PROMPT_CANCEL) {
223
- return Promise.resolve({ answered: false });
224
- }
225
- return Promise.resolve({ answered: true, value: answer });
226
- },
227
- };
228
- }
229
-
230
- // --- Terminal prompter — line-based interactive prompts
231
-
232
- /**
233
- * Create a prompt engine backed by line-based terminal I/O.
234
- *
235
- * Uses a {@linkcode ReadFn} for input and a {@linkcode WriteFn} for output. This is the
236
- * built-in renderer — sufficient for most CLI use cases. For richer
237
- * TUI experiences, users can implement {@linkcode PromptEngine} with a library
238
- * like `@clack/prompts` or `inquirer`.
239
- *
240
- * The prompter does **not** use raw mode — all input is line-based.
241
- * This keeps the implementation portable across Node, Bun, and Deno
242
- * without platform-specific stdin configuration.
243
- *
244
- * @param read - Line reader function (returns `null` on EOF)
245
- * @param write - Output writer function
246
- * @returns A {@linkcode PromptEngine} that prompts via terminal I/O
247
- *
248
- * @example
249
- * ```ts
250
- * import { createInterface } from 'readline';
251
- *
252
- * const rl = createInterface({ input: process.stdin, output: process.stdout });
253
- * const read = () => new Promise<string | null>((resolve) => {
254
- * rl.question('', (answer) => resolve(answer));
255
- * });
256
- * const write: WriteFn = (s) => process.stdout.write(s);
257
- *
258
- * const prompter = createTerminalPrompter(read, write);
259
- * ```
260
- */
261
- function createTerminalPrompter(read: ReadFn, write: WriteFn): PromptEngine {
262
- return {
263
- promptOne(config): Promise<PromptResult> {
264
- switch (config.kind) {
265
- case 'confirm':
266
- return promptConfirm(config, read, write);
267
- case 'input':
268
- return promptInput(config, read, write);
269
- case 'select':
270
- return promptSelect(config, read, write);
271
- case 'multiselect':
272
- return promptMultiselect(config, read, write);
273
- }
274
- },
275
- };
276
- }
277
-
278
- // --- Per-kind prompt implementations
279
-
280
- /** Maximum retries for invalid input before treating as cancel. */
281
- const MAX_RETRIES = 10;
282
-
283
- /**
284
- * Confirm prompt: yes/no question.
285
- *
286
- * Displays `(Y/n)` because empty input defaults to yes.
287
- * Accepts: y, yes, n, no, empty (uses default). Case-insensitive.
288
- *
289
- * @param config - {@link ConfirmPromptConfig} with the question message
290
- * @param read - {@link ReadFn} for reading a line of user input
291
- * @param write - {@link WriteFn} for rendering prompt text
292
- * @returns Resolved {@link PromptResult} — `true`/`false` value, or cancelled on EOF
293
- */
294
- async function promptConfirm(
295
- config: ConfirmPromptConfig,
296
- read: ReadFn,
297
- write: WriteFn,
298
- ): Promise<PromptResult> {
299
- const defaultValue = true;
300
- let retries = 0;
301
-
302
- while (retries < MAX_RETRIES) {
303
- const hint = defaultValue ? '(Y/n)' : '(y/N)';
304
- write(`${config.message} ${hint} `);
305
-
306
- const line = await read();
307
- if (line === null) return { answered: false };
308
-
309
- const lower = line.trim().toLowerCase();
310
- if (lower === '') {
311
- return { answered: true, value: defaultValue };
312
- }
313
- if (lower === 'y' || lower === 'yes') {
314
- return { answered: true, value: true };
315
- }
316
- if (lower === 'n' || lower === 'no') {
317
- return { answered: true, value: false };
318
- }
319
-
320
- write('Please answer y or n.\n');
321
- retries += 1;
322
- }
323
-
324
- write('Too many invalid attempts.\n');
325
- return { answered: false };
326
- }
327
-
328
- /**
329
- * Input prompt: free-text string entry.
330
- *
331
- * Displays the message, reads a line, and optionally validates via
332
- * `config.validate`. Loops on invalid input up to `MAX_RETRIES`.
333
- *
334
- * @param config - {@link InputPromptConfig} with message, optional placeholder and validator
335
- * @param read - {@link ReadFn} for reading a line of user input
336
- * @param write - {@link WriteFn} for rendering prompt text and validation errors
337
- * @returns Resolved {@link PromptResult} — trimmed string value, or cancelled on EOF/exhausted retries
338
- */
339
- async function promptInput(
340
- config: InputPromptConfig,
341
- read: ReadFn,
342
- write: WriteFn,
343
- ): Promise<PromptResult> {
344
- let retries = 0;
345
-
346
- while (retries < MAX_RETRIES) {
347
- const placeholder = config.placeholder !== undefined ? ` (${config.placeholder})` : '';
348
- write(`${config.message}${placeholder}: `);
349
-
350
- const line = await read();
351
- if (line === null) return { answered: false };
352
-
353
- const trimmed = line.trim();
354
-
355
- if (config.validate !== undefined) {
356
- const result = config.validate(trimmed);
357
- if (result !== true) {
358
- write(`${result}\n`);
359
- retries += 1;
360
- continue;
361
- }
362
- }
363
-
364
- return { answered: true, value: trimmed };
365
- }
366
-
367
- // Exhausted retries — cancel
368
- write('Too many invalid attempts.\n');
369
- return { answered: false };
370
- }
371
-
372
- /**
373
- * Select prompt: single choice from a numbered list.
374
- *
375
- * Displays choices with 1-based indices. User enters the number of
376
- * their selection.
377
- *
378
- * @param config - {@link ResolvedSelectPromptConfig} with message and guaranteed non-empty choices
379
- * @param read - {@link ReadFn} for reading a line of user input
380
- * @param write - {@link WriteFn} for rendering the choice list and validation errors
381
- * @returns Resolved {@link PromptResult} — selected {@link SelectChoice.value}, or cancelled on EOF/exhausted retries
382
- */
383
- async function promptSelect(
384
- config: ResolvedSelectPromptConfig,
385
- read: ReadFn,
386
- write: WriteFn,
387
- ): Promise<PromptResult> {
388
- let retries = 0;
389
-
390
- while (retries < MAX_RETRIES) {
391
- write(`${config.message}\n`);
392
- for (let i = 0; i < config.choices.length; i += 1) {
393
- const choice = config.choices[i];
394
- // Choice always defined — guaranteed non-empty tuple and i < length
395
- if (choice === undefined) continue;
396
- const label = choice.label ?? choice.value;
397
- const desc = choice.description !== undefined ? ` - ${choice.description}` : '';
398
- write(` ${i + 1}) ${label}${desc}\n`);
399
- }
400
- write('Enter number: ');
401
-
402
- const line = await read();
403
- if (line === null) return { answered: false };
404
-
405
- const num = Number(line.trim());
406
- if (Number.isNaN(num) || !Number.isInteger(num) || num < 1 || num > config.choices.length) {
407
- write(`Please enter a number between 1 and ${config.choices.length}.\n`);
408
- retries += 1;
409
- continue;
410
- }
411
-
412
- const selected = config.choices[num - 1];
413
- if (selected === undefined) {
414
- // Should not happen given bounds check, but satisfies noUncheckedIndexedAccess
415
- retries += 1;
416
- continue;
417
- }
418
- return { answered: true, value: selected.value };
419
- }
420
-
421
- write('Too many invalid attempts.\n');
422
- return { answered: false };
423
- }
424
-
425
- /**
426
- * Multiselect prompt: multiple choices from a numbered list.
427
- *
428
- * Displays choices with 1-based indices. User enters comma-separated
429
- * numbers of their selections (e.g. `1,3,5`).
430
- *
431
- * Validates against `min`/`max` constraints if configured.
432
- *
433
- * @param config - {@link ResolvedMultiselectPromptConfig} with message, guaranteed non-empty choices, and optional min/max
434
- * @param read - {@link ReadFn} for reading a line of user input
435
- * @param write - {@link WriteFn} for rendering the choice list, hints, and validation errors
436
- * @returns Resolved {@link PromptResult} — array of selected {@link SelectChoice.value} strings, or cancelled on EOF/exhausted retries
437
- */
438
- async function promptMultiselect(
439
- config: ResolvedMultiselectPromptConfig,
440
- read: ReadFn,
441
- write: WriteFn,
442
- ): Promise<PromptResult> {
443
- let retries = 0;
444
-
445
- while (retries < MAX_RETRIES) {
446
- write(`${config.message}\n`);
447
- for (let i = 0; i < config.choices.length; i += 1) {
448
- const choice = config.choices[i];
449
- if (choice === undefined) continue;
450
- const label = choice.label ?? choice.value;
451
- const desc = choice.description !== undefined ? ` - ${choice.description}` : '';
452
- write(` ${i + 1}) ${label}${desc}\n`);
453
- }
454
-
455
- const minHint = config.min !== undefined ? `, min: ${config.min}` : '';
456
- const maxHint = config.max !== undefined ? `, max: ${config.max}` : '';
457
- write(`Enter numbers separated by commas (e.g. 1,3${minHint}${maxHint}): `);
458
-
459
- const line = await read();
460
- if (line === null) return { answered: false };
461
-
462
- const trimmed = line.trim();
463
- if (trimmed === '') {
464
- // Empty = no selection
465
- if (config.min !== undefined && config.min > 0) {
466
- write(`Please select at least ${config.min}.\n`);
467
- retries += 1;
468
- continue;
469
- }
470
- return { answered: true, value: [] };
471
- }
472
-
473
- const parts = trimmed.split(',').map((s) => s.trim());
474
- const indices: number[] = [];
475
- let valid = true;
476
-
477
- for (const part of parts) {
478
- const num = Number(part);
479
- if (Number.isNaN(num) || !Number.isInteger(num) || num < 1 || num > config.choices.length) {
480
- write(`Invalid selection '${part}'. Use numbers between 1 and ${config.choices.length}.\n`);
481
- valid = false;
482
- break;
483
- }
484
- indices.push(num);
485
- }
486
-
487
- if (!valid) {
488
- retries += 1;
489
- continue;
490
- }
491
-
492
- // Deduplicate
493
- const unique = [...new Set(indices)];
494
-
495
- if (config.min !== undefined && unique.length < config.min) {
496
- write(`Please select at least ${config.min}.\n`);
497
- retries += 1;
498
- continue;
499
- }
500
-
501
- if (config.max !== undefined && unique.length > config.max) {
502
- write(`Please select at most ${config.max}.\n`);
503
- retries += 1;
504
- continue;
505
- }
506
-
507
- const selected = unique.map((n) => {
508
- const choice = config.choices[n - 1];
509
- // Bounds already validated above; satisfies noUncheckedIndexedAccess
510
- return choice?.value ?? '';
511
- });
512
-
513
- return { answered: true, value: selected };
514
- }
515
-
516
- write('Too many invalid attempts.\n');
517
- return { answered: false };
518
- }
519
-
520
- // --- Utility: prepare resolved prompt config from raw config + flag schema
521
-
522
- /**
523
- * Prepare a {@linkcode ResolvedPromptConfig} from a raw {@linkcode PromptConfig} and optional
524
- * enum values from the flag schema.
525
- *
526
- * For select/multiselect prompts without explicit choices, this merges
527
- * the flag's enum values into the choices list. Throws if no choices
528
- * are available.
529
- *
530
- * This function is called by the resolution chain (prompt-resolve-1),
531
- * not by the engine itself — keeping the engine free of schema knowledge.
532
- *
533
- * @param config - Raw prompt config from `FlagSchema.prompt`
534
- * @param enumValues - Optional enum values from `FlagSchema.enumValues`
535
- * @returns Resolved config with choices guaranteed for select kinds
536
- * @throws Error if select/multiselect has no choices and no enum values
537
- */
538
- function resolvePromptConfig(
539
- config: PromptConfig,
540
- enumValues: readonly string[] | undefined,
541
- ): ResolvedPromptConfig {
542
- if (config.kind === 'confirm' || config.kind === 'input') {
543
- return config;
544
- }
545
-
546
- // Select or multiselect — ensure choices are present
547
- const rawChoices: readonly SelectChoice[] =
548
- config.choices ?? enumValues?.map((v) => ({ value: v })) ?? [];
549
-
550
- if (rawChoices.length === 0) {
551
- throw new Error(
552
- `Prompt config (${config.kind}) requires choices but none were provided and no enum values are available`,
553
- );
554
- }
555
-
556
- // Non-empty assertion: we just checked length > 0
557
- const choices = rawChoices as readonly [SelectChoice, ...SelectChoice[]];
558
-
559
- if (config.kind === 'select') {
560
- return { kind: 'select', message: config.message, choices };
561
- }
562
-
563
- return {
564
- kind: 'multiselect',
565
- message: config.message,
566
- choices,
567
- ...(config.min !== undefined ? { min: config.min } : {}),
568
- ...(config.max !== undefined ? { max: config.max } : {}),
569
- };
570
- }
571
-
572
- // --- Exports
573
-
574
- export type {
575
- PromptEngine,
576
- ReadFn,
577
- ResolvedMultiselectPromptConfig,
578
- ResolvedPromptConfig,
579
- ResolvedSelectPromptConfig,
580
- TestAnswer,
581
- TestPrompterOptions,
582
- };
583
- export { createTerminalPrompter, createTestPrompter, PROMPT_CANCEL, resolvePromptConfig };