firest commit
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
# @inquirer/ansi
|
||||
|
||||
A lightweight package providing ANSI escape sequences for terminal cursor manipulation and screen clearing.
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/ansi
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/ansi
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import {
|
||||
cursorUp,
|
||||
cursorDown,
|
||||
cursorTo,
|
||||
cursorLeft,
|
||||
cursorHide,
|
||||
cursorShow,
|
||||
eraseLines,
|
||||
} from '@inquirer/ansi';
|
||||
|
||||
// Move cursor up 3 lines
|
||||
process.stdout.write(cursorUp(3));
|
||||
|
||||
// Move cursor to specific position (x: 10, y: 5)
|
||||
process.stdout.write(cursorTo(10, 5));
|
||||
|
||||
// Hide/show cursor
|
||||
process.stdout.write(cursorHide);
|
||||
process.stdout.write(cursorShow);
|
||||
|
||||
// Clear 5 lines
|
||||
process.stdout.write(eraseLines(5));
|
||||
```
|
||||
|
||||
Or when used inside an inquirer prompt:
|
||||
|
||||
```js
|
||||
import { cursorHide } from '@inquirer/ansi';
|
||||
import { createPrompt } from '@inquirer/core';
|
||||
|
||||
export default createPrompt((config, done: (value: void) => void) => {
|
||||
return `Choose an option${cursorHide}`;
|
||||
});
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### Cursor Movement
|
||||
|
||||
- **`cursorUp(count?: number)`** - Move cursor up by `count` lines (default: 1)
|
||||
- **`cursorDown(count?: number)`** - Move cursor down by `count` lines (default: 1)
|
||||
- **`cursorTo(x: number, y?: number)`** - Move cursor to position (x, y). If y is omitted, only moves horizontally
|
||||
- **`cursorLeft`** - Move cursor to beginning of line
|
||||
|
||||
### Cursor Visibility
|
||||
|
||||
- **`cursorHide`** - Hide the cursor
|
||||
- **`cursorShow`** - Show the cursor
|
||||
|
||||
### Screen Manipulation
|
||||
|
||||
- **`eraseLines(count: number)`** - Clear `count` lines and position cursor at the beginning of the first cleared line
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2025 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/** Move cursor to first column */
|
||||
export declare const cursorLeft: string;
|
||||
/** Hide the cursor */
|
||||
export declare const cursorHide: string;
|
||||
/** Show the cursor */
|
||||
export declare const cursorShow: string;
|
||||
/** Move cursor up by count rows */
|
||||
export declare const cursorUp: (rows?: number) => string;
|
||||
/** Move cursor down by count rows */
|
||||
export declare const cursorDown: (rows?: number) => string;
|
||||
/** Move cursor to position (x, y) */
|
||||
export declare const cursorTo: (x: number, y?: number) => string;
|
||||
/** Erase the specified number of lines above the cursor */
|
||||
export declare const eraseLines: (lines: number) => string;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
const ESC = '\u001B[';
|
||||
/** Move cursor to first column */
|
||||
export const cursorLeft = ESC + 'G';
|
||||
/** Hide the cursor */
|
||||
export const cursorHide = ESC + '?25l';
|
||||
/** Show the cursor */
|
||||
export const cursorShow = ESC + '?25h';
|
||||
/** Move cursor up by count rows */
|
||||
export const cursorUp = (rows = 1) => (rows > 0 ? `${ESC}${rows}A` : '');
|
||||
/** Move cursor down by count rows */
|
||||
export const cursorDown = (rows = 1) => rows > 0 ? `${ESC}${rows}B` : '';
|
||||
/** Move cursor to position (x, y) */
|
||||
export const cursorTo = (x, y) => {
|
||||
if (typeof y === 'number' && !Number.isNaN(y)) {
|
||||
return `${ESC}${y + 1};${x + 1}H`;
|
||||
}
|
||||
return `${ESC}${x + 1}G`;
|
||||
};
|
||||
const eraseLine = ESC + '2K';
|
||||
/** Erase the specified number of lines above the cursor */
|
||||
export const eraseLines = (lines) => lines > 0 ? (eraseLine + cursorUp(1)).repeat(lines - 1) + eraseLine + cursorLeft : '';
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "@inquirer/ansi",
|
||||
"version": "2.0.3",
|
||||
"keywords": [
|
||||
"ansi",
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/ansi/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
# `@inquirer/checkbox`
|
||||
|
||||
Simple interactive command line prompt to display a list of checkboxes (multi select).
|
||||
|
||||

|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/checkbox
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/checkbox
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { checkbox, Separator } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import checkbox, { Separator } from '@inquirer/checkbox';
|
||||
|
||||
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)',
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| --------- | --------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| choices | `Choice[]` | yes | List of the available choices. |
|
||||
| pageSize | `number` | no | By default, lists of choice longer than 7 will be paginated. Use this option to control how many choices will appear on the screen at once. |
|
||||
| loop | `boolean` | no | Defaults to `true`. When set to `false`, the cursor will be constrained to the top and bottom of the choice list without looping. |
|
||||
| required | `boolean` | no | When set to `true`, ensures at least one choice must be selected. |
|
||||
| validate | `async (Choice[]) => boolean \| string` | no | On submit, validate the choices. When returning a string, it'll be used as the error message displayed to the user. Note: returning a rejected promise, we'll assume a code error happened and crash. |
|
||||
| shortcuts | [See Shortcuts](#Shortcuts) | no | Customize shortcut keys for `all` and `invert`. |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
`Separator` objects can be used in the `choices` array to render non-selectable lines in the choice list. By default it'll render a line, but you can provide the text as argument (`new Separator('-- Dependencies --')`). This option is often used to add labels to groups within long list of options.
|
||||
|
||||
### `Choice` object
|
||||
|
||||
The `Choice` object is typed as
|
||||
|
||||
```ts
|
||||
type Choice<Value> = {
|
||||
value: Value;
|
||||
name?: string;
|
||||
checkedName?: string;
|
||||
description?: string;
|
||||
short?: string;
|
||||
checked?: boolean;
|
||||
disabled?: boolean | string;
|
||||
};
|
||||
```
|
||||
|
||||
Here's each property:
|
||||
|
||||
- `value`: The value is what will be returned by `await checkbox()`.
|
||||
- `name`: This is the string displayed in the choice list.
|
||||
- `checkedName`: Alternative `name` (or format) displayed when the choice is checked.
|
||||
- `description`: Option for a longer description string that'll appear under the list when the cursor highlight a given choice.
|
||||
- `short`: Once the prompt is done (press enter), we'll use `short` if defined to render next to the question. By default we'll use `name`.
|
||||
- `checked`: If `true`, the option will be checked by default.
|
||||
- `disabled`: Disallow the option from being selected. If `disabled` is a string, it'll be used as a help tip explaining why the choice isn't available.
|
||||
|
||||
Also note the `choices` array can contain `Separator`s to help organize long lists.
|
||||
|
||||
`choices` can also be an array of string, in which case the string will be used both as the `value` and the `name`.
|
||||
|
||||
## Shortcuts
|
||||
|
||||
You can customize the shortcut keys for `all` and `invert` or disable them by setting them to `null`.
|
||||
|
||||
```ts
|
||||
type Shortcuts = {
|
||||
all?: string | null; // default: 'a'
|
||||
invert?: string | null; // default: 'i'
|
||||
};
|
||||
```
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
help: (text: string) => string;
|
||||
highlight: (text: string) => string;
|
||||
key: (text: string) => string;
|
||||
disabledChoice: (text: string) => string;
|
||||
description: (text: string) => string;
|
||||
renderSelectedChoices: <T>(
|
||||
selectedChoices: ReadonlyArray<Choice<T>>,
|
||||
allChoices: ReadonlyArray<Choice<T> | Separator>,
|
||||
) => string;
|
||||
keysHelpTip: (keys: [key: string, action: string][]) => string | undefined;
|
||||
};
|
||||
icon: {
|
||||
checked: string;
|
||||
unchecked: string;
|
||||
cursor: string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### `theme.style.keysHelpTip`
|
||||
|
||||
This function allows you to customize the keyboard shortcuts help tip displayed below the prompt. It receives an array of key-action pairs and should return a formatted string. You can also hook here to localize the labels to different languages.
|
||||
|
||||
It can also returns `undefined` to hide the help tip entirely.
|
||||
|
||||
```js
|
||||
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(' | ');
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { Separator, type Theme, type Keybinding } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type CheckboxTheme = {
|
||||
icon: {
|
||||
checked: string;
|
||||
unchecked: string;
|
||||
cursor: string;
|
||||
};
|
||||
style: {
|
||||
disabledChoice: (text: string) => string;
|
||||
renderSelectedChoices: <T>(selectedChoices: ReadonlyArray<NormalizedChoice<T>>, allChoices: ReadonlyArray<NormalizedChoice<T> | Separator>) => string;
|
||||
description: (text: string) => string;
|
||||
keysHelpTip: (keys: [key: string, action: string][]) => string | undefined;
|
||||
};
|
||||
keybindings: ReadonlyArray<Keybinding>;
|
||||
};
|
||||
type CheckboxShortcuts = {
|
||||
all?: string | null;
|
||||
invert?: string | null;
|
||||
};
|
||||
type Choice<Value> = {
|
||||
value: Value;
|
||||
name?: string;
|
||||
checkedName?: string;
|
||||
description?: string;
|
||||
short?: string;
|
||||
disabled?: boolean | string;
|
||||
checked?: boolean;
|
||||
type?: never;
|
||||
};
|
||||
type NormalizedChoice<Value> = {
|
||||
value: Value;
|
||||
name: string;
|
||||
checkedName: string;
|
||||
description?: string;
|
||||
short: string;
|
||||
disabled: boolean | string;
|
||||
checked: boolean;
|
||||
};
|
||||
declare const _default: <Value>(config: {
|
||||
message: string;
|
||||
prefix?: string | undefined;
|
||||
pageSize?: number | undefined;
|
||||
choices: readonly (string | Separator)[] | readonly (Separator | Choice<Value>)[];
|
||||
loop?: boolean | undefined;
|
||||
required?: boolean | undefined;
|
||||
validate?: ((choices: readonly NormalizedChoice<Value>[]) => boolean | string | Promise<string | boolean>) | undefined;
|
||||
theme?: PartialDeep<Theme<CheckboxTheme>> | undefined;
|
||||
shortcuts?: CheckboxShortcuts | undefined;
|
||||
}, context?: import("@inquirer/type").Context) => Promise<Value[]>;
|
||||
export default _default;
|
||||
export { Separator } from '@inquirer/core';
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
import { createPrompt, useState, useKeypress, usePrefix, usePagination, useMemo, makeTheme, isUpKey, isDownKey, isSpaceKey, isNumberKey, isEnterKey, ValidationError, Separator, } from '@inquirer/core';
|
||||
import { cursorHide } from '@inquirer/ansi';
|
||||
import { styleText } from 'node:util';
|
||||
import figures from '@inquirer/figures';
|
||||
const checkboxTheme = {
|
||||
icon: {
|
||||
checked: styleText('green', figures.circleFilled),
|
||||
unchecked: figures.circle,
|
||||
cursor: figures.pointer,
|
||||
},
|
||||
style: {
|
||||
disabledChoice: (text) => styleText('dim', `- ${text}`),
|
||||
renderSelectedChoices: (selectedChoices) => selectedChoices.map((choice) => choice.short).join(', '),
|
||||
description: (text) => styleText('cyan', text),
|
||||
keysHelpTip: (keys) => keys
|
||||
.map(([key, action]) => `${styleText('bold', key)} ${styleText('dim', action)}`)
|
||||
.join(styleText('dim', ' • ')),
|
||||
},
|
||||
keybindings: [],
|
||||
};
|
||||
function isSelectable(item) {
|
||||
return !Separator.isSeparator(item) && !item.disabled;
|
||||
}
|
||||
function isChecked(item) {
|
||||
return isSelectable(item) && item.checked;
|
||||
}
|
||||
function toggle(item) {
|
||||
return isSelectable(item) ? { ...item, checked: !item.checked } : item;
|
||||
}
|
||||
function check(checked) {
|
||||
return function (item) {
|
||||
return isSelectable(item) ? { ...item, checked } : item;
|
||||
};
|
||||
}
|
||||
function normalizeChoices(choices) {
|
||||
return choices.map((choice) => {
|
||||
if (Separator.isSeparator(choice))
|
||||
return choice;
|
||||
if (typeof choice === 'string') {
|
||||
return {
|
||||
value: choice,
|
||||
name: choice,
|
||||
short: choice,
|
||||
checkedName: choice,
|
||||
disabled: false,
|
||||
checked: false,
|
||||
};
|
||||
}
|
||||
const name = choice.name ?? String(choice.value);
|
||||
const normalizedChoice = {
|
||||
value: choice.value,
|
||||
name,
|
||||
short: choice.short ?? name,
|
||||
checkedName: choice.checkedName ?? name,
|
||||
disabled: choice.disabled ?? false,
|
||||
checked: choice.checked ?? false,
|
||||
};
|
||||
if (choice.description) {
|
||||
normalizedChoice.description = choice.description;
|
||||
}
|
||||
return normalizedChoice;
|
||||
});
|
||||
}
|
||||
export default createPrompt((config, done) => {
|
||||
const { pageSize = 7, loop = true, required, validate = () => true } = config;
|
||||
const shortcuts = { all: 'a', invert: 'i', ...config.shortcuts };
|
||||
const theme = makeTheme(checkboxTheme, config.theme);
|
||||
const { keybindings } = theme;
|
||||
const [status, setStatus] = useState('idle');
|
||||
const prefix = usePrefix({ status, theme });
|
||||
const [items, setItems] = useState(normalizeChoices(config.choices));
|
||||
const bounds = useMemo(() => {
|
||||
const first = items.findIndex(isSelectable);
|
||||
const last = items.findLastIndex(isSelectable);
|
||||
if (first === -1) {
|
||||
throw new ValidationError('[checkbox prompt] No selectable choices. All choices are disabled.');
|
||||
}
|
||||
return { first, last };
|
||||
}, [items]);
|
||||
const [active, setActive] = useState(bounds.first);
|
||||
const [errorMsg, setError] = useState();
|
||||
useKeypress(async (key) => {
|
||||
if (isEnterKey(key)) {
|
||||
const selection = items.filter(isChecked);
|
||||
const isValid = await validate([...selection]);
|
||||
if (required && !items.some(isChecked)) {
|
||||
setError('At least one choice must be selected');
|
||||
}
|
||||
else if (isValid === true) {
|
||||
setStatus('done');
|
||||
done(selection.map((choice) => choice.value));
|
||||
}
|
||||
else {
|
||||
setError(isValid || 'You must select a valid value');
|
||||
}
|
||||
}
|
||||
else if (isUpKey(key, keybindings) || isDownKey(key, keybindings)) {
|
||||
if (loop ||
|
||||
(isUpKey(key, keybindings) && active !== bounds.first) ||
|
||||
(isDownKey(key, keybindings) && active !== bounds.last)) {
|
||||
const offset = isUpKey(key, keybindings) ? -1 : 1;
|
||||
let next = active;
|
||||
do {
|
||||
next = (next + offset + items.length) % items.length;
|
||||
} while (!isSelectable(items[next]));
|
||||
setActive(next);
|
||||
}
|
||||
}
|
||||
else if (isSpaceKey(key)) {
|
||||
setError(undefined);
|
||||
setItems(items.map((choice, i) => (i === active ? toggle(choice) : choice)));
|
||||
}
|
||||
else if (key.name === shortcuts.all) {
|
||||
const selectAll = items.some((choice) => isSelectable(choice) && !choice.checked);
|
||||
setItems(items.map(check(selectAll)));
|
||||
}
|
||||
else if (key.name === shortcuts.invert) {
|
||||
setItems(items.map(toggle));
|
||||
}
|
||||
else if (isNumberKey(key)) {
|
||||
const selectedIndex = Number(key.name) - 1;
|
||||
// Find the nth item (ignoring separators)
|
||||
let selectableIndex = -1;
|
||||
const position = items.findIndex((item) => {
|
||||
if (Separator.isSeparator(item))
|
||||
return false;
|
||||
selectableIndex++;
|
||||
return selectableIndex === selectedIndex;
|
||||
});
|
||||
const selectedItem = items[position];
|
||||
if (selectedItem && isSelectable(selectedItem)) {
|
||||
setActive(position);
|
||||
setItems(items.map((choice, i) => (i === position ? toggle(choice) : choice)));
|
||||
}
|
||||
}
|
||||
});
|
||||
const message = theme.style.message(config.message, status);
|
||||
let description;
|
||||
const page = usePagination({
|
||||
items,
|
||||
active,
|
||||
renderItem({ item, isActive }) {
|
||||
if (Separator.isSeparator(item)) {
|
||||
return ` ${item.separator}`;
|
||||
}
|
||||
if (item.disabled) {
|
||||
const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';
|
||||
return theme.style.disabledChoice(`${item.name} ${disabledLabel}`);
|
||||
}
|
||||
if (isActive) {
|
||||
description = item.description;
|
||||
}
|
||||
const checkbox = item.checked ? theme.icon.checked : theme.icon.unchecked;
|
||||
const name = item.checked ? item.checkedName : item.name;
|
||||
const color = isActive ? theme.style.highlight : (x) => x;
|
||||
const cursor = isActive ? theme.icon.cursor : ' ';
|
||||
return color(`${cursor}${checkbox} ${name}`);
|
||||
},
|
||||
pageSize,
|
||||
loop,
|
||||
});
|
||||
if (status === 'done') {
|
||||
const selection = items.filter(isChecked);
|
||||
const answer = theme.style.answer(theme.style.renderSelectedChoices(selection, items));
|
||||
return [prefix, message, answer].filter(Boolean).join(' ');
|
||||
}
|
||||
const keys = [
|
||||
['↑↓', 'navigate'],
|
||||
['space', 'select'],
|
||||
];
|
||||
if (shortcuts.all)
|
||||
keys.push([shortcuts.all, 'all']);
|
||||
if (shortcuts.invert)
|
||||
keys.push([shortcuts.invert, 'invert']);
|
||||
keys.push(['⏎', 'submit']);
|
||||
const helpLine = theme.style.keysHelpTip(keys);
|
||||
const lines = [
|
||||
[prefix, message].filter(Boolean).join(' '),
|
||||
page,
|
||||
' ',
|
||||
description ? theme.style.description(description) : '',
|
||||
errorMsg ? theme.style.error(errorMsg) : '',
|
||||
helpLine,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
.trimEnd();
|
||||
return `${lines}${cursorHide}`;
|
||||
});
|
||||
export { Separator } from '@inquirer/core';
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"name": "@inquirer/checkbox",
|
||||
"version": "5.0.4",
|
||||
"description": "Inquirer checkbox prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/checkbox/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/ansi": "^2.0.3",
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/figures": "^2.0.3",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# `@inquirer/confirm`
|
||||
|
||||
Simple interactive command line prompt to gather boolean input from users.
|
||||
|
||||

|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/confirm
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/confirm
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { confirm } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import confirm from '@inquirer/confirm';
|
||||
|
||||
const answer = await confirm({ message: 'Continue?' });
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| ----------- | ----------------------- | -------- | ------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| default | `boolean` | no | Default answer (true or false) |
|
||||
| transformer | `(boolean) => string` | no | Transform the prompt printed message to a custom string |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type ConfirmConfig = {
|
||||
message: string;
|
||||
default?: boolean;
|
||||
transformer?: (value: boolean) => string;
|
||||
theme?: PartialDeep<Theme>;
|
||||
};
|
||||
declare const _default: import("@inquirer/type").Prompt<boolean, ConfirmConfig>;
|
||||
export default _default;
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { createPrompt, useState, useKeypress, isEnterKey, isTabKey, usePrefix, makeTheme, } from '@inquirer/core';
|
||||
function getBooleanValue(value, defaultValue) {
|
||||
let answer = defaultValue !== false;
|
||||
if (/^(y|yes)/i.test(value))
|
||||
answer = true;
|
||||
else if (/^(n|no)/i.test(value))
|
||||
answer = false;
|
||||
return answer;
|
||||
}
|
||||
function boolToString(value) {
|
||||
return value ? 'Yes' : 'No';
|
||||
}
|
||||
export default createPrompt((config, done) => {
|
||||
const { transformer = boolToString } = config;
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [value, setValue] = useState('');
|
||||
const theme = makeTheme(config.theme);
|
||||
const prefix = usePrefix({ status, theme });
|
||||
useKeypress((key, rl) => {
|
||||
if (status !== 'idle')
|
||||
return;
|
||||
if (isEnterKey(key)) {
|
||||
const answer = getBooleanValue(value, config.default);
|
||||
setValue(transformer(answer));
|
||||
setStatus('done');
|
||||
done(answer);
|
||||
}
|
||||
else if (isTabKey(key)) {
|
||||
const answer = boolToString(!getBooleanValue(value, config.default));
|
||||
rl.clearLine(0); // Remove the tab character.
|
||||
rl.write(answer);
|
||||
setValue(answer);
|
||||
}
|
||||
else {
|
||||
setValue(rl.line);
|
||||
}
|
||||
});
|
||||
let formattedValue = value;
|
||||
let defaultValue = '';
|
||||
if (status === 'done') {
|
||||
formattedValue = theme.style.answer(value);
|
||||
}
|
||||
else {
|
||||
defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`;
|
||||
}
|
||||
const message = theme.style.message(config.message, status);
|
||||
return `${prefix} ${message}${defaultValue} ${formattedValue}`;
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@inquirer/confirm",
|
||||
"version": "6.0.4",
|
||||
"description": "Inquirer confirm prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/confirm/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
# `@inquirer/core`
|
||||
|
||||
The `@inquirer/core` package is the library enabling the creation of Inquirer prompts.
|
||||
|
||||
It aims to implements a lightweight API similar to React hooks - but without JSX.
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/core
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/core
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
## Basic concept
|
||||
|
||||
Visual terminal apps are at their core strings rendered onto the terminal.
|
||||
|
||||
The most basic prompt is a function returning a string that'll be rendered in the terminal. This function will run every time the prompt state change, and the new returned string will replace the previously rendered one. The prompt cursor appears after the string.
|
||||
|
||||
Wrapping the rendering function with `createPrompt()` will setup the rendering layer, inject the state management utilities, and wait until the `done` callback is called.
|
||||
|
||||
```ts
|
||||
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 */
|
||||
});
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
State management and user interactions are handled through hooks. Hooks are common [within the React ecosystem](https://react.dev/reference/react/hooks), and Inquirer reimplement the common ones.
|
||||
|
||||
### State hook
|
||||
|
||||
State lets a component “remember” information like user input. For example, an input prompt can use state to store the input value, while a list prompt can use state to track the cursor index.
|
||||
|
||||
`useState` declares a state variable that you can update directly.
|
||||
|
||||
```ts
|
||||
import { createPrompt, useState } from '@inquirer/core';
|
||||
|
||||
const input = createPrompt((config, done) => {
|
||||
const [index, setIndex] = useState(0);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
### Keypress hook
|
||||
|
||||
Almost all prompts need to react to user actions. In a terminal, this is done through typing.
|
||||
|
||||
`useKeypress` allows you to react to keypress events, and access the prompt line.
|
||||
|
||||
```ts
|
||||
const input = createPrompt((config, done) => {
|
||||
useKeypress((key) => {
|
||||
if (key.name === 'enter') {
|
||||
done(answer);
|
||||
}
|
||||
});
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
Behind the scenes, Inquirer prompts are wrappers around [readlines](https://nodejs.org/api/readline.html). Aside the keypress event object, the hook also pass the active readline instance to the event handler.
|
||||
|
||||
```ts
|
||||
const input = createPrompt((config, done) => {
|
||||
useKeypress((key, readline) => {
|
||||
setValue(readline.line);
|
||||
});
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
### Ref hook
|
||||
|
||||
Refs let a prompt hold some information that isn’t used for rendering, like a class instance or a timeout ID. Unlike with state, updating a ref does not re-render your prompt. Refs are an “escape hatch” from the rendering paradigm.
|
||||
|
||||
`useRef` declares a ref. You can hold any value in it, but most often it’s used to hold a timeout ID.
|
||||
|
||||
```ts
|
||||
const input = createPrompt((config, done) => {
|
||||
const timeout = useRef(null);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
### Effect Hook
|
||||
|
||||
Effects let a prompt connect to and synchronize with external systems. This includes dealing with network or animations.
|
||||
|
||||
`useEffect` connects a component to an external system.
|
||||
|
||||
```ts
|
||||
const chat = createPrompt((config, done) => {
|
||||
useEffect(() => {
|
||||
const connection = createConnection(roomId);
|
||||
connection.connect();
|
||||
return () => connection.disconnect();
|
||||
}, [roomId]);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
### Performance hook
|
||||
|
||||
A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell Inquirer to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
|
||||
|
||||
`useMemo` lets you cache the result of an expensive calculation.
|
||||
|
||||
```ts
|
||||
const todoSelect = createPrompt((config, done) => {
|
||||
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
### Rendering hooks
|
||||
|
||||
#### Prefix / loading
|
||||
|
||||
All default prompts, and most custom ones, uses a prefix at the beginning of the prompt line. This helps visually delineate different questions, and provides a convenient area to render a loading spinner.
|
||||
|
||||
`usePrefix` is a built-in hook to do this.
|
||||
|
||||
```ts
|
||||
const input = createPrompt((config, done) => {
|
||||
const prefix = usePrefix({ status });
|
||||
|
||||
return `${prefix} My question`;
|
||||
});
|
||||
```
|
||||
|
||||
#### Pagination
|
||||
|
||||
When looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompts to cycle through the list of options.
|
||||
|
||||
Pagination works by taking in the list of options and returning a subset of the rendered items that fit within the page. The hook takes in a few options. It needs a list of options (`items`), and a `pageSize` which is the number of lines to be rendered. The `active` index is the index of the currently selected/selectable item. The `loop` option is a boolean that indicates if the list should loop around when reaching the end: this is the default behavior. The pagination hook renders items only as necessary, so it takes a function that can render an item at an index, including an `active` state, called `renderItem`.
|
||||
|
||||
```js
|
||||
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}`;
|
||||
});
|
||||
```
|
||||
|
||||
## `createPrompt()` API
|
||||
|
||||
As we saw earlier, the rendering function should return a string, and eventually call `done` to close the prompt and return the answer.
|
||||
|
||||
```ts
|
||||
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}`;
|
||||
});
|
||||
```
|
||||
|
||||
The rendering function can also return a tuple of 2 string (`[string, string]`.) The first string represents the prompt. The second one is content to render under the prompt, like an error message. The text input cursor will appear after the first string.
|
||||
|
||||
```ts
|
||||
const number = createPrompt((config, done) => {
|
||||
// Add some logic here
|
||||
|
||||
return [`? My question ${input}`, `! The input must be a number`];
|
||||
});
|
||||
```
|
||||
|
||||
### Typescript
|
||||
|
||||
If using typescript, `createPrompt` takes 2 generic arguments.
|
||||
|
||||
```ts
|
||||
// createPrompt<Value, Config>
|
||||
const input = createPrompt<string, { message: string }>(// ...
|
||||
```
|
||||
|
||||
The first one is the type of the resolved value
|
||||
|
||||
```ts
|
||||
const answer: string = await input();
|
||||
```
|
||||
|
||||
The second one is the type of the prompt config; in other words the interface the created prompt will provide to users.
|
||||
|
||||
```ts
|
||||
const answer = await input({
|
||||
message: 'My question',
|
||||
});
|
||||
```
|
||||
|
||||
## Key utilities
|
||||
|
||||
Listening for keypress events inside an inquirer prompt is a very common pattern. To ease this, we export a few utility functions taking in the keypress event object and return a boolean:
|
||||
|
||||
- `isEnterKey()`
|
||||
- `isBackspaceKey()`
|
||||
- `isSpaceKey()`
|
||||
- `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`)
|
||||
- `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`)
|
||||
- `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
|
||||
|
||||
## Theming
|
||||
|
||||
Theming utilities will allow you to expose customization of the prompt style. Inquirer also has a few standard theme values shared across all the official prompts.
|
||||
|
||||
To allow standard customization:
|
||||
|
||||
```ts
|
||||
import { createPrompt, usePrefix, makeTheme, type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
|
||||
type PromptConfig = {
|
||||
theme?: PartialDeep<Theme>;
|
||||
};
|
||||
|
||||
export default createPrompt<string, PromptConfig>((config, done) => {
|
||||
const theme = makeTheme(config.theme);
|
||||
|
||||
const prefix = usePrefix({ status, theme });
|
||||
|
||||
return `${prefix} ${theme.style.highlight('hello')}`;
|
||||
});
|
||||
```
|
||||
|
||||
To setup a custom theme:
|
||||
|
||||
```ts
|
||||
import { createPrompt, makeTheme, type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
|
||||
type PromptTheme = {};
|
||||
|
||||
const promptTheme: PromptTheme = {
|
||||
icon: '!',
|
||||
};
|
||||
|
||||
type PromptConfig = {
|
||||
theme?: PartialDeep<Theme<PromptTheme>>;
|
||||
};
|
||||
|
||||
export default createPrompt<string, PromptConfig>((config, done) => {
|
||||
const theme = makeTheme(promptTheme, config.theme);
|
||||
|
||||
const prefix = usePrefix({ status, theme });
|
||||
|
||||
return `${prefix} ${theme.icon}`;
|
||||
});
|
||||
```
|
||||
|
||||
The [default theme keys cover](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/src/lib/theme.ts):
|
||||
|
||||
```ts
|
||||
type DefaultTheme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
help: (text: string) => string;
|
||||
highlight: (text: string) => string;
|
||||
key: (text: string) => string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
You can refer to any `@inquirer/prompts` prompts for real examples:
|
||||
|
||||
- [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/confirm/src/index.ts)
|
||||
- [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/input/src/index.ts)
|
||||
- [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/password/src/index.ts)
|
||||
- [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/editor/src/index.ts)
|
||||
- [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/select/src/index.ts)
|
||||
- [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/checkbox/src/index.ts)
|
||||
- [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/rawlist/src/index.ts)
|
||||
- [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/expand/src/index.ts)
|
||||
|
||||
```ts
|
||||
import { styleText } from 'node:util';
|
||||
import {
|
||||
createPrompt,
|
||||
useState,
|
||||
useKeypress,
|
||||
isEnterKey,
|
||||
usePrefix,
|
||||
type Status,
|
||||
} from '@inquirer/core';
|
||||
|
||||
const confirm = createPrompt<boolean, { message: string; default?: boolean }>(
|
||||
(config, done) => {
|
||||
const [status, setStatus] = useState<Status>('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?' });
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, type KeypressEvent, type Keybinding, } from './lib/key.ts';
|
||||
export * from './lib/errors.ts';
|
||||
export { usePrefix } from './lib/use-prefix.ts';
|
||||
export { useState } from './lib/use-state.ts';
|
||||
export { useEffect } from './lib/use-effect.ts';
|
||||
export { useMemo } from './lib/use-memo.ts';
|
||||
export { useRef } from './lib/use-ref.ts';
|
||||
export { useKeypress } from './lib/use-keypress.ts';
|
||||
export { makeTheme } from './lib/make-theme.ts';
|
||||
export type { Theme, Status } from './lib/theme.ts';
|
||||
export { usePagination } from './lib/pagination/use-pagination.ts';
|
||||
export { createPrompt } from './lib/create-prompt.ts';
|
||||
export { Separator } from './lib/Separator.ts';
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, } from "./lib/key.js";
|
||||
export * from "./lib/errors.js";
|
||||
export { usePrefix } from "./lib/use-prefix.js";
|
||||
export { useState } from "./lib/use-state.js";
|
||||
export { useEffect } from "./lib/use-effect.js";
|
||||
export { useMemo } from "./lib/use-memo.js";
|
||||
export { useRef } from "./lib/use-ref.js";
|
||||
export { useKeypress } from "./lib/use-keypress.js";
|
||||
export { makeTheme } from "./lib/make-theme.js";
|
||||
export { usePagination } from "./lib/pagination/use-pagination.js";
|
||||
export { createPrompt } from "./lib/create-prompt.js";
|
||||
export { Separator } from "./lib/Separator.js";
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Separator object
|
||||
* Used to space/separate choices group
|
||||
*/
|
||||
export declare class Separator {
|
||||
readonly separator: string;
|
||||
readonly type: string;
|
||||
constructor(separator?: string);
|
||||
static isSeparator(choice: unknown): choice is Separator;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { styleText } from 'node:util';
|
||||
import figures from '@inquirer/figures';
|
||||
/**
|
||||
* Separator object
|
||||
* Used to space/separate choices group
|
||||
*/
|
||||
export class Separator {
|
||||
separator = styleText('dim', Array.from({ length: 15 }).join(figures.line));
|
||||
type = 'separator';
|
||||
constructor(separator) {
|
||||
if (separator) {
|
||||
this.separator = separator;
|
||||
}
|
||||
}
|
||||
static isSeparator(choice) {
|
||||
return Boolean(choice &&
|
||||
typeof choice === 'object' &&
|
||||
'type' in choice &&
|
||||
choice.type === 'separator');
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { type Prompt, type Prettify } from '@inquirer/type';
|
||||
type ViewFunction<Value, Config> = (config: Prettify<Config>, done: (value: Value) => void) => string | [string, string | undefined];
|
||||
export declare function createPrompt<Value, Config>(view: ViewFunction<Value, Config>): Prompt<Value, Config>;
|
||||
export {};
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import * as readline from 'node:readline';
|
||||
import { AsyncResource } from 'node:async_hooks';
|
||||
import MuteStream from 'mute-stream';
|
||||
import { onExit as onSignalExit } from 'signal-exit';
|
||||
import ScreenManager from "./screen-manager.js";
|
||||
import { PromisePolyfill } from "./promise-polyfill.js";
|
||||
import { withHooks, effectScheduler } from "./hook-engine.js";
|
||||
import { AbortPromptError, CancelPromptError, ExitPromptError } from "./errors.js";
|
||||
function getCallSites() {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
const _prepareStackTrace = Error.prepareStackTrace;
|
||||
let result = [];
|
||||
try {
|
||||
Error.prepareStackTrace = (_, callSites) => {
|
||||
const callSitesWithoutCurrent = callSites.slice(1);
|
||||
result = callSitesWithoutCurrent;
|
||||
return callSitesWithoutCurrent;
|
||||
};
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
new Error().stack;
|
||||
}
|
||||
catch {
|
||||
// An error will occur if the Node flag --frozen-intrinsics is used.
|
||||
// https://nodejs.org/api/cli.html#--frozen-intrinsics
|
||||
return result;
|
||||
}
|
||||
Error.prepareStackTrace = _prepareStackTrace;
|
||||
return result;
|
||||
}
|
||||
export function createPrompt(view) {
|
||||
const callSites = getCallSites();
|
||||
const prompt = (config, context = {}) => {
|
||||
// Default `input` to stdin
|
||||
const { input = process.stdin, signal } = context;
|
||||
const cleanups = new Set();
|
||||
// Add mute capabilities to the output
|
||||
const output = new MuteStream();
|
||||
output.pipe(context.output ?? process.stdout);
|
||||
const rl = readline.createInterface({
|
||||
terminal: true,
|
||||
input,
|
||||
output,
|
||||
});
|
||||
const screen = new ScreenManager(rl);
|
||||
const { promise, resolve, reject } = PromisePolyfill.withResolver();
|
||||
const cancel = () => reject(new CancelPromptError());
|
||||
if (signal) {
|
||||
const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
|
||||
if (signal.aborted) {
|
||||
abort();
|
||||
return Object.assign(promise, { cancel });
|
||||
}
|
||||
signal.addEventListener('abort', abort);
|
||||
cleanups.add(() => signal.removeEventListener('abort', abort));
|
||||
}
|
||||
cleanups.add(onSignalExit((code, signal) => {
|
||||
reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
|
||||
}));
|
||||
// SIGINT must be explicitly handled by the prompt so the ExitPromptError can be handled.
|
||||
// Otherwise, the prompt will stop and in some scenarios never resolve.
|
||||
// Ref issue #1741
|
||||
const sigint = () => reject(new ExitPromptError(`User force closed the prompt with SIGINT`));
|
||||
rl.on('SIGINT', sigint);
|
||||
cleanups.add(() => rl.removeListener('SIGINT', sigint));
|
||||
// Re-renders only happen when the state change; but the readline cursor could change position
|
||||
// and that also requires a re-render (and a manual one because we mute the streams).
|
||||
// We set the listener after the initial workLoop to avoid a double render if render triggered
|
||||
// by a state change sets the cursor to the right position.
|
||||
const checkCursorPos = () => screen.checkCursorPos();
|
||||
rl.input.on('keypress', checkCursorPos);
|
||||
cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
|
||||
return withHooks(rl, (cycle) => {
|
||||
// The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
|
||||
// triggers after the process is done (which happens after timeouts are done triggering.)
|
||||
// We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
|
||||
const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());
|
||||
rl.on('close', hooksCleanup);
|
||||
cleanups.add(() => rl.removeListener('close', hooksCleanup));
|
||||
cycle(() => {
|
||||
try {
|
||||
const nextView = view(config, (value) => {
|
||||
setImmediate(() => resolve(value));
|
||||
});
|
||||
// Typescript won't allow this, but not all users rely on typescript.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (nextView === undefined) {
|
||||
const callerFilename = callSites[1]?.getFileName();
|
||||
throw new Error(`Prompt functions must return a string.\n at ${callerFilename}`);
|
||||
}
|
||||
const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
|
||||
screen.render(content, bottomContent);
|
||||
effectScheduler.run();
|
||||
}
|
||||
catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
return Object.assign(promise
|
||||
.then((answer) => {
|
||||
effectScheduler.clearAll();
|
||||
return answer;
|
||||
}, (error) => {
|
||||
effectScheduler.clearAll();
|
||||
throw error;
|
||||
})
|
||||
// Wait for the promise to settle, then cleanup.
|
||||
.finally(() => {
|
||||
cleanups.forEach((cleanup) => cleanup());
|
||||
screen.done({ clearContent: Boolean(context.clearPromptOnDone) });
|
||||
output.end();
|
||||
})
|
||||
// Once cleanup is done, let the expose promise resolve/reject to the internal one.
|
||||
.then(() => promise), { cancel });
|
||||
});
|
||||
};
|
||||
return prompt;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
export declare class AbortPromptError extends Error {
|
||||
name: string;
|
||||
message: string;
|
||||
constructor(options?: {
|
||||
cause?: unknown;
|
||||
});
|
||||
}
|
||||
export declare class CancelPromptError extends Error {
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
export declare class ExitPromptError extends Error {
|
||||
name: string;
|
||||
}
|
||||
export declare class HookError extends Error {
|
||||
name: string;
|
||||
}
|
||||
export declare class ValidationError extends Error {
|
||||
name: string;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
export class AbortPromptError extends Error {
|
||||
name = 'AbortPromptError';
|
||||
message = 'Prompt was aborted';
|
||||
constructor(options) {
|
||||
super();
|
||||
this.cause = options?.cause;
|
||||
}
|
||||
}
|
||||
export class CancelPromptError extends Error {
|
||||
name = 'CancelPromptError';
|
||||
message = 'Prompt was canceled';
|
||||
}
|
||||
export class ExitPromptError extends Error {
|
||||
name = 'ExitPromptError';
|
||||
}
|
||||
export class HookError extends Error {
|
||||
name = 'HookError';
|
||||
}
|
||||
export class ValidationError extends Error {
|
||||
name = 'ValidationError';
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import type { InquirerReadline } from '@inquirer/type';
|
||||
export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
|
||||
export declare function readline(): InquirerReadline;
|
||||
export declare function withUpdates<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R;
|
||||
type SetPointer<Value> = {
|
||||
get(): Value;
|
||||
set(value: Value): void;
|
||||
initialized: true;
|
||||
};
|
||||
type UnsetPointer<Value> = {
|
||||
get(): void;
|
||||
set(value: Value): void;
|
||||
initialized: false;
|
||||
};
|
||||
type Pointer<Value> = SetPointer<Value> | UnsetPointer<Value>;
|
||||
export declare function withPointer<Value, ReturnValue>(cb: (pointer: Pointer<Value>) => ReturnValue): ReturnValue;
|
||||
export declare function handleChange(): void;
|
||||
export declare const effectScheduler: {
|
||||
queue(cb: (readline: InquirerReadline) => void | (() => void)): void;
|
||||
run(): void;
|
||||
clearAll(): void;
|
||||
};
|
||||
export {};
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/* eslint @typescript-eslint/no-explicit-any: ["off"] */
|
||||
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
|
||||
import { HookError, ValidationError } from "./errors.js";
|
||||
const hookStorage = new AsyncLocalStorage();
|
||||
function createStore(rl) {
|
||||
const store = {
|
||||
rl,
|
||||
hooks: [],
|
||||
hooksCleanup: [],
|
||||
hooksEffect: [],
|
||||
index: 0,
|
||||
handleChange() { },
|
||||
};
|
||||
return store;
|
||||
}
|
||||
// Run callback in with the hook engine setup.
|
||||
export function withHooks(rl, cb) {
|
||||
const store = createStore(rl);
|
||||
return hookStorage.run(store, () => {
|
||||
function cycle(render) {
|
||||
store.handleChange = () => {
|
||||
store.index = 0;
|
||||
render();
|
||||
};
|
||||
store.handleChange();
|
||||
}
|
||||
return cb(cycle);
|
||||
});
|
||||
}
|
||||
// Safe getStore utility that'll return the store or throw if undefined.
|
||||
function getStore() {
|
||||
const store = hookStorage.getStore();
|
||||
if (!store) {
|
||||
throw new HookError('[Inquirer] Hook functions can only be called from within a prompt');
|
||||
}
|
||||
return store;
|
||||
}
|
||||
export function readline() {
|
||||
return getStore().rl;
|
||||
}
|
||||
// Merge state updates happening within the callback function to avoid multiple renders.
|
||||
export function withUpdates(fn) {
|
||||
const wrapped = (...args) => {
|
||||
const store = getStore();
|
||||
let shouldUpdate = false;
|
||||
const oldHandleChange = store.handleChange;
|
||||
store.handleChange = () => {
|
||||
shouldUpdate = true;
|
||||
};
|
||||
const returnValue = fn(...args);
|
||||
if (shouldUpdate) {
|
||||
oldHandleChange();
|
||||
}
|
||||
store.handleChange = oldHandleChange;
|
||||
return returnValue;
|
||||
};
|
||||
return AsyncResource.bind(wrapped);
|
||||
}
|
||||
export function withPointer(cb) {
|
||||
const store = getStore();
|
||||
const { index } = store;
|
||||
const pointer = {
|
||||
get() {
|
||||
return store.hooks[index];
|
||||
},
|
||||
set(value) {
|
||||
store.hooks[index] = value;
|
||||
},
|
||||
initialized: index in store.hooks,
|
||||
};
|
||||
const returnValue = cb(pointer);
|
||||
store.index++;
|
||||
return returnValue;
|
||||
}
|
||||
export function handleChange() {
|
||||
getStore().handleChange();
|
||||
}
|
||||
export const effectScheduler = {
|
||||
queue(cb) {
|
||||
const store = getStore();
|
||||
const { index } = store;
|
||||
store.hooksEffect.push(() => {
|
||||
store.hooksCleanup[index]?.();
|
||||
const cleanFn = cb(readline());
|
||||
if (cleanFn != null && typeof cleanFn !== 'function') {
|
||||
throw new ValidationError('useEffect return value must be a cleanup function or nothing.');
|
||||
}
|
||||
store.hooksCleanup[index] = cleanFn;
|
||||
});
|
||||
},
|
||||
run() {
|
||||
const store = getStore();
|
||||
withUpdates(() => {
|
||||
store.hooksEffect.forEach((effect) => {
|
||||
effect();
|
||||
});
|
||||
// Warning: Clean the hooks before exiting the `withUpdates` block.
|
||||
// Failure to do so means an updates would hit the same effects again.
|
||||
store.hooksEffect.length = 0;
|
||||
})();
|
||||
},
|
||||
clearAll() {
|
||||
const store = getStore();
|
||||
store.hooksCleanup.forEach((cleanFn) => {
|
||||
cleanFn?.();
|
||||
});
|
||||
store.hooksEffect.length = 0;
|
||||
store.hooksCleanup.length = 0;
|
||||
},
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
export type KeypressEvent = {
|
||||
name: string;
|
||||
ctrl: boolean;
|
||||
shift: boolean;
|
||||
};
|
||||
export type Keybinding = 'emacs' | 'vim';
|
||||
export declare const isUpKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
|
||||
export declare const isDownKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
|
||||
export declare const isSpaceKey: (key: KeypressEvent) => boolean;
|
||||
export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
|
||||
export declare const isTabKey: (key: KeypressEvent) => boolean;
|
||||
export declare const isNumberKey: (key: KeypressEvent) => boolean;
|
||||
export declare const isEnterKey: (key: KeypressEvent) => boolean;
|
||||
export declare const isShiftKey: (key: KeypressEvent) => boolean;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
export const isUpKey = (key, keybindings = []) =>
|
||||
// The up key
|
||||
key.name === 'up' ||
|
||||
// Vim keybinding: hjkl keys map to left/down/up/right
|
||||
(keybindings.includes('vim') && key.name === 'k') ||
|
||||
// Emacs keybinding: Ctrl+P means "previous" in Emacs navigation conventions
|
||||
(keybindings.includes('emacs') && key.ctrl && key.name === 'p');
|
||||
export const isDownKey = (key, keybindings = []) =>
|
||||
// The down key
|
||||
key.name === 'down' ||
|
||||
// Vim keybinding: hjkl keys map to left/down/up/right
|
||||
(keybindings.includes('vim') && key.name === 'j') ||
|
||||
// Emacs keybinding: Ctrl+N means "next" in Emacs navigation conventions
|
||||
(keybindings.includes('emacs') && key.ctrl && key.name === 'n');
|
||||
export const isSpaceKey = (key) => key.name === 'space';
|
||||
export const isBackspaceKey = (key) => key.name === 'backspace';
|
||||
export const isTabKey = (key) => key.name === 'tab';
|
||||
export const isNumberKey = (key) => '1234567890'.includes(key.name);
|
||||
export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return';
|
||||
export const isShiftKey = (key) => key.shift;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Prettify, PartialDeep } from '@inquirer/type';
|
||||
import { type Theme } from './theme.ts';
|
||||
export declare function makeTheme<SpecificTheme extends object>(...themes: ReadonlyArray<undefined | PartialDeep<Theme<SpecificTheme>>>): Prettify<Theme<SpecificTheme>>;
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { defaultTheme } from "./theme.js";
|
||||
function isPlainObject(value) {
|
||||
if (typeof value !== 'object' || value === null)
|
||||
return false;
|
||||
let proto = value;
|
||||
while (Object.getPrototypeOf(proto) !== null) {
|
||||
proto = Object.getPrototypeOf(proto);
|
||||
}
|
||||
return Object.getPrototypeOf(value) === proto;
|
||||
}
|
||||
function deepMerge(...objects) {
|
||||
const output = {};
|
||||
for (const obj of objects) {
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const prevValue = output[key];
|
||||
output[key] =
|
||||
isPlainObject(prevValue) && isPlainObject(value)
|
||||
? deepMerge(prevValue, value)
|
||||
: value;
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
export function makeTheme(...themes) {
|
||||
const themesToMerge = [
|
||||
defaultTheme,
|
||||
...themes.filter((theme) => theme != null),
|
||||
];
|
||||
return deepMerge(...themesToMerge);
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { Prettify } from '@inquirer/type';
|
||||
export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
|
||||
items: ReadonlyArray<T>;
|
||||
/** The index of the active item. */
|
||||
active: number;
|
||||
/** Renders an item as part of a page. */
|
||||
renderItem: (layout: Prettify<{
|
||||
item: T;
|
||||
index: number;
|
||||
isActive: boolean;
|
||||
}>) => string;
|
||||
/** The size of the page. */
|
||||
pageSize: number;
|
||||
/** Allows creating an infinitely looping list. `true` if unspecified. */
|
||||
loop?: boolean;
|
||||
}): string;
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import { useRef } from "../use-ref.js";
|
||||
import { readlineWidth, breakLines } from "../utils.js";
|
||||
function usePointerPosition({ active, renderedItems, pageSize, loop, }) {
|
||||
const state = useRef({
|
||||
lastPointer: active,
|
||||
lastActive: undefined,
|
||||
});
|
||||
const { lastPointer, lastActive } = state.current;
|
||||
const middle = Math.floor(pageSize / 2);
|
||||
const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
|
||||
const defaultPointerPosition = renderedItems
|
||||
.slice(0, active)
|
||||
.reduce((acc, item) => acc + item.length, 0);
|
||||
let pointer = defaultPointerPosition;
|
||||
if (renderedLength > pageSize) {
|
||||
if (loop) {
|
||||
/**
|
||||
* Creates the next position for the pointer considering an infinitely
|
||||
* looping list of items to be rendered on the page.
|
||||
*
|
||||
* The goal is to progressively move the cursor to the middle position as the user move down, and then keep
|
||||
* the cursor there. When the user move up, maintain the cursor position.
|
||||
*/
|
||||
// By default, keep the cursor position as-is.
|
||||
pointer = lastPointer;
|
||||
if (
|
||||
// First render, skip this logic.
|
||||
lastActive != null &&
|
||||
// Only move the pointer down when the user moves down.
|
||||
lastActive < active &&
|
||||
// Check user didn't move up across page boundary.
|
||||
active - lastActive < pageSize) {
|
||||
pointer = Math.min(
|
||||
// Furthest allowed position for the pointer is the middle of the list
|
||||
middle, Math.abs(active - lastActive) === 1
|
||||
? Math.min(
|
||||
// Move the pointer at most the height of the last active item.
|
||||
lastPointer + (renderedItems[lastActive]?.length ?? 0),
|
||||
// If the user moved by one item, move the pointer to the natural position of the active item as
|
||||
// long as it doesn't move the cursor up.
|
||||
Math.max(defaultPointerPosition, lastPointer))
|
||||
: // Otherwise, move the pointer down by the difference between the active and last active item.
|
||||
lastPointer + active - lastActive);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Creates the next position for the pointer considering a finite list of
|
||||
* items to be rendered on a page.
|
||||
*
|
||||
* The goal is to keep the pointer in the middle of the page whenever possible, until
|
||||
* we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively
|
||||
* to the bottom or top of the list.
|
||||
*/
|
||||
const spaceUnderActive = renderedItems
|
||||
.slice(active)
|
||||
.reduce((acc, item) => acc + item.length, 0);
|
||||
pointer =
|
||||
spaceUnderActive < pageSize - middle
|
||||
? // If the active item is near the end of the list, progressively move the cursor towards the end.
|
||||
pageSize - spaceUnderActive
|
||||
: // Otherwise, progressively move the pointer to the middle of the list.
|
||||
Math.min(defaultPointerPosition, middle);
|
||||
}
|
||||
}
|
||||
// Save state for the next render
|
||||
state.current.lastPointer = pointer;
|
||||
state.current.lastActive = active;
|
||||
return pointer;
|
||||
}
|
||||
export function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
|
||||
const width = readlineWidth();
|
||||
const bound = (num) => ((num % items.length) + items.length) % items.length;
|
||||
const renderedItems = items.map((item, index) => {
|
||||
if (item == null)
|
||||
return [];
|
||||
return breakLines(renderItem({ item, index, isActive: index === active }), width).split('\n');
|
||||
});
|
||||
const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
|
||||
const renderItemAtIndex = (index) => renderedItems[index] ?? [];
|
||||
const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });
|
||||
// Render the active item to decide the position.
|
||||
// If the active item fits under the pointer, we render it there.
|
||||
// Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.
|
||||
const activeItem = renderItemAtIndex(active).slice(0, pageSize);
|
||||
const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;
|
||||
// Create an array of lines for the page, and add the lines of the active item into the page
|
||||
const pageBuffer = Array.from({ length: pageSize });
|
||||
pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);
|
||||
// Store to prevent rendering the same item twice
|
||||
const itemVisited = new Set([active]);
|
||||
// Fill the page under the active item
|
||||
let bufferPointer = activeItemPosition + activeItem.length;
|
||||
let itemPointer = bound(active + 1);
|
||||
while (bufferPointer < pageSize &&
|
||||
!itemVisited.has(itemPointer) &&
|
||||
(loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {
|
||||
const lines = renderItemAtIndex(itemPointer);
|
||||
const linesToAdd = lines.slice(0, pageSize - bufferPointer);
|
||||
pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);
|
||||
// Move pointers for next iteration
|
||||
itemVisited.add(itemPointer);
|
||||
bufferPointer += linesToAdd.length;
|
||||
itemPointer = bound(itemPointer + 1);
|
||||
}
|
||||
// Fill the page over the active item
|
||||
bufferPointer = activeItemPosition - 1;
|
||||
itemPointer = bound(active - 1);
|
||||
while (bufferPointer >= 0 &&
|
||||
!itemVisited.has(itemPointer) &&
|
||||
(loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {
|
||||
const lines = renderItemAtIndex(itemPointer);
|
||||
const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));
|
||||
pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);
|
||||
// Move pointers for next iteration
|
||||
itemVisited.add(itemPointer);
|
||||
bufferPointer -= linesToAdd.length;
|
||||
itemPointer = bound(itemPointer - 1);
|
||||
}
|
||||
return pageBuffer.filter((line) => typeof line === 'string').join('\n');
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
export declare class PromisePolyfill<T> extends Promise<T> {
|
||||
static withResolver<T>(): {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
};
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
// TODO: Remove this class once Node 22 becomes the minimum supported version.
|
||||
export class PromisePolyfill extends Promise {
|
||||
// Available starting from Node 22
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
|
||||
static withResolver() {
|
||||
let resolve;
|
||||
let reject;
|
||||
const promise = new Promise((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve: resolve, reject: reject };
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import type { InquirerReadline } from '@inquirer/type';
|
||||
export default class ScreenManager {
|
||||
private height;
|
||||
private extraLinesUnderPrompt;
|
||||
private cursorPos;
|
||||
private readonly rl;
|
||||
constructor(rl: InquirerReadline);
|
||||
write(content: string): void;
|
||||
render(content: string, bottomContent?: string): void;
|
||||
checkCursorPos(): void;
|
||||
done({ clearContent }: {
|
||||
clearContent: boolean;
|
||||
}): void;
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import { stripVTControlCharacters } from 'node:util';
|
||||
import { breakLines, readlineWidth } from "./utils.js";
|
||||
import { cursorDown, cursorUp, cursorTo, cursorShow, eraseLines } from '@inquirer/ansi';
|
||||
const height = (content) => content.split('\n').length;
|
||||
const lastLine = (content) => content.split('\n').pop() ?? '';
|
||||
export default class ScreenManager {
|
||||
// These variables are keeping information to allow correct prompt re-rendering
|
||||
height = 0;
|
||||
extraLinesUnderPrompt = 0;
|
||||
cursorPos;
|
||||
rl;
|
||||
constructor(rl) {
|
||||
this.rl = rl;
|
||||
this.cursorPos = rl.getCursorPos();
|
||||
}
|
||||
write(content) {
|
||||
this.rl.output.unmute();
|
||||
this.rl.output.write(content);
|
||||
this.rl.output.mute();
|
||||
}
|
||||
render(content, bottomContent = '') {
|
||||
// Write message to screen and setPrompt to control backspace
|
||||
const promptLine = lastLine(content);
|
||||
const rawPromptLine = stripVTControlCharacters(promptLine);
|
||||
// Remove the rl.line from our prompt. We can't rely on the content of
|
||||
// rl.line (mainly because of the password prompt), so just rely on it's
|
||||
// length.
|
||||
let prompt = rawPromptLine;
|
||||
if (this.rl.line.length > 0) {
|
||||
prompt = prompt.slice(0, -this.rl.line.length);
|
||||
}
|
||||
this.rl.setPrompt(prompt);
|
||||
// SetPrompt will change cursor position, now we can get correct value
|
||||
this.cursorPos = this.rl.getCursorPos();
|
||||
const width = readlineWidth();
|
||||
content = breakLines(content, width);
|
||||
bottomContent = breakLines(bottomContent, width);
|
||||
// Manually insert an extra line if we're at the end of the line.
|
||||
// This prevent the cursor from appearing at the beginning of the
|
||||
// current line.
|
||||
if (rawPromptLine.length % width === 0) {
|
||||
content += '\n';
|
||||
}
|
||||
let output = content + (bottomContent ? '\n' + bottomContent : '');
|
||||
/**
|
||||
* Re-adjust the cursor at the correct position.
|
||||
*/
|
||||
// We need to consider parts of the prompt under the cursor as part of the bottom
|
||||
// content in order to correctly cleanup and re-render.
|
||||
const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;
|
||||
const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
|
||||
// Return cursor to the input position (on top of the bottomContent)
|
||||
if (bottomContentHeight > 0)
|
||||
output += cursorUp(bottomContentHeight);
|
||||
// Return cursor to the initial left offset.
|
||||
output += cursorTo(this.cursorPos.cols);
|
||||
/**
|
||||
* Render and store state for future re-rendering
|
||||
*/
|
||||
this.write(cursorDown(this.extraLinesUnderPrompt) + eraseLines(this.height) + output);
|
||||
this.extraLinesUnderPrompt = bottomContentHeight;
|
||||
this.height = height(output);
|
||||
}
|
||||
checkCursorPos() {
|
||||
const cursorPos = this.rl.getCursorPos();
|
||||
if (cursorPos.cols !== this.cursorPos.cols) {
|
||||
this.write(cursorTo(cursorPos.cols));
|
||||
this.cursorPos = cursorPos;
|
||||
}
|
||||
}
|
||||
done({ clearContent }) {
|
||||
this.rl.setPrompt('');
|
||||
let output = cursorDown(this.extraLinesUnderPrompt);
|
||||
output += clearContent ? eraseLines(this.height) : '\n';
|
||||
output += cursorShow;
|
||||
this.write(output);
|
||||
this.rl.close();
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import type { Prettify } from '@inquirer/type';
|
||||
/**
|
||||
* Union type representing the possible statuses of a prompt.
|
||||
*
|
||||
* - `'loading'`: The prompt is currently loading.
|
||||
* - `'idle'`: The prompt is loaded and currently waiting for the user to
|
||||
* submit an answer.
|
||||
* - `'done'`: The user has submitted an answer and the prompt is finished.
|
||||
* - `string`: Any other string: The prompt is in a custom state.
|
||||
*/
|
||||
export type Status = 'loading' | 'idle' | 'done' | (string & {});
|
||||
type DefaultTheme = {
|
||||
/**
|
||||
* Prefix to prepend to the message. If a function is provided, it will be
|
||||
* called with the current status of the prompt, and the return value will be
|
||||
* used as the prefix.
|
||||
*
|
||||
* @remarks
|
||||
* If `status === 'loading'`, this property is ignored and the spinner (styled
|
||||
* by the `spinner` property) will be displayed instead.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (status) => status === 'done' ? styleText('green', '✔') : styleText('blue', '?')
|
||||
* ```
|
||||
*/
|
||||
prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
|
||||
/**
|
||||
* Configuration for the spinner that is displayed when the prompt is in the
|
||||
* `'loading'` state.
|
||||
*
|
||||
* We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
|
||||
*/
|
||||
spinner: {
|
||||
/**
|
||||
* The time interval between frames, in milliseconds.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* 80
|
||||
* ```
|
||||
*/
|
||||
interval: number;
|
||||
/**
|
||||
* A list of frames to show for the spinner.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
|
||||
* ```
|
||||
*/
|
||||
frames: string[];
|
||||
};
|
||||
/**
|
||||
* Object containing functions to style different parts of the prompt.
|
||||
*/
|
||||
style: {
|
||||
/**
|
||||
* Style to apply to the user's answer once it has been submitted.
|
||||
*
|
||||
* @param text - The user's answer.
|
||||
* @returns The styled answer.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('cyan', text)
|
||||
* ```
|
||||
*/
|
||||
answer: (text: string) => string;
|
||||
/**
|
||||
* Style to apply to the message displayed to the user.
|
||||
*
|
||||
* @param text - The message to style.
|
||||
* @param status - The current status of the prompt.
|
||||
* @returns The styled message.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text, status) => styleText('bold', text)
|
||||
* ```
|
||||
*/
|
||||
message: (text: string, status: Status) => string;
|
||||
/**
|
||||
* Style to apply to error messages.
|
||||
*
|
||||
* @param text - The error message.
|
||||
* @returns The styled error message.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('red', `> ${text}`)
|
||||
* ```
|
||||
*/
|
||||
error: (text: string) => string;
|
||||
/**
|
||||
* Style to apply to the default answer when one is provided.
|
||||
*
|
||||
* @param text - The default answer.
|
||||
* @returns The styled default answer.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('dim', `(${text})`)
|
||||
* ```
|
||||
*/
|
||||
defaultAnswer: (text: string) => string;
|
||||
/**
|
||||
* Style to apply to help text.
|
||||
*
|
||||
* @param text - The help text.
|
||||
* @returns The styled help text.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('dim', text)
|
||||
* ```
|
||||
*/
|
||||
help: (text: string) => string;
|
||||
/**
|
||||
* Style to apply to highlighted text.
|
||||
*
|
||||
* @param text - The text to highlight.
|
||||
* @returns The highlighted text.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('cyan', text)
|
||||
* ```
|
||||
*/
|
||||
highlight: (text: string) => string;
|
||||
/**
|
||||
* Style to apply to keyboard keys referred to in help texts.
|
||||
*
|
||||
* @param text - The key to style.
|
||||
* @returns The styled key.
|
||||
*
|
||||
* @defaultValue
|
||||
* ```ts
|
||||
* // import { styleText } from 'node:util';
|
||||
* (text) => styleText('cyan', styleText('bold', `<${text}>`))
|
||||
* ```
|
||||
*/
|
||||
key: (text: string) => string;
|
||||
};
|
||||
};
|
||||
export type Theme<Extension extends object = object> = Prettify<Extension & DefaultTheme>;
|
||||
export declare const defaultTheme: DefaultTheme;
|
||||
export {};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { styleText } from 'node:util';
|
||||
import figures from '@inquirer/figures';
|
||||
export const defaultTheme = {
|
||||
prefix: {
|
||||
idle: styleText('blue', '?'),
|
||||
done: styleText('green', figures.tick),
|
||||
},
|
||||
spinner: {
|
||||
interval: 80,
|
||||
frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => styleText('yellow', frame)),
|
||||
},
|
||||
style: {
|
||||
answer: (text) => styleText('cyan', text),
|
||||
message: (text) => styleText('bold', text),
|
||||
error: (text) => styleText('red', `> ${text}`),
|
||||
defaultAnswer: (text) => styleText('dim', `(${text})`),
|
||||
help: (text) => styleText('dim', text),
|
||||
highlight: (text) => styleText('cyan', text),
|
||||
key: (text) => styleText('cyan', styleText('bold', `<${text}>`)),
|
||||
},
|
||||
};
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { InquirerReadline } from '@inquirer/type';
|
||||
export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: ReadonlyArray<unknown>): void;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { withPointer, effectScheduler } from "./hook-engine.js";
|
||||
export function useEffect(cb, depArray) {
|
||||
withPointer((pointer) => {
|
||||
const oldDeps = pointer.get();
|
||||
const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
|
||||
if (hasChanged) {
|
||||
effectScheduler.queue(cb);
|
||||
}
|
||||
pointer.set(depArray);
|
||||
});
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { type InquirerReadline } from '@inquirer/type';
|
||||
import { type KeypressEvent } from './key.ts';
|
||||
export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void | Promise<void>): void;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { useRef } from "./use-ref.js";
|
||||
import { useEffect } from "./use-effect.js";
|
||||
import { withUpdates } from "./hook-engine.js";
|
||||
export function useKeypress(userHandler) {
|
||||
const signal = useRef(userHandler);
|
||||
signal.current = userHandler;
|
||||
useEffect((rl) => {
|
||||
let ignore = false;
|
||||
const handler = withUpdates((_input, event) => {
|
||||
if (ignore)
|
||||
return;
|
||||
void signal.current(event, rl);
|
||||
});
|
||||
rl.input.on('keypress', handler);
|
||||
return () => {
|
||||
ignore = true;
|
||||
rl.input.removeListener('keypress', handler);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function useMemo<Value>(fn: () => Value, dependencies: ReadonlyArray<unknown>): Value;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { withPointer } from "./hook-engine.js";
|
||||
export function useMemo(fn, dependencies) {
|
||||
return withPointer((pointer) => {
|
||||
const prev = pointer.get();
|
||||
if (!prev ||
|
||||
prev.dependencies.length !== dependencies.length ||
|
||||
prev.dependencies.some((dep, i) => dep !== dependencies[i])) {
|
||||
const value = fn();
|
||||
pointer.set({ value, dependencies });
|
||||
return value;
|
||||
}
|
||||
return prev.value;
|
||||
});
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { Theme, Status } from './theme.ts';
|
||||
export declare function usePrefix({ status, theme, }: {
|
||||
status?: Status;
|
||||
theme?: Theme;
|
||||
}): string;
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { useState } from "./use-state.js";
|
||||
import { useEffect } from "./use-effect.js";
|
||||
import { makeTheme } from "./make-theme.js";
|
||||
export function usePrefix({ status = 'idle', theme, }) {
|
||||
const [showLoader, setShowLoader] = useState(false);
|
||||
const [tick, setTick] = useState(0);
|
||||
const { prefix, spinner } = makeTheme(theme);
|
||||
useEffect(() => {
|
||||
if (status === 'loading') {
|
||||
let tickInterval;
|
||||
let inc = -1;
|
||||
// Delay displaying spinner by 300ms, to avoid flickering
|
||||
const delayTimeout = setTimeout(() => {
|
||||
setShowLoader(true);
|
||||
tickInterval = setInterval(() => {
|
||||
inc = inc + 1;
|
||||
setTick(inc % spinner.frames.length);
|
||||
}, spinner.interval);
|
||||
}, 300);
|
||||
return () => {
|
||||
clearTimeout(delayTimeout);
|
||||
clearInterval(tickInterval);
|
||||
};
|
||||
}
|
||||
else {
|
||||
setShowLoader(false);
|
||||
}
|
||||
}, [status]);
|
||||
if (showLoader) {
|
||||
return spinner.frames[tick];
|
||||
}
|
||||
// There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
|
||||
const iconName = status === 'loading' ? 'idle' : status;
|
||||
return typeof prefix === 'string' ? prefix : (prefix[iconName] ?? prefix['idle']);
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
export declare function useRef<Value>(val: Value): {
|
||||
current: Value;
|
||||
};
|
||||
export declare function useRef<Value>(val?: Value): {
|
||||
current: Value | undefined;
|
||||
};
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { useState } from "./use-state.js";
|
||||
export function useRef(val) {
|
||||
return useState({ current: val })[0];
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
|
||||
export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
|
||||
export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
|
||||
export {};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { AsyncResource } from 'node:async_hooks';
|
||||
import { withPointer, handleChange } from "./hook-engine.js";
|
||||
export function useState(defaultValue) {
|
||||
return withPointer((pointer) => {
|
||||
const setState = AsyncResource.bind(function setState(newValue) {
|
||||
// Noop if the value is still the same.
|
||||
if (pointer.get() !== newValue) {
|
||||
pointer.set(newValue);
|
||||
// Trigger re-render
|
||||
handleChange();
|
||||
}
|
||||
});
|
||||
if (pointer.initialized) {
|
||||
return [pointer.get(), setState];
|
||||
}
|
||||
const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
|
||||
pointer.set(value);
|
||||
return [value, setState];
|
||||
});
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Force line returns at specific width. This function is ANSI code friendly and it'll
|
||||
* ignore invisible codes during width calculation.
|
||||
* @param {string} content
|
||||
* @param {number} width
|
||||
* @return {string}
|
||||
*/
|
||||
export declare function breakLines(content: string, width: number): string;
|
||||
/**
|
||||
* Returns the width of the active readline, or 80 as default value.
|
||||
* @returns {number}
|
||||
*/
|
||||
export declare function readlineWidth(): number;
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import cliWidth from 'cli-width';
|
||||
import wrapAnsi from 'wrap-ansi';
|
||||
import { readline } from "./hook-engine.js";
|
||||
/**
|
||||
* Force line returns at specific width. This function is ANSI code friendly and it'll
|
||||
* ignore invisible codes during width calculation.
|
||||
* @param {string} content
|
||||
* @param {number} width
|
||||
* @return {string}
|
||||
*/
|
||||
export function breakLines(content, width) {
|
||||
return content
|
||||
.split('\n')
|
||||
.flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true })
|
||||
.split('\n')
|
||||
.map((str) => str.trimEnd()))
|
||||
.join('\n');
|
||||
}
|
||||
/**
|
||||
* Returns the width of the active readline, or 80 as default value.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function readlineWidth() {
|
||||
return cliWidth({ defaultWidth: 80, output: readline().output });
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"name": "@inquirer/core",
|
||||
"version": "11.1.1",
|
||||
"description": "Core Inquirer prompt API",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/ansi": "^2.0.3",
|
||||
"@inquirer/figures": "^2.0.3",
|
||||
"@inquirer/type": "^4.0.3",
|
||||
"cli-width": "^4.1.0",
|
||||
"mute-stream": "^3.0.0",
|
||||
"signal-exit": "^4.1.0",
|
||||
"wrap-ansi": "^9.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"@types/mute-stream": "^0.0.4",
|
||||
"@types/node": "^25.0.2",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# `@inquirer/editor`
|
||||
|
||||
Prompt that'll open the user preferred editor with default content and allow for a convenient multi-line input controlled through the command line.
|
||||
|
||||
The editor launched is the one [defined by the user's `EDITOR` environment variable](https://dev.to/jonasbn/til-integrate-visual-studio-code-with-shell--cli-2l1l).
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/editor
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/editor
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { editor } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import editor from '@inquirer/editor';
|
||||
|
||||
const answer = await editor({
|
||||
message: 'Enter a description',
|
||||
});
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| ---------------- | ------------------------------------------------------------------------------ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| default | `string` | no | Default value which will automatically be present in the editor |
|
||||
| validate | `string => boolean \| string \| Promise<boolean \| string>` | no | On submit, validate the content. When returning a string, it'll be used as the error message displayed to the user. Note: returning a rejected promise, we'll assume a code error happened and crash. |
|
||||
| postfix | `string` | no (default to `.txt`) | The postfix of the file being edited. Adding this will add color highlighting to the file content in most editors. |
|
||||
| file | [`IFileOptions`](https://github.com/mrkmg/node-external-editor#config-options) | no | Exposes the [`external-editor` package options](https://github.com/mrkmg/node-external-editor#config-options) to configure the temporary file. |
|
||||
| waitForUserInput | `boolean` | no (default to `true`) | Open the editor automatically without waiting for the user to press enter. Note that this mean the user will not see the question! So make sure you have a default value that provide guidance if it's unclear what input is expected. |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```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';
|
||||
};
|
||||
```
|
||||
|
||||
`validationFailureMode` defines the behavior of the prompt when the value submitted is invalid. By default, we'll keep the value allowing the user to edit it. When the theme option is set to `clear`, we'll remove and reset to the default value or empty string.
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { type IFileOptions } from '@inquirer/external-editor';
|
||||
import { type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type EditorTheme = {
|
||||
validationFailureMode: 'keep' | 'clear';
|
||||
};
|
||||
type EditorConfig = {
|
||||
message: string;
|
||||
default?: string;
|
||||
postfix?: string;
|
||||
waitForUserInput?: boolean;
|
||||
validate?: (value: string) => boolean | string | Promise<string | boolean>;
|
||||
file?: IFileOptions;
|
||||
theme?: PartialDeep<Theme<EditorTheme>>;
|
||||
};
|
||||
declare const _default: import("@inquirer/type").Prompt<string, EditorConfig>;
|
||||
export default _default;
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { editAsync } from '@inquirer/external-editor';
|
||||
import { createPrompt, useEffect, useState, useKeypress, usePrefix, isEnterKey, makeTheme, } from '@inquirer/core';
|
||||
const editorTheme = {
|
||||
validationFailureMode: 'keep',
|
||||
};
|
||||
export default createPrompt((config, done) => {
|
||||
const { waitForUserInput = true, file: { postfix = config.postfix ?? '.txt', ...fileProps } = {}, validate = () => true, } = config;
|
||||
const theme = makeTheme(editorTheme, config.theme);
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [value = '', setValue] = useState(config.default);
|
||||
const [errorMsg, setError] = useState();
|
||||
const prefix = usePrefix({ status, theme });
|
||||
function startEditor(rl) {
|
||||
rl.pause();
|
||||
const editCallback = async (error, answer) => {
|
||||
rl.resume();
|
||||
if (error) {
|
||||
setError(error.toString());
|
||||
}
|
||||
else {
|
||||
setStatus('loading');
|
||||
const finalAnswer = answer ?? '';
|
||||
const isValid = await validate(finalAnswer);
|
||||
if (isValid === true) {
|
||||
setError(undefined);
|
||||
setStatus('done');
|
||||
done(finalAnswer);
|
||||
}
|
||||
else {
|
||||
if (theme.validationFailureMode === 'clear') {
|
||||
setValue(config.default);
|
||||
}
|
||||
else {
|
||||
setValue(finalAnswer);
|
||||
}
|
||||
setError(isValid || 'You must provide a valid value');
|
||||
setStatus('idle');
|
||||
}
|
||||
}
|
||||
};
|
||||
editAsync(value, (error, answer) => void editCallback(error, answer), {
|
||||
postfix,
|
||||
...fileProps,
|
||||
});
|
||||
}
|
||||
useEffect((rl) => {
|
||||
if (!waitForUserInput) {
|
||||
startEditor(rl);
|
||||
}
|
||||
}, []);
|
||||
useKeypress((key, rl) => {
|
||||
// Ignore keypress while our prompt is doing other processing.
|
||||
if (status !== 'idle') {
|
||||
return;
|
||||
}
|
||||
if (isEnterKey(key)) {
|
||||
startEditor(rl);
|
||||
}
|
||||
});
|
||||
const message = theme.style.message(config.message, status);
|
||||
let helpTip = '';
|
||||
if (status === 'loading') {
|
||||
helpTip = theme.style.help('Received');
|
||||
}
|
||||
else if (status === 'idle') {
|
||||
const enterKey = theme.style.key('enter');
|
||||
helpTip = theme.style.help(`Press ${enterKey} to launch your preferred editor.`);
|
||||
}
|
||||
let error = '';
|
||||
if (errorMsg) {
|
||||
error = theme.style.error(errorMsg);
|
||||
}
|
||||
return [[prefix, message, helpTip].filter(Boolean).join(' '), error];
|
||||
});
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"name": "@inquirer/editor",
|
||||
"version": "5.0.4",
|
||||
"description": "Inquirer multiline editor prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/editor/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/external-editor": "^2.0.3",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
# `@inquirer/expand`
|
||||
|
||||
Compact single select prompt. Every option is assigned a shortcut key, and selecting `h` will expand all the choices and their descriptions.
|
||||
|
||||

|
||||

|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/expand
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/expand
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { expand } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import expand from '@inquirer/expand';
|
||||
|
||||
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',
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| -------- | ----------------------- | -------- | ----------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| choices | `Choice[]` | yes | Array of the different allowed choices. The `h`/help option is always provided by default |
|
||||
| default | `string` | no | Default choices to be selected. (value must be one of the choices `key`) |
|
||||
| expanded | `boolean` | no | Expand the choices by default |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
`Separator` objects can be used in the `choices` array to render non-selectable lines in the choice list. By default it'll render a line, but you can provide the text as argument (`new Separator('-- Dependencies --')`). This option is often used to add labels to groups within long list of options.
|
||||
|
||||
### `Choice` object
|
||||
|
||||
The `Choice` object is typed as
|
||||
|
||||
```ts
|
||||
type Choice<Value> = {
|
||||
value: Value;
|
||||
name?: string;
|
||||
key: string;
|
||||
};
|
||||
```
|
||||
|
||||
Here's each property:
|
||||
|
||||
- `value`: The value is what will be returned by `await expand()`.
|
||||
- `name`: The string displayed in the choice list. It'll default to the stringify `value`.
|
||||
- `key`: The input the use must provide to select the choice. Must be a lowercase single alpha-numeric character string.
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
highlight: (text: string) => string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { Separator, type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type Key = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
||||
type Choice<Value> = {
|
||||
key: Key;
|
||||
value: Value;
|
||||
} | {
|
||||
key: Key;
|
||||
name: string;
|
||||
value: Value;
|
||||
};
|
||||
declare const _default: <Value>(config: {
|
||||
message: string;
|
||||
choices: readonly {
|
||||
key: Key;
|
||||
name: string;
|
||||
}[] | readonly (Separator | Choice<Value>)[];
|
||||
default?: (Key | "h") | undefined;
|
||||
expanded?: boolean | undefined;
|
||||
theme?: PartialDeep<Theme> | undefined;
|
||||
}, context?: import("@inquirer/type").Context) => Promise<Value>;
|
||||
export default _default;
|
||||
export { Separator } from '@inquirer/core';
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import { createPrompt, useMemo, useState, useKeypress, usePrefix, isEnterKey, makeTheme, Separator, } from '@inquirer/core';
|
||||
import { styleText } from 'node:util';
|
||||
function normalizeChoices(choices) {
|
||||
return choices.map((choice) => {
|
||||
if (Separator.isSeparator(choice)) {
|
||||
return choice;
|
||||
}
|
||||
const name = 'name' in choice ? choice.name : String(choice.value);
|
||||
const value = 'value' in choice ? choice.value : name;
|
||||
return {
|
||||
value: value,
|
||||
name,
|
||||
key: choice.key.toLowerCase(),
|
||||
};
|
||||
});
|
||||
}
|
||||
const helpChoice = {
|
||||
key: 'h',
|
||||
name: 'Help, list all options',
|
||||
value: undefined,
|
||||
};
|
||||
export default createPrompt((config, done) => {
|
||||
const { default: defaultKey = 'h' } = config;
|
||||
const choices = useMemo(() => normalizeChoices(config.choices), [config.choices]);
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [value, setValue] = useState('');
|
||||
const [expanded, setExpanded] = useState(config.expanded ?? false);
|
||||
const [errorMsg, setError] = useState();
|
||||
const theme = makeTheme(config.theme);
|
||||
const prefix = usePrefix({ theme, status });
|
||||
useKeypress((event, rl) => {
|
||||
if (isEnterKey(event)) {
|
||||
const answer = (value || defaultKey).toLowerCase();
|
||||
if (answer === 'h' && !expanded) {
|
||||
setExpanded(true);
|
||||
}
|
||||
else {
|
||||
const selectedChoice = choices.find((choice) => !Separator.isSeparator(choice) && choice.key === answer);
|
||||
if (selectedChoice) {
|
||||
setStatus('done');
|
||||
// Set the value as we might've selected the default one.
|
||||
setValue(answer);
|
||||
done(selectedChoice.value);
|
||||
}
|
||||
else if (value === '') {
|
||||
setError('Please input a value');
|
||||
}
|
||||
else {
|
||||
setError(`"${styleText('red', value)}" isn't an available option`);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
setValue(rl.line);
|
||||
setError(undefined);
|
||||
}
|
||||
});
|
||||
const message = theme.style.message(config.message, status);
|
||||
if (status === 'done') {
|
||||
// If the prompt is done, it's safe to assume there is a selected value.
|
||||
const selectedChoice = choices.find((choice) => !Separator.isSeparator(choice) && choice.key === value.toLowerCase());
|
||||
return `${prefix} ${message} ${theme.style.answer(selectedChoice.name)}`;
|
||||
}
|
||||
const allChoices = expanded ? choices : [...choices, helpChoice];
|
||||
// Collapsed display style
|
||||
let longChoices = '';
|
||||
let shortChoices = allChoices
|
||||
.map((choice) => {
|
||||
if (Separator.isSeparator(choice))
|
||||
return '';
|
||||
if (choice.key === defaultKey) {
|
||||
return choice.key.toUpperCase();
|
||||
}
|
||||
return choice.key;
|
||||
})
|
||||
.join('');
|
||||
shortChoices = ` ${theme.style.defaultAnswer(shortChoices)}`;
|
||||
// Expanded display style
|
||||
if (expanded) {
|
||||
shortChoices = '';
|
||||
longChoices = allChoices
|
||||
.map((choice) => {
|
||||
if (Separator.isSeparator(choice)) {
|
||||
return ` ${choice.separator}`;
|
||||
}
|
||||
const line = ` ${choice.key}) ${choice.name}`;
|
||||
if (choice.key === value.toLowerCase()) {
|
||||
return theme.style.highlight(line);
|
||||
}
|
||||
return line;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
let helpTip = '';
|
||||
const currentOption = choices.find((choice) => !Separator.isSeparator(choice) && choice.key === value.toLowerCase());
|
||||
if (currentOption) {
|
||||
helpTip = `${styleText('cyan', '>>')} ${currentOption.name}`;
|
||||
}
|
||||
let error = '';
|
||||
if (errorMsg) {
|
||||
error = theme.style.error(errorMsg);
|
||||
}
|
||||
return [
|
||||
`${prefix} ${message}${shortChoices} ${value}`,
|
||||
[longChoices, helpTip, error].filter(Boolean).join('\n'),
|
||||
];
|
||||
});
|
||||
export { Separator } from '@inquirer/core';
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@inquirer/expand",
|
||||
"version": "5.0.4",
|
||||
"description": "Inquirer checkbox prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/expand/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
# `@inquirer/external-editor`
|
||||
|
||||
A Node.js module to edit a string with the user's preferred text editor using $VISUAL or $EDITOR.
|
||||
|
||||
> [!NOTE]
|
||||
> This package is a replacement for the unmaintained `external-editor`. It includes security fixes.
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/external-editor
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/external-editor
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Usage
|
||||
|
||||
A simple example using the `edit` function
|
||||
|
||||
```ts
|
||||
import { edit } from '@inquirer/external-editor';
|
||||
|
||||
const data = edit('\n\n# Please write your text above');
|
||||
console.log(data);
|
||||
```
|
||||
|
||||
Example relying on the class construct
|
||||
|
||||
```ts
|
||||
import {
|
||||
ExternalEditor,
|
||||
CreateFileError,
|
||||
ReadFileError,
|
||||
RemoveFileError,
|
||||
LaunchEditorError,
|
||||
} from '@inquirer/external-editor';
|
||||
|
||||
try {
|
||||
const editor = new ExternalEditor();
|
||||
const text = editor.run(); // the text is also available in editor.text
|
||||
|
||||
if (editor.lastExitStatus !== 0) {
|
||||
console.log('The editor exited with a non-zero code');
|
||||
}
|
||||
|
||||
// Do things with the text
|
||||
editor.cleanup();
|
||||
} catch (err) {
|
||||
if (err instanceof CreateFileError) {
|
||||
console.log('Failed to create the temporary file');
|
||||
} else if (err instanceof ReadFileError) {
|
||||
console.log('Failed to read the temporary file');
|
||||
} else if (err instanceof LaunchEditorError) {
|
||||
console.log('Failed to launch your editor');
|
||||
} else if (err instanceof RemoveFileError) {
|
||||
console.log('Failed to remove the temporary file');
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### API
|
||||
|
||||
**Convenience Functions**
|
||||
|
||||
- `edit(text, config)`
|
||||
- `text` (string) _Optional_ Defaults to empty string
|
||||
- `config` (Config) _Optional_ Options for temporary file creation
|
||||
- **Returns** (string) The contents of the file
|
||||
- Could throw `CreateFileError`, `ReadFileError`, or `LaunchEditorError`, or `RemoveFileError`
|
||||
- `editAsync(text, callback, config)`
|
||||
- `text` (string) _Optional_ Defaults to empty string
|
||||
- `callback` (function (error?, text?))
|
||||
- `error` could be of type `CreateFileError`, `ReadFileError`, `LaunchEditorError`, or `RemoveFileError`
|
||||
- `text` (string) The contents of the file
|
||||
- `config` (Config) _Optional_ Options for temporary file creation
|
||||
|
||||
**Errors**
|
||||
|
||||
- `CreateFileError` Error thrown if the temporary file could not be created.
|
||||
- `ReadFileError` Error thrown if the temporary file could not be read.
|
||||
- `RemoveFileError` Error thrown if the temporary file could not be removed during cleanup.
|
||||
- `LaunchEditorError` Error thrown if the editor could not be launched.
|
||||
|
||||
**External Editor Public Methods**
|
||||
|
||||
- `new ExternalEditor(text, config)`
|
||||
- `text` (string) _Optional_ Defaults to empty string
|
||||
- `config` (Config) _Optional_ Options for temporary file creation
|
||||
- Could throw `CreateFileError`
|
||||
- `run()` Launches the editor.
|
||||
- **Returns** (string) The contents of the file
|
||||
- Could throw `LaunchEditorError` or `ReadFileError`
|
||||
- `runAsync(callback)` Launches the editor in an async way
|
||||
- `callback` (function (error?, text?))
|
||||
- `error` could be of type `ReadFileError` or `LaunchEditorError`
|
||||
- `text` (string) The contents of the file
|
||||
- `cleanup()` Removes the temporary file.
|
||||
- Could throw `RemoveFileError`
|
||||
|
||||
**External Editor Public Properties**
|
||||
|
||||
- `text` (string) _readonly_ The text in the temporary file.
|
||||
- `editor.bin` (string) The editor determined from the environment.
|
||||
- `editor.args` (array) Default arguments for the bin
|
||||
- `tempFile` (string) Path to temporary file. Can be changed, but be careful as the temporary file probably already
|
||||
exists and would need be removed manually.
|
||||
- `lastExitStatus` (number) The last exit code emitted from the editor.
|
||||
|
||||
**Config Options**
|
||||
|
||||
- `prefix` (string) _Optional_ A prefix for the file name.
|
||||
- `postfix` (string) _Optional_ A postfix for the file name. Useful if you want to provide an extension.
|
||||
- `mode` (number) _Optional_ Which mode to create the file with. e.g. 644
|
||||
- `dir` (string) _Optional_ Which path to store the file.
|
||||
|
||||
## Why Synchronous?
|
||||
|
||||
Everything is synchronous to make sure the editor has complete control of the stdin and stdout. Testing has shown
|
||||
async launching of the editor can lead to issues when using readline or other packages which try to read from stdin or
|
||||
write to stdout. Seeing as this will be used in an interactive CLI environment, I made the decision to force the package
|
||||
to be synchronous. If you know a reliable way to force all stdin and stdout to be limited only to the child_process,
|
||||
please submit a PR.
|
||||
|
||||
If async is really needed, you can use `editAsync` or `runAsync`. If you are using readline or have anything else
|
||||
listening to the stdin or you write to stdout, you will most likely have problem, so make sure to remove any other
|
||||
listeners on stdin, stdout, or stderr.
|
||||
|
||||
## Demo
|
||||
|
||||
[](https://asciinema.org/a/a1qh9lypbe65mj0ivfuoslz2s)
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2025 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class CreateFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export class CreateFileError extends Error {
|
||||
originalError;
|
||||
constructor(originalError) {
|
||||
super(`Failed to create temporary file. ${originalError.message}`);
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class LaunchEditorError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export class LaunchEditorError extends Error {
|
||||
originalError;
|
||||
constructor(originalError) {
|
||||
super(`Failed to launch editor. ${originalError.message}`);
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class ReadFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export class ReadFileError extends Error {
|
||||
originalError;
|
||||
constructor(originalError) {
|
||||
super(`Failed to read temporary file. ${originalError.message}`);
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class RemoveFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export class RemoveFileError extends Error {
|
||||
originalError;
|
||||
constructor(originalError) {
|
||||
super(`Failed to remove temporary file. ${originalError.message}`);
|
||||
this.originalError = originalError;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { CreateFileError } from './errors/CreateFileError.ts';
|
||||
import { LaunchEditorError } from './errors/LaunchEditorError.ts';
|
||||
import { ReadFileError } from './errors/ReadFileError.ts';
|
||||
import { RemoveFileError } from './errors/RemoveFileError.ts';
|
||||
export interface IEditorParams {
|
||||
args: string[];
|
||||
bin: string;
|
||||
}
|
||||
export interface IFileOptions {
|
||||
prefix?: string;
|
||||
postfix?: string;
|
||||
mode?: number;
|
||||
template?: string;
|
||||
dir?: string;
|
||||
}
|
||||
export type StringCallback = (err: Error | undefined, result: string | undefined) => void;
|
||||
export type VoidCallback = () => void;
|
||||
export { CreateFileError, LaunchEditorError, ReadFileError, RemoveFileError };
|
||||
export declare function edit(text?: string, fileOptions?: IFileOptions): string;
|
||||
export declare function editAsync(text: string | undefined, callback: StringCallback, fileOptions?: IFileOptions): void;
|
||||
export declare class ExternalEditor {
|
||||
text: string;
|
||||
tempFile: string;
|
||||
editor: IEditorParams;
|
||||
lastExitStatus: number;
|
||||
private fileOptions;
|
||||
get temp_file(): string;
|
||||
get last_exit_status(): number;
|
||||
constructor(text?: string, fileOptions?: IFileOptions);
|
||||
run(): string;
|
||||
runAsync(callback: StringCallback): void;
|
||||
cleanup(): void;
|
||||
private determineEditor;
|
||||
private createTemporaryFile;
|
||||
private readTemporaryFile;
|
||||
private removeTemporaryFile;
|
||||
private launchEditor;
|
||||
private launchEditorAsync;
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
import { detect } from 'chardet';
|
||||
import { spawn, spawnSync } from 'child_process';
|
||||
import { readFileSync, unlinkSync, writeFileSync } from 'fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import iconv from 'iconv-lite';
|
||||
import { CreateFileError } from "./errors/CreateFileError.js";
|
||||
import { LaunchEditorError } from "./errors/LaunchEditorError.js";
|
||||
import { ReadFileError } from "./errors/ReadFileError.js";
|
||||
import { RemoveFileError } from "./errors/RemoveFileError.js";
|
||||
export { CreateFileError, LaunchEditorError, ReadFileError, RemoveFileError };
|
||||
export function edit(text = '', fileOptions) {
|
||||
const editor = new ExternalEditor(text, fileOptions);
|
||||
editor.run();
|
||||
editor.cleanup();
|
||||
return editor.text;
|
||||
}
|
||||
export function editAsync(text = '', callback, fileOptions) {
|
||||
const editor = new ExternalEditor(text, fileOptions);
|
||||
editor.runAsync((err, result) => {
|
||||
if (err) {
|
||||
setImmediate(callback, err, undefined);
|
||||
}
|
||||
else {
|
||||
try {
|
||||
editor.cleanup();
|
||||
setImmediate(callback, undefined, result);
|
||||
}
|
||||
catch (cleanupError) {
|
||||
setImmediate(callback, cleanupError, undefined);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function sanitizeAffix(affix) {
|
||||
if (!affix)
|
||||
return '';
|
||||
return affix.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
||||
}
|
||||
function splitStringBySpace(str) {
|
||||
const pieces = [];
|
||||
let currentString = '';
|
||||
for (let strIndex = 0; strIndex < str.length; strIndex++) {
|
||||
const currentLetter = str.charAt(strIndex);
|
||||
if (strIndex > 0 &&
|
||||
currentLetter === ' ' &&
|
||||
str[strIndex - 1] !== '\\' &&
|
||||
currentString.length > 0) {
|
||||
pieces.push(currentString);
|
||||
currentString = '';
|
||||
}
|
||||
else {
|
||||
currentString = `${currentString}${currentLetter}`;
|
||||
}
|
||||
}
|
||||
if (currentString.length > 0) {
|
||||
pieces.push(currentString);
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
export class ExternalEditor {
|
||||
text = '';
|
||||
tempFile;
|
||||
editor;
|
||||
lastExitStatus = 0;
|
||||
fileOptions = {};
|
||||
get temp_file() {
|
||||
console.log('DEPRECATED: temp_file. Use tempFile moving forward.');
|
||||
return this.tempFile;
|
||||
}
|
||||
get last_exit_status() {
|
||||
console.log('DEPRECATED: last_exit_status. Use lastExitStatus moving forward.');
|
||||
return this.lastExitStatus;
|
||||
}
|
||||
constructor(text = '', fileOptions) {
|
||||
this.text = text;
|
||||
if (fileOptions) {
|
||||
this.fileOptions = fileOptions;
|
||||
}
|
||||
this.determineEditor();
|
||||
this.createTemporaryFile();
|
||||
}
|
||||
run() {
|
||||
this.launchEditor();
|
||||
this.readTemporaryFile();
|
||||
return this.text;
|
||||
}
|
||||
runAsync(callback) {
|
||||
try {
|
||||
this.launchEditorAsync(() => {
|
||||
try {
|
||||
this.readTemporaryFile();
|
||||
setImmediate(callback, undefined, this.text);
|
||||
}
|
||||
catch (readError) {
|
||||
setImmediate(callback, readError, undefined);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (launchError) {
|
||||
setImmediate(callback, launchError, undefined);
|
||||
}
|
||||
}
|
||||
cleanup() {
|
||||
this.removeTemporaryFile();
|
||||
}
|
||||
determineEditor() {
|
||||
const editor = process.env['VISUAL']
|
||||
? process.env['VISUAL']
|
||||
: process.env['EDITOR']
|
||||
? process.env['EDITOR']
|
||||
: process.platform.startsWith('win')
|
||||
? 'notepad'
|
||||
: 'vim';
|
||||
const editorOpts = splitStringBySpace(editor).map((piece) => piece.replace('\\ ', ' '));
|
||||
const bin = editorOpts.shift();
|
||||
this.editor = { args: editorOpts, bin };
|
||||
}
|
||||
createTemporaryFile() {
|
||||
try {
|
||||
const baseDir = this.fileOptions.dir ?? os.tmpdir();
|
||||
const id = randomUUID();
|
||||
const prefix = sanitizeAffix(this.fileOptions.prefix);
|
||||
const postfix = sanitizeAffix(this.fileOptions.postfix);
|
||||
const filename = `${prefix}${id}${postfix}`;
|
||||
const candidate = path.resolve(baseDir, filename);
|
||||
const baseResolved = path.resolve(baseDir) + path.sep;
|
||||
if (!candidate.startsWith(baseResolved)) {
|
||||
throw new Error('Resolved temporary file escaped the base directory');
|
||||
}
|
||||
this.tempFile = candidate;
|
||||
const opt = { encoding: 'utf8', flag: 'wx' };
|
||||
if (Object.prototype.hasOwnProperty.call(this.fileOptions, 'mode')) {
|
||||
opt.mode = this.fileOptions.mode;
|
||||
}
|
||||
writeFileSync(this.tempFile, this.text, opt);
|
||||
}
|
||||
catch (createFileError) {
|
||||
throw new CreateFileError(createFileError);
|
||||
}
|
||||
}
|
||||
readTemporaryFile() {
|
||||
try {
|
||||
const tempFileBuffer = readFileSync(this.tempFile);
|
||||
if (tempFileBuffer.length === 0) {
|
||||
this.text = '';
|
||||
}
|
||||
else {
|
||||
let encoding = detect(tempFileBuffer) ?? 'utf8';
|
||||
if (!iconv.encodingExists(encoding)) {
|
||||
// Probably a bad idea, but will at least prevent crashing
|
||||
encoding = 'utf8';
|
||||
}
|
||||
this.text = iconv.decode(tempFileBuffer, encoding);
|
||||
}
|
||||
}
|
||||
catch (readFileError) {
|
||||
throw new ReadFileError(readFileError);
|
||||
}
|
||||
}
|
||||
removeTemporaryFile() {
|
||||
try {
|
||||
unlinkSync(this.tempFile);
|
||||
}
|
||||
catch (removeFileError) {
|
||||
throw new RemoveFileError(removeFileError);
|
||||
}
|
||||
}
|
||||
launchEditor() {
|
||||
try {
|
||||
const editorProcess = spawnSync(this.editor.bin, this.editor.args.concat([this.tempFile]), { stdio: 'inherit' });
|
||||
this.lastExitStatus = editorProcess.status ?? 0;
|
||||
}
|
||||
catch (launchError) {
|
||||
throw new LaunchEditorError(launchError);
|
||||
}
|
||||
}
|
||||
launchEditorAsync(callback) {
|
||||
try {
|
||||
const editorProcess = spawn(this.editor.bin, this.editor.args.concat([this.tempFile]), { stdio: 'inherit' });
|
||||
editorProcess.on('exit', (code) => {
|
||||
this.lastExitStatus = code;
|
||||
setImmediate(callback);
|
||||
});
|
||||
}
|
||||
catch (launchError) {
|
||||
throw new LaunchEditorError(launchError);
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"name": "@inquirer/external-editor",
|
||||
"version": "2.0.3",
|
||||
"description": "Edit a string with the users preferred text editor using $VISUAL or $ENVIRONMENT",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"editor",
|
||||
"enquirer",
|
||||
"external",
|
||||
"external-editor",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"user",
|
||||
"visual",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/external-editor/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"chardet": "^2.1.1",
|
||||
"iconv-lite": "^0.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/chardet": "^1.0.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
declare const common: {
|
||||
circleQuestionMark: string;
|
||||
questionMarkPrefix: string;
|
||||
square: string;
|
||||
squareDarkShade: string;
|
||||
squareMediumShade: string;
|
||||
squareLightShade: string;
|
||||
squareTop: string;
|
||||
squareBottom: string;
|
||||
squareLeft: string;
|
||||
squareRight: string;
|
||||
squareCenter: string;
|
||||
bullet: string;
|
||||
dot: string;
|
||||
ellipsis: string;
|
||||
pointerSmall: string;
|
||||
triangleUp: string;
|
||||
triangleUpSmall: string;
|
||||
triangleDown: string;
|
||||
triangleDownSmall: string;
|
||||
triangleLeftSmall: string;
|
||||
triangleRightSmall: string;
|
||||
home: string;
|
||||
heart: string;
|
||||
musicNote: string;
|
||||
musicNoteBeamed: string;
|
||||
arrowUp: string;
|
||||
arrowDown: string;
|
||||
arrowLeft: string;
|
||||
arrowRight: string;
|
||||
arrowLeftRight: string;
|
||||
arrowUpDown: string;
|
||||
almostEqual: string;
|
||||
notEqual: string;
|
||||
lessOrEqual: string;
|
||||
greaterOrEqual: string;
|
||||
identical: string;
|
||||
infinity: string;
|
||||
subscriptZero: string;
|
||||
subscriptOne: string;
|
||||
subscriptTwo: string;
|
||||
subscriptThree: string;
|
||||
subscriptFour: string;
|
||||
subscriptFive: string;
|
||||
subscriptSix: string;
|
||||
subscriptSeven: string;
|
||||
subscriptEight: string;
|
||||
subscriptNine: string;
|
||||
oneHalf: string;
|
||||
oneThird: string;
|
||||
oneQuarter: string;
|
||||
oneFifth: string;
|
||||
oneSixth: string;
|
||||
oneEighth: string;
|
||||
twoThirds: string;
|
||||
twoFifths: string;
|
||||
threeQuarters: string;
|
||||
threeFifths: string;
|
||||
threeEighths: string;
|
||||
fourFifths: string;
|
||||
fiveSixths: string;
|
||||
fiveEighths: string;
|
||||
sevenEighths: string;
|
||||
line: string;
|
||||
lineBold: string;
|
||||
lineDouble: string;
|
||||
lineDashed0: string;
|
||||
lineDashed1: string;
|
||||
lineDashed2: string;
|
||||
lineDashed3: string;
|
||||
lineDashed4: string;
|
||||
lineDashed5: string;
|
||||
lineDashed6: string;
|
||||
lineDashed7: string;
|
||||
lineDashed8: string;
|
||||
lineDashed9: string;
|
||||
lineDashed10: string;
|
||||
lineDashed11: string;
|
||||
lineDashed12: string;
|
||||
lineDashed13: string;
|
||||
lineDashed14: string;
|
||||
lineDashed15: string;
|
||||
lineVertical: string;
|
||||
lineVerticalBold: string;
|
||||
lineVerticalDouble: string;
|
||||
lineVerticalDashed0: string;
|
||||
lineVerticalDashed1: string;
|
||||
lineVerticalDashed2: string;
|
||||
lineVerticalDashed3: string;
|
||||
lineVerticalDashed4: string;
|
||||
lineVerticalDashed5: string;
|
||||
lineVerticalDashed6: string;
|
||||
lineVerticalDashed7: string;
|
||||
lineVerticalDashed8: string;
|
||||
lineVerticalDashed9: string;
|
||||
lineVerticalDashed10: string;
|
||||
lineVerticalDashed11: string;
|
||||
lineDownLeft: string;
|
||||
lineDownLeftArc: string;
|
||||
lineDownBoldLeftBold: string;
|
||||
lineDownBoldLeft: string;
|
||||
lineDownLeftBold: string;
|
||||
lineDownDoubleLeftDouble: string;
|
||||
lineDownDoubleLeft: string;
|
||||
lineDownLeftDouble: string;
|
||||
lineDownRight: string;
|
||||
lineDownRightArc: string;
|
||||
lineDownBoldRightBold: string;
|
||||
lineDownBoldRight: string;
|
||||
lineDownRightBold: string;
|
||||
lineDownDoubleRightDouble: string;
|
||||
lineDownDoubleRight: string;
|
||||
lineDownRightDouble: string;
|
||||
lineUpLeft: string;
|
||||
lineUpLeftArc: string;
|
||||
lineUpBoldLeftBold: string;
|
||||
lineUpBoldLeft: string;
|
||||
lineUpLeftBold: string;
|
||||
lineUpDoubleLeftDouble: string;
|
||||
lineUpDoubleLeft: string;
|
||||
lineUpLeftDouble: string;
|
||||
lineUpRight: string;
|
||||
lineUpRightArc: string;
|
||||
lineUpBoldRightBold: string;
|
||||
lineUpBoldRight: string;
|
||||
lineUpRightBold: string;
|
||||
lineUpDoubleRightDouble: string;
|
||||
lineUpDoubleRight: string;
|
||||
lineUpRightDouble: string;
|
||||
lineUpDownLeft: string;
|
||||
lineUpBoldDownBoldLeftBold: string;
|
||||
lineUpBoldDownBoldLeft: string;
|
||||
lineUpDownLeftBold: string;
|
||||
lineUpBoldDownLeftBold: string;
|
||||
lineUpDownBoldLeftBold: string;
|
||||
lineUpDownBoldLeft: string;
|
||||
lineUpBoldDownLeft: string;
|
||||
lineUpDoubleDownDoubleLeftDouble: string;
|
||||
lineUpDoubleDownDoubleLeft: string;
|
||||
lineUpDownLeftDouble: string;
|
||||
lineUpDownRight: string;
|
||||
lineUpBoldDownBoldRightBold: string;
|
||||
lineUpBoldDownBoldRight: string;
|
||||
lineUpDownRightBold: string;
|
||||
lineUpBoldDownRightBold: string;
|
||||
lineUpDownBoldRightBold: string;
|
||||
lineUpDownBoldRight: string;
|
||||
lineUpBoldDownRight: string;
|
||||
lineUpDoubleDownDoubleRightDouble: string;
|
||||
lineUpDoubleDownDoubleRight: string;
|
||||
lineUpDownRightDouble: string;
|
||||
lineDownLeftRight: string;
|
||||
lineDownBoldLeftBoldRightBold: string;
|
||||
lineDownLeftBoldRightBold: string;
|
||||
lineDownBoldLeftRight: string;
|
||||
lineDownBoldLeftBoldRight: string;
|
||||
lineDownBoldLeftRightBold: string;
|
||||
lineDownLeftRightBold: string;
|
||||
lineDownLeftBoldRight: string;
|
||||
lineDownDoubleLeftDoubleRightDouble: string;
|
||||
lineDownDoubleLeftRight: string;
|
||||
lineDownLeftDoubleRightDouble: string;
|
||||
lineUpLeftRight: string;
|
||||
lineUpBoldLeftBoldRightBold: string;
|
||||
lineUpLeftBoldRightBold: string;
|
||||
lineUpBoldLeftRight: string;
|
||||
lineUpBoldLeftBoldRight: string;
|
||||
lineUpBoldLeftRightBold: string;
|
||||
lineUpLeftRightBold: string;
|
||||
lineUpLeftBoldRight: string;
|
||||
lineUpDoubleLeftDoubleRightDouble: string;
|
||||
lineUpDoubleLeftRight: string;
|
||||
lineUpLeftDoubleRightDouble: string;
|
||||
lineUpDownLeftRight: string;
|
||||
lineUpBoldDownBoldLeftBoldRightBold: string;
|
||||
lineUpDownBoldLeftBoldRightBold: string;
|
||||
lineUpBoldDownLeftBoldRightBold: string;
|
||||
lineUpBoldDownBoldLeftRightBold: string;
|
||||
lineUpBoldDownBoldLeftBoldRight: string;
|
||||
lineUpBoldDownLeftRight: string;
|
||||
lineUpDownBoldLeftRight: string;
|
||||
lineUpDownLeftBoldRight: string;
|
||||
lineUpDownLeftRightBold: string;
|
||||
lineUpBoldDownBoldLeftRight: string;
|
||||
lineUpDownLeftBoldRightBold: string;
|
||||
lineUpBoldDownLeftBoldRight: string;
|
||||
lineUpBoldDownLeftRightBold: string;
|
||||
lineUpDownBoldLeftBoldRight: string;
|
||||
lineUpDownBoldLeftRightBold: string;
|
||||
lineUpDoubleDownDoubleLeftDoubleRightDouble: string;
|
||||
lineUpDoubleDownDoubleLeftRight: string;
|
||||
lineUpDownLeftDoubleRightDouble: string;
|
||||
lineCross: string;
|
||||
lineBackslash: string;
|
||||
lineSlash: string;
|
||||
};
|
||||
declare const specialMainSymbols: {
|
||||
tick: string;
|
||||
info: string;
|
||||
warning: string;
|
||||
cross: string;
|
||||
squareSmall: string;
|
||||
squareSmallFilled: string;
|
||||
circle: string;
|
||||
circleFilled: string;
|
||||
circleDotted: string;
|
||||
circleDouble: string;
|
||||
circleCircle: string;
|
||||
circleCross: string;
|
||||
circlePipe: string;
|
||||
radioOn: string;
|
||||
radioOff: string;
|
||||
checkboxOn: string;
|
||||
checkboxOff: string;
|
||||
checkboxCircleOn: string;
|
||||
checkboxCircleOff: string;
|
||||
pointer: string;
|
||||
triangleUpOutline: string;
|
||||
triangleLeft: string;
|
||||
triangleRight: string;
|
||||
lozenge: string;
|
||||
lozengeOutline: string;
|
||||
hamburger: string;
|
||||
smiley: string;
|
||||
mustache: string;
|
||||
star: string;
|
||||
play: string;
|
||||
nodejs: string;
|
||||
oneSeventh: string;
|
||||
oneNinth: string;
|
||||
oneTenth: string;
|
||||
};
|
||||
declare const specialFallbackSymbols: {
|
||||
tick: string;
|
||||
info: string;
|
||||
warning: string;
|
||||
cross: string;
|
||||
squareSmall: string;
|
||||
squareSmallFilled: string;
|
||||
circle: string;
|
||||
circleFilled: string;
|
||||
circleDotted: string;
|
||||
circleDouble: string;
|
||||
circleCircle: string;
|
||||
circleCross: string;
|
||||
circlePipe: string;
|
||||
radioOn: string;
|
||||
radioOff: string;
|
||||
checkboxOn: string;
|
||||
checkboxOff: string;
|
||||
checkboxCircleOn: string;
|
||||
checkboxCircleOff: string;
|
||||
pointer: string;
|
||||
triangleUpOutline: string;
|
||||
triangleLeft: string;
|
||||
triangleRight: string;
|
||||
lozenge: string;
|
||||
lozengeOutline: string;
|
||||
hamburger: string;
|
||||
smiley: string;
|
||||
mustache: string;
|
||||
star: string;
|
||||
play: string;
|
||||
nodejs: string;
|
||||
oneSeventh: string;
|
||||
oneNinth: string;
|
||||
oneTenth: string;
|
||||
};
|
||||
export declare const mainSymbols: typeof common & typeof specialMainSymbols;
|
||||
export declare const fallbackSymbols: (typeof common & typeof specialFallbackSymbols) & Record<string, string>;
|
||||
declare const figures: typeof mainSymbols | typeof fallbackSymbols;
|
||||
export default figures;
|
||||
export declare const replaceSymbols: (string: string, { useFallback }?: {
|
||||
useFallback?: boolean;
|
||||
}) => string;
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
// process.env dot-notation access prints:
|
||||
// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111)
|
||||
/* eslint dot-notation: ["off"] */
|
||||
import process from 'node:process';
|
||||
// Ported from is-unicode-supported
|
||||
function isUnicodeSupported() {
|
||||
if (process.platform !== 'win32') {
|
||||
return process.env['TERM'] !== 'linux'; // Linux console (kernel)
|
||||
}
|
||||
return (Boolean(process.env['WT_SESSION']) || // Windows Terminal
|
||||
Boolean(process.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27)
|
||||
process.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder
|
||||
process.env['TERM_PROGRAM'] === 'Terminus-Sublime' ||
|
||||
process.env['TERM_PROGRAM'] === 'vscode' ||
|
||||
process.env['TERM'] === 'xterm-256color' ||
|
||||
process.env['TERM'] === 'alacritty' ||
|
||||
process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm');
|
||||
}
|
||||
// Ported from figures
|
||||
const common = {
|
||||
circleQuestionMark: '(?)',
|
||||
questionMarkPrefix: '(?)',
|
||||
square: '█',
|
||||
squareDarkShade: '▓',
|
||||
squareMediumShade: '▒',
|
||||
squareLightShade: '░',
|
||||
squareTop: '▀',
|
||||
squareBottom: '▄',
|
||||
squareLeft: '▌',
|
||||
squareRight: '▐',
|
||||
squareCenter: '■',
|
||||
bullet: '●',
|
||||
dot: '․',
|
||||
ellipsis: '…',
|
||||
pointerSmall: '›',
|
||||
triangleUp: '▲',
|
||||
triangleUpSmall: '▴',
|
||||
triangleDown: '▼',
|
||||
triangleDownSmall: '▾',
|
||||
triangleLeftSmall: '◂',
|
||||
triangleRightSmall: '▸',
|
||||
home: '⌂',
|
||||
heart: '♥',
|
||||
musicNote: '♪',
|
||||
musicNoteBeamed: '♫',
|
||||
arrowUp: '↑',
|
||||
arrowDown: '↓',
|
||||
arrowLeft: '←',
|
||||
arrowRight: '→',
|
||||
arrowLeftRight: '↔',
|
||||
arrowUpDown: '↕',
|
||||
almostEqual: '≈',
|
||||
notEqual: '≠',
|
||||
lessOrEqual: '≤',
|
||||
greaterOrEqual: '≥',
|
||||
identical: '≡',
|
||||
infinity: '∞',
|
||||
subscriptZero: '₀',
|
||||
subscriptOne: '₁',
|
||||
subscriptTwo: '₂',
|
||||
subscriptThree: '₃',
|
||||
subscriptFour: '₄',
|
||||
subscriptFive: '₅',
|
||||
subscriptSix: '₆',
|
||||
subscriptSeven: '₇',
|
||||
subscriptEight: '₈',
|
||||
subscriptNine: '₉',
|
||||
oneHalf: '½',
|
||||
oneThird: '⅓',
|
||||
oneQuarter: '¼',
|
||||
oneFifth: '⅕',
|
||||
oneSixth: '⅙',
|
||||
oneEighth: '⅛',
|
||||
twoThirds: '⅔',
|
||||
twoFifths: '⅖',
|
||||
threeQuarters: '¾',
|
||||
threeFifths: '⅗',
|
||||
threeEighths: '⅜',
|
||||
fourFifths: '⅘',
|
||||
fiveSixths: '⅚',
|
||||
fiveEighths: '⅝',
|
||||
sevenEighths: '⅞',
|
||||
line: '─',
|
||||
lineBold: '━',
|
||||
lineDouble: '═',
|
||||
lineDashed0: '┄',
|
||||
lineDashed1: '┅',
|
||||
lineDashed2: '┈',
|
||||
lineDashed3: '┉',
|
||||
lineDashed4: '╌',
|
||||
lineDashed5: '╍',
|
||||
lineDashed6: '╴',
|
||||
lineDashed7: '╶',
|
||||
lineDashed8: '╸',
|
||||
lineDashed9: '╺',
|
||||
lineDashed10: '╼',
|
||||
lineDashed11: '╾',
|
||||
lineDashed12: '−',
|
||||
lineDashed13: '–',
|
||||
lineDashed14: '‐',
|
||||
lineDashed15: '⁃',
|
||||
lineVertical: '│',
|
||||
lineVerticalBold: '┃',
|
||||
lineVerticalDouble: '║',
|
||||
lineVerticalDashed0: '┆',
|
||||
lineVerticalDashed1: '┇',
|
||||
lineVerticalDashed2: '┊',
|
||||
lineVerticalDashed3: '┋',
|
||||
lineVerticalDashed4: '╎',
|
||||
lineVerticalDashed5: '╏',
|
||||
lineVerticalDashed6: '╵',
|
||||
lineVerticalDashed7: '╷',
|
||||
lineVerticalDashed8: '╹',
|
||||
lineVerticalDashed9: '╻',
|
||||
lineVerticalDashed10: '╽',
|
||||
lineVerticalDashed11: '╿',
|
||||
lineDownLeft: '┐',
|
||||
lineDownLeftArc: '╮',
|
||||
lineDownBoldLeftBold: '┓',
|
||||
lineDownBoldLeft: '┒',
|
||||
lineDownLeftBold: '┑',
|
||||
lineDownDoubleLeftDouble: '╗',
|
||||
lineDownDoubleLeft: '╖',
|
||||
lineDownLeftDouble: '╕',
|
||||
lineDownRight: '┌',
|
||||
lineDownRightArc: '╭',
|
||||
lineDownBoldRightBold: '┏',
|
||||
lineDownBoldRight: '┎',
|
||||
lineDownRightBold: '┍',
|
||||
lineDownDoubleRightDouble: '╔',
|
||||
lineDownDoubleRight: '╓',
|
||||
lineDownRightDouble: '╒',
|
||||
lineUpLeft: '┘',
|
||||
lineUpLeftArc: '╯',
|
||||
lineUpBoldLeftBold: '┛',
|
||||
lineUpBoldLeft: '┚',
|
||||
lineUpLeftBold: '┙',
|
||||
lineUpDoubleLeftDouble: '╝',
|
||||
lineUpDoubleLeft: '╜',
|
||||
lineUpLeftDouble: '╛',
|
||||
lineUpRight: '└',
|
||||
lineUpRightArc: '╰',
|
||||
lineUpBoldRightBold: '┗',
|
||||
lineUpBoldRight: '┖',
|
||||
lineUpRightBold: '┕',
|
||||
lineUpDoubleRightDouble: '╚',
|
||||
lineUpDoubleRight: '╙',
|
||||
lineUpRightDouble: '╘',
|
||||
lineUpDownLeft: '┤',
|
||||
lineUpBoldDownBoldLeftBold: '┫',
|
||||
lineUpBoldDownBoldLeft: '┨',
|
||||
lineUpDownLeftBold: '┥',
|
||||
lineUpBoldDownLeftBold: '┩',
|
||||
lineUpDownBoldLeftBold: '┪',
|
||||
lineUpDownBoldLeft: '┧',
|
||||
lineUpBoldDownLeft: '┦',
|
||||
lineUpDoubleDownDoubleLeftDouble: '╣',
|
||||
lineUpDoubleDownDoubleLeft: '╢',
|
||||
lineUpDownLeftDouble: '╡',
|
||||
lineUpDownRight: '├',
|
||||
lineUpBoldDownBoldRightBold: '┣',
|
||||
lineUpBoldDownBoldRight: '┠',
|
||||
lineUpDownRightBold: '┝',
|
||||
lineUpBoldDownRightBold: '┡',
|
||||
lineUpDownBoldRightBold: '┢',
|
||||
lineUpDownBoldRight: '┟',
|
||||
lineUpBoldDownRight: '┞',
|
||||
lineUpDoubleDownDoubleRightDouble: '╠',
|
||||
lineUpDoubleDownDoubleRight: '╟',
|
||||
lineUpDownRightDouble: '╞',
|
||||
lineDownLeftRight: '┬',
|
||||
lineDownBoldLeftBoldRightBold: '┳',
|
||||
lineDownLeftBoldRightBold: '┯',
|
||||
lineDownBoldLeftRight: '┰',
|
||||
lineDownBoldLeftBoldRight: '┱',
|
||||
lineDownBoldLeftRightBold: '┲',
|
||||
lineDownLeftRightBold: '┮',
|
||||
lineDownLeftBoldRight: '┭',
|
||||
lineDownDoubleLeftDoubleRightDouble: '╦',
|
||||
lineDownDoubleLeftRight: '╥',
|
||||
lineDownLeftDoubleRightDouble: '╤',
|
||||
lineUpLeftRight: '┴',
|
||||
lineUpBoldLeftBoldRightBold: '┻',
|
||||
lineUpLeftBoldRightBold: '┷',
|
||||
lineUpBoldLeftRight: '┸',
|
||||
lineUpBoldLeftBoldRight: '┹',
|
||||
lineUpBoldLeftRightBold: '┺',
|
||||
lineUpLeftRightBold: '┶',
|
||||
lineUpLeftBoldRight: '┵',
|
||||
lineUpDoubleLeftDoubleRightDouble: '╩',
|
||||
lineUpDoubleLeftRight: '╨',
|
||||
lineUpLeftDoubleRightDouble: '╧',
|
||||
lineUpDownLeftRight: '┼',
|
||||
lineUpBoldDownBoldLeftBoldRightBold: '╋',
|
||||
lineUpDownBoldLeftBoldRightBold: '╈',
|
||||
lineUpBoldDownLeftBoldRightBold: '╇',
|
||||
lineUpBoldDownBoldLeftRightBold: '╊',
|
||||
lineUpBoldDownBoldLeftBoldRight: '╉',
|
||||
lineUpBoldDownLeftRight: '╀',
|
||||
lineUpDownBoldLeftRight: '╁',
|
||||
lineUpDownLeftBoldRight: '┽',
|
||||
lineUpDownLeftRightBold: '┾',
|
||||
lineUpBoldDownBoldLeftRight: '╂',
|
||||
lineUpDownLeftBoldRightBold: '┿',
|
||||
lineUpBoldDownLeftBoldRight: '╃',
|
||||
lineUpBoldDownLeftRightBold: '╄',
|
||||
lineUpDownBoldLeftBoldRight: '╅',
|
||||
lineUpDownBoldLeftRightBold: '╆',
|
||||
lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬',
|
||||
lineUpDoubleDownDoubleLeftRight: '╫',
|
||||
lineUpDownLeftDoubleRightDouble: '╪',
|
||||
lineCross: '╳',
|
||||
lineBackslash: '╲',
|
||||
lineSlash: '╱',
|
||||
};
|
||||
const specialMainSymbols = {
|
||||
tick: '✔',
|
||||
info: 'ℹ',
|
||||
warning: '⚠',
|
||||
cross: '✘',
|
||||
squareSmall: '◻',
|
||||
squareSmallFilled: '◼',
|
||||
circle: '◯',
|
||||
circleFilled: '◉',
|
||||
circleDotted: '◌',
|
||||
circleDouble: '◎',
|
||||
circleCircle: 'ⓞ',
|
||||
circleCross: 'ⓧ',
|
||||
circlePipe: 'Ⓘ',
|
||||
radioOn: '◉',
|
||||
radioOff: '◯',
|
||||
checkboxOn: '☒',
|
||||
checkboxOff: '☐',
|
||||
checkboxCircleOn: 'ⓧ',
|
||||
checkboxCircleOff: 'Ⓘ',
|
||||
pointer: '❯',
|
||||
triangleUpOutline: '△',
|
||||
triangleLeft: '◀',
|
||||
triangleRight: '▶',
|
||||
lozenge: '◆',
|
||||
lozengeOutline: '◇',
|
||||
hamburger: '☰',
|
||||
smiley: '㋡',
|
||||
mustache: '෴',
|
||||
star: '★',
|
||||
play: '▶',
|
||||
nodejs: '⬢',
|
||||
oneSeventh: '⅐',
|
||||
oneNinth: '⅑',
|
||||
oneTenth: '⅒',
|
||||
};
|
||||
const specialFallbackSymbols = {
|
||||
tick: '√',
|
||||
info: 'i',
|
||||
warning: '‼',
|
||||
cross: '×',
|
||||
squareSmall: '□',
|
||||
squareSmallFilled: '■',
|
||||
circle: '( )',
|
||||
circleFilled: '(*)',
|
||||
circleDotted: '( )',
|
||||
circleDouble: '( )',
|
||||
circleCircle: '(○)',
|
||||
circleCross: '(×)',
|
||||
circlePipe: '(│)',
|
||||
radioOn: '(*)',
|
||||
radioOff: '( )',
|
||||
checkboxOn: '[×]',
|
||||
checkboxOff: '[ ]',
|
||||
checkboxCircleOn: '(×)',
|
||||
checkboxCircleOff: '( )',
|
||||
pointer: '>',
|
||||
triangleUpOutline: '∆',
|
||||
triangleLeft: '◄',
|
||||
triangleRight: '►',
|
||||
lozenge: '♦',
|
||||
lozengeOutline: '◊',
|
||||
hamburger: '≡',
|
||||
smiley: '☺',
|
||||
mustache: '┌─┐',
|
||||
star: '✶',
|
||||
play: '►',
|
||||
nodejs: '♦',
|
||||
oneSeventh: '1/7',
|
||||
oneNinth: '1/9',
|
||||
oneTenth: '1/10',
|
||||
};
|
||||
export const mainSymbols = {
|
||||
...common,
|
||||
...specialMainSymbols,
|
||||
};
|
||||
export const fallbackSymbols = {
|
||||
...common,
|
||||
...specialFallbackSymbols,
|
||||
};
|
||||
const shouldUseMain = isUnicodeSupported();
|
||||
const figures = shouldUseMain
|
||||
? mainSymbols
|
||||
: fallbackSymbols;
|
||||
export default figures;
|
||||
const replacements = Object.entries(specialMainSymbols);
|
||||
// On terminals which do not support Unicode symbols, substitute them to other symbols
|
||||
export const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => {
|
||||
if (useFallback) {
|
||||
for (const [key, mainSymbol] of replacements) {
|
||||
const fallbackSymbol = fallbackSymbols[key];
|
||||
if (!fallbackSymbol) {
|
||||
throw new Error(`Unable to find fallback for ${key}`);
|
||||
}
|
||||
string = string.replaceAll(mainSymbol, fallbackSymbol);
|
||||
}
|
||||
}
|
||||
return string;
|
||||
};
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"name": "@inquirer/figures",
|
||||
"version": "2.0.3",
|
||||
"description": "Vendored version of figures, for CJS compatibility",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"types",
|
||||
"typescript",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# `@inquirer/input`
|
||||
|
||||
Interactive free text input component for command line interfaces. Supports validation, filtering, transformation, etc.
|
||||
|
||||

|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/input
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/input
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { input } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import input from '@inquirer/input';
|
||||
|
||||
const answer = await input({ message: 'Enter your name' });
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| ------------ | ----------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| default | `string` | no | Default value if no answer is provided; see the prefill option below for governing it's behaviour. |
|
||||
| prefill | `'tab' \| 'editable'` | no | Defaults to `'tab'`. If set to `'tab'`, pressing `backspace` will clear the default and pressing `tab` will inline the value for edits; If set to `'editable'`, the default value will already be inlined to edit. |
|
||||
| required | `boolean` | no | Defaults to `false`. If set to true, `undefined` (empty) will not be accepted for this. |
|
||||
| transformer | `(string, { isFinal: boolean }) => string` | no | Transform/Format the raw value entered by the user. Once the prompt is completed, `isFinal` will be `true`. This function is purely visual, modify the answer in your code if needed. |
|
||||
| validate | `string => boolean \| string \| Promise<boolean \| string>` | no | On submit, validate the filtered answered content. When returning a string, it'll be used as the error message displayed to the user. Note: returning a rejected promise, we'll assume a code error happened and crash. |
|
||||
| pattern | `RegExp` | no | Regular expression to validate the input against. If the input doesn't match the pattern, validation will fail with the error message specified in `patternError`. |
|
||||
| patternError | `string` | no | Error message to display when the input doesn't match the `pattern`. Defaults to `'Invalid input'`. |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
};
|
||||
validationFailureMode: 'keep' | 'clear';
|
||||
};
|
||||
```
|
||||
|
||||
`validationFailureMode` defines the behavior of the prompt when the value submitted is invalid. By default, we'll keep the value allowing the user to edit it. When the theme option is set to `clear`, we'll remove and reset to an empty string.
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type InputTheme = {
|
||||
validationFailureMode: 'keep' | 'clear';
|
||||
};
|
||||
type InputConfig = {
|
||||
message: string;
|
||||
default?: string;
|
||||
prefill?: 'tab' | 'editable';
|
||||
required?: boolean;
|
||||
transformer?: (value: string, { isFinal }: {
|
||||
isFinal: boolean;
|
||||
}) => string;
|
||||
validate?: (value: string) => boolean | string | Promise<string | boolean>;
|
||||
theme?: PartialDeep<Theme<InputTheme>>;
|
||||
pattern?: RegExp;
|
||||
patternError?: string;
|
||||
};
|
||||
declare const _default: import("@inquirer/type").Prompt<string, InputConfig>;
|
||||
export default _default;
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { createPrompt, useState, useKeypress, useEffect, usePrefix, isBackspaceKey, isEnterKey, isTabKey, makeTheme, } from '@inquirer/core';
|
||||
const inputTheme = {
|
||||
validationFailureMode: 'keep',
|
||||
};
|
||||
export default createPrompt((config, done) => {
|
||||
const { prefill = 'tab' } = config;
|
||||
const theme = makeTheme(inputTheme, config.theme);
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [defaultValue = '', setDefaultValue] = useState(config.default);
|
||||
const [errorMsg, setError] = useState();
|
||||
const [value, setValue] = useState('');
|
||||
const prefix = usePrefix({ status, theme });
|
||||
async function validate(value) {
|
||||
const { required, pattern, patternError = 'Invalid input' } = config;
|
||||
if (required && !value) {
|
||||
return 'You must provide a value';
|
||||
}
|
||||
if (pattern && !pattern.test(value)) {
|
||||
return patternError;
|
||||
}
|
||||
if (typeof config.validate === 'function') {
|
||||
return (await config.validate(value)) || 'You must provide a valid value';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
useKeypress(async (key, rl) => {
|
||||
// Ignore keypress while our prompt is doing other processing.
|
||||
if (status !== 'idle') {
|
||||
return;
|
||||
}
|
||||
if (isEnterKey(key)) {
|
||||
const answer = value || defaultValue;
|
||||
setStatus('loading');
|
||||
const isValid = await validate(answer);
|
||||
if (isValid === true) {
|
||||
setValue(answer);
|
||||
setStatus('done');
|
||||
done(answer);
|
||||
}
|
||||
else {
|
||||
if (theme.validationFailureMode === 'clear') {
|
||||
setValue('');
|
||||
}
|
||||
else {
|
||||
// Reset the readline line value to the previous value. On line event, the value
|
||||
// get cleared, forcing the user to re-enter the value instead of fixing it.
|
||||
rl.write(value);
|
||||
}
|
||||
setError(isValid);
|
||||
setStatus('idle');
|
||||
}
|
||||
}
|
||||
else if (isBackspaceKey(key) && !value) {
|
||||
setDefaultValue(undefined);
|
||||
}
|
||||
else if (isTabKey(key) && !value) {
|
||||
setDefaultValue(undefined);
|
||||
rl.clearLine(0); // Remove the tab character.
|
||||
rl.write(defaultValue);
|
||||
setValue(defaultValue);
|
||||
}
|
||||
else {
|
||||
setValue(rl.line);
|
||||
setError(undefined);
|
||||
}
|
||||
});
|
||||
// If prefill is set to 'editable' cut out the default value and paste into current state and the user's cli buffer
|
||||
// They can edit the value immediately instead of needing to press 'tab'
|
||||
useEffect((rl) => {
|
||||
if (prefill === 'editable' && defaultValue) {
|
||||
rl.write(defaultValue);
|
||||
setValue(defaultValue);
|
||||
}
|
||||
}, []);
|
||||
const message = theme.style.message(config.message, status);
|
||||
let formattedValue = value;
|
||||
if (typeof config.transformer === 'function') {
|
||||
formattedValue = config.transformer(value, { isFinal: status === 'done' });
|
||||
}
|
||||
else if (status === 'done') {
|
||||
formattedValue = theme.style.answer(value);
|
||||
}
|
||||
let defaultStr;
|
||||
if (defaultValue && status !== 'done' && !value) {
|
||||
defaultStr = theme.style.defaultAnswer(defaultValue);
|
||||
}
|
||||
let error = '';
|
||||
if (errorMsg) {
|
||||
error = theme.style.error(errorMsg);
|
||||
}
|
||||
return [
|
||||
[prefix, message, defaultStr, formattedValue]
|
||||
.filter((v) => v !== undefined)
|
||||
.join(' '),
|
||||
error,
|
||||
];
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@inquirer/input",
|
||||
"version": "5.0.4",
|
||||
"description": "Inquirer input text prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/input/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
# `@inquirer/number`
|
||||
|
||||
Interactive free number input component for command line interfaces. Supports validation, filtering, transformation, etc.
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/number
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/number
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { number } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import number from '@inquirer/number';
|
||||
|
||||
const answer = await number({ message: 'Enter your age' });
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| -------- | -------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| default | `number` | no | Default value if no answer is provided (clear it by pressing backspace) |
|
||||
| min | `number` | no | The minimum value to accept for this input. |
|
||||
| max | `number` | no | The maximum value to accept for this input. |
|
||||
| step | `number \| 'any'` | no | The step option is a number that specifies the granularity that the value must adhere to. Only values which are equal to the basis for stepping (min if specified) are valid. This value defaults to 1, meaning by default the prompt will only allow integers. |
|
||||
| required | `boolean` | no | Defaults to `false`. If set to true, `undefined` (empty) will not be accepted for this. |
|
||||
| validate | `(number \| undefined) => boolean \| string \| Promise<boolean \| string>` | no | On submit, validate the filtered answered content. When returning a string, it'll be used as the error message displayed to the user. Note: returning a rejected promise, we'll assume a code error happened and crash. |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
defaultAnswer: (text: string) => string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
declare const _default: <Required extends boolean>(config: {
|
||||
message: string;
|
||||
default?: number | undefined;
|
||||
min?: number | undefined;
|
||||
max?: number | undefined;
|
||||
step?: number | "any" | undefined;
|
||||
required?: Required | undefined;
|
||||
validate?: ((value: Required extends true ? number : number | undefined) => boolean | string | Promise<string | boolean>) | undefined;
|
||||
theme?: PartialDeep<Theme> | undefined;
|
||||
}, context?: import("@inquirer/type").Context) => Promise<Required extends true ? number : number | undefined>;
|
||||
export default _default;
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import { createPrompt, useState, useKeypress, usePrefix, isBackspaceKey, isEnterKey, isTabKey, makeTheme, } from '@inquirer/core';
|
||||
function isStepOf(value, step, min) {
|
||||
const valuePow = value * Math.pow(10, 6);
|
||||
const stepPow = step * Math.pow(10, 6);
|
||||
const minPow = min * Math.pow(10, 6);
|
||||
return (valuePow - (Number.isFinite(min) ? minPow : 0)) % stepPow === 0;
|
||||
}
|
||||
function validateNumber(value, { min, max, step, }) {
|
||||
if (value == null || Number.isNaN(value)) {
|
||||
return false;
|
||||
}
|
||||
else if (value < min || value > max) {
|
||||
return `Value must be between ${min} and ${max}`;
|
||||
}
|
||||
else if (step !== 'any' && !isStepOf(value, step, min)) {
|
||||
return `Value must be a multiple of ${step}${Number.isFinite(min) ? ` starting from ${min}` : ''}`;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export default createPrompt((config, done) => {
|
||||
const { validate = () => true, min = -Infinity, max = Infinity, step = 1, required = false, } = config;
|
||||
const theme = makeTheme(config.theme);
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [value, setValue] = useState(''); // store the input value as string and convert to number on "Enter"
|
||||
// Ignore default if not valid.
|
||||
const validDefault = validateNumber(config.default, { min, max, step }) === true
|
||||
? config.default?.toString()
|
||||
: undefined;
|
||||
const [defaultValue = '', setDefaultValue] = useState(validDefault);
|
||||
const [errorMsg, setError] = useState();
|
||||
const prefix = usePrefix({ status, theme });
|
||||
useKeypress(async (key, rl) => {
|
||||
// Ignore keypress while our prompt is doing other processing.
|
||||
if (status !== 'idle') {
|
||||
return;
|
||||
}
|
||||
if (isEnterKey(key)) {
|
||||
const input = value || defaultValue;
|
||||
const answer = input === '' ? undefined : Number(input);
|
||||
setStatus('loading');
|
||||
let isValid = true;
|
||||
if (required || answer != null) {
|
||||
isValid = validateNumber(answer, { min, max, step });
|
||||
}
|
||||
if (isValid === true) {
|
||||
isValid = await validate(answer);
|
||||
}
|
||||
if (isValid === true) {
|
||||
setValue(String(answer ?? ''));
|
||||
setStatus('done');
|
||||
done(answer);
|
||||
}
|
||||
else {
|
||||
// Reset the readline line value to the previous value. On line event, the value
|
||||
// get cleared, forcing the user to re-enter the value instead of fixing it.
|
||||
rl.write(value);
|
||||
setError(isValid || 'You must provide a valid numeric value');
|
||||
setStatus('idle');
|
||||
}
|
||||
}
|
||||
else if (isBackspaceKey(key) && !value) {
|
||||
setDefaultValue(undefined);
|
||||
}
|
||||
else if (isTabKey(key) && !value) {
|
||||
setDefaultValue(undefined);
|
||||
rl.clearLine(0); // Remove the tab character.
|
||||
rl.write(defaultValue);
|
||||
setValue(defaultValue);
|
||||
}
|
||||
else {
|
||||
setValue(rl.line);
|
||||
setError(undefined);
|
||||
}
|
||||
});
|
||||
const message = theme.style.message(config.message, status);
|
||||
let formattedValue = value;
|
||||
if (status === 'done') {
|
||||
formattedValue = theme.style.answer(value);
|
||||
}
|
||||
let defaultStr;
|
||||
if (defaultValue && status !== 'done' && !value) {
|
||||
defaultStr = theme.style.defaultAnswer(defaultValue);
|
||||
}
|
||||
let error = '';
|
||||
if (errorMsg) {
|
||||
error = theme.style.error(errorMsg);
|
||||
}
|
||||
return [
|
||||
[prefix, message, defaultStr, formattedValue]
|
||||
.filter((v) => v !== undefined)
|
||||
.join(' '),
|
||||
error,
|
||||
];
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@inquirer/number",
|
||||
"version": "4.0.4",
|
||||
"description": "Inquirer number prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/number/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
# `@inquirer/password`
|
||||
|
||||
Interactive password input component for command line interfaces. Supports input validation and masked or transparent modes.
|
||||
|
||||

|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan="2" align="center">Or</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/password
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/password
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { password } from '@inquirer/prompts';
|
||||
// Or
|
||||
// import password from '@inquirer/password';
|
||||
|
||||
const answer = await password({ message: 'Enter your name' });
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| -------- | ----------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| message | `string` | yes | The question to ask |
|
||||
| mask | `boolean` | no | Show a `*` mask over the input or keep it transparent |
|
||||
| validate | `string => boolean \| string \| Promise<boolean \| string>` | no | On submit, validate the filtered answered content. When returning a string, it'll be used as the error message displayed to the user. Note: returning a rejected promise, we'll assume a code error happened and crash. |
|
||||
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
|
||||
|
||||
## Theming
|
||||
|
||||
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
|
||||
|
||||
```ts
|
||||
type Theme = {
|
||||
prefix: string | { idle: string; done: string };
|
||||
spinner: {
|
||||
interval: number;
|
||||
frames: string[];
|
||||
};
|
||||
style: {
|
||||
answer: (text: string) => string;
|
||||
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
|
||||
error: (text: string) => string;
|
||||
help: (text: string) => string;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { type Theme } from '@inquirer/core';
|
||||
import type { PartialDeep } from '@inquirer/type';
|
||||
type PasswordConfig = {
|
||||
message: string;
|
||||
mask?: boolean | string;
|
||||
validate?: (value: string) => boolean | string | Promise<string | boolean>;
|
||||
theme?: PartialDeep<Theme>;
|
||||
};
|
||||
declare const _default: import("@inquirer/type").Prompt<string, PasswordConfig>;
|
||||
export default _default;
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { createPrompt, useState, useKeypress, usePrefix, isEnterKey, makeTheme, } from '@inquirer/core';
|
||||
import { cursorHide } from '@inquirer/ansi';
|
||||
export default createPrompt((config, done) => {
|
||||
const { validate = () => true } = config;
|
||||
const theme = makeTheme(config.theme);
|
||||
const [status, setStatus] = useState('idle');
|
||||
const [errorMsg, setError] = useState();
|
||||
const [value, setValue] = useState('');
|
||||
const prefix = usePrefix({ status, theme });
|
||||
useKeypress(async (key, rl) => {
|
||||
// Ignore keypress while our prompt is doing other processing.
|
||||
if (status !== 'idle') {
|
||||
return;
|
||||
}
|
||||
if (isEnterKey(key)) {
|
||||
const answer = value;
|
||||
setStatus('loading');
|
||||
const isValid = await validate(answer);
|
||||
if (isValid === true) {
|
||||
setValue(answer);
|
||||
setStatus('done');
|
||||
done(answer);
|
||||
}
|
||||
else {
|
||||
// Reset the readline line value to the previous value. On line event, the value
|
||||
// get cleared, forcing the user to re-enter the value instead of fixing it.
|
||||
rl.write(value);
|
||||
setError(isValid || 'You must provide a valid value');
|
||||
setStatus('idle');
|
||||
}
|
||||
}
|
||||
else {
|
||||
setValue(rl.line);
|
||||
setError(undefined);
|
||||
}
|
||||
});
|
||||
const message = theme.style.message(config.message, status);
|
||||
let formattedValue = '';
|
||||
let helpTip;
|
||||
if (config.mask) {
|
||||
const maskChar = typeof config.mask === 'string' ? config.mask : '*';
|
||||
formattedValue = maskChar.repeat(value.length);
|
||||
}
|
||||
else if (status !== 'done') {
|
||||
helpTip = `${theme.style.help('[input is masked]')}${cursorHide}`;
|
||||
}
|
||||
if (status === 'done') {
|
||||
formattedValue = theme.style.answer(formattedValue);
|
||||
}
|
||||
let error = '';
|
||||
if (errorMsg) {
|
||||
error = theme.style.error(errorMsg);
|
||||
}
|
||||
return [[prefix, message, config.mask ? formattedValue : helpTip].join(' '), error];
|
||||
});
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"name": "@inquirer/password",
|
||||
"version": "5.0.4",
|
||||
"description": "Inquirer password prompt",
|
||||
"keywords": [
|
||||
"answer",
|
||||
"answers",
|
||||
"ask",
|
||||
"base",
|
||||
"cli",
|
||||
"command",
|
||||
"command-line",
|
||||
"confirm",
|
||||
"enquirer",
|
||||
"generate",
|
||||
"generator",
|
||||
"hyper",
|
||||
"input",
|
||||
"inquire",
|
||||
"inquirer",
|
||||
"interface",
|
||||
"iterm",
|
||||
"javascript",
|
||||
"menu",
|
||||
"node",
|
||||
"nodejs",
|
||||
"prompt",
|
||||
"promptly",
|
||||
"prompts",
|
||||
"question",
|
||||
"readline",
|
||||
"scaffold",
|
||||
"scaffolder",
|
||||
"scaffolding",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"terminal",
|
||||
"tty",
|
||||
"ui",
|
||||
"yeoman",
|
||||
"yo",
|
||||
"zsh"
|
||||
],
|
||||
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/password/README.md",
|
||||
"license": "MIT",
|
||||
"author": "Simon Boudrias <admin@simonboudrias.com>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SBoudrias/Inquirer.js.git"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/ansi": "^2.0.3",
|
||||
"@inquirer/core": "^11.1.1",
|
||||
"@inquirer/type": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@inquirer/testing": "^3.0.4",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2025 Simon Boudrias
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+528
@@ -0,0 +1,528 @@
|
||||
<img width="75px" height="75px" align="right" alt="Inquirer Logo" src="https://raw.githubusercontent.com/SBoudrias/Inquirer.js/main/assets/inquirer_readme.svg?sanitize=true" title="Inquirer.js"/>
|
||||
|
||||
# Inquirer
|
||||
|
||||
[](https://www.npmjs.com/package/@inquirer/prompts)
|
||||
[](https://app.fossa.com/projects/git%2Bgithub.com%2FSBoudrias%2FInquirer.js?ref=badge_shield)
|
||||
|
||||
A collection of common interactive command line user interfaces.
|
||||
|
||||

|
||||
|
||||
Give it a try in your own terminal!
|
||||
|
||||
```sh
|
||||
npx @inquirer/demo@latest
|
||||
```
|
||||
|
||||
# Installation
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>npm</th>
|
||||
<th>yarn</th>
|
||||
<th>pnpm</th>
|
||||
<th>bun</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
npm install @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
yarn add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
pnpm add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
```sh
|
||||
bun add @inquirer/prompts
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
> [!NOTE]
|
||||
> Inquirer recently underwent a rewrite from the ground up to reduce the package size and improve performance. The previous version of the package is still maintained (though not actively developed), and offered hundreds of community contributed prompts that might not have been migrated to the latest API. If this is what you're looking for, the [previous package is over here](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/inquirer).
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
import { input } from '@inquirer/prompts';
|
||||
|
||||
const answer = await input({ message: 'Enter your name' });
|
||||
```
|
||||
|
||||
# Prompts
|
||||
|
||||
## [Input](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/input)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { input } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/input) for usage example and options documentation.
|
||||
|
||||
## [Select](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/select)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { select } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/select) for usage example and options documentation.
|
||||
|
||||
## [Checkbox](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/checkbox)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { checkbox } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/checkbox) for usage example and options documentation.
|
||||
|
||||
## [Confirm](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/confirm)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { confirm } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/confirm) for usage example and options documentation.
|
||||
|
||||
## [Search](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/search)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { search } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/search) for usage example and options documentation.
|
||||
|
||||
## [Password](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/password)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { password } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/password) for usage example and options documentation.
|
||||
|
||||
## [Expand](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/expand)
|
||||
|
||||

|
||||

|
||||
|
||||
```js
|
||||
import { expand } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/expand) for usage example and options documentation.
|
||||
|
||||
## [Editor](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/editor)
|
||||
|
||||
Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the content of the temporary file is read as the answer. The editor used is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, the OS default is used (notepad on Windows, vim on Mac or Linux.)
|
||||
|
||||
```js
|
||||
import { editor } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/editor) for usage example and options documentation.
|
||||
|
||||
## [Number](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/number)
|
||||
|
||||
Very similar to the `input` prompt, but with built-in number validation configuration option.
|
||||
|
||||
```js
|
||||
import { number } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/number) for usage example and options documentation.
|
||||
|
||||
## [Raw List](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/rawlist)
|
||||
|
||||

|
||||
|
||||
```js
|
||||
import { rawlist } from '@inquirer/prompts';
|
||||
```
|
||||
|
||||
[See documentation](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/rawlist) for usage example and options documentation.
|
||||
|
||||
# Create your own prompts
|
||||
|
||||
The [API documentation is over here](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/core), and our [testing utilities here](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/testing).
|
||||
|
||||
# Advanced usage
|
||||
|
||||
All inquirer prompts are a function taking 2 arguments. The first argument is the prompt configuration (unique to each prompt). The second is providing contextual or runtime configuration.
|
||||
|
||||
The context options are:
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
| ----------------- | ----------------------- | -------- | ------------------------------------------------------------ |
|
||||
| input | `NodeJS.ReadableStream` | no | The stdin stream (defaults to `process.stdin`) |
|
||||
| output | `NodeJS.WritableStream` | no | The stdout stream (defaults to `process.stdout`) |
|
||||
| clearPromptOnDone | `boolean` | no | If true, we'll clear the screen after the prompt is answered |
|
||||
| signal | `AbortSignal` | no | An AbortSignal to cancel prompts asynchronously |
|
||||
|
||||
> [!WARNING]
|
||||
> When providing an input stream or piping `process.stdin`, it's very likely you need to call `process.stdin.setRawMode(true)`
|
||||
> before calling inquirer functions. Node.js usually does it automatically, but when we shadow the stdin, Node can loss track
|
||||
> and not know it has to. If the prompt isn't interactive (arrows don't work, etc), it's likely due to this.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
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,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
## Canceling prompt
|
||||
|
||||
This can be done with either an `AbortController` or `AbortSignal`.
|
||||
|
||||
```js
|
||||
// Example 1: using built-in AbortSignal utilities
|
||||
import { confirm } from '@inquirer/prompts';
|
||||
|
||||
const answer = await confirm({ ... }, { signal: AbortSignal.timeout(5000) });
|
||||
```
|
||||
|
||||
```js
|
||||
// Example 2: implementing custom cancellation with an AbortController
|
||||
import { confirm } from '@inquirer/prompts';
|
||||
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => {
|
||||
controller.abort(); // This will reject the promise
|
||||
}, 5000);
|
||||
|
||||
const answer = await confirm({ ... }, { signal: controller.signal });
|
||||
```
|
||||
|
||||
# Recipes
|
||||
|
||||
## Handling `ctrl+c` gracefully
|
||||
|
||||
When a user press `ctrl+c` to exit a prompt, Inquirer rejects the prompt promise. This is the expected behavior in order to allow your program to teardown/cleanup its environment. When using `async/await`, rejected promises throw their error. When unhandled, those errors print their stack trace in your user's terminal.
|
||||
|
||||
```
|
||||
ExitPromptError: User force closed the prompt with 0 null
|
||||
at file://example/packages/core/dist/esm/lib/create-prompt.js:55:20
|
||||
at Emitter.emit (file://example/node_modules/signal-exit/dist/mjs/index.js:67:19)
|
||||
at #processEmit (file://example/node_modules/signal-exit/dist/mjs/index.js:236:27)
|
||||
at #process.emit (file://example/node_modules/signal-exit/dist/mjs/index.js:187:37)
|
||||
at process.callbackTrampoline (node:internal/async_hooks:130:17)
|
||||
```
|
||||
|
||||
This isn't a great UX, which is why we highly recommend you to handle those errors gracefully.
|
||||
|
||||
First option is to wrap your scripts in `try/catch`; like [we do in our demo program](https://github.com/SBoudrias/Inquirer.js/blob/649e78147cbb6390a162ff842d4b21d53a233472/packages/demo/src/index.ts#L89-L95). Or handle the error in your CLI framework mechanism; for example [`Clipanion catch` method](https://mael.dev/clipanion/docs/errors#custom-error-handling).
|
||||
|
||||
Lastly, you could handle the error globally with an event listener and silence it.
|
||||
|
||||
```ts
|
||||
process.on('uncaughtException', (error) => {
|
||||
if (error instanceof Error && error.name === 'ExitPromptError') {
|
||||
console.log('👋 until next time!');
|
||||
} else {
|
||||
// Rethrow unknown errors
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Get answers in an object
|
||||
|
||||
When asking many questions, you might not want to keep one variable per answer everywhere. In which case, you can put the answer inside an object.
|
||||
|
||||
```js
|
||||
import { input, confirm } from '@inquirer/prompts';
|
||||
|
||||
const answers = {
|
||||
firstName: await input({ message: "What's your first name?" }),
|
||||
allowEmail: await confirm({ message: 'Do you allow us to send you email?' }),
|
||||
};
|
||||
|
||||
console.log(answers.firstName);
|
||||
```
|
||||
|
||||
## Ask a question conditionally
|
||||
|
||||
Maybe some questions depend on some other question's answer.
|
||||
|
||||
```js
|
||||
import { input, confirm } from '@inquirer/prompts';
|
||||
|
||||
const allowEmail = await confirm({ message: 'Do you allow us to send you email?' });
|
||||
|
||||
let email;
|
||||
if (allowEmail) {
|
||||
email = await input({ message: 'What is your email address' });
|
||||
}
|
||||
```
|
||||
|
||||
## Get default value after timeout
|
||||
|
||||
```js
|
||||
import { input } from '@inquirer/prompts';
|
||||
|
||||
const answer = await input(
|
||||
{ message: 'Enter a value (timing out in 5 seconds)' },
|
||||
{ signal: AbortSignal.timeout(5000) },
|
||||
).catch((error) => {
|
||||
if (error.name === 'AbortPromptError') {
|
||||
return 'Default value';
|
||||
}
|
||||
|
||||
throw error;
|
||||
});
|
||||
```
|
||||
|
||||
## Using as pre-commit/git hooks, or scripts
|
||||
|
||||
By default scripts ran from tools like `husky`/`lint-staged` might not run inside an interactive shell. In non-interactive shell, Inquirer cannot run, and users cannot send keypress events to the process.
|
||||
|
||||
For it to work, you must make sure you start a `tty` (or "interactive" input stream.)
|
||||
|
||||
If those scripts are set within your `package.json`, you can define the stream like so:
|
||||
|
||||
```json
|
||||
"precommit": "my-script < /dev/tty"
|
||||
```
|
||||
|
||||
Or if in a shell script file, you'll do it like so: (on Windows that's likely your only option)
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
exec < /dev/tty
|
||||
|
||||
node my-script.js
|
||||
```
|
||||
|
||||
## Using with nodemon
|
||||
|
||||
When using inquirer prompts with nodemon, you need to pass the `--no-stdin` flag for everything to work as expected.
|
||||
|
||||
```sh
|
||||
npx nodemon ./packages/demo/demos/password.mjs --no-stdin
|
||||
```
|
||||
|
||||
Note that for most of you, you'll be able to use the new watch-mode built-in Node. This mode works out of the box with inquirer.
|
||||
|
||||
```sh
|
||||
# One of depending on your need
|
||||
node --watch script.js
|
||||
node --watch-path=packages/ packages/demo/
|
||||
```
|
||||
|
||||
## Wait for config
|
||||
|
||||
Maybe some question configuration require to await a value.
|
||||
|
||||
```js
|
||||
import { confirm } from '@inquirer/prompts';
|
||||
|
||||
const answer = await confirm({ message: await getMessage() });
|
||||
```
|
||||
|
||||
## Usage with `npx` within bash scripts
|
||||
|
||||
You can use Inquirer prompts directly in the shell via [`npx`](https://docs.npmjs.com/cli/v8/commands/npx), which is useful for quick scripts or `package.json` commands.
|
||||
|
||||
A community library, [@inquirer-cli](https://github.com/fishballapp/inquirer-cli), exposes each prompt as a standalone CLI.
|
||||
|
||||
For example, to prompt for input:
|
||||
|
||||
```bash
|
||||
name=$(npx -y @inquirer-cli/input -r "What is your name?")
|
||||
echo "Hello, $name!"
|
||||
```
|
||||
|
||||
Or to create an interactive version bump:
|
||||
|
||||
```bash
|
||||
$ npm version $(npx -y @inquirer-cli/select -c patch -c minor -c major 'Select Version')
|
||||
```
|
||||
|
||||
Find out more: [@inquirer-cli](https://github.com/fishballapp/inquirer-cli).
|
||||
|
||||
# Community prompts
|
||||
|
||||
If you created a cool prompt, [send us a PR adding it](https://github.com/SBoudrias/Inquirer.js/edit/main/packages/prompts/README.md) to the list below!
|
||||
|
||||
[**Interactive List Prompt**](https://github.com/pgibler/inquirer-interactive-list-prompt)<br/>
|
||||
Select a choice either with arrow keys + Enter or by pressing a key associated with a choice.
|
||||
|
||||
```
|
||||
? Choose an option:
|
||||
> Run command (D)
|
||||
Quit (Q)
|
||||
```
|
||||
|
||||
[**Action Select Prompt**](https://github.com/zenithlight/inquirer-action-select)<br/>
|
||||
Choose an item from a list and choose an action to take by pressing a key.
|
||||
|
||||
```
|
||||
? Choose a file Open <O> Edit <E> Delete <X>
|
||||
❯ image.png
|
||||
audio.mp3
|
||||
code.py
|
||||
```
|
||||
|
||||
[**Table Multiple Prompt**](https://github.com/Bartheleway/inquirer-table-multiple)<br/>
|
||||
Select multiple answer from a table display.
|
||||
|
||||
```sh
|
||||
Choose between choices? (Press <space> to select, <Up and Down> to move rows,
|
||||
<Left and Right> to move columns)
|
||||
|
||||
┌──────────┬───────┬───────┐
|
||||
│ 1-2 of 2 │ Yes? │ No? |
|
||||
├──────────┼───────┼───────┤
|
||||
│ Choice 1 │ [ ◯ ] │ ◯ |
|
||||
├──────────┼───────┼───────┤
|
||||
│ Choice 2 │ ◯ │ ◯ |
|
||||
└──────────┴───────┴───────┘
|
||||
|
||||
```
|
||||
|
||||
[**Toggle Prompt**](https://github.com/skarahoda/inquirer-toggle)<br/>
|
||||
Confirm with a toggle. Select a choice with arrow keys + Enter.
|
||||
|
||||
```
|
||||
? Do you want to continue? no / yes
|
||||
```
|
||||
|
||||
[**Sortable Checkbox Prompt**](https://github.com/th0r/inquirer-sortable-checkbox)<br/>
|
||||
The same as built-in checkbox prompt, but also allowing to reorder choices using ctrl+up/down.
|
||||
|
||||
```
|
||||
? Which PRs and in what order would you like to merge? (Press <space> to select, <a> to toggle all, <i> to invert selection, <ctrl+up> to move item up, <ctrl+down> to move item down, and <enter> to proceed)
|
||||
❯ ◯ PR 1
|
||||
◯ PR 2
|
||||
◯ PR 3
|
||||
```
|
||||
|
||||
[**Multi Select Prompt**](https://github.com/jeffwcx/inquirer-select-pro)
|
||||
|
||||
An inquirer select that supports multiple selections and filtering/searching.
|
||||
|
||||
```
|
||||
? Choose your OS, IDE, PL, etc. (Press <tab> to select/deselect, <backspace> to remove selected
|
||||
option, <enter> to select option)
|
||||
>> vue
|
||||
>[ ] vue
|
||||
[ ] vuejs
|
||||
[ ] fuelphp
|
||||
[ ] venv
|
||||
[ ] vercel
|
||||
(Use arrow keys to reveal more options)
|
||||
```
|
||||
|
||||
[**File Selector Prompt**](https://github.com/br14n-sol/inquirer-file-selector)<br/>
|
||||
A file selector, you can navigate freely between directories, choose what type of files you want to allow and it is fully customizable.
|
||||
|
||||
```sh
|
||||
? Select a file:
|
||||
/main/path/
|
||||
├── folder1/
|
||||
├── folder2/
|
||||
├── folder3/
|
||||
├── file1.txt
|
||||
├── file2.pdf
|
||||
└── file3.jpg (not allowed)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
Use ↑↓ to navigate through the list
|
||||
Press <esc> to navigate to the parent directory
|
||||
Press <enter> to select a file or navigate to a directory
|
||||
```
|
||||
|
||||
[**Select Prompt with Stateful Banner**](https://github.com/patik/inquirer-select-with-state)<br/>
|
||||
The same as built-in select prompt, but it also displays a banner above the prompt which can be updated with a `setState` function. For example, it can display the results of a long-running command without making the user wait to see the prompt.
|
||||
|
||||
Initial display:
|
||||
|
||||
```
|
||||
Directory size: loading...
|
||||
? Choose an option
|
||||
❯ Rename
|
||||
Copy
|
||||
Delete
|
||||
```
|
||||
|
||||
A moment later:
|
||||
|
||||
```
|
||||
Directory size: 123M
|
||||
? Choose an option
|
||||
❯ Rename
|
||||
Copy
|
||||
Delete
|
||||
```
|
||||
|
||||
[**Ordered Checkbox Prompt**](https://github.com/kyou-izumi/inquirer-ordered-checkbox)<br/>
|
||||
A sortable checkbox prompt that maintains the order of selection. Perfect for prioritizing tasks or ranking options.
|
||||
|
||||
```
|
||||
? 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)
|
||||
```
|
||||
|
||||
[**Checkbox Plus Plus Prompt**](https://github.com/behnamazimi/inquirer-checkbox-plus-plus)<br/>
|
||||
A modern multiselect checkbox prompt with search and filter capabilities, highlighting, autocomplete, and improved UX. Supports both ESM and CommonJS and is compatible with @inquirer/core v10+.
|
||||
|
||||
```
|
||||
? 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
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
|
||||
Licensed under the MIT license.
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export { default as checkbox, Separator } from '@inquirer/checkbox';
|
||||
export { default as editor } from '@inquirer/editor';
|
||||
export { default as confirm } from '@inquirer/confirm';
|
||||
export { default as input } from '@inquirer/input';
|
||||
export { default as number } from '@inquirer/number';
|
||||
export { default as expand } from '@inquirer/expand';
|
||||
export { default as rawlist } from '@inquirer/rawlist';
|
||||
export { default as password } from '@inquirer/password';
|
||||
export { default as search } from '@inquirer/search';
|
||||
export { default as select } from '@inquirer/select';
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export { default as checkbox, Separator } from '@inquirer/checkbox';
|
||||
export { default as editor } from '@inquirer/editor';
|
||||
export { default as confirm } from '@inquirer/confirm';
|
||||
export { default as input } from '@inquirer/input';
|
||||
export { default as number } from '@inquirer/number';
|
||||
export { default as expand } from '@inquirer/expand';
|
||||
export { default as rawlist } from '@inquirer/rawlist';
|
||||
export { default as password } from '@inquirer/password';
|
||||
export { default as search } from '@inquirer/search';
|
||||
export { default as select } from '@inquirer/select';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user