### Running Inquirer.js Examples Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md These commands show how to run specific examples from the Inquirer.js package. Navigate to the examples folder to see the code. ```shell yarn node packages/inquirer/examples/pizza.js yarn node packages/inquirer/examples/checkbox.js # etc... ``` -------------------------------- ### Install @inquirer/i18n with bun Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/i18n/README.md Install the package using bun. ```sh bun add @inquirer/i18n ``` -------------------------------- ### Install @sboudrias/package with bun Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/package/README.md Install the package as a development dependency using bun. ```sh bun add @sboudrias/package --dev ``` -------------------------------- ### Install @inquirer/core with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Install the @inquirer/core package using yarn. ```sh yarn add @inquirer/core ``` -------------------------------- ### Install @inquirer/ansi with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/ansi/README.md Install the package using yarn. ```sh yarn add @inquirer/ansi ``` -------------------------------- ### Install @inquirer/rawlist with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/rawlist/README.md Install the @inquirer/rawlist package directly using yarn. This is an alternative to installing the full @inquirer/prompts package. ```sh yarn add @inquirer/rawlist ``` -------------------------------- ### Install Inquirer.js with bun Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Install the Inquirer.js prompts package using bun. ```sh bun add @inquirer/prompts ``` -------------------------------- ### Install @inquirer/select Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/select/README.md Alternatively, install the specific @inquirer/select package using npm or yarn. ```sh npm install @inquirer/select ``` ```sh yarn add @inquirer/select ``` -------------------------------- ### Install @inquirer/prompts Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/expand/README.md Install the @inquirer/prompts package using npm or yarn. ```sh npm install @inquirer/prompts ``` ```sh yarn add @inquirer/prompts ``` -------------------------------- ### Action Select Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Shows an action select prompt for choosing an item and then selecting an action to perform on it. ```text ? Choose a file Open Edit Delete ❯ image.png audio.mp3 code.py ``` -------------------------------- ### Install @inquirer/input Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/input/README.md Install the input component package using npm or yarn. ```sh npm install @inquirer/input ``` ```sh yarn add @inquirer/input ``` -------------------------------- ### Install @inquirer/prompts with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/confirm/README.md Install the @inquirer/prompts package using yarn. ```sh yarn add @inquirer/prompts ``` -------------------------------- ### Install @sboudrias/package with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/package/README.md Install the package as a development dependency using npm. ```sh npm install @sboudrias/package --save-dev ``` -------------------------------- ### File Selector Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Shows a file selector prompt for navigating directories and choosing files, with customization options. ```sh ? Select a file: /main/path/ ├── folder1/ ├── folder2/ ├── folder3/ ├── file1.txt ├── file2.pdf └── file3.jpg (not allowed) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Use ↑↓ to navigate through the list Press to navigate to the parent directory Press to select a file or navigate to a directory ``` -------------------------------- ### Install @inquirer/number Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/number/README.md Install the dedicated number prompt package. ```sh npm install @inquirer/number ``` ```sh yarn add @inquirer/number ``` -------------------------------- ### Install @inquirer/search Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/search/README.md Install the specific search prompt package using npm or yarn. ```sh npm install @inquirer/search ``` ```sh yarn add @inquirer/search ``` -------------------------------- ### Install @inquirer/i18n with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/i18n/README.md Install the package using yarn. ```sh yarn add @inquirer/i18n ``` -------------------------------- ### Install @inquirer/prompts with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/confirm/README.md Install the @inquirer/prompts package using npm. ```sh npm install @inquirer/prompts ``` -------------------------------- ### Install Inquirer.js with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md Use this command to install Inquirer.js using yarn. ```sh yarn add inquirer ``` -------------------------------- ### Install Inquirer.js with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md Use this command to install Inquirer.js using npm. ```sh npm install inquirer ``` -------------------------------- ### Install @inquirer/core with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Install the @inquirer/core package using npm. ```sh npm install @inquirer/core ``` -------------------------------- ### Install @inquirer/confirm with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/confirm/README.md Install the @inquirer/confirm package using yarn. ```sh yarn add @inquirer/confirm ``` -------------------------------- ### Unit Test Input Prompt with render() Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Test an input prompt in isolation using the `render()` function. This example demonstrates typing characters and pressing enter to get an answer. ```typescript import { render } from '@inquirer/testing'; import input from '@inquirer/input'; describe('input prompt', () => { it('handle simple use case', async () => { const { answer, events, getScreen } = await render(input, { message: 'What is your name', }); expect(getScreen()).toMatchInlineSnapshot(`"? What is your name"`); events.type('J'); expect(getScreen()).toMatchInlineSnapshot(`"? What is your name J"`); events.type('ohn'); events.keypress('enter'); await expect(answer).resolves.toEqual('John'); expect(getScreen()).toMatchInlineSnapshot(`"? What is your name John"`); }); }); ``` -------------------------------- ### Install @inquirer/rawlist with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/rawlist/README.md Install the @inquirer/rawlist package directly using npm. This is an alternative to installing the full @inquirer/prompts package. ```sh npm install @inquirer/rawlist ``` -------------------------------- ### Install @inquirer/testing with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Install the testing package as a development dependency using yarn. ```sh yarn add @inquirer/testing --dev ``` -------------------------------- ### Install @inquirer/ansi with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/ansi/README.md Install the package using npm. ```sh npm install @inquirer/ansi ``` -------------------------------- ### Install @inquirer/i18n with pnpm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/i18n/README.md Install the package using pnpm. ```sh pnpm add @inquirer/i18n ``` -------------------------------- ### Install @sboudrias/package with pnpm Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/package/README.md Install the package as a development dependency using pnpm. ```sh pnpm add @sboudrias/package --save-dev ``` -------------------------------- ### Toggle Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md A simple toggle prompt for confirming an action, with options like 'no' or 'yes'. ```text ? Do you want to continue? no / yes ``` -------------------------------- ### Install @sboudrias/package with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/package/README.md Install the package as a development dependency using yarn. ```sh yarn add @sboudrias/package --dev ``` -------------------------------- ### Create Prompt with Custom Theme Setup Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md This snippet demonstrates how to set up a custom theme for a prompt, including defining custom theme keys like 'icon'. It merges custom theme properties with potential overrides. ```typescript import { createPrompt, makeTheme, type Theme } from '@inquirer/core'; import type { PartialDeep } from '@inquirer/type'; type PromptTheme = {}; const promptTheme: PromptTheme = { icon: '!', }; type PromptConfig = { theme?: PartialDeep>; }; export default createPrompt((config, done) => { const theme = makeTheme(promptTheme, config.theme); const prefix = usePrefix({ status, theme }); return `${prefix} ${theme.icon}`; }); ``` -------------------------------- ### Editor Prompt Theming Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/editor/README.md Customize the appearance of the editor prompt by providing a theme object. ```ts type Theme = { prefix: string | { idle: string; done: string }; spinner: { interval: number; frames: string[]; }; style: { message: (text: string, status: 'idle' | 'done' | 'loading') => string; error: (text: string) => string; help: (text: string) => string; key: (text: string) => string; }; validationFailureMode: 'keep' | 'clear'; }; const answer = await editor({ message: 'Enter a description', theme: { prefix: '✨', style: { message: (text) => `\x1b[36m${text}\x1b[0m`, }, }, }); ``` -------------------------------- ### Install @inquirer/i18n with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/i18n/README.md Install the package using npm. ```sh npm install @inquirer/i18n ``` -------------------------------- ### Install Inquirer.js with pnpm Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Install the Inquirer.js prompts package using pnpm. ```sh pnpm add @inquirer/prompts ``` -------------------------------- ### Install @inquirer/confirm with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/confirm/README.md Install the @inquirer/confirm package using npm. ```sh npm install @inquirer/confirm ``` -------------------------------- ### Install @inquirer/editor Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/editor/README.md Install the @inquirer/editor package using npm or yarn. ```sh npm install @inquirer/editor ``` ```sh yarn add @inquirer/editor ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/CONTRIBUTING.md Ensures Yarn is enabled and installs project dependencies. This is a prerequisite for running the project locally. ```sh corepack enable yarn install ``` -------------------------------- ### Multi Select Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md An example of a multi-select prompt that supports filtering and searching through options. ```text ? Choose your OS, IDE, PL, etc. (Press to select/deselect, to remove selected option, to select option) >> vue >[ ] vue [ ] vuejs [ ] fuelphp [ ] venv [ ] vercel (Use arrow keys to reveal more options) ``` -------------------------------- ### Install @inquirer/expand Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/expand/README.md Install the @inquirer/expand package specifically using npm or yarn. ```sh npm install @inquirer/expand ``` ```sh yarn add @inquirer/expand ``` -------------------------------- ### Install @inquirer/checkbox Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/checkbox/README.md Install the specific @inquirer/checkbox package using npm or yarn. ```sh npm install @inquirer/checkbox ``` ```sh yarn add @inquirer/checkbox ``` -------------------------------- ### Install @inquirer/testing with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Install the testing package as a development dependency using npm. ```sh npm install @inquirer/testing --save-dev ``` -------------------------------- ### Interactive List Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Demonstrates an interactive list prompt where users can select options using arrow keys or associated keys. ```text ? Choose an option: > Run command (D) Quit (Q) ``` -------------------------------- ### Sortable Checkbox Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Demonstrates a sortable checkbox prompt that allows reordering of choices using keyboard shortcuts. ```text ? Which PRs and in what order would you like to merge? (Press to select, to toggle all, to invert selection, to move item up, to move item down, and to proceed) ❯ ◯ PR 1 ◯ PR 2 ◯ PR 3 ``` -------------------------------- ### Table Multiple Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Illustrates a table multiple prompt allowing users to select multiple answers from a table display. ```sh Choose between choices? (Press to select, to move rows, to move columns) ┌──────────┬───────┬───────┐ │ 1-2 of 2 │ Yes? │ No? | ├──────────┼───────┼───────┤ │ Choice 1 │ [ ◯ ] │ ◯ | ├──────────┼───────┼───────┤ │ Choice 2 │ ◯ │ ◯ | └──────────┴───────┴───────┘ ``` -------------------------------- ### Install @inquirer/external-editor with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/external-editor/README.md Use this command to add the package to your project using npm. ```sh npm install @inquirer/external-editor ``` -------------------------------- ### Ordered Checkbox Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Demonstrates an ordered checkbox prompt for prioritizing or ranking options, maintaining selection order. ```text ? Configure your development workflow: [1] Set up CI/CD pipeline ❯ [3] Code quality tools [ ] Documentation [2] Performance monitoring ────────────── - Legacy system (disabled) (Linting, formatting, and analysis) ``` -------------------------------- ### Install @inquirer/external-editor with yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/external-editor/README.md Use this command to add the package to your project using yarn. ```sh yarn add @inquirer/external-editor ``` -------------------------------- ### Install @inquirer/password Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/password/README.md Install the password package directly using npm or yarn. ```sh npm install @inquirer/password ``` ```sh yarn add @inquirer/password ``` -------------------------------- ### Advanced Usage with Custom Output Stream Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/prompts/README.md Example demonstrating advanced usage by providing a custom Writable stream for output. This allows for custom handling of prompt output, such as logging or processing. ```javascript import { confirm } from '@inquirer/prompts'; import Stream from 'stream'; const allowEmail = await confirm( { message: 'Do you allow us to send you email?' }, { output: new Stream.Writable({ write(chunk, _encoding, next) { // Do something next(); }, }), clearPromptOnDone: true, }, ); ``` -------------------------------- ### Confirm Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/confirm/README.md Demonstrates how to import and use the confirm prompt to ask a question and get a boolean answer. ```APIDOC ## confirm ### Description Displays an interactive prompt to the user asking a yes/no question. ### Method Signature `confirm(options)` ### Parameters #### Options Object - **message** (`string`) - Required - The question to ask the user. - **default** (`boolean`) - Optional - The default answer if the user presses Enter without typing (true or false). - **transformer** (`(boolean) => string`) - Optional - A function to transform the displayed prompt message. - **theme** (`object`) - Optional - An object to customize the prompt's appearance. See Theming section for details. ### Request Example ```javascript import { confirm } from '@inquirer/prompts'; const answer = await confirm({ message: 'Continue?' }); ``` ### Response - **answer** (`boolean`) - The user's answer (true for yes, false for no). ``` -------------------------------- ### CD Directly into Isolated Directory Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/isolate-monorepo-package/README.md Example of directly changing the directory into the isolated package environment. ```bash cd $(isolate-monorepo-package @inquirer/demo) ``` -------------------------------- ### Basic Select Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/select/README.md Demonstrates how to use the select prompt to ask a user to choose a package manager. Includes choices with descriptions and a separator. ```js import { select, Separator } from '@inquirer/prompts'; // Or // import select, { Separator } from '@inquirer/select'; const answer = await select({ message: 'Select a package manager', choices: [ { name: 'npm', value: 'npm', description: 'npm is the most popular package manager', }, { name: 'yarn', value: 'yarn', description: 'yarn is an awesome package manager', }, new Separator(), { name: 'jspm', value: 'jspm', disabled: true, }, { name: 'pnpm', value: 'pnpm', disabled: '(pnpm is not available)', }, ], }); ``` -------------------------------- ### Create a Custom Confirm Prompt Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md This example shows how to create a custom confirm prompt using `createPrompt`, `useState`, and `useKeypress`. It handles user input for 'yes' or 'no' and returns a boolean answer. ```typescript import { styleText } from 'node:util'; import { createPrompt, useState, useKeypress, isEnterKey, usePrefix, type Status, } from '@inquirer/core'; const confirm = createPrompt( (config, done) => { const [status, setStatus] = useState('idle'); const [value, setValue] = useState(''); const prefix = usePrefix({}); useKeypress((key, rl) => { if (isEnterKey(key)) { const answer = value ? /^y(es)?/i.test(value) : config.default !== false; setValue(answer ? 'yes' : 'no'); setStatus('done'); done(answer); } else { setValue(rl.line); } }); let formattedValue = value; let defaultValue = ''; if (status === 'done') { formattedValue = styleText('cyan', value); } else { defaultValue = styleText('dim', config.default === false ? ' (y/N)' : ' (Y/n)'); } const message = styleText('bold', config.message); return `${prefix} ${message}${defaultValue} ${formattedValue}`; }, ); /** * Which then can be used like this: */ const answer = await confirm({ message: 'Do you want to continue?' }); ``` -------------------------------- ### Expand Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md The 'expand' prompt allows users to select from a list of choices, each associated with a unique key. It's useful for actions with keyboard shortcuts. The 'h' option is automatically added for help. ```javascript inquirer.prompt([ { type: 'expand', name: 'action', message: 'What do you want to do?', choices: [ { key: 'y', name: 'Yes', value: 'confirm' }, { key: 'n', name: 'No', value: 'deny' } ] } ]).then(answers => { console.log('Answer:', answers.action); }); ``` -------------------------------- ### One-liner to Isolate and Test with npm Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/isolate-monorepo-package/README.md A one-liner command to isolate a package, CD into the directory, install dependencies, and run tests using npm. ```bash cd $(yarn isolate-monorepo-package @inquirer/demo) npm install npm test cd - ``` -------------------------------- ### Table Multiple Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/prompts/README.md Shows a table multiple prompt allowing users to select multiple answers from a tabular display. Navigation includes rows, columns, and selection with the spacebar. ```sh Choose between choices? (Press to select, to move rows, to move columns) ┌──────────┬───────┬───────┐ │ 1-2 of 2 │ Yes? │ No? | ├──────────┼───────┼───────┤ │ Choice 1 │ [ ◯ ] │ ◯ | ├──────────┼───────┼───────┤ │ Choice 2 │ ◯ │ ◯ | └──────────┴───────┴───────┘ ``` -------------------------------- ### Editor Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md The 'editor' type opens the user's default editor for multi-line input. The 'postfix' property can specify a file extension for the temporary file. ```javascript inquirer.prompt([ { type: 'editor', name: 'bio', message: 'Please enter a short bio.', postfix: '.txt' } ]).then(answers => { console.log('Answer:', answers.bio); }); ``` -------------------------------- ### E2E Test CLI with Vitest Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Test a full CLI application using the `screen` utility from `@inquirer/testing/vitest`. This example shows interacting with multiple prompts in sequence. ```typescript import { describe, it, expect } from 'vitest'; import { screen } from '@inquirer/testing/vitest'; // Import your CLI AFTER @inquirer/testing/vitest import { runMyCli } from './my-cli.js'; describe('my CLI', () => { it('asks for name and confirms', async () => { const result = runMyCli(); // First prompt is immediately available expect(screen.getScreen()).toContain('What is your name?'); screen.type('John'); screen.keypress('enter'); // Wait for next prompt await screen.next(); expect(screen.getScreen()).toContain('Confirm?'); screen.keypress('enter'); await result; }); }); ``` -------------------------------- ### Expand Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/expand/README.md Demonstrates how to import and use the expand prompt with various options. ```APIDOC ## expand ### Description Provides a compact single-select prompt where each option has an assigned shortcut key. Selecting 'h' expands all choices and their descriptions. ### Method `expand(options)` ### Parameters #### Options - **message** (string) - Required - The question to ask the user. - **choices** (Choice[]) - Required - An array of choice objects. The 'h'/help option is always provided by default. - **default** (string) - Optional - The default choice key to be selected. - **expanded** (boolean) - Optional - Whether to expand the choices by default. - **theme** (object) - Optional - An object to customize the prompt's appearance. ### Choice Object ```ts type Choice = { value: Value; name?: string; key: string; }; ``` - **value**: The value returned when the choice is selected. - **name**: The string displayed for the choice. Defaults to the stringified `value`. - **key**: A lowercase single alphanumeric character used as the shortcut to select the choice. ### Request Example ```js import { expand } from '@inquirer/prompts'; const answer = await expand({ message: 'Conflict on file.js', default: 'y', choices: [ { key: 'y', name: 'Overwrite', value: 'overwrite', }, { key: 'a', name: 'Overwrite this one and all next', value: 'overwrite_all', }, { key: 'd', name: 'Show diff', value: 'diff', }, { key: 'x', name: 'Abort', value: 'abort', }, ], }); ``` ### Response - **answer** (string) - The `value` of the selected choice. ``` -------------------------------- ### Advanced Usage with Custom Output Stream Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Example demonstrating advanced usage of a prompt with a custom output stream and clearPromptOnDone option. Ensure process.stdin.setRawMode(true) is called if piping stdin. ```javascript import { confirm } from '@inquirer/prompts'; const allowEmail = await confirm( { message: 'Do you allow us to send you email?' }, { output: new Stream.Writable({ write(chunk, _encoding, next) { // Do something next(); }, }), clearPromptOnDone: true, }, ); ``` -------------------------------- ### Basic Rawlist Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/rawlist/README.md Demonstrates how to use the rawlist prompt to ask a user to select a package manager. Ensure you import the `rawlist` function. ```js import { rawlist } from '@inquirer/prompts'; // Or // import rawlist from '@inquirer/rawlist'; const answer = await rawlist({ message: 'Select a package manager', choices: [ { name: 'npm', value: 'npm' }, { name: 'yarn', value: 'yarn' }, { name: 'pnpm', value: 'pnpm' }, ], }); ``` -------------------------------- ### Using the Search Prompt Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/search/README.md Demonstrates how to import and use the search prompt component with a custom source function to fetch search results from the npm registry. ```APIDOC ## Using the Search Prompt This example shows how to integrate the search prompt into your CLI application. It imports the `search` function and defines a `source` function to fetch data from an external API based on user input. ### Method ```javascript await search({ message: string, source: (term: string | void, { signal }: { signal: AbortSignal }) => Promise; pageSize?: number; default?: Value; validate?: (value: Value) => boolean | string | Promise; theme?: any; // See Theming documentation }); ``` ### Parameters #### `message` (string, required) The main question or prompt displayed to the user. #### `source` (function, required) A function that takes a search term (or void if empty) and an AbortSignal. It should return a Promise resolving to an array of `Choice` objects or `Separator`s. This function is responsible for fetching and filtering the options based on the user's input. ##### `source` function signature: ```typescript function(term: string | void, opt: { signal: AbortSignal }): Promise | Separator>> ``` ##### `Choice` object structure: ```typescript type Choice = { value: Value; name?: string; description?: string; short?: string; disabled?: boolean | string; }; ``` - `value`: The actual value returned when the choice is selected. - `name`: The text displayed for the choice in the list. - `description`: Additional details shown when a choice is highlighted. - `short`: Text displayed next to the question after selection (defaults to `name`). - `disabled`: If true or a string, the choice cannot be selected, with the string providing a reason. Choices can also be an array of strings, where each string serves as both `name` and `value`. #### `pageSize` (number, optional) Determines how many choices are displayed on the screen at once before pagination. Defaults to 7. #### `default` (Value, optional) Specifies the initially selected choice. #### `validate` (function, optional) A function to validate the user's final selection. It can return a boolean or a string (for error messages). A rejected promise will cause a crash. #### `theme` (any, optional) Allows customization of the prompt's appearance. Refer to the [Theming documentation](#Theming) for details. ### Request Example ```javascript import { search } from '@inquirer/prompts'; const answer = await search({ message: 'Select an npm package', source: async (input, { signal }) => { if (!input) { return []; } const response = await fetch( `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(input)}&size=20`, { signal }, ); const data = await response.json(); return data.objects.map((pkg) => ({ name: pkg.package.name, value: pkg.package.name, description: pkg.package.description, })); }, }); console.log('Selected package:', answer); ``` ### Response #### Success Response - `answer` (Value): The `value` of the selected `Choice`. #### Response Example ```json { "example": "my-selected-package" } ``` ``` -------------------------------- ### Customize keysHelpTip in Theme Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/select/README.md Demonstrates how to customize the keyboard shortcuts help tip displayed below the prompt. You can return `undefined` to hide it or format the string to your preference. ```javascript theme: { style: { keysHelpTip: (keys) => { // Return undefined to hide the help tip completely. return undefined; // Or customize the formatting. Or localize the labels. return keys.map(([key, action]) => `${key}: ${action}`).join(' | '); } } } ``` -------------------------------- ### Create a Basic Prompt Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Demonstrates the basic concept of creating a prompt using createPrompt. The prompt function returns a string to be rendered and is called with configuration. ```typescript import { createPrompt } from '@inquirer/core'; const input = createPrompt((config, done) => { // Implement logic return '? My question'; }); // And it is then called as const answer = await input({ /* config */ }); ``` -------------------------------- ### Create a Basic Input Prompt Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Shows how to create a simple text input prompt using `createPrompt`. It utilizes `useState` for input value and `useKeypress` to handle user input, calling `done` on 'enter'. ```typescript const input = createPrompt((config, done) => { const [value, setValue] = useState(); useKeypress((key, readline) => { if (key.name === 'enter') { done(answer); } else { setValue(readline.line); } }); return `? ${config.message} ${value}`; }); ``` -------------------------------- ### Editor Prompt with File Postfix Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/editor/README.md Specify a file postfix to enable syntax highlighting in the editor. Defaults to '.txt'. ```js const answer = await editor({ message: 'Enter a description', postfix: '.md', }); ``` -------------------------------- ### Capture Isolated Directory Path Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/isolate-monorepo-package/README.md Example of capturing the output path of the isolated directory into a variable for scripting. ```bash TEST_DIR=$(isolate-monorepo-package @inquirer/demo) ``` -------------------------------- ### Confirm Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md The 'confirm' type is for boolean yes/no questions. The 'default' property expects a boolean value. ```javascript inquirer.prompt([ { type: 'confirm', name: 'toggle', message: 'Are you sure?', default: true } ]).then(answers => { console.log('Answer:', answers.toggle); }); ``` -------------------------------- ### Create Prompt with Standard Theme Customization Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Use this snippet to create a prompt that allows standard theme customization. It utilizes `makeTheme` with a provided theme configuration. ```typescript import { createPrompt, usePrefix, makeTheme, type Theme } from '@inquirer/core'; import type { PartialDeep } from '@inquirer/type'; type PromptConfig = { theme?: PartialDeep; }; export default createPrompt((config, done) => { const theme = makeTheme(config.theme); const prefix = usePrefix({ status, theme }); return `${prefix} ${theme.style.highlight('hello')}`; }); ``` -------------------------------- ### Checkbox Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/checkbox/README.md Demonstrates how to import and use the checkbox prompt with various configuration options. ```APIDOC ## checkbox ### Description Displays an interactive list of checkboxes allowing the user to select multiple options. ### Method `checkbox(options)` ### Parameters #### Options Object - **message** (string) - Required - The question to ask the user. - **choices** (Choice[]) - Required - An array of choices for the prompt. Each choice can be an object with `name`, `value`, and optional `disabled` properties, or a `Separator` object. - **pageSize** (number) - Optional - The number of choices to display per page. Defaults to 7. - **loop** (boolean) - Optional - Whether the cursor should loop around the list. Defaults to `true`. - **required** (boolean) - Optional - If `true`, at least one choice must be selected. - **validate** (async (Choice[]) => boolean | string) - Optional - A validation function that runs on submit. It can return `true` for valid, `false` for invalid, or a string error message. - **shortcuts** ([See Shortcuts](#Shortcuts)) - Optional - Customizes shortcut keys for actions like 'all' and 'invert'. - **theme** ([See Theming](#Theming)) - Optional - Allows customization of the prompt's appearance. ### Choices Choices can be objects with the following structure: - **name** (string) - The display name of the choice. - **value** (any) - The value returned when the choice is selected. - **disabled** (boolean | string) - Optional - If `true`, the choice is disabled. If a string, it's displayed as the reason for being disabled. `Separator` objects can be used to visually group choices with a dividing line and an optional label (e.g., `new Separator('-- Dependencies --')`). ### Request Example ```js import { checkbox, Separator } from '@inquirer/prompts'; const answer = await checkbox({ message: 'Select a package manager', choices: [ { name: 'npm', value: 'npm' }, { name: 'yarn', value: 'yarn' }, new Separator(), { name: 'pnpm', value: 'pnpm', disabled: true }, { name: 'pnpm', value: 'pnpm', disabled: '(pnpm is not available)', }, ], }); ``` ### Response #### Success Response - Returns an array of the `value`s of the selected choices. ``` -------------------------------- ### Basic Password Input Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/password/README.md Import and use the password prompt to get user input. The message option is required. ```js import { password } from '@inquirer/prompts'; // Or // import password from '@inquirer/password'; const answer = await password({ message: 'Enter your name' }); ``` -------------------------------- ### Use npx for Select Prompt Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Create an interactive version bump prompt using npx and @inquirer-cli/select. Options are provided as arguments to the CLI. ```bash $ npm version $(npx -y @inquirer-cli/select -c patch -c minor -c major 'Select Version') ``` -------------------------------- ### Customizing keysHelpTip Function Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/checkbox/README.md Demonstrates how to customize the keyboard shortcuts help tip displayed below the prompt using the `theme.style.keysHelpTip` function. It can hide the tip or format its output. ```javascript theme: { style: { keysHelpTip: (keys) => { // Return undefined to hide the help tip completely return undefined; // Or customize the formatting. Or localize the labels. return keys.map(([key, action]) => `${key}: ${action}`).join(' | '); } } } ``` -------------------------------- ### Cancel Prompt with AbortSignal.timeout Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Example of canceling a prompt using the built-in AbortSignal.timeout utility. The prompt will automatically abort after the specified duration. ```javascript // Example 1: using built-in AbortSignal utilities import { confirm } from '@inquirer/prompts'; const answer = await confirm({ ... }, { signal: AbortSignal.timeout(5000) }); ``` -------------------------------- ### Basic Input Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Use the input prompt to get text input from the user. Import the 'input' function from '@inquirer/prompts'. ```js import { input } from '@inquirer/prompts'; const answer = await input({ message: 'Enter your name' }); ``` -------------------------------- ### One-liner to Isolate and Test with Yarn Source: https://github.com/sboudrias/inquirer.js/blob/main/tools/isolate-monorepo-package/README.md A one-liner command to isolate a package, CD into the directory, install dependencies, and run tests using Yarn. ```bash cd $(yarn isolate-monorepo-package @inquirer/demo) yarn set version stable yarn install yarn test cd - ``` -------------------------------- ### Password Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md Use the 'password' type for sensitive input like passwords. The 'mask' property is required to obscure the input characters. ```javascript inquirer.prompt([ { type: 'password', name: 'secret', message: 'Enter your secret code', mask: '*' } ]).then(answers => { console.log('Answer:', answers.secret); }); ``` -------------------------------- ### Editor Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/editor/README.md Demonstrates how to import and use the editor prompt in your application. It shows the basic structure for prompting the user for input that will be edited in their default text editor. ```APIDOC ## editor Prompt ### Description Prompts the user to enter multi-line text using their preferred external editor. The content is controlled via the command line. ### Method `editor(options)` ### Parameters #### Options - **message** (string) - Required - The question to ask the user. - **default** (string) - Optional - The default value to pre-fill in the editor. - **validate** (string => boolean | string | Promise) - Optional - A function to validate the user's input. Returns a boolean or an error message string. Can also return a rejected promise. - **postfix** (string) - Optional - The file extension for the temporary file (e.g., `.js`, `.txt`). Defaults to `.txt`. Affects syntax highlighting in the editor. - **file** (object) - Optional - Options to configure the temporary file, passed to the `external-editor` package. - **waitForUserInput** (boolean) - Optional - If true (default), the prompt waits for user input before opening the editor. If false, the editor opens immediately without displaying the question. - **theme** (object) - Optional - An object to customize the prompt's appearance. See Theming section for details. ### Request Example ```js import { editor } from '@inquirer/prompts'; const answer = await editor({ message: 'Enter a description', default: 'Initial content', validate: (text) => { if (text.length < 10) { return 'Description must be at least 10 characters long.'; } return true; }, postfix: '.md', }); console.log('User entered:', answer); ``` ### Response #### Success Response - **answer** (string) - The text content entered by the user in the editor. ``` -------------------------------- ### Number Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md The 'number' type is specifically for numeric input. It shares properties like 'default', 'filter', and 'validate' with the 'input' type. ```javascript inquirer.prompt([ { type: 'number', name: 'age', message: 'What\'s your age?', default: 25 } ]).then(answers => { console.log('Answer:', answers.age); }); ``` -------------------------------- ### Checkbox Plus Plus Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Shows a modern multiselect checkbox prompt with advanced features like search, filter, and autocomplete. ```text ? Select colors [searching: "re"] ❯ ◉ The red color ◯ The green color ◉ The purple color ◯ The orange color ↑↓ navigate • space de/select • type search • 2 selected • ⏎ submit ``` -------------------------------- ### Basic Search Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/search/README.md Use the search prompt to allow users to select an item from a dynamically fetched list. The source function fetches data from the npm registry based on user input and returns formatted choices. Ensure to handle the AbortSignal for cancelling network requests. ```js import { search, Separator } from '@inquirer/prompts'; // Or // import search, { Separator } from '@inquirer/search'; const answer = await search({ message: 'Select an npm package', source: async (input, { signal }) => { if (!input) { return []; } const response = await fetch( `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(input)}&size=20`, { signal }, ); const data = await response.json(); return data.objects.map((pkg) => ({ name: pkg.package.name, value: pkg.package.name, description: pkg.package.description, })); }, }); ``` -------------------------------- ### Mocking Third-Party Prompts with wrapPrompt Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Demonstrates how to use `wrapPrompt` to mock custom or third-party prompt packages within your test environment. ```APIDOC ## Mocking Third-Party Prompts All `@inquirer/*` prompts are mocked automatically. To mock a third-party or custom prompt package, use `wrapPrompt` in your own mock call: ### Vitest ```ts import { screen, wrapPrompt } from '@inquirer/testing/vitest'; vi.mock('@my-company/custom-prompt', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, default: wrapPrompt(actual.default) }; }); ``` ### Jest In Jest, `jest.mock()` factories are hoisted before imports, so `wrapPrompt` must be accessed via `jest.requireActual()` inside the factory: ```ts import { screen } from '@inquirer/testing/jest'; jest.mock('@my-company/custom-prompt', () => { const { wrapPrompt } = jest.requireActual('@inquirer/testing/jest'); const actual = jest.requireActual('@my-company/custom-prompt'); return { ...actual, default: wrapPrompt(actual.default) }; }); ``` ``` -------------------------------- ### Access Readline Instance with useKeypress Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Demonstrates accessing the active readline instance within the useKeypress hook to get the current line input. ```typescript const input = createPrompt((config, done) => { useKeypress((key, readline) => { setValue(readline.line); }); // ... ``` -------------------------------- ### Publish New Versions Source: https://github.com/sboudrias/inquirer.js/blob/main/CONTRIBUTING.md Publishes new versions of the package using Lerna. This action requires specific npm permissions and 2FA setup. ```sh yarn lerna publish ``` -------------------------------- ### Input Prompt Example Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md Use the 'input' type for free-form text entry. It accepts 'default', 'filter', and 'validate' properties for input manipulation and validation. ```javascript inquirer.prompt([ { type: 'input', name: 'username', message: 'What\'s your username?' } ]).then(answers => { console.log('Answer:', answers.username); }); ``` -------------------------------- ### Basic Inquirer.js Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/inquirer/README.md This is a basic example of how to use inquirer.prompt to ask questions and handle answers. It includes error handling for non-interactive environments. ```javascript import inquirer from 'inquirer'; inquirer .prompt([ /* Pass your questions in here */ ]) .then((answers) => { // Use user feedback for... whatever!! }) .catch((error) => { if (error.isTtyError) { // Prompt couldn't be rendered in the current environment } else { // Something else went wrong } }); ``` -------------------------------- ### Cancel Prompt with AbortSignal.timeout Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/prompts/README.md Example of canceling a prompt asynchronously using the built-in AbortSignal.timeout utility. This will reject the prompt's promise after the specified duration. ```javascript // Example 1: using built-in AbortSignal utilities import { confirm } from '@inquirer/prompts'; const answer = await confirm({ ... }, { signal: AbortSignal.timeout(5000) }); ``` -------------------------------- ### Customize Keys Help Tip Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/search/README.md Customize the keyboard shortcuts help tip displayed below the prompt. This function receives an array of key-action pairs and should return a formatted string or `undefined` to hide the tip. ```javascript theme: { style: { keysHelpTip: (keys) => { // Return undefined to hide the help tip completely. return undefined; // Or customize the formatting. Or localize the labels. return keys.map(([key, action]) => `${key}: ${action}`).join(' | '); }; } } ``` -------------------------------- ### Basic Editor Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/editor/README.md Use the editor prompt to get multi-line input from the user. The prompt will open the user's default editor. ```js import { editor } from '@inquirer/prompts'; // Or // import editor from '@inquirer/editor'; const answer = await editor({ message: 'Enter a description', }); ``` -------------------------------- ### Number Prompt Usage Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/number/README.md Demonstrates the basic usage of the number prompt, including importing and awaiting the prompt's answer. ```APIDOC ## Number Prompt ### Description This prompt allows users to input a number. It supports various configuration options to customize its behavior and appearance. ### Method `number(options)` ### Parameters #### Options - **message** (string) - Required - The question to ask the user. - **default** (number) - Optional - The default value if no answer is provided. - **min** (number) - Optional - The minimum acceptable value. - **max** (number) - Optional - The maximum acceptable value. - **step** (number | 'any') - Optional - The granularity for valid input values. Defaults to 1. - **required** (boolean) - Optional - If true, an empty answer is not accepted. Defaults to `false`. - **validate** ((number | undefined) => boolean | string | Promise) - Optional - A validation function that runs on submit. It can return `true` for valid, `false` for invalid, or a string error message. - **theme** (object) - Optional - An object to customize the prompt's appearance. See Theming section for details. ### Request Example ```js import { number } from '@inquirer/prompts'; const answer = await number({ message: 'Enter your age', default: 18, min: 0, max: 120, validate: (value) => { if (value === undefined) { return 'Please enter a number'; } if (value < 0) { return 'Age cannot be negative'; } return true; } }); console.log(`Your age is: ${answer}`); ``` ### Response - **answer** (number) - The validated number entered by the user. ``` -------------------------------- ### E2E Test CLI with Jest Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/testing/README.md Test a full CLI application using the `screen` utility from `@inquirer/testing/jest`. This example demonstrates interacting with multiple prompts sequentially. ```typescript import { screen } from '@inquirer/testing/jest'; import { runMyCli } from './my-cli.js'; describe('my CLI', () => { it('asks for name and confirms', async () => { const result = runMyCli(); // First prompt is immediately available expect(screen.getScreen()).toContain('What is your name?'); screen.type('John'); screen.keypress('enter'); // Wait for next prompt await screen.next(); expect(screen.getScreen()).toContain('Confirm?'); screen.keypress('enter'); await result; }); }); ``` -------------------------------- ### Create a Select Prompt with Pagination Source: https://github.com/sboudrias/inquirer.js/blob/main/packages/core/README.md Demonstrates how to use the `usePagination` hook within a custom prompt to handle long lists of choices. It requires `items`, `active` index, `pageSize`, and a `renderItem` function. ```javascript export default createPrompt((config, done) => { const [active, setActive] = useState(0); const allChoices = config.choices.map((choice) => choice.name); const page = usePagination({ items: allChoices, active: active, renderItem: ({ item, index, isActive }) => `${isActive ? ">" : " "}${index}. ${item.toString()}`, pageSize: config.pageSize, loop: config.loop, }); return `... ${page}`; }); ``` -------------------------------- ### Select Prompt with Stateful Banner - Initial Display Source: https://github.com/sboudrias/inquirer.js/blob/main/README.md Initial display of a select prompt featuring a stateful banner that shows loading information. ```text Directory size: loading... ? Choose an option ❯ Rename Copy Delete ```