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