@inquirer/core 9.1.0 → 9.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -154,7 +154,7 @@ All default prompts, and most custom ones, uses a prefix at the beginning of the
154
154
 
155
155
  ```ts
156
156
  const input = createPrompt((config, done) => {
157
- const prefix = usePrefix({ isLoading });
157
+ const prefix = usePrefix({ status });
158
158
 
159
159
  return `${prefix} My question`;
160
160
  });
@@ -265,7 +265,7 @@ type PromptConfig = {
265
265
  export default createPrompt<string, PromptConfig>((config, done) => {
266
266
  const theme = makeTheme(config.theme);
267
267
 
268
- const prefix = usePrefix({ isLoading, theme });
268
+ const prefix = usePrefix({ status, theme });
269
269
 
270
270
  return `${prefix} ${theme.style.highlight('hello')}`;
271
271
  });
@@ -290,7 +290,7 @@ type PromptConfig = {
290
290
  export default createPrompt<string, PromptConfig>((config, done) => {
291
291
  const theme = makeTheme(promptTheme, config.theme);
292
292
 
293
- const prefix = usePrefix({ isLoading, theme });
293
+ const prefix = usePrefix({ status, theme });
294
294
 
295
295
  return `${prefix} ${theme.icon}`;
296
296
  });
@@ -300,14 +300,14 @@ The [default theme keys cover](https://github.com/SBoudrias/Inquirer.js/blob/the
300
300
 
301
301
  ```ts
302
302
  type DefaultTheme = {
303
- prefix: string;
303
+ prefix: string | { idle: string; done: string };
304
304
  spinner: {
305
305
  interval: number;
306
306
  frames: string[];
307
307
  };
308
308
  style: {
309
309
  answer: (text: string) => string;
310
- message: (text: string) => string;
310
+ message: (text: string, status: 'idle' | 'done' | 'loading') => string;
311
311
  error: (text: string) => string;
312
312
  defaultAnswer: (text: string) => string;
313
313
  help: (text: string) => string;
@@ -338,11 +338,12 @@ import {
338
338
  useKeypress,
339
339
  isEnterKey,
340
340
  usePrefix,
341
+ type Status,
341
342
  } from '@inquirer/core';
342
343
 
343
344
  const confirm = createPrompt<boolean, { message: string; default?: boolean }>(
344
345
  (config, done) => {
345
- const [status, setStatus] = useState('pending');
346
+ const [status, setStatus] = useState<Status>('idle');
346
347
  const [value, setValue] = useState('');
347
348
  const prefix = usePrefix({});
348
349
 
@@ -32,7 +32,7 @@ const node_async_hooks_1 = require("node:async_hooks");
32
32
  const mute_stream_1 = __importDefault(require("mute-stream"));
33
33
  const signal_exit_1 = require("signal-exit");
34
34
  const screen_manager_mjs_1 = __importDefault(require('./screen-manager.js'));
35
- const type_1 = require("@inquirer/type");
35
+ const promise_polyfill_mjs_1 = require('./promise-polyfill.js');
36
36
  const hook_engine_mjs_1 = require('./hook-engine.js');
37
37
  const errors_mjs_1 = require('./errors.js');
38
38
  function createPrompt(view) {
@@ -40,6 +40,7 @@ function createPrompt(view) {
40
40
  var _a;
41
41
  // Default `input` to stdin
42
42
  const { input = process.stdin, signal } = context;
43
+ const cleanups = new Set();
43
44
  // Add mute capabilities to the output
44
45
  const output = new mute_stream_1.default();
45
46
  output.pipe((_a = context.output) !== null && _a !== void 0 ? _a : process.stdout);
@@ -49,75 +50,65 @@ function createPrompt(view) {
49
50
  output,
50
51
  });
51
52
  const screen = new screen_manager_mjs_1.default(rl);
52
- const cleanups = new Set();
53
- const { promise, resolve, reject } = type_1.CancelablePromise.withResolver();
54
- function onExit() {
55
- cleanups.forEach((cleanup) => cleanup());
56
- screen.done({ clearContent: Boolean(context === null || context === void 0 ? void 0 : context.clearPromptOnDone) });
57
- output.end();
58
- }
59
- function fail(error) {
60
- onExit();
61
- reject(error);
62
- }
53
+ const { promise, resolve, reject } = promise_polyfill_mjs_1.PromisePolyfill.withResolver();
54
+ /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */
55
+ const cancel = () => reject(new errors_mjs_1.CancelPromptError());
63
56
  if (signal) {
64
- const abort = () => fail(new errors_mjs_1.AbortPromptError({ cause: signal.reason }));
57
+ const abort = () => reject(new errors_mjs_1.AbortPromptError({ cause: signal.reason }));
65
58
  if (signal.aborted) {
66
59
  abort();
67
- return promise;
60
+ return Object.assign(promise, { cancel });
68
61
  }
69
62
  signal.addEventListener('abort', abort);
70
63
  cleanups.add(() => signal.removeEventListener('abort', abort));
71
64
  }
72
- (0, hook_engine_mjs_1.withHooks)(rl, (cycle) => {
73
- cleanups.add((0, signal_exit_1.onExit)((code, signal) => {
74
- fail(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
75
- }));
76
- const hooksCleanup = node_async_hooks_1.AsyncResource.bind(() => {
77
- try {
78
- hook_engine_mjs_1.effectScheduler.clearAll();
79
- }
80
- catch (error) {
81
- reject(error);
82
- }
83
- });
84
- cleanups.add(hooksCleanup);
85
- // Re-renders only happen when the state change; but the readline cursor could change position
86
- // and that also requires a re-render (and a manual one because we mute the streams).
87
- // We set the listener after the initial workLoop to avoid a double render if render triggered
88
- // by a state change sets the cursor to the right position.
89
- const checkCursorPos = () => screen.checkCursorPos();
90
- rl.input.on('keypress', checkCursorPos);
91
- cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
65
+ cleanups.add((0, signal_exit_1.onExit)((code, signal) => {
66
+ reject(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
67
+ }));
68
+ // Re-renders only happen when the state change; but the readline cursor could change position
69
+ // and that also requires a re-render (and a manual one because we mute the streams).
70
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
71
+ // by a state change sets the cursor to the right position.
72
+ const checkCursorPos = () => screen.checkCursorPos();
73
+ rl.input.on('keypress', checkCursorPos);
74
+ cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
75
+ return (0, hook_engine_mjs_1.withHooks)(rl, (cycle) => {
92
76
  // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
93
77
  // triggers after the process is done (which happens after timeouts are done triggering.)
94
78
  // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
79
+ const hooksCleanup = node_async_hooks_1.AsyncResource.bind(() => hook_engine_mjs_1.effectScheduler.clearAll());
95
80
  rl.on('close', hooksCleanup);
96
81
  cleanups.add(() => rl.removeListener('close', hooksCleanup));
97
- function done(value) {
98
- // Delay execution to let time to the hookCleanup functions to registers.
99
- setImmediate(() => {
100
- onExit();
101
- // Finally we resolve our promise
102
- resolve(value);
103
- });
104
- }
105
82
  cycle(() => {
106
83
  try {
107
- const nextView = view(config, done);
84
+ const nextView = view(config, (value) => {
85
+ setImmediate(() => resolve(value));
86
+ });
108
87
  const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
109
88
  screen.render(content, bottomContent);
110
89
  hook_engine_mjs_1.effectScheduler.run();
111
90
  }
112
91
  catch (error) {
113
- fail(error);
92
+ reject(error);
114
93
  }
115
94
  });
95
+ return Object.assign(promise
96
+ .then((answer) => {
97
+ hook_engine_mjs_1.effectScheduler.clearAll();
98
+ return answer;
99
+ }, (error) => {
100
+ hook_engine_mjs_1.effectScheduler.clearAll();
101
+ throw error;
102
+ })
103
+ // Wait for the promise to settle, then cleanup.
104
+ .finally(() => {
105
+ cleanups.forEach((cleanup) => cleanup());
106
+ screen.done({ clearContent: Boolean(context === null || context === void 0 ? void 0 : context.clearPromptOnDone) });
107
+ output.end();
108
+ })
109
+ // Once cleanup is done, let the expose promise resolve/reject to the internal one.
110
+ .then(() => promise), { cancel });
116
111
  });
117
- promise.cancel = () => {
118
- fail(new errors_mjs_1.CancelPromptError());
119
- };
120
- return promise;
121
112
  };
122
113
  return prompt;
123
114
  }
@@ -32,7 +32,7 @@ function withHooks(rl, cb) {
32
32
  };
33
33
  store.handleChange();
34
34
  }
35
- cb(cycle);
35
+ return cb(cycle);
36
36
  });
37
37
  }
38
38
  // Safe getStore utility that'll return the store or throw if undefined.
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PromisePolyfill = void 0;
4
+ // TODO: Remove this class once Node 22 becomes the minimum supported version.
5
+ class PromisePolyfill extends Promise {
6
+ // Available starting from Node 22
7
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
8
+ static withResolver() {
9
+ let resolve;
10
+ let reject;
11
+ const promise = new Promise((res, rej) => {
12
+ resolve = res;
13
+ reject = rej;
14
+ });
15
+ return { promise, resolve: resolve, reject: reject };
16
+ }
17
+ }
18
+ exports.PromisePolyfill = PromisePolyfill;
@@ -5,12 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.defaultTheme = void 0;
7
7
  const yoctocolors_cjs_1 = __importDefault(require("yoctocolors-cjs"));
8
- const cli_spinners_1 = __importDefault(require("cli-spinners"));
8
+ const figures_1 = __importDefault(require("@inquirer/figures"));
9
9
  exports.defaultTheme = {
10
- prefix: yoctocolors_cjs_1.default.green('?'),
10
+ prefix: {
11
+ idle: yoctocolors_cjs_1.default.blue('?'),
12
+ // TODO: use figure
13
+ done: yoctocolors_cjs_1.default.green(figures_1.default.tick),
14
+ },
11
15
  spinner: {
12
- interval: cli_spinners_1.default.dots.interval,
13
- frames: cli_spinners_1.default.dots.frames.map((frame) => yoctocolors_cjs_1.default.yellow(frame)),
16
+ interval: 80,
17
+ frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => yoctocolors_cjs_1.default.yellow(frame)),
14
18
  },
15
19
  style: {
16
20
  answer: yoctocolors_cjs_1.default.cyan,
@@ -5,12 +5,12 @@ const node_async_hooks_1 = require("node:async_hooks");
5
5
  const use_state_mjs_1 = require('./use-state.js');
6
6
  const use_effect_mjs_1 = require('./use-effect.js');
7
7
  const make_theme_mjs_1 = require('./make-theme.js');
8
- function usePrefix({ isLoading = false, theme, }) {
8
+ function usePrefix({ status = 'idle', theme, }) {
9
9
  const [showLoader, setShowLoader] = (0, use_state_mjs_1.useState)(false);
10
10
  const [tick, setTick] = (0, use_state_mjs_1.useState)(0);
11
11
  const { prefix, spinner } = (0, make_theme_mjs_1.makeTheme)(theme);
12
12
  (0, use_effect_mjs_1.useEffect)(() => {
13
- if (isLoading) {
13
+ if (status === 'loading') {
14
14
  let tickInterval;
15
15
  let inc = -1;
16
16
  // Delay displaying spinner by 300ms, to avoid flickering
@@ -29,9 +29,11 @@ function usePrefix({ isLoading = false, theme, }) {
29
29
  else {
30
30
  setShowLoader(false);
31
31
  }
32
- }, [isLoading]);
32
+ }, [status]);
33
33
  if (showLoader) {
34
34
  return spinner.frames[tick];
35
35
  }
36
- return prefix;
36
+ // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
37
+ const iconName = status === 'loading' ? 'idle' : status;
38
+ return typeof prefix === 'string' ? prefix : prefix[iconName];
37
39
  }
@@ -7,7 +7,7 @@ export { useMemo } from './lib/use-memo.js';
7
7
  export { useRef } from './lib/use-ref.js';
8
8
  export { useKeypress } from './lib/use-keypress.js';
9
9
  export { makeTheme } from './lib/make-theme.js';
10
- export type { Theme } from './lib/theme.js';
10
+ export type { Theme, Status } from './lib/theme.js';
11
11
  export { usePagination } from './lib/pagination/use-pagination.js';
12
12
  export { createPrompt } from './lib/create-prompt.js';
13
13
  export { Separator } from './lib/Separator.js';
@@ -1,5 +1,5 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
- export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
2
+ export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
3
3
  export declare function readline(): InquirerReadline;
4
4
  export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
@@ -0,0 +1,7 @@
1
+ export declare class PromisePolyfill<T> extends Promise<T> {
2
+ static withResolver<T>(): {
3
+ promise: Promise<T>;
4
+ resolve: (value: T) => void;
5
+ reject: (error: unknown) => void;
6
+ };
7
+ }
@@ -1,17 +1,151 @@
1
1
  import type { Prettify } from '@inquirer/type';
2
+ /**
3
+ * Union type representing the possible statuses of a prompt.
4
+ *
5
+ * - `'loading'`: The prompt is currently loading.
6
+ * - `'idle'`: The prompt is loaded and currently waiting for the user to
7
+ * submit an answer.
8
+ * - `'done'`: The user has submitted an answer and the prompt is finished.
9
+ */
10
+ export type Status = 'loading' | 'idle' | 'done';
2
11
  type DefaultTheme = {
3
- prefix: string;
12
+ /**
13
+ * Prefix to prepend to the message. If a function is provided, it will be
14
+ * called with the current status of the prompt, and the return value will be
15
+ * used as the prefix.
16
+ *
17
+ * @remarks
18
+ * If `status === 'loading'`, this property is ignored and the spinner (styled
19
+ * by the `spinner` property) will be displayed instead.
20
+ *
21
+ * @defaultValue
22
+ * ```ts
23
+ * // import colors from 'yoctocolors-cjs';
24
+ * (status) => status === 'done' ? colors.green('✔') : colors.blue('?')
25
+ * ```
26
+ */
27
+ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
28
+ /**
29
+ * Configuration for the spinner that is displayed when the prompt is in the
30
+ * `'loading'` state.
31
+ *
32
+ * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
33
+ */
4
34
  spinner: {
35
+ /**
36
+ * The time interval between frames, in milliseconds.
37
+ *
38
+ * @defaultValue
39
+ * ```ts
40
+ * 80
41
+ * ```
42
+ */
5
43
  interval: number;
44
+ /**
45
+ * A list of frames to show for the spinner.
46
+ *
47
+ * @defaultValue
48
+ * ```ts
49
+ * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
50
+ * ```
51
+ */
6
52
  frames: string[];
7
53
  };
54
+ /**
55
+ * Object containing functions to style different parts of the prompt.
56
+ */
8
57
  style: {
58
+ /**
59
+ * Style to apply to the user's answer once it has been submitted.
60
+ *
61
+ * @param text - The user's answer.
62
+ * @returns The styled answer.
63
+ *
64
+ * @defaultValue
65
+ * ```ts
66
+ * // import colors from 'yoctocolors-cjs';
67
+ * (text) => colors.cyan(text)
68
+ * ```
69
+ */
9
70
  answer: (text: string) => string;
10
- message: (text: string) => string;
71
+ /**
72
+ * Style to apply to the message displayed to the user.
73
+ *
74
+ * @param text - The message to style.
75
+ * @param status - The current status of the prompt.
76
+ * @returns The styled message.
77
+ *
78
+ * @defaultValue
79
+ * ```ts
80
+ * // import colors from 'yoctocolors-cjs';
81
+ * (text, status) => colors.bold(text)
82
+ * ```
83
+ */
84
+ message: (text: string, status: Status) => string;
85
+ /**
86
+ * Style to apply to error messages.
87
+ *
88
+ * @param text - The error message.
89
+ * @returns The styled error message.
90
+ *
91
+ * @defaultValue
92
+ * ```ts
93
+ * // import colors from 'yoctocolors-cjs';
94
+ * (text) => colors.red(`> ${text}`)
95
+ * ```
96
+ */
11
97
  error: (text: string) => string;
98
+ /**
99
+ * Style to apply to the default answer when one is provided.
100
+ *
101
+ * @param text - The default answer.
102
+ * @returns The styled default answer.
103
+ *
104
+ * @defaultValue
105
+ * ```ts
106
+ * // import colors from 'yoctocolors-cjs';
107
+ * (text) => colors.dim(`(${text})`)
108
+ * ```
109
+ */
12
110
  defaultAnswer: (text: string) => string;
111
+ /**
112
+ * Style to apply to help text.
113
+ *
114
+ * @param text - The help text.
115
+ * @returns The styled help text.
116
+ *
117
+ * @defaultValue
118
+ * ```ts
119
+ * // import colors from 'yoctocolors-cjs';
120
+ * (text) => colors.dim(text)
121
+ * ```
122
+ */
13
123
  help: (text: string) => string;
124
+ /**
125
+ * Style to apply to highlighted text.
126
+ *
127
+ * @param text - The text to highlight.
128
+ * @returns The highlighted text.
129
+ *
130
+ * @defaultValue
131
+ * ```ts
132
+ * // import colors from 'yoctocolors-cjs';
133
+ * (text) => colors.cyan(text)
134
+ * ```
135
+ */
14
136
  highlight: (text: string) => string;
137
+ /**
138
+ * Style to apply to keyboard keys referred to in help texts.
139
+ *
140
+ * @param text - The key to style.
141
+ * @returns The styled key.
142
+ *
143
+ * @defaultValue
144
+ * ```ts
145
+ * // import colors from 'yoctocolors-cjs';
146
+ * (text) => colors.cyan(colors.bold(`<${text}>`))
147
+ * ```
148
+ */
15
149
  key: (text: string) => string;
16
150
  };
17
151
  };
@@ -1,5 +1,5 @@
1
- import { type Theme } from './theme.js';
2
- export declare function usePrefix({ isLoading, theme, }: {
3
- isLoading?: boolean;
1
+ import type { Theme, Status } from './theme.js';
2
+ export declare function usePrefix({ status, theme, }: {
3
+ status?: Status;
4
4
  theme?: Theme;
5
5
  }): string;
@@ -1,4 +1,4 @@
1
1
  type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
2
  export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
- export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void];
3
+ export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
4
4
  export {};
@@ -3,13 +3,14 @@ import { AsyncResource } from 'node:async_hooks';
3
3
  import MuteStream from 'mute-stream';
4
4
  import { onExit as onSignalExit } from 'signal-exit';
5
5
  import ScreenManager from './screen-manager.mjs';
6
- import { CancelablePromise } from '@inquirer/type';
6
+ import { PromisePolyfill } from './promise-polyfill.mjs';
7
7
  import { withHooks, effectScheduler } from './hook-engine.mjs';
8
8
  import { AbortPromptError, CancelPromptError, ExitPromptError } from './errors.mjs';
9
9
  export function createPrompt(view) {
10
10
  const prompt = (config, context = {}) => {
11
11
  // Default `input` to stdin
12
12
  const { input = process.stdin, signal } = context;
13
+ const cleanups = new Set();
13
14
  // Add mute capabilities to the output
14
15
  const output = new MuteStream();
15
16
  output.pipe(context.output ?? process.stdout);
@@ -19,75 +20,65 @@ export function createPrompt(view) {
19
20
  output,
20
21
  });
21
22
  const screen = new ScreenManager(rl);
22
- const cleanups = new Set();
23
- const { promise, resolve, reject } = CancelablePromise.withResolver();
24
- function onExit() {
25
- cleanups.forEach((cleanup) => cleanup());
26
- screen.done({ clearContent: Boolean(context?.clearPromptOnDone) });
27
- output.end();
28
- }
29
- function fail(error) {
30
- onExit();
31
- reject(error);
32
- }
23
+ const { promise, resolve, reject } = PromisePolyfill.withResolver();
24
+ /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */
25
+ const cancel = () => reject(new CancelPromptError());
33
26
  if (signal) {
34
- const abort = () => fail(new AbortPromptError({ cause: signal.reason }));
27
+ const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
35
28
  if (signal.aborted) {
36
29
  abort();
37
- return promise;
30
+ return Object.assign(promise, { cancel });
38
31
  }
39
32
  signal.addEventListener('abort', abort);
40
33
  cleanups.add(() => signal.removeEventListener('abort', abort));
41
34
  }
42
- withHooks(rl, (cycle) => {
43
- cleanups.add(onSignalExit((code, signal) => {
44
- fail(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
45
- }));
46
- const hooksCleanup = AsyncResource.bind(() => {
47
- try {
48
- effectScheduler.clearAll();
49
- }
50
- catch (error) {
51
- reject(error);
52
- }
53
- });
54
- cleanups.add(hooksCleanup);
55
- // Re-renders only happen when the state change; but the readline cursor could change position
56
- // and that also requires a re-render (and a manual one because we mute the streams).
57
- // We set the listener after the initial workLoop to avoid a double render if render triggered
58
- // by a state change sets the cursor to the right position.
59
- const checkCursorPos = () => screen.checkCursorPos();
60
- rl.input.on('keypress', checkCursorPos);
61
- cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
35
+ cleanups.add(onSignalExit((code, signal) => {
36
+ reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
37
+ }));
38
+ // Re-renders only happen when the state change; but the readline cursor could change position
39
+ // and that also requires a re-render (and a manual one because we mute the streams).
40
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
41
+ // by a state change sets the cursor to the right position.
42
+ const checkCursorPos = () => screen.checkCursorPos();
43
+ rl.input.on('keypress', checkCursorPos);
44
+ cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
45
+ return withHooks(rl, (cycle) => {
62
46
  // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
63
47
  // triggers after the process is done (which happens after timeouts are done triggering.)
64
48
  // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
49
+ const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());
65
50
  rl.on('close', hooksCleanup);
66
51
  cleanups.add(() => rl.removeListener('close', hooksCleanup));
67
- function done(value) {
68
- // Delay execution to let time to the hookCleanup functions to registers.
69
- setImmediate(() => {
70
- onExit();
71
- // Finally we resolve our promise
72
- resolve(value);
73
- });
74
- }
75
52
  cycle(() => {
76
53
  try {
77
- const nextView = view(config, done);
54
+ const nextView = view(config, (value) => {
55
+ setImmediate(() => resolve(value));
56
+ });
78
57
  const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
79
58
  screen.render(content, bottomContent);
80
59
  effectScheduler.run();
81
60
  }
82
61
  catch (error) {
83
- fail(error);
62
+ reject(error);
84
63
  }
85
64
  });
65
+ return Object.assign(promise
66
+ .then((answer) => {
67
+ effectScheduler.clearAll();
68
+ return answer;
69
+ }, (error) => {
70
+ effectScheduler.clearAll();
71
+ throw error;
72
+ })
73
+ // Wait for the promise to settle, then cleanup.
74
+ .finally(() => {
75
+ cleanups.forEach((cleanup) => cleanup());
76
+ screen.done({ clearContent: Boolean(context?.clearPromptOnDone) });
77
+ output.end();
78
+ })
79
+ // Once cleanup is done, let the expose promise resolve/reject to the internal one.
80
+ .then(() => promise), { cancel });
86
81
  });
87
- promise.cancel = () => {
88
- fail(new CancelPromptError());
89
- };
90
- return promise;
91
82
  };
92
83
  return prompt;
93
84
  }
@@ -24,7 +24,7 @@ export function withHooks(rl, cb) {
24
24
  };
25
25
  store.handleChange();
26
26
  }
27
- cb(cycle);
27
+ return cb(cycle);
28
28
  });
29
29
  }
30
30
  // Safe getStore utility that'll return the store or throw if undefined.
@@ -0,0 +1,14 @@
1
+ // TODO: Remove this class once Node 22 becomes the minimum supported version.
2
+ export class PromisePolyfill extends Promise {
3
+ // Available starting from Node 22
4
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
5
+ static withResolver() {
6
+ let resolve;
7
+ let reject;
8
+ const promise = new Promise((res, rej) => {
9
+ resolve = res;
10
+ reject = rej;
11
+ });
12
+ return { promise, resolve: resolve, reject: reject };
13
+ }
14
+ }
@@ -1,10 +1,14 @@
1
1
  import colors from 'yoctocolors-cjs';
2
- import spinners from 'cli-spinners';
2
+ import figures from '@inquirer/figures';
3
3
  export const defaultTheme = {
4
- prefix: colors.green('?'),
4
+ prefix: {
5
+ idle: colors.blue('?'),
6
+ // TODO: use figure
7
+ done: colors.green(figures.tick),
8
+ },
5
9
  spinner: {
6
- interval: spinners.dots.interval,
7
- frames: spinners.dots.frames.map((frame) => colors.yellow(frame)),
10
+ interval: 80,
11
+ frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => colors.yellow(frame)),
8
12
  },
9
13
  style: {
10
14
  answer: colors.cyan,
@@ -2,12 +2,12 @@ import { AsyncResource } from 'node:async_hooks';
2
2
  import { useState } from './use-state.mjs';
3
3
  import { useEffect } from './use-effect.mjs';
4
4
  import { makeTheme } from './make-theme.mjs';
5
- export function usePrefix({ isLoading = false, theme, }) {
5
+ export function usePrefix({ status = 'idle', theme, }) {
6
6
  const [showLoader, setShowLoader] = useState(false);
7
7
  const [tick, setTick] = useState(0);
8
8
  const { prefix, spinner } = makeTheme(theme);
9
9
  useEffect(() => {
10
- if (isLoading) {
10
+ if (status === 'loading') {
11
11
  let tickInterval;
12
12
  let inc = -1;
13
13
  // Delay displaying spinner by 300ms, to avoid flickering
@@ -26,9 +26,11 @@ export function usePrefix({ isLoading = false, theme, }) {
26
26
  else {
27
27
  setShowLoader(false);
28
28
  }
29
- }, [isLoading]);
29
+ }, [status]);
30
30
  if (showLoader) {
31
31
  return spinner.frames[tick];
32
32
  }
33
- return prefix;
33
+ // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
34
+ const iconName = status === 'loading' ? 'idle' : status;
35
+ return typeof prefix === 'string' ? prefix : prefix[iconName];
34
36
  }
@@ -7,7 +7,7 @@ export { useMemo } from './lib/use-memo.mjs';
7
7
  export { useRef } from './lib/use-ref.mjs';
8
8
  export { useKeypress } from './lib/use-keypress.mjs';
9
9
  export { makeTheme } from './lib/make-theme.mjs';
10
- export type { Theme } from './lib/theme.mjs';
10
+ export type { Theme, Status } from './lib/theme.mjs';
11
11
  export { usePagination } from './lib/pagination/use-pagination.mjs';
12
12
  export { createPrompt } from './lib/create-prompt.mjs';
13
13
  export { Separator } from './lib/Separator.mjs';
@@ -1,5 +1,5 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
- export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
2
+ export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
3
3
  export declare function readline(): InquirerReadline;
4
4
  export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
@@ -0,0 +1,7 @@
1
+ export declare class PromisePolyfill<T> extends Promise<T> {
2
+ static withResolver<T>(): {
3
+ promise: Promise<T>;
4
+ resolve: (value: T) => void;
5
+ reject: (error: unknown) => void;
6
+ };
7
+ }
@@ -1,17 +1,151 @@
1
1
  import type { Prettify } from '@inquirer/type';
2
+ /**
3
+ * Union type representing the possible statuses of a prompt.
4
+ *
5
+ * - `'loading'`: The prompt is currently loading.
6
+ * - `'idle'`: The prompt is loaded and currently waiting for the user to
7
+ * submit an answer.
8
+ * - `'done'`: The user has submitted an answer and the prompt is finished.
9
+ */
10
+ export type Status = 'loading' | 'idle' | 'done';
2
11
  type DefaultTheme = {
3
- prefix: string;
12
+ /**
13
+ * Prefix to prepend to the message. If a function is provided, it will be
14
+ * called with the current status of the prompt, and the return value will be
15
+ * used as the prefix.
16
+ *
17
+ * @remarks
18
+ * If `status === 'loading'`, this property is ignored and the spinner (styled
19
+ * by the `spinner` property) will be displayed instead.
20
+ *
21
+ * @defaultValue
22
+ * ```ts
23
+ * // import colors from 'yoctocolors-cjs';
24
+ * (status) => status === 'done' ? colors.green('✔') : colors.blue('?')
25
+ * ```
26
+ */
27
+ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
28
+ /**
29
+ * Configuration for the spinner that is displayed when the prompt is in the
30
+ * `'loading'` state.
31
+ *
32
+ * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
33
+ */
4
34
  spinner: {
35
+ /**
36
+ * The time interval between frames, in milliseconds.
37
+ *
38
+ * @defaultValue
39
+ * ```ts
40
+ * 80
41
+ * ```
42
+ */
5
43
  interval: number;
44
+ /**
45
+ * A list of frames to show for the spinner.
46
+ *
47
+ * @defaultValue
48
+ * ```ts
49
+ * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
50
+ * ```
51
+ */
6
52
  frames: string[];
7
53
  };
54
+ /**
55
+ * Object containing functions to style different parts of the prompt.
56
+ */
8
57
  style: {
58
+ /**
59
+ * Style to apply to the user's answer once it has been submitted.
60
+ *
61
+ * @param text - The user's answer.
62
+ * @returns The styled answer.
63
+ *
64
+ * @defaultValue
65
+ * ```ts
66
+ * // import colors from 'yoctocolors-cjs';
67
+ * (text) => colors.cyan(text)
68
+ * ```
69
+ */
9
70
  answer: (text: string) => string;
10
- message: (text: string) => string;
71
+ /**
72
+ * Style to apply to the message displayed to the user.
73
+ *
74
+ * @param text - The message to style.
75
+ * @param status - The current status of the prompt.
76
+ * @returns The styled message.
77
+ *
78
+ * @defaultValue
79
+ * ```ts
80
+ * // import colors from 'yoctocolors-cjs';
81
+ * (text, status) => colors.bold(text)
82
+ * ```
83
+ */
84
+ message: (text: string, status: Status) => string;
85
+ /**
86
+ * Style to apply to error messages.
87
+ *
88
+ * @param text - The error message.
89
+ * @returns The styled error message.
90
+ *
91
+ * @defaultValue
92
+ * ```ts
93
+ * // import colors from 'yoctocolors-cjs';
94
+ * (text) => colors.red(`> ${text}`)
95
+ * ```
96
+ */
11
97
  error: (text: string) => string;
98
+ /**
99
+ * Style to apply to the default answer when one is provided.
100
+ *
101
+ * @param text - The default answer.
102
+ * @returns The styled default answer.
103
+ *
104
+ * @defaultValue
105
+ * ```ts
106
+ * // import colors from 'yoctocolors-cjs';
107
+ * (text) => colors.dim(`(${text})`)
108
+ * ```
109
+ */
12
110
  defaultAnswer: (text: string) => string;
111
+ /**
112
+ * Style to apply to help text.
113
+ *
114
+ * @param text - The help text.
115
+ * @returns The styled help text.
116
+ *
117
+ * @defaultValue
118
+ * ```ts
119
+ * // import colors from 'yoctocolors-cjs';
120
+ * (text) => colors.dim(text)
121
+ * ```
122
+ */
13
123
  help: (text: string) => string;
124
+ /**
125
+ * Style to apply to highlighted text.
126
+ *
127
+ * @param text - The text to highlight.
128
+ * @returns The highlighted text.
129
+ *
130
+ * @defaultValue
131
+ * ```ts
132
+ * // import colors from 'yoctocolors-cjs';
133
+ * (text) => colors.cyan(text)
134
+ * ```
135
+ */
14
136
  highlight: (text: string) => string;
137
+ /**
138
+ * Style to apply to keyboard keys referred to in help texts.
139
+ *
140
+ * @param text - The key to style.
141
+ * @returns The styled key.
142
+ *
143
+ * @defaultValue
144
+ * ```ts
145
+ * // import colors from 'yoctocolors-cjs';
146
+ * (text) => colors.cyan(colors.bold(`<${text}>`))
147
+ * ```
148
+ */
15
149
  key: (text: string) => string;
16
150
  };
17
151
  };
@@ -1,5 +1,5 @@
1
- import { type Theme } from './theme.mjs';
2
- export declare function usePrefix({ isLoading, theme, }: {
3
- isLoading?: boolean;
1
+ import type { Theme, Status } from './theme.mjs';
2
+ export declare function usePrefix({ status, theme, }: {
3
+ status?: Status;
4
4
  theme?: Theme;
5
5
  }): string;
@@ -1,4 +1,4 @@
1
1
  type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
2
  export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
- export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void];
3
+ export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
4
4
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "9.1.0",
3
+ "version": "9.2.1",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },
@@ -57,13 +57,12 @@
57
57
  "license": "MIT",
58
58
  "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/README.md",
59
59
  "dependencies": {
60
- "@inquirer/figures": "^1.0.5",
61
- "@inquirer/type": "^1.5.3",
60
+ "@inquirer/figures": "^1.0.6",
61
+ "@inquirer/type": "^2.0.0",
62
62
  "@types/mute-stream": "^0.0.4",
63
- "@types/node": "^22.5.2",
63
+ "@types/node": "^22.5.5",
64
64
  "@types/wrap-ansi": "^3.0.0",
65
65
  "ansi-escapes": "^4.3.2",
66
- "cli-spinners": "^2.9.2",
67
66
  "cli-width": "^4.1.0",
68
67
  "mute-stream": "^1.0.0",
69
68
  "signal-exit": "^4.1.0",
@@ -72,7 +71,7 @@
72
71
  "yoctocolors-cjs": "^2.1.2"
73
72
  },
74
73
  "devDependencies": {
75
- "@inquirer/testing": "^2.1.32"
74
+ "@inquirer/testing": "^2.1.34"
76
75
  },
77
76
  "scripts": {
78
77
  "tsc": "yarn run tsc:esm && yarn run tsc:cjs",
@@ -96,5 +95,5 @@
96
95
  }
97
96
  },
98
97
  "sideEffects": false,
99
- "gitHead": "0c039599ef88fe9eb804fe083ee386ec906a856f"
98
+ "gitHead": "9e29035c2efc78f44aed3c7732aee46ab1d64ca2"
100
99
  }