inquirerer 3.0.1 → 4.1.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/prompt.js ADDED
@@ -0,0 +1,1071 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Inquirerer = void 0;
7
+ exports.reorderQuestionsByDeps = reorderQuestionsByDeps;
8
+ const yanse_1 = require("yanse");
9
+ const readline_1 = __importDefault(require("readline"));
10
+ const keypress_1 = require("./keypress");
11
+ const resolvers_1 = require("./resolvers");
12
+ function reorderQuestionsByDeps(questions) {
13
+ const nameToIndex = new Map();
14
+ questions.forEach((q, idx) => nameToIndex.set(q.name, idx));
15
+ const resolved = new Set();
16
+ const result = [];
17
+ function addQuestion(q) {
18
+ // If this question depends on others, ensure those are added first
19
+ if (q.dependsOn && q.dependsOn.length > 0) {
20
+ for (const dep of q.dependsOn) {
21
+ if (!resolved.has(dep)) {
22
+ const depIdx = nameToIndex.get(dep);
23
+ if (depIdx === undefined) {
24
+ throw new Error(`Unknown dependency: ${dep}`);
25
+ }
26
+ addQuestion(questions[depIdx]);
27
+ }
28
+ }
29
+ }
30
+ if (!resolved.has(q.name)) {
31
+ resolved.add(q.name);
32
+ result.push(q);
33
+ }
34
+ }
35
+ for (const q of questions) {
36
+ addQuestion(q);
37
+ }
38
+ return result;
39
+ }
40
+ const validationMessage = (question, ctx) => {
41
+ if (ctx.numTries === 0 || ctx.validation.success) {
42
+ return ''; // No message if first attempt or validation was successful
43
+ }
44
+ if (ctx.validation.reason) {
45
+ return (0, yanse_1.red)(`The field "${question.name}" is invalid: ${ctx.validation.reason}\n`);
46
+ }
47
+ switch (ctx.validation.type) {
48
+ case 'required':
49
+ return (0, yanse_1.red)(`The field "${question.name}" is required. Please provide a value.\n`);
50
+ case 'pattern':
51
+ return (0, yanse_1.red)(`The field "${question.name}" does not match the pattern: ${question.pattern}.\n`);
52
+ default:
53
+ return (0, yanse_1.red)(`The field "${question.name}" is invalid. Please try again.\n`);
54
+ }
55
+ };
56
+ class PromptContext {
57
+ numTries = 0;
58
+ needsInput = true;
59
+ validation = { success: false };
60
+ constructor() { }
61
+ tryAgain(validation) {
62
+ this.numTries++;
63
+ this.needsInput = true;
64
+ this.validation = { ...this.validation, ...validation, success: false };
65
+ }
66
+ nextQuestion() {
67
+ this.numTries = 0;
68
+ this.needsInput = false;
69
+ this.validation = { success: true };
70
+ }
71
+ process(validation) {
72
+ if (typeof validation === 'boolean') {
73
+ if (validation) {
74
+ this.nextQuestion();
75
+ }
76
+ else {
77
+ this.tryAgain({ type: 'validation' });
78
+ }
79
+ }
80
+ else {
81
+ if (validation.success) {
82
+ this.nextQuestion();
83
+ }
84
+ else {
85
+ this.tryAgain(validation);
86
+ }
87
+ }
88
+ return this.validation;
89
+ }
90
+ }
91
+ function generatePromptMessage(question, ctx) {
92
+ const { message, name, type, default: def, options = [], description } = question;
93
+ const lines = [];
94
+ // 1. Main prompt label with --name inline (and aliases if present)
95
+ const aliasInfo = question.alias
96
+ ? `, ${(Array.isArray(question.alias) ? question.alias : [question.alias])
97
+ .map(a => a.length === 1 ? `-${a}` : `--${a}`)
98
+ .join(', ')}`
99
+ : '';
100
+ let promptLine = yanse_1.whiteBright.bold(message || `${name}?`) + ' ' + (0, yanse_1.dim)(`(--${name}${aliasInfo})`);
101
+ // 2. Append default inline (only if present)
102
+ switch (type) {
103
+ case 'confirm':
104
+ promptLine += ' (y/n)';
105
+ if (def !== undefined) {
106
+ promptLine += ` ${(0, yanse_1.yellow)(`[${def ? 'y' : 'n'}]`)}`;
107
+ }
108
+ break;
109
+ case 'text':
110
+ case 'number':
111
+ if (def !== undefined) {
112
+ promptLine += ` ${(0, yanse_1.yellow)(`[${def}]`)}`;
113
+ }
114
+ break;
115
+ case 'autocomplete':
116
+ case 'list':
117
+ case 'checkbox':
118
+ if (def !== undefined) {
119
+ const defaults = Array.isArray(def) ? def : [def];
120
+ const rendered = defaults.map(d => (0, yanse_1.yellow)(d)).join((0, yanse_1.gray)(', '));
121
+ promptLine += ` ${(0, yanse_1.yellow)(`[${rendered}]`)}`;
122
+ }
123
+ break;
124
+ }
125
+ lines.push(promptLine);
126
+ // 3. Optional description below title
127
+ if (description) {
128
+ lines.push((0, yanse_1.dim)(description));
129
+ }
130
+ // 4. Validation message if applicable
131
+ const validation = validationMessage(question, ctx);
132
+ if (validation) {
133
+ lines.push(validation); // already styled red
134
+ }
135
+ return lines.join('\n') + '\n';
136
+ }
137
+ class Inquirerer {
138
+ rl;
139
+ keypress;
140
+ noTty;
141
+ output;
142
+ input;
143
+ useDefaults;
144
+ globalMaxLines;
145
+ mutateArgs;
146
+ resolverRegistry;
147
+ handledKeys = new Set();
148
+ constructor(options) {
149
+ const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true, resolverRegistry = resolvers_1.globalResolverRegistry } = options ?? {};
150
+ this.useDefaults = useDefaults;
151
+ this.noTty = noTty;
152
+ this.output = output;
153
+ this.mutateArgs = mutateArgs;
154
+ this.input = input;
155
+ this.globalMaxLines = globalMaxLines;
156
+ this.resolverRegistry = resolverRegistry;
157
+ if (!noTty) {
158
+ this.rl = readline_1.default.createInterface({
159
+ input,
160
+ output
161
+ });
162
+ this.keypress = new keypress_1.TerminalKeypress(noTty, input);
163
+ }
164
+ else {
165
+ this.rl = null;
166
+ this.keypress = null;
167
+ }
168
+ }
169
+ clearScreen() {
170
+ // same as console.clear()
171
+ this.output.write('\x1Bc'); // This is the escape sequence to clear the terminal screen.
172
+ }
173
+ write(message) {
174
+ this.output.write(message);
175
+ }
176
+ log(message) {
177
+ this.output.write(message + '\n');
178
+ }
179
+ getInput(input) {
180
+ return `${(0, yanse_1.white)('>')} ${input}`;
181
+ }
182
+ getPrompt(question, ctx, input) {
183
+ const promptMessage = generatePromptMessage(question, ctx);
184
+ return promptMessage + this.getInput(input);
185
+ }
186
+ displayPrompt(question, ctx, input) {
187
+ const prompt = this.getPrompt(question, ctx, input);
188
+ this.log(prompt);
189
+ }
190
+ generateManPage(opts) {
191
+ let manPage = `${(0, yanse_1.white)('NAME')}\n\t${(0, yanse_1.white)(opts.commandName)} ${opts.description ?? ''}\n\n`;
192
+ // Constructing the SYNOPSIS section with required and optional arguments
193
+ let requiredArgs = '';
194
+ let optionalArgs = '';
195
+ opts.questions.forEach(question => {
196
+ if (question.required) {
197
+ requiredArgs += ` ${(0, yanse_1.white)('--' + question.name)} <${(0, yanse_1.gray)(question.name)}>`;
198
+ }
199
+ else {
200
+ optionalArgs += ` [${(0, yanse_1.white)('--' + question.name)}${question.default ? `=${(0, yanse_1.gray)(String(question.default))}` : ''}]`;
201
+ }
202
+ });
203
+ manPage += `${(0, yanse_1.white)('SYNOPSIS')}\n\t${(0, yanse_1.white)(opts.commandName)}${(0, yanse_1.gray)(requiredArgs)}${(0, yanse_1.gray)(optionalArgs)}\n\n`;
204
+ manPage += `${(0, yanse_1.white)('DESCRIPTION')}\n\tUse this command to interact with the application. It supports the following options:\n\n`;
205
+ opts.questions.forEach(question => {
206
+ manPage += `${(0, yanse_1.white)(question.name.toUpperCase())}\n`;
207
+ manPage += `\t${(0, yanse_1.white)('Type:')} ${(0, yanse_1.gray)(question.type)}\n`;
208
+ if (question.alias) {
209
+ const aliases = Array.isArray(question.alias) ? question.alias : [question.alias];
210
+ const aliasStr = aliases.map(a => a.length === 1 ? `-${a}` : `--${a}`).join(', ');
211
+ manPage += `\t${(0, yanse_1.white)('Alias:')} ${(0, yanse_1.gray)(aliasStr)}\n`;
212
+ }
213
+ if (question.message) {
214
+ manPage += `\t${(0, yanse_1.white)('Summary:')} ${(0, yanse_1.gray)(question.message)}\n`;
215
+ }
216
+ if (question.description) {
217
+ manPage += `\t${(0, yanse_1.white)('Description:')} ${(0, yanse_1.gray)(question.description)}\n`;
218
+ }
219
+ if ('options' in question) {
220
+ const optionsList = Array.isArray(question.options)
221
+ ? question.options.map(opt => typeof opt === 'string' ? (0, yanse_1.gray)(opt) : `${(0, yanse_1.gray)(opt.name)} (${(0, yanse_1.gray)(opt.value)})`).join(', ')
222
+ : '';
223
+ manPage += `\t${(0, yanse_1.white)('Options:')} ${(0, yanse_1.gray)(optionsList)}\n`;
224
+ }
225
+ if (question.default !== undefined) {
226
+ manPage += `\t${(0, yanse_1.white)('Default:')} ${(0, yanse_1.gray)(JSON.stringify(question.default))}\n`;
227
+ }
228
+ if (question.required) {
229
+ manPage += `\t${(0, yanse_1.white)('Required:')} ${(0, yanse_1.gray)('Yes')}\n`;
230
+ }
231
+ else {
232
+ manPage += `\t${(0, yanse_1.white)('Required:')} ${(0, yanse_1.gray)('No')}\n`;
233
+ }
234
+ manPage += '\n';
235
+ });
236
+ manPage += `${(0, yanse_1.white)('EXAMPLES')}\n\tExample usage of \`${(0, yanse_1.white)(opts.commandName)}\`.\n\t$ ${(0, yanse_1.white)(opts.commandName)}${(0, yanse_1.gray)(requiredArgs)}${(0, yanse_1.gray)(optionalArgs)}\n\n`;
237
+ manPage += opts.author ? `${(0, yanse_1.white)('AUTHOR')}\n\t${(0, yanse_1.white)(opts.author)}\n` : '';
238
+ return manPage;
239
+ }
240
+ isValidatableAnswer(answer) {
241
+ return answer !== undefined;
242
+ }
243
+ validateAnswer(question, answer, obj, ctx) {
244
+ const validation = this.validateAnswerPattern(question, answer);
245
+ if (!validation.success) {
246
+ return ctx.process(validation);
247
+ }
248
+ if (question.validate) {
249
+ const customValidation = question.validate(answer, obj);
250
+ return ctx.process(customValidation);
251
+ }
252
+ return ctx.process({
253
+ success: true
254
+ });
255
+ }
256
+ isValid(question, obj, ctx) {
257
+ if (this.isValidatableAnswer(obj[question.name])) {
258
+ obj[question.name] = this.sanitizeAnswer(question, obj[question.name], obj);
259
+ const validationResult = this.validateAnswer(question, obj[question.name], obj, ctx);
260
+ if (!validationResult.success) {
261
+ return false;
262
+ }
263
+ }
264
+ if (question.required && this.isEmptyAnswer(obj[question.name])) {
265
+ ctx.tryAgain({ type: 'required' });
266
+ return false;
267
+ }
268
+ return true;
269
+ }
270
+ validateAnswerPattern(question, answer) {
271
+ if (question.pattern && typeof answer === 'string') {
272
+ const regex = new RegExp(question.pattern);
273
+ const success = regex.test(answer);
274
+ if (success) {
275
+ return {
276
+ success
277
+ };
278
+ }
279
+ else {
280
+ return {
281
+ type: 'pattern',
282
+ success: false,
283
+ reason: question.pattern
284
+ };
285
+ }
286
+ }
287
+ return {
288
+ success: true
289
+ };
290
+ }
291
+ isEmptyAnswer(answer) {
292
+ switch (true) {
293
+ case answer === undefined:
294
+ case answer === null:
295
+ case answer === '':
296
+ case Array.isArray(answer) && answer.length === 0:
297
+ return true;
298
+ }
299
+ return false;
300
+ }
301
+ sanitizeAnswer(question, answer, obj) {
302
+ if (question.sanitize) {
303
+ return question.sanitize(answer, obj);
304
+ }
305
+ return answer;
306
+ }
307
+ exit() {
308
+ this.clearScreen();
309
+ this.close();
310
+ }
311
+ async prompt(argv, questions, options) {
312
+ // use local mutateArgs if defined, otherwise global mutateArgs
313
+ const shouldMutate = options?.mutateArgs !== undefined ? options.mutateArgs : this.mutateArgs;
314
+ // Create a working copy of argv - deep clone the _ array to avoid shared reference
315
+ let obj = shouldMutate ? argv : { ...argv };
316
+ const argvAny = argv;
317
+ if (!shouldMutate && Array.isArray(argvAny._)) {
318
+ obj._ = [...argvAny._];
319
+ }
320
+ // Expand aliases before any other processing
321
+ // This allows users to use short flags like -w instead of --workspace
322
+ this.expandAliases(questions, obj);
323
+ // Resolve dynamic defaults before processing questions
324
+ await this.resolveDynamicDefaults(questions);
325
+ // Resolve dynamic options before processing questions
326
+ await this.resolveOptionsFrom(questions);
327
+ // Resolve setFrom values - these bypass prompting entirely
328
+ await this.resolveSetValues(questions, obj);
329
+ // Extract positional arguments from argv._ and assign to questions with _: true
330
+ // This must happen before applyOverrides so positional values flow through override pipeline
331
+ // Returns the number of positional arguments consumed for stripping
332
+ const consumedCount = this.extractPositionalArgs(obj, questions);
333
+ // Strip consumed positionals from obj._ (the working copy)
334
+ if (consumedCount > 0 && Array.isArray(obj._)) {
335
+ obj._ = obj._.slice(consumedCount);
336
+ // If mutating, also update the original argv._
337
+ if (shouldMutate) {
338
+ argvAny._ = obj._;
339
+ }
340
+ }
341
+ // first loop through the question, and set any overrides in case other questions use objs for validation
342
+ this.applyOverrides(obj, obj, questions);
343
+ // Check for required arguments when no terminal is available (non-interactive mode)
344
+ if (this.noTty && this.hasMissingRequiredArgs(questions, argv)) {
345
+ // Apply default values for all questions
346
+ this.applyDefaultValues(questions, obj);
347
+ // Recheck for missing required arguments after applying defaults
348
+ // NOT so sure this would ever happen, but possible if developer did something wrong
349
+ if (!this.hasMissingRequiredArgs(questions, argv)) {
350
+ return obj; // Return the updated object if no required arguments are missing
351
+ }
352
+ // Handle error for missing required arguments
353
+ this.handleMissingArgsError(options);
354
+ throw new Error('Missing required arguments. Please provide all required parameters.');
355
+ }
356
+ const ordered = reorderQuestionsByDeps(questions);
357
+ for (let index = 0; index < ordered.length; index++) {
358
+ const question = ordered[index];
359
+ const ctx = new PromptContext();
360
+ // obj is already either argv itself, or a clone, but let's check if it has the property
361
+ if (question.name in obj) {
362
+ this.handleOverrides(argv, obj, question);
363
+ ctx.nextQuestion();
364
+ continue;
365
+ }
366
+ if (question.when && !question.when(obj)) {
367
+ ctx.nextQuestion();
368
+ continue;
369
+ }
370
+ // Apply default value if applicable
371
+ // this is if useDefault is set, rare! not typical defaults which happen AFTER
372
+ // this is mostly to avoid a prompt for "hidden" options
373
+ if ('default' in question && (this.useDefaults || question.useDefault)) {
374
+ obj[question.name] = question.default;
375
+ continue; // Skip to the next question since the default is applied
376
+ }
377
+ while (ctx.needsInput) {
378
+ obj[question.name] = await this.handleQuestionType(question, ctx);
379
+ if (!this.isValid(question, obj, ctx)) {
380
+ if (this.noTty) {
381
+ // If you're not valid and here with noTty, you're out!
382
+ this.clearScreen(); // clear before leaving, not calling exit() since it may be a bad pattern to continue, devs should try/catch
383
+ throw new Error('Missing required arguments. Please provide all required parameters.');
384
+ }
385
+ continue;
386
+ }
387
+ // If input passes validation and is not empty, or not required, move to the next question
388
+ ctx.nextQuestion();
389
+ }
390
+ }
391
+ return obj;
392
+ }
393
+ handleMissingArgsError(options) {
394
+ this.clearScreen();
395
+ if (options?.usageText) {
396
+ this.log(options.usageText);
397
+ }
398
+ else if (options?.manPageInfo) {
399
+ this.log(this.generateManPage(options.manPageInfo));
400
+ }
401
+ else {
402
+ this.log('Missing required arguments. Please provide all required parameters.');
403
+ }
404
+ }
405
+ hasMissingRequiredArgs(questions, argv) {
406
+ return questions.some(question => question.required && this.isEmptyAnswer(argv[question.name]));
407
+ }
408
+ /**
409
+ * Resolves the default value for a question using the resolver system.
410
+ * Priority: defaultFrom > default > undefined
411
+ */
412
+ async resolveQuestionDefault(question) {
413
+ // Try to resolve from defaultFrom first
414
+ if ('defaultFrom' in question && question.defaultFrom) {
415
+ const resolved = await this.resolverRegistry.resolve(question.defaultFrom);
416
+ if (resolved !== undefined) {
417
+ return resolved;
418
+ }
419
+ }
420
+ // Fallback to static default
421
+ if ('default' in question) {
422
+ return question.default;
423
+ }
424
+ return undefined;
425
+ }
426
+ /**
427
+ * Resolves dynamic defaults for all questions that have defaultFrom specified.
428
+ * Updates the question.default property with the resolved value.
429
+ */
430
+ async resolveDynamicDefaults(questions) {
431
+ for (const question of questions) {
432
+ if ('defaultFrom' in question && question.defaultFrom) {
433
+ const resolved = await this.resolveQuestionDefault(question);
434
+ if (resolved !== undefined) {
435
+ // Update question.default with resolved value
436
+ question.default = resolved;
437
+ }
438
+ }
439
+ }
440
+ }
441
+ /**
442
+ * Resolves setFrom values for all questions that have setFrom specified.
443
+ * Sets the value directly in obj, bypassing the prompt entirely.
444
+ */
445
+ async resolveSetValues(questions, obj) {
446
+ for (const question of questions) {
447
+ if ('setFrom' in question && question.setFrom) {
448
+ // Only set if not already provided in args
449
+ if (!(question.name in obj)) {
450
+ const resolved = await this.resolverRegistry.resolve(question.setFrom);
451
+ if (resolved !== undefined) {
452
+ obj[question.name] = resolved;
453
+ }
454
+ }
455
+ }
456
+ }
457
+ }
458
+ /**
459
+ * Expands aliases for all questions that have alias specified.
460
+ * If an alias key exists in obj but the main name doesn't, copies the value to the main name.
461
+ * This allows users to use short flags like -w instead of --workspace.
462
+ */
463
+ expandAliases(questions, obj) {
464
+ for (const question of questions) {
465
+ if ('alias' in question && question.alias) {
466
+ // Skip if the main name already has a value
467
+ if (question.name in obj) {
468
+ continue;
469
+ }
470
+ // Normalize alias to array
471
+ const aliases = Array.isArray(question.alias) ? question.alias : [question.alias];
472
+ // Check each alias and use the first one found
473
+ for (const alias of aliases) {
474
+ if (alias in obj) {
475
+ obj[question.name] = obj[alias];
476
+ // Optionally clean up the alias key to avoid confusion
477
+ delete obj[alias];
478
+ break;
479
+ }
480
+ }
481
+ }
482
+ }
483
+ }
484
+ /**
485
+ * Resolves optionsFrom values for all questions that have optionsFrom specified.
486
+ * Updates the question.options property with the resolved array.
487
+ */
488
+ async resolveOptionsFrom(questions) {
489
+ for (const question of questions) {
490
+ if ('optionsFrom' in question && question.optionsFrom) {
491
+ const resolved = await this.resolverRegistry.resolve(question.optionsFrom);
492
+ if (resolved !== undefined && Array.isArray(resolved)) {
493
+ // Update question.options with resolved array
494
+ question.options = resolved;
495
+ }
496
+ }
497
+ }
498
+ }
499
+ /**
500
+ * Extracts positional arguments from obj._ and assigns them to questions marked with _: true.
501
+ *
502
+ * Rules:
503
+ * 1. Named arguments take precedence - if a question already has a value in obj, skip it
504
+ * 2. Positional questions consume from obj._ left-to-right in declaration order
505
+ * 3. Returns the count of consumed positionals so caller can strip them from obj._
506
+ * 4. Missing positional values leave questions unset (for prompting/validation)
507
+ *
508
+ * This effectively allows "naming positional parameters" - users can pass values
509
+ * without flags and they'll be assigned to the appropriate question names.
510
+ *
511
+ * @returns The number of positional arguments consumed
512
+ */
513
+ extractPositionalArgs(obj, questions) {
514
+ // Get positional arguments array from obj (minimist convention)
515
+ const positionals = Array.isArray(obj._) ? obj._ : [];
516
+ if (positionals.length === 0) {
517
+ return 0;
518
+ }
519
+ // Track which positional index we're consuming from
520
+ let positionalIndex = 0;
521
+ // Process questions in declaration order to maintain predictable assignment
522
+ for (const question of questions) {
523
+ // Only process questions marked as positional
524
+ if (!question._) {
525
+ continue;
526
+ }
527
+ // Skip if this question already has a named argument value
528
+ // Named arguments always take precedence over positional
529
+ if (question.name in obj && question.name !== '_') {
530
+ continue;
531
+ }
532
+ // Skip if we've exhausted all positional arguments
533
+ if (positionalIndex >= positionals.length) {
534
+ break;
535
+ }
536
+ // Assign the next positional value to this question
537
+ const value = positionals[positionalIndex];
538
+ obj[question.name] = value;
539
+ positionalIndex++;
540
+ }
541
+ return positionalIndex;
542
+ }
543
+ applyDefaultValues(questions, obj) {
544
+ questions.forEach(question => {
545
+ if ('default' in question) {
546
+ obj[question.name] = question.default; // Set default value if specified
547
+ }
548
+ });
549
+ }
550
+ applyOverrides(argv, obj, questions) {
551
+ questions.forEach(question => {
552
+ if (question.name in argv) {
553
+ this.handleOverrides(argv, obj, question);
554
+ }
555
+ });
556
+ }
557
+ handleOverrides(argv, obj, question) {
558
+ if (!Object.prototype.hasOwnProperty.call(argv, question.name)) {
559
+ return;
560
+ }
561
+ if (this.handledKeys.has(question.name)) {
562
+ return; // Already handled, skip further processing
563
+ }
564
+ this.handledKeys.add(question.name);
565
+ switch (question.type) {
566
+ case 'text':
567
+ case 'number':
568
+ case 'confirm':
569
+ // do nothing, already set!
570
+ break;
571
+ case 'checkbox':
572
+ this.handleOverridesForCheckboxOptions(argv, obj, question);
573
+ break;
574
+ case 'autocomplete':
575
+ case 'list':
576
+ // get the value from options :)
577
+ this.handleOverridesWithOptions(argv, obj, question);
578
+ break;
579
+ default:
580
+ return;
581
+ }
582
+ }
583
+ handleOverridesForCheckboxOptions(argv, obj, question) {
584
+ const options = this.sanitizeOptions(question);
585
+ const input = argv[question.name];
586
+ // Normalize to array
587
+ const inputs = Array.isArray(input) ? input.map(String) : [String(input)];
588
+ // Set of matched values
589
+ const inputSet = new Set(inputs);
590
+ // Base list of processed options
591
+ const result = options.map(opt => ({
592
+ ...opt,
593
+ selected: inputSet.has(opt.name) || inputSet.has(String(opt.value))
594
+ }));
595
+ // Add extras if allowed
596
+ if (question.allowCustomOptions) {
597
+ const knownValues = new Set(options.map(opt => String(opt.value)));
598
+ const unknowns = inputs.filter(val => !knownValues.has(val));
599
+ for (const val of unknowns) {
600
+ result.push({
601
+ name: val,
602
+ value: val,
603
+ selected: true
604
+ });
605
+ }
606
+ }
607
+ // Assign final result
608
+ obj[question.name] = question.returnFullResults
609
+ ? result
610
+ : result.filter(opt => opt.selected);
611
+ }
612
+ handleOverridesWithOptions(argv, obj, question) {
613
+ const input = argv[question.name];
614
+ if (typeof input !== 'string')
615
+ return;
616
+ const options = this.sanitizeOptions(question);
617
+ const found = options.find(opt => opt.name === input || String(opt.value) === input);
618
+ if (found) {
619
+ obj[question.name] = found.value;
620
+ }
621
+ else if (question.allowCustomOptions) {
622
+ obj[question.name] = input; // Store as-is
623
+ }
624
+ }
625
+ async handleQuestionType(question, ctx) {
626
+ this.keypress?.clearHandlers();
627
+ switch (question.type) {
628
+ case 'confirm':
629
+ return this.confirm(question, ctx);
630
+ case 'checkbox':
631
+ return this.checkbox(question, ctx);
632
+ case 'list':
633
+ return this.list(question, ctx);
634
+ case 'autocomplete':
635
+ return this.autocomplete(question, ctx);
636
+ case 'number':
637
+ return this.number(question, ctx);
638
+ case 'text':
639
+ return this.text(question, ctx);
640
+ default:
641
+ return this.text(question, ctx);
642
+ }
643
+ }
644
+ async confirm(question, ctx) {
645
+ if (this.noTty || !this.rl)
646
+ return question.default ?? false; // Return default if non-interactive
647
+ return new Promise((resolve) => {
648
+ this.clearScreen();
649
+ this.rl.question(this.getPrompt(question, ctx, ''), (answer) => {
650
+ const userInput = answer.trim().toLowerCase();
651
+ if (userInput === '') {
652
+ resolve(question.default ?? false); // Use default value if input is empty
653
+ }
654
+ else if (['yes', 'y'].includes(userInput)) {
655
+ resolve(true);
656
+ }
657
+ else {
658
+ resolve(false);
659
+ }
660
+ });
661
+ });
662
+ }
663
+ async text(question, ctx) {
664
+ if (this.noTty || !this.rl) {
665
+ if ('default' in question) {
666
+ return question.default;
667
+ }
668
+ return;
669
+ }
670
+ let input = '';
671
+ return new Promise((resolve) => {
672
+ this.clearScreen();
673
+ this.rl.question(this.getPrompt(question, ctx, input), (answer) => {
674
+ input = answer;
675
+ if (input.trim() !== '') {
676
+ resolve(input); // Return input if not empty
677
+ }
678
+ else if ('default' in question) {
679
+ resolve(question.default); // Use default if input is empty
680
+ }
681
+ else {
682
+ resolve(null); // Return null if empty and not required
683
+ }
684
+ });
685
+ });
686
+ }
687
+ async number(question, ctx) {
688
+ if (this.noTty || !this.rl) {
689
+ if ('default' in question) {
690
+ return question.default;
691
+ }
692
+ return;
693
+ }
694
+ let input = '';
695
+ return new Promise((resolve) => {
696
+ this.clearScreen();
697
+ this.rl.question(this.getPrompt(question, ctx, input), (answer) => {
698
+ input = answer.trim();
699
+ if (input !== '') {
700
+ const num = Number(input);
701
+ if (!isNaN(num)) {
702
+ resolve(num);
703
+ }
704
+ else {
705
+ resolve(null); // Let validation handle bad input
706
+ }
707
+ }
708
+ else if ('default' in question) {
709
+ resolve(question.default); // Use default if input is empty
710
+ }
711
+ else {
712
+ resolve(null); // Empty and no default
713
+ }
714
+ });
715
+ });
716
+ }
717
+ async checkbox(question, ctx) {
718
+ if (this.noTty || !this.rl) {
719
+ const options = this.sanitizeOptions(question);
720
+ const defaults = Array.isArray(question.default)
721
+ ? question.default
722
+ : [question.default];
723
+ // If returnFullResults is true, return all options with boolean selection
724
+ if (question.returnFullResults) {
725
+ return options.map(opt => ({
726
+ name: opt.name,
727
+ value: opt.value,
728
+ selected: defaults.includes(opt.name)
729
+ }));
730
+ }
731
+ // Otherwise, return only selected options
732
+ return options
733
+ .filter(opt => defaults.includes(opt.name) || defaults.includes(opt.value))
734
+ .map(opt => ({
735
+ name: opt.name,
736
+ value: opt.value,
737
+ selected: true
738
+ }));
739
+ }
740
+ if (!question.options.length) {
741
+ // no arguments don't make sense
742
+ throw new Error('checkbox requires options');
743
+ }
744
+ this.keypress.resume();
745
+ const options = this.sanitizeOptions(question);
746
+ let input = ''; // Search input
747
+ let filteredOptions = options;
748
+ let selectedIndex = 0;
749
+ let startIndex = 0; // Start index for visible options
750
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
751
+ // const selections: boolean[] = new Array(options.length).fill(false);
752
+ const selections = options.map(opt => {
753
+ if (!question.default)
754
+ return false;
755
+ const defaults = Array.isArray(question.default)
756
+ ? question.default
757
+ : [question.default];
758
+ return defaults.includes(opt.name);
759
+ });
760
+ const updateFilteredOptions = () => {
761
+ filteredOptions = this.filterOptions(options, input);
762
+ };
763
+ const display = () => {
764
+ this.clearScreen();
765
+ this.displayPrompt(question, ctx, input);
766
+ const endIndex = Math.min(startIndex + maxLines, filteredOptions.length);
767
+ for (let i = startIndex; i < endIndex; i++) {
768
+ const option = filteredOptions[i];
769
+ const isSelected = selectedIndex === i;
770
+ const marker = isSelected ? '>' : ' ';
771
+ const index = options.map(o => o.name).indexOf(option.name);
772
+ if (index >= 0) {
773
+ const isChecked = selections[index] ? '◉' : '○'; // Use the original index in options
774
+ const line = `${marker} ${isChecked} ${option.name}`;
775
+ this.log(isSelected ? (0, yanse_1.blue)(line) : line);
776
+ }
777
+ else {
778
+ this.log('No options'); // sometimes user searches and there are no options...
779
+ }
780
+ }
781
+ };
782
+ display();
783
+ // Handling BACKSPACE key
784
+ this.keypress.on(keypress_1.KEY_CODES.BACKSPACE, () => {
785
+ input = input.slice(0, -1);
786
+ updateFilteredOptions();
787
+ display();
788
+ });
789
+ // Register alphanumeric keypresses to accumulate input, excluding space
790
+ 'abcdefghijklmnopqrstuvwxyz0123456789'.split('').forEach(char => {
791
+ this.keypress.on(char, () => {
792
+ input += char;
793
+ updateFilteredOptions();
794
+ display();
795
+ });
796
+ });
797
+ this.keypress.on(keypress_1.KEY_CODES.UP_ARROW, () => {
798
+ selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : filteredOptions.length - 1;
799
+ if (selectedIndex < startIndex) {
800
+ startIndex = selectedIndex; // Scroll up
801
+ }
802
+ else if (selectedIndex === filteredOptions.length - 1) {
803
+ startIndex = Math.max(0, filteredOptions.length - maxLines); // Jump to the bottom of the list
804
+ }
805
+ display();
806
+ });
807
+ this.keypress.on(keypress_1.KEY_CODES.DOWN_ARROW, () => {
808
+ selectedIndex = (selectedIndex + 1) % filteredOptions.length;
809
+ if (selectedIndex >= startIndex + maxLines) {
810
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
811
+ }
812
+ else if (selectedIndex === 0) {
813
+ startIndex = 0; // Jump to the top of the list
814
+ }
815
+ display();
816
+ });
817
+ this.keypress.on(keypress_1.KEY_CODES.SPACE, () => {
818
+ // Map filtered index back to the original index in options
819
+ selections[options.indexOf(filteredOptions[selectedIndex])] = !selections[options.indexOf(filteredOptions[selectedIndex])];
820
+ display();
821
+ });
822
+ return new Promise(resolve => {
823
+ this.keypress.on(keypress_1.KEY_CODES.ENTER, () => {
824
+ this.keypress.pause();
825
+ const result = [];
826
+ if (question.returnFullResults) {
827
+ // Return all options with their selected status
828
+ options.forEach((option, index) => {
829
+ result.push({
830
+ name: option.name,
831
+ value: option.value,
832
+ selected: selections[index]
833
+ });
834
+ });
835
+ }
836
+ else {
837
+ // Return only options that are selected
838
+ options.forEach((option, index) => {
839
+ if (selections[index]) {
840
+ result.push({
841
+ name: option.name,
842
+ value: option.value,
843
+ selected: selections[index]
844
+ });
845
+ }
846
+ });
847
+ }
848
+ resolve(result);
849
+ });
850
+ });
851
+ }
852
+ async autocomplete(question, ctx) {
853
+ if (this.noTty || !this.rl) {
854
+ if ('default' in question) {
855
+ return question.default;
856
+ }
857
+ return;
858
+ }
859
+ if (!question.options.length) {
860
+ throw new Error('autocomplete requires options');
861
+ }
862
+ this.keypress.resume();
863
+ const options = this.sanitizeOptions(question);
864
+ let input = '';
865
+ let filteredOptions = options;
866
+ let selectedIndex = 0;
867
+ let startIndex = 0; // Start index for visible options
868
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
869
+ const display = () => {
870
+ this.clearScreen();
871
+ this.displayPrompt(question, ctx, input);
872
+ // Determine the range of options to display
873
+ const endIndex = Math.min(startIndex + maxLines, filteredOptions.length);
874
+ for (let i = startIndex; i < endIndex; i++) {
875
+ const option = filteredOptions[i];
876
+ if (!option) {
877
+ this.log('No options'); // sometimes user searches and there are no options...
878
+ }
879
+ else if (i === selectedIndex) {
880
+ this.log((0, yanse_1.blue)('> ' + option.name)); // Highlight the selected option with yanse
881
+ }
882
+ else {
883
+ this.log(' ' + option.name);
884
+ }
885
+ }
886
+ };
887
+ const updateFilteredOptions = () => {
888
+ filteredOptions = this.filterOptions(options, input);
889
+ // Adjust startIndex to keep the selectedIndex in the visible range
890
+ if (selectedIndex < startIndex) {
891
+ startIndex = selectedIndex;
892
+ }
893
+ else if (selectedIndex >= startIndex + maxLines) {
894
+ startIndex = selectedIndex - maxLines + 1;
895
+ }
896
+ if (selectedIndex >= filteredOptions.length) {
897
+ selectedIndex = Math.max(filteredOptions.length - 1, 0);
898
+ }
899
+ };
900
+ display();
901
+ // Handling BACKSPACE key
902
+ this.keypress.on(keypress_1.KEY_CODES.BACKSPACE, () => {
903
+ input = input.slice(0, -1);
904
+ updateFilteredOptions();
905
+ display();
906
+ });
907
+ // Register alphanumeric and space keypresses to accumulate input
908
+ 'abcdefghijklmnopqrstuvwxyz0123456789 '.split('').forEach(char => {
909
+ this.keypress.on(char, () => {
910
+ input += char;
911
+ updateFilteredOptions();
912
+ display();
913
+ });
914
+ });
915
+ // Navigation
916
+ this.keypress.on(keypress_1.KEY_CODES.UP_ARROW, () => {
917
+ selectedIndex = selectedIndex - 1 >= 0 ? selectedIndex - 1 : filteredOptions.length - 1;
918
+ if (selectedIndex < startIndex) {
919
+ startIndex = selectedIndex; // Scroll up
920
+ }
921
+ else if (selectedIndex === filteredOptions.length - 1) {
922
+ startIndex = Math.max(0, filteredOptions.length - maxLines); // Jump to the bottom of the list
923
+ }
924
+ display();
925
+ });
926
+ this.keypress.on(keypress_1.KEY_CODES.DOWN_ARROW, () => {
927
+ selectedIndex = (selectedIndex + 1) % filteredOptions.length;
928
+ if (selectedIndex >= startIndex + maxLines) {
929
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
930
+ }
931
+ else if (selectedIndex === 0) {
932
+ startIndex = 0; // Jump to the top of the list
933
+ }
934
+ display();
935
+ });
936
+ return new Promise(resolve => {
937
+ this.keypress.on(keypress_1.KEY_CODES.ENTER, () => {
938
+ this.keypress.pause();
939
+ resolve(filteredOptions[selectedIndex]?.value || input);
940
+ });
941
+ });
942
+ }
943
+ async list(question, ctx) {
944
+ if (this.noTty || !this.rl) {
945
+ if ('default' in question) {
946
+ return question.default;
947
+ }
948
+ return;
949
+ }
950
+ if (!question.options.length) {
951
+ throw new Error('list requires options');
952
+ }
953
+ this.keypress.resume();
954
+ const options = this.sanitizeOptions(question);
955
+ let input = '';
956
+ let selectedIndex = 0;
957
+ let startIndex = 0; // Start index for visible options
958
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
959
+ const display = () => {
960
+ this.clearScreen();
961
+ this.displayPrompt(question, ctx, input);
962
+ // Determine the range of options to display
963
+ const endIndex = Math.min(startIndex + maxLines, options.length);
964
+ for (let i = startIndex; i < endIndex; i++) {
965
+ const option = options[i];
966
+ if (!option) {
967
+ this.log('No options'); // sometimes user searches and there are no options...
968
+ }
969
+ else if (i === selectedIndex) {
970
+ this.log((0, yanse_1.blue)('> ' + option.name)); // Highlight the selected option with yanse
971
+ }
972
+ else {
973
+ this.log(' ' + option.name);
974
+ }
975
+ }
976
+ };
977
+ display();
978
+ // Navigation
979
+ this.keypress.on(keypress_1.KEY_CODES.UP_ARROW, () => {
980
+ selectedIndex = selectedIndex - 1 >= 0 ? selectedIndex - 1 : options.length - 1;
981
+ if (selectedIndex < startIndex) {
982
+ startIndex = selectedIndex; // Scroll up
983
+ }
984
+ else if (selectedIndex === options.length - 1) {
985
+ startIndex = Math.max(0, options.length - maxLines); // Jump to the bottom of the list
986
+ }
987
+ display();
988
+ });
989
+ this.keypress.on(keypress_1.KEY_CODES.DOWN_ARROW, () => {
990
+ selectedIndex = (selectedIndex + 1) % options.length;
991
+ if (selectedIndex >= startIndex + maxLines) {
992
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
993
+ }
994
+ else if (selectedIndex === 0) {
995
+ startIndex = 0; // Jump to the top of the list
996
+ }
997
+ display();
998
+ });
999
+ return new Promise(resolve => {
1000
+ this.keypress.on(keypress_1.KEY_CODES.ENTER, () => {
1001
+ this.keypress.pause();
1002
+ resolve(options[selectedIndex]?.value || input);
1003
+ });
1004
+ });
1005
+ }
1006
+ getOptionValue(option) {
1007
+ if (typeof option === 'string') {
1008
+ return { name: option, value: option };
1009
+ }
1010
+ else if (typeof option === 'object' && option && 'name' in option) {
1011
+ return { name: option.name, value: option.value };
1012
+ }
1013
+ else {
1014
+ return undefined;
1015
+ }
1016
+ }
1017
+ sanitizeOptions(question) {
1018
+ const options = (question.options ?? []).map(option => this.getOptionValue(option));
1019
+ return options.filter(Boolean);
1020
+ }
1021
+ filterOptions(options, input) {
1022
+ input = input.toLowerCase(); // Normalize input for case-insensitive comparison
1023
+ // Fuzzy matching: Check if all characters of the input can be found in the option name in order
1024
+ const fuzzyMatch = (option, input) => {
1025
+ if (!input || !input.trim().length)
1026
+ return true;
1027
+ const length = input.length;
1028
+ let position = 0; // Position in the input string
1029
+ // Iterate over each character in the option name
1030
+ for (let i = 0; i < option.length; i++) {
1031
+ if (option[i] === input[position]) {
1032
+ position++; // Move to the next character in the input
1033
+ if (position === length) { // Check if we've matched all characters
1034
+ return true;
1035
+ }
1036
+ }
1037
+ }
1038
+ return false;
1039
+ };
1040
+ return options
1041
+ .filter(option => fuzzyMatch(option.name.toLowerCase(), input))
1042
+ .sort((a, b) => {
1043
+ if (a.name < b.name) {
1044
+ return -1;
1045
+ }
1046
+ if (a.name > b.name) {
1047
+ return 1;
1048
+ }
1049
+ return 0;
1050
+ });
1051
+ }
1052
+ getMaxLines(question, defaultLength) {
1053
+ if (question.maxDisplayLines) {
1054
+ return question.maxDisplayLines;
1055
+ }
1056
+ // if (!this.noTty && (this.output as any).isTTY) {
1057
+ // const rows = Math.round(((this.output as any).rows ?? 0) / 7);
1058
+ // return Math.max(rows, defaultLength);
1059
+ // }
1060
+ return Math.min(this.globalMaxLines, defaultLength);
1061
+ }
1062
+ // Method to cleanly close the readline interface
1063
+ // NOTE: use exit() to close!
1064
+ close() {
1065
+ if (this.rl) {
1066
+ this.rl.close();
1067
+ this.keypress.destroy();
1068
+ }
1069
+ }
1070
+ }
1071
+ exports.Inquirerer = Inquirerer;