@inquirer/core 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/cjs/index.js +17 -268
  2. package/dist/cjs/lib/Separator.js +2 -5
  3. package/dist/cjs/lib/create-prompt.js +111 -0
  4. package/dist/cjs/lib/hook-engine.js +100 -0
  5. package/dist/cjs/lib/read-line.type.js +2 -0
  6. package/dist/cjs/lib/screen-manager.js +3 -6
  7. package/dist/cjs/lib/use-effect.js +15 -0
  8. package/dist/cjs/lib/use-keypress.js +20 -0
  9. package/dist/cjs/lib/use-pagination.js +34 -0
  10. package/dist/cjs/lib/{prefix.js → use-prefix.js} +7 -9
  11. package/dist/cjs/lib/use-ref.js +8 -0
  12. package/dist/cjs/lib/use-state.js +28 -0
  13. package/dist/cjs/lib/utils.js +2 -5
  14. package/dist/cjs/types/index.d.ts +9 -36
  15. package/dist/cjs/types/lib/create-prompt.d.ts +11 -0
  16. package/dist/cjs/types/lib/hook-engine.d.ts +24 -0
  17. package/dist/cjs/types/lib/key.d.ts +1 -2
  18. package/dist/cjs/types/lib/read-line.type.d.ts +9 -0
  19. package/dist/cjs/types/lib/screen-manager.d.ts +1 -1
  20. package/dist/cjs/types/lib/use-effect.d.ts +2 -0
  21. package/dist/cjs/types/lib/use-keypress.d.ts +3 -0
  22. package/dist/cjs/types/lib/use-pagination.d.ts +4 -0
  23. package/dist/cjs/types/lib/use-ref.d.ts +3 -0
  24. package/dist/cjs/types/lib/use-state.d.ts +3 -0
  25. package/dist/esm/index.mjs +8 -243
  26. package/dist/esm/lib/create-prompt.mjs +99 -0
  27. package/dist/esm/lib/hook-engine.mjs +91 -0
  28. package/dist/esm/lib/read-line.type.mjs +1 -0
  29. package/dist/esm/lib/use-effect.mjs +11 -0
  30. package/dist/esm/lib/use-keypress.mjs +16 -0
  31. package/dist/esm/lib/use-pagination.mjs +30 -0
  32. package/dist/esm/lib/{prefix.mjs → use-prefix.mjs} +3 -2
  33. package/dist/esm/lib/use-ref.mjs +4 -0
  34. package/dist/esm/lib/use-state.mjs +24 -0
  35. package/dist/esm/lib/utils.mjs +1 -1
  36. package/dist/esm/types/index.d.mts +9 -36
  37. package/dist/esm/types/lib/create-prompt.d.mts +11 -0
  38. package/dist/esm/types/lib/hook-engine.d.mts +24 -0
  39. package/dist/esm/types/lib/key.d.mts +1 -2
  40. package/dist/esm/types/lib/read-line.type.d.mts +9 -0
  41. package/dist/esm/types/lib/screen-manager.d.mts +1 -1
  42. package/dist/esm/types/lib/use-effect.d.mts +2 -0
  43. package/dist/esm/types/lib/use-keypress.d.mts +3 -0
  44. package/dist/esm/types/lib/use-pagination.d.mts +4 -0
  45. package/dist/esm/types/lib/use-ref.d.mts +3 -0
  46. package/dist/esm/types/lib/use-state.d.mts +3 -0
  47. package/package.json +9 -9
  48. package/dist/cjs/lib/options.js +0 -19
  49. package/dist/cjs/types/lib/options.d.ts +0 -2
  50. package/dist/esm/lib/options.mjs +0 -8
  51. package/dist/esm/types/lib/options.d.mts +0 -2
  52. /package/dist/cjs/types/lib/{prefix.d.ts → use-prefix.d.ts} +0 -0
  53. /package/dist/esm/types/lib/{prefix.d.mts → use-prefix.d.mts} +0 -0
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useState = void 0;
4
+ const hook_engine_mjs_1 = require('./hook-engine.js');
5
+ function useState(defaultValue) {
6
+ return (0, hook_engine_mjs_1.withPointer)((pointer) => {
7
+ if (!pointer.initialized) {
8
+ if (typeof defaultValue === 'function') {
9
+ pointer.set(defaultValue());
10
+ }
11
+ else {
12
+ pointer.set(defaultValue);
13
+ }
14
+ }
15
+ return [
16
+ pointer.get(),
17
+ (newValue) => {
18
+ // Noop if the value is still the same.
19
+ if (pointer.get() !== newValue) {
20
+ pointer.set(newValue);
21
+ // Trigger re-render
22
+ (0, hook_engine_mjs_1.handleChange)();
23
+ }
24
+ },
25
+ ];
26
+ });
27
+ }
28
+ exports.useState = useState;
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.breakLines = void 0;
7
- const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
4
+ const wrap_ansi_1 = require("wrap-ansi");
8
5
  /**
9
6
  * Force line returns at specific width. This function is ANSI code friendly and it'll
10
7
  * ignore invisible codes during width calculation.
@@ -16,6 +13,6 @@ const breakLines = (content, width) => content
16
13
  .split('\n')
17
14
  .flatMap((line) => (0, wrap_ansi_1.default)(line, width, { trim: false, hard: true })
18
15
  .split('\n')
19
- .map((line) => line.trimEnd()))
16
+ .map((str) => str.trimEnd()))
20
17
  .join('\n');
21
18
  exports.breakLines = breakLines;
@@ -1,37 +1,10 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import * as readline from 'node:readline';
4
- import { type Prompt } from '@inquirer/type';
5
- import MuteStream from 'mute-stream';
6
- export { usePrefix } from './lib/prefix.js';
7
1
  export * from './lib/key.js';
8
- export * from './lib/Separator.js';
9
- export type InquirerReadline = readline.ReadLine & {
10
- output: MuteStream;
11
- input: NodeJS.ReadableStream;
12
- clearLine: (dir: 0 | 1 | -1) => void;
13
- };
14
- export type KeypressEvent = {
15
- name: string;
16
- ctrl: boolean;
17
- };
18
- type NotFunction<T> = T extends Function ? never : T;
19
- export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
20
- export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void;
21
- export declare function useRef<Value>(val: Value): {
22
- current: Value;
23
- };
24
- export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
25
- export declare function usePagination(output: string, { active, pageSize, }: {
26
- active: number;
27
- pageSize?: number;
28
- }): string;
29
- export type AsyncPromptConfig = {
30
- message: string | Promise<string> | (() => Promise<string>);
31
- validate?: (value: string) => boolean | string | Promise<string | boolean>;
32
- };
33
- export type ResolvedPromptConfig = {
34
- message: string;
35
- validate: (value: string) => boolean | string | Promise<string | boolean>;
36
- };
37
- export declare function createPrompt<Value, Config extends AsyncPromptConfig>(view: (config: Config & ResolvedPromptConfig, done: (value: Value) => void) => string | [string, string | undefined]): Prompt<Value, Config>;
2
+ export { usePrefix } from './lib/use-prefix.js';
3
+ export { useState } from './lib/use-state.js';
4
+ export { useEffect } from './lib/use-effect.js';
5
+ export { useRef } from './lib/use-ref.js';
6
+ export { useKeypress } from './lib/use-keypress.js';
7
+ export { usePagination } from './lib/use-pagination.js';
8
+ export { createPrompt, type AsyncPromptConfig } from './lib/create-prompt.js';
9
+ export { Separator } from './lib/Separator.js';
10
+ export { type InquirerReadline } from './lib/read-line.type.js';
@@ -0,0 +1,11 @@
1
+ import { type Prompt } from '@inquirer/type';
2
+ export type AsyncPromptConfig = {
3
+ message: string | Promise<string> | (() => Promise<string>);
4
+ validate?: (value: string) => boolean | string | Promise<string | boolean>;
5
+ };
6
+ type ResolvedPromptConfig = {
7
+ message: string;
8
+ validate: (value: string) => boolean | string | Promise<string | boolean>;
9
+ };
10
+ export declare function createPrompt<Value, Config extends AsyncPromptConfig>(view: (config: Config & ResolvedPromptConfig, done: (value: Value) => void) => string | [string, string | undefined]): Prompt<Value, Config>;
11
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { InquirerReadline } from './read-line.type.js';
2
+ type HookStore = {
3
+ rl: InquirerReadline;
4
+ hooks: any[];
5
+ hooksCleanup: Array<void | (() => void)>;
6
+ hooksEffect: Array<() => void>;
7
+ index: number;
8
+ handleChange: () => void;
9
+ };
10
+ type Pointer = {
11
+ get(): any;
12
+ set(value: any): void;
13
+ initialized: boolean;
14
+ };
15
+ export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void;
16
+ export declare function readline(): InquirerReadline;
17
+ export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
18
+ export declare function withPointer<Value>(cb: (pointer: Pointer) => Value): Value;
19
+ export declare function handleChange(): void;
20
+ export declare const effectScheduler: {
21
+ queue(cb: (readline: InquirerReadline) => void): void;
22
+ run(): void;
23
+ };
24
+ export {};
@@ -1,4 +1,4 @@
1
- type KeypressEvent = {
1
+ export type KeypressEvent = {
2
2
  name: string;
3
3
  ctrl: boolean;
4
4
  };
@@ -8,4 +8,3 @@ export declare const isSpaceKey: (key: KeypressEvent) => boolean;
8
8
  export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
9
9
  export declare const isNumberKey: (key: KeypressEvent) => boolean;
10
10
  export declare const isEnterKey: (key: KeypressEvent) => boolean;
11
- export {};
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import * as readline from 'node:readline';
4
+ import MuteStream from 'mute-stream';
5
+ export type InquirerReadline = readline.ReadLine & {
6
+ output: MuteStream;
7
+ input: NodeJS.ReadableStream;
8
+ clearLine: (dir: 0 | 1 | -1) => void;
9
+ };
@@ -1,4 +1,4 @@
1
- import { InquirerReadline } from '../index.js';
1
+ import type { InquirerReadline } from './read-line.type.js';
2
2
  export default class ScreenManager {
3
3
  private readonly rl;
4
4
  private height;
@@ -0,0 +1,2 @@
1
+ import type { InquirerReadline } from './read-line.type.js';
2
+ export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void;
@@ -0,0 +1,3 @@
1
+ import { type InquirerReadline } from './read-line.type.js';
2
+ import { type KeypressEvent } from './key.js';
3
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
@@ -0,0 +1,4 @@
1
+ export declare function usePagination(output: string, { active, pageSize, }: {
2
+ active: number;
3
+ pageSize?: number;
4
+ }): string;
@@ -0,0 +1,3 @@
1
+ export declare function useRef<Value>(val: Value): {
2
+ current: Value;
3
+ };
@@ -0,0 +1,3 @@
1
+ type NotFunction<T> = T extends Function ? never : T;
2
+ export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
+ export {};
@@ -1,244 +1,9 @@
1
- import * as readline from 'node:readline';
2
- import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
3
- import { CancelablePromise } from '@inquirer/type';
4
- import chalk from 'chalk';
5
- import cliWidth from 'cli-width';
6
- import MuteStream from 'mute-stream';
7
- import ScreenManager from './lib/screen-manager.mjs';
8
- import { getPromptConfig } from './lib/options.mjs';
9
- import { breakLines } from './lib/utils.mjs';
10
- export { usePrefix } from './lib/prefix.mjs';
11
1
  export * from './lib/key.mjs';
12
- export * from './lib/Separator.mjs';
13
- const hookStorage = new AsyncLocalStorage();
14
- const context = {
15
- getStore() {
16
- const store = hookStorage.getStore();
17
- if (!store) {
18
- throw new Error('[Inquirer] Hook functions can only be called from within a prompt');
19
- }
20
- return store;
21
- },
22
- withPointer(cb) {
23
- const store = context.getStore();
24
- const value = cb(store.index, store);
25
- store.index++;
26
- return value;
27
- },
28
- handleChange() {
29
- const { handleChange } = context.getStore();
30
- handleChange();
31
- },
32
- mergeStateUpdates(fn) {
33
- const wrapped = (...args) => {
34
- const store = context.getStore();
35
- let shouldUpdate = false;
36
- const oldHandleChange = store.handleChange;
37
- store.handleChange = () => {
38
- shouldUpdate = true;
39
- };
40
- const returnValue = fn(...args);
41
- if (shouldUpdate) {
42
- oldHandleChange();
43
- }
44
- store.handleChange = oldHandleChange;
45
- return returnValue;
46
- };
47
- return wrapped;
48
- },
49
- };
50
- const effectScheduler = {
51
- queue(cb) {
52
- const store = context.getStore();
53
- const { index } = store;
54
- store.hooksEffect.push(() => {
55
- store.hooksCleanup[index]?.();
56
- const cleanFn = cb(store.rl);
57
- if (cleanFn != null && typeof cleanFn !== 'function') {
58
- throw new Error('useEffect return value must be a cleanup function or nothing.');
59
- }
60
- store.hooksCleanup[index] = cleanFn;
61
- });
62
- },
63
- run: context.mergeStateUpdates(() => {
64
- const store = context.getStore();
65
- store.hooksEffect.forEach((effect) => {
66
- effect();
67
- });
68
- store.hooksEffect.length = 0;
69
- }),
70
- };
71
- export function useState(defaultValue) {
72
- return context.withPointer((pointer, store) => {
73
- const { hooks } = store;
74
- if (!(pointer in hooks)) {
75
- if (typeof defaultValue === 'function') {
76
- hooks[pointer] = defaultValue();
77
- }
78
- else {
79
- hooks[pointer] = defaultValue;
80
- }
81
- }
82
- return [
83
- hooks[pointer],
84
- (newValue) => {
85
- // Noop if the value is still the same.
86
- if (hooks[pointer] !== newValue) {
87
- hooks[pointer] = newValue;
88
- // Trigger re-render
89
- context.handleChange();
90
- }
91
- },
92
- ];
93
- });
94
- }
95
- export function useEffect(cb, depArray) {
96
- return context.withPointer((pointer, store) => {
97
- const { hooks } = store;
98
- const oldDeps = hooks[pointer];
99
- const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
100
- if (hasChanged) {
101
- effectScheduler.queue(cb);
102
- }
103
- hooks[pointer] = depArray;
104
- });
105
- }
106
- export function useRef(val) {
107
- return useState({ current: val })[0];
108
- }
109
- export function useKeypress(userHandler) {
110
- const signal = useRef(userHandler);
111
- signal.current = userHandler;
112
- useEffect((rl) => {
113
- const handler = AsyncResource.bind(context.mergeStateUpdates((_input, event) => {
114
- signal.current(event, rl);
115
- }));
116
- rl.input.on('keypress', handler);
117
- return () => {
118
- rl.input.removeListener('keypress', handler);
119
- };
120
- }, []);
121
- }
122
- export function usePagination(output, { active, pageSize = 7, }) {
123
- const { rl } = context.getStore();
124
- const state = useRef({
125
- pointer: 0,
126
- lastIndex: 0,
127
- });
128
- const width = cliWidth({ defaultWidth: 80, output: rl.output });
129
- const lines = breakLines(output, width).split('\n');
130
- // Make sure there's enough lines to paginate
131
- if (lines.length <= pageSize) {
132
- return output;
133
- }
134
- const middleOfList = Math.floor(pageSize / 2);
135
- // Move the pointer only when the user go down and limit it to the middle of the list
136
- const { pointer: prevPointer, lastIndex } = state.current;
137
- if (prevPointer < middleOfList && lastIndex < active && active - lastIndex < pageSize) {
138
- state.current.pointer = Math.min(middleOfList, prevPointer + active - lastIndex);
139
- }
140
- state.current.lastIndex = active;
141
- // Duplicate the lines so it give an infinite list look
142
- const infinite = [lines, lines, lines].flat();
143
- const topIndex = Math.max(0, active + lines.length - state.current.pointer);
144
- const section = infinite.splice(topIndex, pageSize).join('\n');
145
- return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
146
- }
147
- export function createPrompt(view) {
148
- const prompt = (config, context) => {
149
- // Default `input` to stdin
150
- const input = context?.input ?? process.stdin;
151
- // Add mute capabilities to the output
152
- const output = new MuteStream();
153
- output.pipe(context?.output ?? process.stdout);
154
- const rl = readline.createInterface({
155
- terminal: true,
156
- input,
157
- output,
158
- });
159
- const screen = new ScreenManager(rl);
160
- const store = {
161
- rl,
162
- hooks: [],
163
- hooksCleanup: [],
164
- hooksEffect: [],
165
- index: 0,
166
- handleChange() { },
167
- };
168
- let cancel = () => { };
169
- const answer = new CancelablePromise((resolve, reject) => {
170
- hookStorage.run(store, () => {
171
- const checkCursorPos = () => {
172
- screen.checkCursorPos();
173
- };
174
- const onExit = AsyncResource.bind(() => {
175
- try {
176
- store.hooksCleanup.forEach((cleanFn) => {
177
- cleanFn?.();
178
- });
179
- }
180
- catch (err) {
181
- reject(err);
182
- }
183
- if (context?.clearPromptOnDone) {
184
- screen.clean();
185
- }
186
- else {
187
- screen.clearContent();
188
- }
189
- screen.done();
190
- process.removeListener('SIGINT', onForceExit);
191
- store.rl.input.removeListener('keypress', checkCursorPos);
192
- });
193
- cancel = AsyncResource.bind(() => {
194
- onExit();
195
- reject(new Error('Prompt was canceled'));
196
- });
197
- let shouldHandleExit = true;
198
- const onForceExit = AsyncResource.bind(() => {
199
- if (shouldHandleExit) {
200
- shouldHandleExit = false;
201
- onExit();
202
- reject(new Error('User force closed the prompt with CTRL+C'));
203
- }
204
- });
205
- // Handle cleanup on force exit. Main reason is so we restore the cursor if a prompt hide it.
206
- process.on('SIGINT', onForceExit);
207
- const done = (value) => {
208
- // Delay execution to let time to the hookCleanup functions to registers.
209
- setImmediate(() => {
210
- onExit();
211
- // Finally we resolve our promise
212
- resolve(value);
213
- });
214
- };
215
- const workLoop = (resolvedConfig) => {
216
- store.index = 0;
217
- store.handleChange = () => workLoop(resolvedConfig);
218
- try {
219
- const nextView = view(resolvedConfig, done);
220
- const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
221
- screen.render(content, bottomContent);
222
- effectScheduler.run();
223
- }
224
- catch (err) {
225
- onExit();
226
- reject(err);
227
- }
228
- };
229
- // TODO: we should display a loader while we get the default options.
230
- getPromptConfig(config).then((resolvedConfig) => {
231
- workLoop(resolvedConfig);
232
- // Re-renders only happen when the state change; but the readline cursor could change position
233
- // and that also requires a re-render (and a manual one because we mute the streams).
234
- // We set the listener after the initial workLoop to avoid a double render if render triggered
235
- // by a state change sets the cursor to the right position.
236
- store.rl.input.on('keypress', checkCursorPos);
237
- }, reject);
238
- });
239
- });
240
- answer.cancel = cancel;
241
- return answer;
242
- };
243
- return prompt;
244
- }
2
+ export { usePrefix } from './lib/use-prefix.mjs';
3
+ export { useState } from './lib/use-state.mjs';
4
+ export { useEffect } from './lib/use-effect.mjs';
5
+ export { useRef } from './lib/use-ref.mjs';
6
+ export { useKeypress } from './lib/use-keypress.mjs';
7
+ export { usePagination } from './lib/use-pagination.mjs';
8
+ export { createPrompt } from './lib/create-prompt.mjs';
9
+ export { Separator } from './lib/Separator.mjs';
@@ -0,0 +1,99 @@
1
+ import * as readline from 'node:readline';
2
+ import { CancelablePromise } from '@inquirer/type';
3
+ import MuteStream from 'mute-stream';
4
+ import { onExit as onSignalExit } from 'signal-exit';
5
+ import ScreenManager from './screen-manager.mjs';
6
+ import { withHooks, effectScheduler } from './hook-engine.mjs';
7
+ // Take an AsyncPromptConfig and resolves all it's values.
8
+ async function getPromptConfig(config) {
9
+ const message = typeof config.message === 'function' ? config.message() : config.message;
10
+ return {
11
+ validate: () => true,
12
+ ...config,
13
+ message: await message,
14
+ };
15
+ }
16
+ export function createPrompt(view) {
17
+ const prompt = (config, context) => {
18
+ // Default `input` to stdin
19
+ const input = context?.input ?? process.stdin;
20
+ // Add mute capabilities to the output
21
+ const output = new MuteStream();
22
+ output.pipe(context?.output ?? process.stdout);
23
+ const rl = readline.createInterface({
24
+ terminal: true,
25
+ input,
26
+ output,
27
+ });
28
+ const screen = new ScreenManager(rl);
29
+ let cancel = () => { };
30
+ const answer = new CancelablePromise((resolve, reject) => {
31
+ withHooks(rl, (store) => {
32
+ function checkCursorPos() {
33
+ screen.checkCursorPos();
34
+ }
35
+ const removeExitListener = onSignalExit((code, signal) => {
36
+ onExit();
37
+ reject(new Error(`User force closed the prompt with ${code} ${signal}`));
38
+ });
39
+ function onExit() {
40
+ try {
41
+ store.hooksCleanup.forEach((cleanFn) => {
42
+ cleanFn?.();
43
+ });
44
+ }
45
+ catch (err) {
46
+ reject(err);
47
+ }
48
+ if (context?.clearPromptOnDone) {
49
+ screen.clean();
50
+ }
51
+ else {
52
+ screen.clearContent();
53
+ }
54
+ screen.done();
55
+ removeExitListener();
56
+ store.rl.input.removeListener('keypress', checkCursorPos);
57
+ }
58
+ cancel = () => {
59
+ onExit();
60
+ reject(new Error('Prompt was canceled'));
61
+ };
62
+ function done(value) {
63
+ // Delay execution to let time to the hookCleanup functions to registers.
64
+ setImmediate(() => {
65
+ onExit();
66
+ // Finally we resolve our promise
67
+ resolve(value);
68
+ });
69
+ }
70
+ function workLoop(resolvedConfig) {
71
+ store.index = 0;
72
+ store.handleChange = () => workLoop(resolvedConfig);
73
+ try {
74
+ const nextView = view(resolvedConfig, done);
75
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
76
+ screen.render(content, bottomContent);
77
+ effectScheduler.run();
78
+ }
79
+ catch (err) {
80
+ onExit();
81
+ reject(err);
82
+ }
83
+ }
84
+ // TODO: we should display a loader while we get the default options.
85
+ getPromptConfig(config).then((resolvedConfig) => {
86
+ workLoop(resolvedConfig);
87
+ // Re-renders only happen when the state change; but the readline cursor could change position
88
+ // and that also requires a re-render (and a manual one because we mute the streams).
89
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
90
+ // by a state change sets the cursor to the right position.
91
+ store.rl.input.on('keypress', checkCursorPos);
92
+ }, reject);
93
+ });
94
+ });
95
+ answer.cancel = cancel;
96
+ return answer;
97
+ };
98
+ return prompt;
99
+ }
@@ -0,0 +1,91 @@
1
+ import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
2
+ const hookStorage = new AsyncLocalStorage();
3
+ function createStore(rl) {
4
+ const store = {
5
+ rl,
6
+ hooks: [],
7
+ hooksCleanup: [],
8
+ hooksEffect: [],
9
+ index: 0,
10
+ handleChange() { },
11
+ };
12
+ return store;
13
+ }
14
+ // Run callback in with the hook engine setup.
15
+ export function withHooks(rl, cb) {
16
+ const store = createStore(rl);
17
+ return hookStorage.run(store, () => {
18
+ cb(store);
19
+ });
20
+ }
21
+ // Safe getStore utility that'll return the store or throw if undefined.
22
+ function getStore() {
23
+ const store = hookStorage.getStore();
24
+ if (!store) {
25
+ throw new Error('[Inquirer] Hook functions can only be called from within a prompt');
26
+ }
27
+ return store;
28
+ }
29
+ export function readline() {
30
+ return getStore().rl;
31
+ }
32
+ // Merge state updates happening within the callback function to avoid multiple renders.
33
+ export function withUpdates(fn) {
34
+ const wrapped = (...args) => {
35
+ const store = getStore();
36
+ let shouldUpdate = false;
37
+ const oldHandleChange = store.handleChange;
38
+ store.handleChange = () => {
39
+ shouldUpdate = true;
40
+ };
41
+ const returnValue = fn(...args);
42
+ if (shouldUpdate) {
43
+ oldHandleChange();
44
+ }
45
+ store.handleChange = oldHandleChange;
46
+ return returnValue;
47
+ };
48
+ return AsyncResource.bind(wrapped);
49
+ }
50
+ export function withPointer(cb) {
51
+ const store = getStore();
52
+ const { index } = store;
53
+ const pointer = {
54
+ get() {
55
+ return store.hooks[index];
56
+ },
57
+ set(value) {
58
+ store.hooks[index] = value;
59
+ },
60
+ initialized: index in store.hooks,
61
+ };
62
+ const returnValue = cb(pointer);
63
+ store.index++;
64
+ return returnValue;
65
+ }
66
+ export function handleChange() {
67
+ getStore().handleChange();
68
+ }
69
+ export const effectScheduler = {
70
+ queue(cb) {
71
+ const store = getStore();
72
+ const { index } = store;
73
+ store.hooksEffect.push(() => {
74
+ store.hooksCleanup[index]?.();
75
+ const cleanFn = cb(readline());
76
+ if (cleanFn != null && typeof cleanFn !== 'function') {
77
+ throw new Error('useEffect return value must be a cleanup function or nothing.');
78
+ }
79
+ store.hooksCleanup[index] = cleanFn;
80
+ });
81
+ },
82
+ run() {
83
+ const store = getStore();
84
+ withUpdates(() => {
85
+ store.hooksEffect.forEach((effect) => {
86
+ effect();
87
+ });
88
+ })();
89
+ store.hooksEffect.length = 0;
90
+ },
91
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { withPointer, effectScheduler } from './hook-engine.mjs';
2
+ export function useEffect(cb, depArray) {
3
+ withPointer((pointer) => {
4
+ const oldDeps = pointer.get();
5
+ const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
6
+ if (hasChanged) {
7
+ effectScheduler.queue(cb);
8
+ }
9
+ pointer.set(depArray);
10
+ });
11
+ }
@@ -0,0 +1,16 @@
1
+ import { useRef } from './use-ref.mjs';
2
+ import { useEffect } from './use-effect.mjs';
3
+ import { withUpdates } from './hook-engine.mjs';
4
+ export function useKeypress(userHandler) {
5
+ const signal = useRef(userHandler);
6
+ signal.current = userHandler;
7
+ useEffect((rl) => {
8
+ const handler = withUpdates((_input, event) => {
9
+ signal.current(event, rl);
10
+ });
11
+ rl.input.on('keypress', handler);
12
+ return () => {
13
+ rl.input.removeListener('keypress', handler);
14
+ };
15
+ }, []);
16
+ }