inquirerer 2.4.0 → 3.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # inquirerer
2
2
 
3
3
  <p align="center" width="100%">
4
- <img height="90" src="https://raw.githubusercontent.com/hyperweb-io/dev-utils/refs/heads/main/docs/img/inquirerer.svg" />
4
+ <img height="90" src="https://raw.githubusercontent.com/constructive-io/dev-utils/refs/heads/main/docs/img/genomic.svg" />
5
5
  </p>
6
6
 
7
7
  <p align="center" width="100%">
@@ -12,11 +12,36 @@
12
12
  <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
13
  </a>
14
14
  <a href="https://www.npmjs.com/package/inquirerer"><img height="20" src="https://img.shields.io/npm/dt/inquirerer"></a>
15
- <a href="https://www.npmjs.com/package/inquirerer"><img height="20" src="https://img.shields.io/github/package-json/v/hyperweb-io/dev-utils?filename=packages%2Finquirerer%2Fpackage.json"></a>
15
+ <a href="https://www.npmjs.com/package/inquirerer"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/dev-utils?filename=packages%2Finquirerer%2Fpackage.json"></a>
16
16
  </p>
17
17
 
18
+ > **Note:** This package has been renamed to [`genomic`](https://www.npmjs.com/package/genomic). Please migrate to `genomic` for the latest features and updates.
19
+
18
20
  A powerful, TypeScript-first library for building beautiful command-line interfaces. Create interactive CLI tools with ease using intuitive prompts, validation, and rich user experiences.
19
21
 
22
+ ## Migration to genomic
23
+
24
+ This package is now maintained as `genomic`. To migrate:
25
+
26
+ ```bash
27
+ npm uninstall inquirerer
28
+ npm install genomic
29
+ ```
30
+
31
+ Then update your imports:
32
+
33
+ ```typescript
34
+ // Before
35
+ import { Inquirerer, InquirererOptions } from 'inquirerer';
36
+
37
+ // After
38
+ import { Prompter, PrompterOptions } from 'genomic';
39
+ ```
40
+
41
+ The API is the same, only the class names have changed:
42
+ - `Inquirerer` -> `Prompter`
43
+ - `InquirererOptions` -> `PrompterOptions`
44
+
20
45
  ## Installation
21
46
 
22
47
  ```bash
@@ -25,53 +50,22 @@ npm install inquirerer
25
50
 
26
51
  ## Features
27
52
 
28
- - 🔌 **CLI Builder** - Build command-line utilties fast
29
- - 🖊 **Multiple Question Types** - Support for text, autocomplete, checkbox, and confirm questions
30
- - 🤖 **Non-Interactive Mode** - Fallback to defaults for CI/CD environments, great for testing
31
- - ✅ **Smart Validation** - Built-in pattern matching, custom validators, and sanitizers
32
- - 🔀 **Conditional Logic** - Show/hide questions based on previous answers
33
- - 🎨 **Interactive UX** - Fuzzy search, keyboard navigation, and visual feedback
34
- - 🔄 **Dynamic Defaults** - Auto-populate defaults from git config, date/time, or custom resolvers
35
-
36
- ## Table of Contents
37
-
38
- - [Quick Start](#quick-start)
39
- - [Core Concepts](#core-concepts)
40
- - [TypeScript Support](#typescript-support)
41
- - [Question Types](#question-types)
42
- - [Non-Interactive Mode](#non-interactive-mode)
43
- - [API Reference](#api-reference)
44
- - [Inquirerer Class](#inquirerer-class)
45
- - [Question Types](#question-types-1)
46
- - [Text Question](#text-question)
47
- - [Number Question](#number-question)
48
- - [Confirm Question](#confirm-question)
49
- - [List Question](#list-question)
50
- - [Autocomplete Question](#autocomplete-question)
51
- - [Checkbox Question](#checkbox-question)
52
- - [Advanced Question Options](#advanced-question-options)
53
- - [Positional Arguments](#positional-arguments)
54
- - [Real-World Examples](#real-world-examples)
55
- - [Project Setup Wizard](#project-setup-wizard)
56
- - [Configuration Builder](#configuration-builder)
57
- - [CLI with Commander Integration](#cli-with-commander-integration)
58
- - [Dynamic Dependencies](#dynamic-dependencies)
59
- - [Custom Validation](#custom-validation)
60
- - [Dynamic Defaults with Resolvers](#dynamic-defaults-with-resolvers)
61
- - [Built-in Resolvers](#built-in-resolvers)
62
- - [Custom Resolvers](#custom-resolvers)
63
- - [Resolver Examples](#resolver-examples)
64
- - [CLI Helper](#cli-helper)
65
- - [Developing](#developing)
53
+ - **CLI Builder** - Build command-line utilities fast
54
+ - **Multiple Question Types** - Support for text, autocomplete, checkbox, and confirm questions
55
+ - **Non-Interactive Mode** - Fallback to defaults for CI/CD environments, great for testing
56
+ - **Smart Validation** - Built-in pattern matching, custom validators, and sanitizers
57
+ - **Conditional Logic** - Show/hide questions based on previous answers
58
+ - **Interactive UX** - Fuzzy search, keyboard navigation, and visual feedback
59
+ - **Dynamic Defaults** - Auto-populate defaults from git config, date/time, or custom resolvers
66
60
 
67
61
  ## Quick Start
68
62
 
69
63
  ```typescript
70
64
  import { Inquirerer } from 'inquirerer';
71
65
 
72
- const prompter = new Inquirerer();
66
+ const inquirerer = new Inquirerer();
73
67
 
74
- const answers = await prompter.prompt({}, [
68
+ const answers = await inquirerer.prompt({}, [
75
69
  {
76
70
  type: 'text',
77
71
  name: 'username',
@@ -118,7 +112,7 @@ interface UserConfig {
118
112
  newsletter: boolean;
119
113
  }
120
114
 
121
- const answers = await prompter.prompt<UserConfig>({}, questions);
115
+ const answers = await inquirerer.prompt<UserConfig>({}, questions);
122
116
  // answers is typed as UserConfig
123
117
  ```
124
118
 
@@ -151,7 +145,7 @@ interface BaseQuestion {
151
145
  When running in CI/CD or without a TTY, inquirerer automatically falls back to default values:
152
146
 
153
147
  ```typescript
154
- const prompter = new Inquirerer({
148
+ const inquirerer = new Inquirerer({
155
149
  noTty: true, // Force non-interactive mode
156
150
  useDefaults: true // Use defaults without prompting
157
151
  });
@@ -174,7 +168,7 @@ interface InquirererOptions {
174
168
  resolverRegistry?: DefaultResolverRegistry; // Custom resolver registry
175
169
  }
176
170
 
177
- const prompter = new Inquirerer(options);
171
+ const inquirerer = new Inquirerer(options);
178
172
  ```
179
173
 
180
174
  #### Methods
@@ -191,987 +185,13 @@ close(): void
191
185
  exit(): void
192
186
  ```
193
187
 
194
- #### Managing Multiple Instances
195
-
196
- When working with multiple `Inquirerer` instances that share the same input stream (typically `process.stdin`), only one instance should be actively prompting at a time. Each instance attaches its own keyboard listener, so having multiple active instances will cause duplicate or unexpected keypress behavior.
197
-
198
- **Best practices:**
199
-
200
- 1. **Reuse a single instance** - Create one `Inquirerer` instance and reuse it for all prompts:
201
- ```typescript
202
- const prompter = new Inquirerer();
203
-
204
- // Use the same instance for multiple prompt sessions
205
- const answers1 = await prompter.prompt({}, questions1);
206
- const answers2 = await prompter.prompt({}, questions2);
207
-
208
- prompter.close(); // Clean up when done
209
- ```
210
-
211
- 2. **Close before creating another** - If you need separate instances, close the first before using the second:
212
- ```typescript
213
- const prompter1 = new Inquirerer();
214
- const answers1 = await prompter1.prompt({}, questions1);
215
- prompter1.close(); // Important: close before creating another
216
-
217
- const prompter2 = new Inquirerer();
218
- const answers2 = await prompter2.prompt({}, questions2);
219
- prompter2.close();
220
- ```
221
-
222
- ### Question Types
223
-
224
- #### Text Question
225
-
226
- Collect string input from users.
227
-
228
- ```typescript
229
- {
230
- type: 'text',
231
- name: 'projectName',
232
- message: 'What is your project name?',
233
- default: 'my-app',
234
- required: true,
235
- pattern: '^[a-z0-9-]+$', // Regex validation
236
- validate: (input) => {
237
- if (input.length < 3) {
238
- return { success: false, reason: 'Name must be at least 3 characters' };
239
- }
240
- return true;
241
- }
242
- }
243
- ```
244
-
245
- #### Number Question
246
-
247
- Collect numeric input.
248
-
249
- ```typescript
250
- {
251
- type: 'number',
252
- name: 'port',
253
- message: 'Which port to use?',
254
- default: 3000,
255
- validate: (input) => {
256
- if (input < 1 || input > 65535) {
257
- return { success: false, reason: 'Port must be between 1 and 65535' };
258
- }
259
- return true;
260
- }
261
- }
262
- ```
263
-
264
- #### Confirm Question
265
-
266
- Yes/no questions.
267
-
268
- ```typescript
269
- {
270
- type: 'confirm',
271
- name: 'useTypeScript',
272
- message: 'Use TypeScript?',
273
- default: true // Default to 'yes'
274
- }
275
- ```
276
-
277
- #### List Question
278
-
279
- Select one option from a list (no search).
280
-
281
- ```typescript
282
- {
283
- type: 'list',
284
- name: 'license',
285
- message: 'Choose a license',
286
- options: ['MIT', 'Apache-2.0', 'GPL-3.0', 'BSD-3-Clause'],
287
- default: 'MIT',
288
- maxDisplayLines: 5
289
- }
290
- ```
291
-
292
- #### Autocomplete Question
293
-
294
- Select with fuzzy search capabilities.
295
-
296
- ```typescript
297
- {
298
- type: 'autocomplete',
299
- name: 'framework',
300
- message: 'Choose your framework',
301
- options: [
302
- { name: 'React', value: 'react' },
303
- { name: 'Vue.js', value: 'vue' },
304
- { name: 'Angular', value: 'angular' },
305
- { name: 'Svelte', value: 'svelte' }
306
- ],
307
- allowCustomOptions: true, // Allow user to enter custom value
308
- maxDisplayLines: 8
309
- }
310
- ```
311
-
312
- #### Checkbox Question
313
-
314
- Multi-select with search.
315
-
316
- ```typescript
317
- {
318
- type: 'checkbox',
319
- name: 'features',
320
- message: 'Select features to include',
321
- options: [
322
- 'Authentication',
323
- 'Database',
324
- 'API Routes',
325
- 'Testing',
326
- 'Documentation'
327
- ],
328
- default: ['Authentication', 'API Routes'],
329
- returnFullResults: false, // Only return selected items
330
- required: true
331
- }
332
- ```
333
-
334
- With `returnFullResults: true`, returns all options with selection status:
335
-
336
- ```typescript
337
- [
338
- { name: 'Authentication', value: 'Authentication', selected: true },
339
- { name: 'Database', value: 'Database', selected: false },
340
- // ...
341
- ]
342
- ```
188
+ ## Full Documentation
343
189
 
344
- ### Advanced Question Options
345
-
346
- #### Custom Validation
347
-
348
- ```typescript
349
- {
350
- type: 'text',
351
- name: 'email',
352
- message: 'Enter your email',
353
- pattern: '^[^@]+@[^@]+\\.[^@]+$',
354
- validate: (email, answers) => {
355
- // Custom async validation possible
356
- if (email.endsWith('@example.com')) {
357
- return {
358
- success: false,
359
- reason: 'Please use a real email address'
360
- };
361
- }
362
- return { success: true };
363
- }
364
- }
365
- ```
366
-
367
- #### Value Sanitization
368
-
369
- ```typescript
370
- {
371
- type: 'text',
372
- name: 'tags',
373
- message: 'Enter tags (comma-separated)',
374
- sanitize: (input) => {
375
- return input.split(',').map(tag => tag.trim());
376
- }
377
- }
378
- ```
190
+ For complete documentation, examples, and advanced usage, please see the [`genomic` package documentation](https://www.npmjs.com/package/genomic).
379
191
 
380
- #### Conditional Questions
192
+ ## License
381
193
 
382
- ```typescript
383
- const questions: Question[] = [
384
- {
385
- type: 'confirm',
386
- name: 'useDatabase',
387
- message: 'Do you need a database?',
388
- default: false
389
- },
390
- {
391
- type: 'list',
392
- name: 'database',
393
- message: 'Which database?',
394
- options: ['PostgreSQL', 'MySQL', 'MongoDB', 'SQLite'],
395
- when: (answers) => answers.useDatabase === true // Only show if useDatabase is true
396
- }
397
- ];
398
- ```
399
-
400
- #### Question Dependencies
401
-
402
- Ensure questions appear in the correct order:
403
-
404
- ```typescript
405
- [
406
- {
407
- type: 'checkbox',
408
- name: 'services',
409
- message: 'Select services',
410
- options: ['Auth', 'Storage', 'Functions']
411
- },
412
- {
413
- type: 'text',
414
- name: 'authProvider',
415
- message: 'Which auth provider?',
416
- dependsOn: ['services'], // Wait for services question
417
- when: (answers) => {
418
- const selected = answers.services.find(s => s.name === 'Auth');
419
- return selected?.selected === true;
420
- }
421
- }
422
- ]
423
- ```
424
-
425
- ### Positional Arguments
426
-
427
- The `_` property allows you to name positional parameters, enabling users to pass values without flags. This is useful for CLI tools where the first few arguments have obvious meanings.
428
-
429
- #### Basic Usage
430
-
431
- ```typescript
432
- const questions: Question[] = [
433
- {
434
- _: true,
435
- name: 'database',
436
- type: 'text',
437
- message: 'Database name',
438
- required: true
439
- }
440
- ];
441
-
442
- const argv = minimist(process.argv.slice(2));
443
- const result = await prompter.prompt(argv, questions);
444
- ```
445
-
446
- Now users can run either:
447
- ```bash
448
- node myprogram.js mydb1
449
- # or equivalently:
450
- node myprogram.js --database mydb1
451
- ```
452
-
453
- #### Multiple Positional Arguments
454
-
455
- Positional arguments are assigned in declaration order:
456
-
457
- ```typescript
458
- const questions: Question[] = [
459
- { _: true, name: 'source', type: 'text', message: 'Source file' },
460
- { name: 'verbose', type: 'confirm', default: false },
461
- { _: true, name: 'destination', type: 'text', message: 'Destination file' }
462
- ];
463
-
464
- // Running: node copy.js input.txt output.txt --verbose
465
- // Results in: { source: 'input.txt', destination: 'output.txt', verbose: true }
466
- ```
467
-
468
- #### Named Arguments Take Precedence
469
-
470
- When both positional and named arguments are provided, named arguments win and the positional slot is preserved for the next positional question:
471
-
472
- ```typescript
473
- const questions: Question[] = [
474
- { _: true, name: 'foo', type: 'text' },
475
- { _: true, name: 'bar', type: 'text' },
476
- { _: true, name: 'baz', type: 'text' }
477
- ];
478
-
479
- // Running: node myprogram.js pos1 pos2 --bar named-bar
480
- // Results in: { foo: 'pos1', bar: 'named-bar', baz: 'pos2' }
481
- ```
482
-
483
- In this example, `bar` gets its value from the named flag, so the two positional values go to `foo` and `baz`.
484
-
485
- #### Positional with Options
486
-
487
- Positional arguments work with list, autocomplete, and checkbox questions. The value is mapped through the options:
488
-
489
- ```typescript
490
- const questions: Question[] = [
491
- {
492
- _: true,
493
- name: 'framework',
494
- type: 'list',
495
- options: [
496
- { name: 'React', value: 'react' },
497
- { name: 'Vue', value: 'vue' }
498
- ]
499
- }
500
- ];
501
-
502
- // Running: node setup.js React
503
- // Results in: { framework: 'react' }
504
- ```
505
-
506
- ## Real-World Examples
507
-
508
- ### Project Setup Wizard
509
-
510
- ```typescript
511
- import { Inquirerer, Question } from 'inquirerer';
512
- import minimist from 'minimist';
513
-
514
- const argv = minimist(process.argv.slice(2));
515
- const prompter = new Inquirerer();
516
-
517
- const questions: Question[] = [
518
- {
519
- type: 'text',
520
- name: 'projectName',
521
- message: 'Project name',
522
- required: true,
523
- pattern: '^[a-z0-9-]+$'
524
- },
525
- {
526
- type: 'text',
527
- name: 'description',
528
- message: 'Project description',
529
- default: 'My awesome project'
530
- },
531
- {
532
- type: 'confirm',
533
- name: 'typescript',
534
- message: 'Use TypeScript?',
535
- default: true
536
- },
537
- {
538
- type: 'autocomplete',
539
- name: 'framework',
540
- message: 'Choose a framework',
541
- options: ['React', 'Vue', 'Svelte', 'None'],
542
- default: 'React'
543
- },
544
- {
545
- type: 'checkbox',
546
- name: 'tools',
547
- message: 'Additional tools',
548
- options: ['ESLint', 'Prettier', 'Jest', 'Husky'],
549
- default: ['ESLint', 'Prettier']
550
- }
551
- ];
552
-
553
- const config = await prompter.prompt(argv, questions);
554
- console.log('Creating project with:', config);
555
- ```
556
-
557
- Run interactively:
558
- ```bash
559
- node setup.js
560
- ```
561
-
562
- Or with CLI args:
563
- ```bash
564
- node setup.js --projectName=my-app --typescript --framework=React
565
- ```
566
-
567
- ### Configuration Builder
568
-
569
- ```typescript
570
- interface AppConfig {
571
- port: number;
572
- host: string;
573
- ssl: boolean;
574
- sslCert?: string;
575
- sslKey?: string;
576
- database: string;
577
- logLevel: string;
578
- }
579
-
580
- const questions: Question[] = [
581
- {
582
- type: 'number',
583
- name: 'port',
584
- message: 'Server port',
585
- default: 3000,
586
- validate: (port) => port > 0 && port < 65536
587
- },
588
- {
589
- type: 'text',
590
- name: 'host',
591
- message: 'Server host',
592
- default: '0.0.0.0'
593
- },
594
- {
595
- type: 'confirm',
596
- name: 'ssl',
597
- message: 'Enable SSL?',
598
- default: false
599
- },
600
- {
601
- type: 'text',
602
- name: 'sslCert',
603
- message: 'SSL certificate path',
604
- when: (answers) => answers.ssl === true,
605
- required: true
606
- },
607
- {
608
- type: 'text',
609
- name: 'sslKey',
610
- message: 'SSL key path',
611
- when: (answers) => answers.ssl === true,
612
- required: true
613
- },
614
- {
615
- type: 'list',
616
- name: 'database',
617
- message: 'Database type',
618
- options: ['PostgreSQL', 'MySQL', 'SQLite'],
619
- default: 'PostgreSQL'
620
- },
621
- {
622
- type: 'list',
623
- name: 'logLevel',
624
- message: 'Log level',
625
- options: ['error', 'warn', 'info', 'debug'],
626
- default: 'info'
627
- }
628
- ];
629
-
630
- const config = await prompter.prompt<AppConfig>(argv, questions);
631
-
632
- // Write config to file
633
- fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
634
- ```
635
-
636
- ### CLI with Commander Integration
637
-
638
- ```typescript
639
- import { CLI, CommandHandler } from 'inquirerer';
640
- import { Question } from 'inquirerer';
641
-
642
- const handler: CommandHandler = async (argv, prompter, options) => {
643
- const questions: Question[] = [
644
- {
645
- type: 'text',
646
- name: 'name',
647
- message: 'What is your name?',
648
- required: true
649
- },
650
- {
651
- type: 'number',
652
- name: 'age',
653
- message: 'What is your age?',
654
- validate: (age) => age >= 0 && age <= 120
655
- }
656
- ];
657
-
658
- const answers = await prompter.prompt(argv, questions);
659
- console.log('Hello,', answers.name);
660
- };
661
-
662
- const cli = new CLI(handler, {
663
- version: 'myapp@1.0.0',
664
- minimistOpts: {
665
- alias: {
666
- n: 'name',
667
- a: 'age',
668
- v: 'version'
669
- }
670
- }
671
- });
672
-
673
- await cli.run();
674
- ```
675
-
676
- ### Dynamic Dependencies
677
-
678
- ```typescript
679
- const questions: Question[] = [
680
- {
681
- type: 'checkbox',
682
- name: 'cloud',
683
- message: 'Select cloud services',
684
- options: ['AWS', 'Azure', 'GCP'],
685
- returnFullResults: true
686
- },
687
- {
688
- type: 'text',
689
- name: 'awsRegion',
690
- message: 'AWS Region',
691
- dependsOn: ['cloud'],
692
- when: (answers) => {
693
- const aws = answers.cloud?.find(c => c.name === 'AWS');
694
- return aws?.selected === true;
695
- },
696
- default: 'us-east-1'
697
- },
698
- {
699
- type: 'text',
700
- name: 'azureLocation',
701
- message: 'Azure Location',
702
- dependsOn: ['cloud'],
703
- when: (answers) => {
704
- const azure = answers.cloud?.find(c => c.name === 'Azure');
705
- return azure?.selected === true;
706
- },
707
- default: 'eastus'
708
- },
709
- {
710
- type: 'text',
711
- name: 'gcpZone',
712
- message: 'GCP Zone',
713
- dependsOn: ['cloud'],
714
- when: (answers) => {
715
- const gcp = answers.cloud?.find(c => c.name === 'GCP');
716
- return gcp?.selected === true;
717
- },
718
- default: 'us-central1-a'
719
- }
720
- ];
721
-
722
- const config = await prompter.prompt({}, questions);
723
- ```
724
-
725
- ### Custom Validation
726
-
727
- ```typescript
728
- const questions: Question[] = [
729
- {
730
- type: 'text',
731
- name: 'username',
732
- message: 'Choose a username',
733
- required: true,
734
- pattern: '^[a-zA-Z0-9_]{3,20}$',
735
- validate: async (username) => {
736
- // Simulate API call to check availability
737
- const available = await checkUsernameAvailability(username);
738
- if (!available) {
739
- return {
740
- success: false,
741
- reason: 'Username is already taken'
742
- };
743
- }
744
- return { success: true };
745
- }
746
- },
747
- {
748
- type: 'text',
749
- name: 'password',
750
- message: 'Choose a password',
751
- required: true,
752
- validate: (password) => {
753
- if (password.length < 8) {
754
- return {
755
- success: false,
756
- reason: 'Password must be at least 8 characters'
757
- };
758
- }
759
- if (!/[A-Z]/.test(password)) {
760
- return {
761
- success: false,
762
- reason: 'Password must contain an uppercase letter'
763
- };
764
- }
765
- if (!/[0-9]/.test(password)) {
766
- return {
767
- success: false,
768
- reason: 'Password must contain a number'
769
- };
770
- }
771
- return { success: true };
772
- }
773
- },
774
- {
775
- type: 'text',
776
- name: 'confirmPassword',
777
- message: 'Confirm password',
778
- required: true,
779
- dependsOn: ['password'],
780
- validate: (confirm, answers) => {
781
- if (confirm !== answers.password) {
782
- return {
783
- success: false,
784
- reason: 'Passwords do not match'
785
- };
786
- }
787
- return { success: true };
788
- }
789
- }
790
- ];
791
- ```
792
-
793
- ## Dynamic Defaults with Resolvers
794
-
795
- The `defaultFrom` feature allows you to automatically populate question defaults from dynamic sources like git configuration, environment variables, date/time values, or custom resolvers. This eliminates repetitive boilerplate code for common default values.
796
-
797
- ### Quick Example
798
-
799
- ```typescript
800
- import { Inquirerer } from 'inquirerer';
801
-
802
- const questions = [
803
- {
804
- type: 'text',
805
- name: 'authorName',
806
- message: 'Author name?',
807
- defaultFrom: 'git.user.name' // Auto-fills from git config
808
- },
809
- {
810
- type: 'text',
811
- name: 'authorEmail',
812
- message: 'Author email?',
813
- defaultFrom: 'git.user.email' // Auto-fills from git config
814
- },
815
- {
816
- type: 'text',
817
- name: 'npmUser',
818
- message: 'NPM username?',
819
- defaultFrom: 'npm.whoami' // Auto-fills from npm whoami
820
- },
821
- {
822
- type: 'text',
823
- name: 'copyrightYear',
824
- message: 'Copyright year?',
825
- defaultFrom: 'date.year' // Auto-fills current year
826
- }
827
- ];
828
-
829
- const prompter = new Inquirerer();
830
- const answers = await prompter.prompt({}, questions);
831
- ```
832
-
833
- ### Built-in Resolvers
834
-
835
- Inquirerer comes with several built-in resolvers ready to use:
836
-
837
- #### Git Configuration
838
-
839
- | Resolver | Description | Example Output |
840
- |----------|-------------|----------------|
841
- | `git.user.name` | Git global user name | `"John Doe"` |
842
- | `git.user.email` | Git global user email | `"john@example.com"` |
843
-
844
- #### NPM
845
-
846
- | Resolver | Description | Example Output |
847
- |----------|-------------|----------------|
848
- | `npm.whoami` | Currently logged in npm user | `"johndoe"` |
849
-
850
- #### Date & Time
851
-
852
- | Resolver | Description | Example Output |
853
- |----------|-------------|----------------|
854
- | `date.year` | Current year | `"2025"` |
855
- | `date.month` | Current month (zero-padded) | `"11"` |
856
- | `date.day` | Current day (zero-padded) | `"23"` |
857
- | `date.iso` | ISO date (YYYY-MM-DD) | `"2025-11-23"` |
858
- | `date.now` | ISO timestamp | `"2025-11-23T15:30:45.123Z"` |
859
- | `date.timestamp` | Unix timestamp (ms) | `"1732375845123"` |
860
-
861
- #### Workspace (nearest package.json)
862
-
863
- | Resolver | Description | Example Output |
864
- |----------|-------------|----------------|
865
- | `workspace.name` | Repo slug from `repository` URL (fallback: `package.json` `name`) | `"dev-utils"` |
866
- | `workspace.repo.name` | Repo name from `repository` URL | `"dev-utils"` |
867
- | `workspace.repo.organization` | Repo org/owner from `repository` URL | `"constructive-io"` |
868
- | `workspace.organization.name` | Alias for `workspace.repo.organization` | `"constructive-io"` |
869
- | `workspace.license` | License field from `package.json` | `"MIT"` |
870
- | `workspace.author` | Author name from `package.json` | `"Constructive"` |
871
- | `workspace.author.name` | Author name from `package.json` | `"Constructive"` |
872
- | `workspace.author.email` | Author email from `package.json` | `"email@example.org"` |
873
-
874
- ### Priority Order
875
-
876
- When resolving default values, inquirerer follows this priority:
877
-
878
- 1. **CLI Arguments** - Values passed via command line (highest priority)
879
- 2. **`setFrom`** - Auto-set values (bypasses prompt entirely)
880
- 3. **`defaultFrom`** - Dynamically resolved default values
881
- 4. **`default`** - Static default values
882
- 5. **`undefined`** - No default available
883
-
884
- ```typescript
885
- {
886
- type: 'text',
887
- name: 'author',
888
- defaultFrom: 'git.user.name', // Try git first
889
- default: 'Anonymous' // Fallback if git not configured
890
- }
891
- ```
892
-
893
- ### `setFrom` vs `defaultFrom`
894
-
895
- Both `setFrom` and `defaultFrom` use resolvers to get values, but they behave differently:
896
-
897
- | Feature | `defaultFrom` | `setFrom` |
898
- |---------|---------------|-----------|
899
- | Sets value as | Default (user can override) | Final value (no prompt) |
900
- | User prompted? | Yes, with pre-filled default | No, question is skipped |
901
- | Use case | Suggested values | Auto-computed values |
902
-
903
- **`defaultFrom`** - The resolved value becomes the default, but the user is still prompted and can change it:
904
-
905
- ```typescript
906
- {
907
- type: 'text',
908
- name: 'authorName',
909
- message: 'Author name?',
910
- defaultFrom: 'git.user.name' // User sees "Author name? [John Doe]" and can change it
911
- }
912
- ```
913
-
914
- **`setFrom`** - The resolved value is set directly and the question is skipped entirely:
915
-
916
- ```typescript
917
- {
918
- type: 'text',
919
- name: 'year',
920
- message: 'Copyright year?',
921
- setFrom: 'date.year' // Automatically set to "2025", no prompt shown
922
- }
923
- ```
924
-
925
- #### When to use each
926
-
927
- Use `defaultFrom` when:
928
- - The value is a suggestion the user might want to change
929
- - User confirmation is desired
930
-
931
- Use `setFrom` when:
932
- - The value should be computed automatically
933
- - No user input is needed (e.g., timestamps, computed fields)
934
- - You want to reduce the number of prompts
935
-
936
- #### Combined example
937
-
938
- ```typescript
939
- const questions = [
940
- {
941
- type: 'text',
942
- name: 'authorName',
943
- message: 'Author name?',
944
- defaultFrom: 'git.user.name' // User can override
945
- },
946
- {
947
- type: 'text',
948
- name: 'createdAt',
949
- setFrom: 'date.iso' // Auto-set, no prompt
950
- },
951
- {
952
- type: 'text',
953
- name: 'copyrightYear',
954
- setFrom: 'date.year' // Auto-set, no prompt
955
- }
956
- ];
957
-
958
- // User only sees prompt for authorName
959
- // createdAt and copyrightYear are set automatically
960
- ```
961
-
962
- ### Custom Resolvers
963
-
964
- Register your own custom resolvers for project-specific needs:
965
-
966
- ```typescript
967
- import { registerDefaultResolver } from 'inquirerer';
968
-
969
- // Register a resolver for current directory name
970
- registerDefaultResolver('cwd.name', () => {
971
- return process.cwd().split('/').pop();
972
- });
973
-
974
- // Register a resolver for environment variable
975
- registerDefaultResolver('env.user', () => {
976
- return process.env.USER;
977
- });
978
-
979
- // Use in questions
980
- const questions = [
981
- {
982
- type: 'text',
983
- name: 'projectName',
984
- message: 'Project name?',
985
- defaultFrom: 'cwd.name',
986
- default: 'my-project'
987
- },
988
- {
989
- type: 'text',
990
- name: 'author',
991
- message: 'Author?',
992
- defaultFrom: 'env.user'
993
- }
994
- ];
995
- ```
996
-
997
- ### Instance-Specific Resolvers
998
-
999
- For isolated resolver registries, use a custom resolver registry per Inquirerer instance:
1000
-
1001
- ```typescript
1002
- import { DefaultResolverRegistry, Inquirerer } from 'inquirerer';
1003
-
1004
- const customRegistry = new DefaultResolverRegistry();
1005
-
1006
- // Register resolvers specific to this instance
1007
- customRegistry.register('app.name', () => 'my-app');
1008
- customRegistry.register('app.port', () => 3000);
1009
-
1010
- const prompter = new Inquirerer({
1011
- resolverRegistry: customRegistry // Use custom registry
1012
- });
1013
-
1014
- const questions = [
1015
- {
1016
- type: 'text',
1017
- name: 'appName',
1018
- defaultFrom: 'app.name'
1019
- },
1020
- {
1021
- type: 'number',
1022
- name: 'port',
1023
- defaultFrom: 'app.port'
1024
- }
1025
- ];
1026
-
1027
- const answers = await prompter.prompt({}, questions);
1028
- ```
1029
-
1030
- ### Resolver Examples
1031
-
1032
- #### System Information
1033
-
1034
- ```typescript
1035
- import os from 'os';
1036
- import { registerDefaultResolver } from 'inquirerer';
1037
-
1038
- registerDefaultResolver('system.hostname', () => os.hostname());
1039
- registerDefaultResolver('system.username', () => os.userInfo().username);
1040
-
1041
- const questions = [
1042
- {
1043
- type: 'text',
1044
- name: 'hostname',
1045
- message: 'Hostname?',
1046
- defaultFrom: 'system.hostname'
1047
- }
1048
- ];
1049
- ```
1050
-
1051
- #### Conditional Defaults
1052
-
1053
- ```typescript
1054
- registerDefaultResolver('app.port', () => {
1055
- return process.env.NODE_ENV === 'production' ? 80 : 3000;
1056
- });
1057
-
1058
- const questions = [
1059
- {
1060
- type: 'number',
1061
- name: 'port',
1062
- message: 'Port?',
1063
- defaultFrom: 'app.port'
1064
- }
1065
- ];
1066
- ```
1067
-
1068
- ### Error Handling
1069
-
1070
- Resolvers fail silently by default. If a resolver throws an error or returns `undefined`, inquirerer falls back to the static `default` value (if provided):
1071
-
1072
- ```typescript
1073
- {
1074
- type: 'text',
1075
- name: 'author',
1076
- defaultFrom: 'git.user.name', // May fail if git not configured
1077
- default: 'Anonymous', // Used if resolver fails
1078
- required: true
1079
- }
1080
- ```
1081
-
1082
- For debugging, set `DEBUG=inquirerer` to see resolver errors:
1083
-
1084
- ```bash
1085
- DEBUG=inquirerer node your-cli.js
1086
- ```
1087
-
1088
- ### Real-World Use Case
1089
-
1090
- ```typescript
1091
- import { Inquirerer, registerDefaultResolver } from 'inquirerer';
1092
-
1093
- // Register a resolver for current directory name
1094
- registerDefaultResolver('cwd.name', () => {
1095
- return process.cwd().split('/').pop();
1096
- });
1097
-
1098
- const questions = [
1099
- {
1100
- type: 'text',
1101
- name: 'projectName',
1102
- message: 'Project name?',
1103
- defaultFrom: 'cwd.name',
1104
- required: true
1105
- },
1106
- {
1107
- type: 'text',
1108
- name: 'author',
1109
- message: 'Author?',
1110
- defaultFrom: 'git.user.name',
1111
- required: true
1112
- },
1113
- {
1114
- type: 'text',
1115
- name: 'email',
1116
- message: 'Email?',
1117
- defaultFrom: 'git.user.email',
1118
- required: true
1119
- },
1120
- {
1121
- type: 'text',
1122
- name: 'year',
1123
- message: 'Copyright year?',
1124
- defaultFrom: 'date.year'
1125
- }
1126
- ];
1127
-
1128
- const prompter = new Inquirerer();
1129
- const config = await prompter.prompt({}, questions);
1130
- ```
1131
-
1132
- With git configured, the prompts will show:
1133
-
1134
- ```bash
1135
- Project name? (my-project-dir)
1136
- Author? (John Doe)
1137
- Email? (john@example.com)
1138
- Copyright year? (2025)
1139
- ```
1140
-
1141
- All defaults automatically populated from git config, directory name, and current date!
1142
-
1143
- ## CLI Helper
1144
-
1145
- The `CLI` class provides integration with command-line argument parsing:
1146
-
1147
- ```typescript
1148
- import { CLI, CommandHandler, CLIOptions } from 'inquirerer';
1149
-
1150
- const options: Partial<CLIOptions> = {
1151
- version: 'myapp@1.0.0',
1152
- minimistOpts: {
1153
- alias: {
1154
- v: 'version',
1155
- h: 'help'
1156
- },
1157
- boolean: ['help', 'version'],
1158
- string: ['name', 'output']
1159
- }
1160
- };
1161
-
1162
- const handler: CommandHandler = async (argv, prompter) => {
1163
- if (argv.help) {
1164
- console.log('Usage: myapp [options]');
1165
- process.exit(0);
1166
- }
1167
-
1168
- const answers = await prompter.prompt(argv, questions);
1169
- // Handle answers
1170
- };
1171
-
1172
- const cli = new CLI(handler, options);
1173
- await cli.run();
1174
- ```
194
+ MIT
1175
195
 
1176
196
  ---
1177
197