@inquirer/core 12.0.6 → 12.1.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
@@ -282,8 +282,10 @@ Listening for keypress events inside an inquirer prompt is a very common pattern
282
282
  - `isEnterKey()`
283
283
  - `isBackspaceKey()`
284
284
  - `isSpaceKey()`
285
- - `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`)
286
- - `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`)
285
+ - `isTabKey()`
286
+ - `isShiftKey()` - true when shift is held
287
+ - `isUpKey()` - Note: pass `theme.keybindings` as the second argument to also handle vim and emacs keybindings (`k` and `ctrl+p`); without it, only the up arrow matches
288
+ - `isDownKey()` - Note: pass `theme.keybindings` as the second argument to also handle vim and emacs keybindings (`j` and `ctrl+n`); without it, only the down arrow matches
287
289
  - `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
288
290
 
289
291
  Set `INQUIRER_KEYBINDINGS=vim`, `INQUIRER_KEYBINDINGS=emacs`, or `INQUIRER_KEYBINDINGS=vim,emacs` to enable alternative navigation keybindings globally. Prompt-level `theme.keybindings` values override the environment variable.
@@ -111,12 +111,19 @@ export function createPrompt(view) {
111
111
  // Otherwise, the prompt will stop and in some scenarios never resolve.
112
112
  // Ref issue #1741
113
113
  cleanups.add(listenTo(rl, 'SIGINT', () => rejectPrompt(new ExitPromptError(`User force closed the prompt with SIGINT`))));
114
- // Fallback for readline closing without the prompt settling (e.g. stdin
115
- // EOF), so active effect timeouts still get cleared. Every settlement
116
- // path already clears effects through settlePrompt; this event triggers
117
- // immediately when the user presses ctrl+c, while signal-exit only
118
- // triggers after the process is done (after timeouts finish triggering).
119
- cleanups.add(listenTo(rl, 'close', clearEffects));
114
+ // A TTY closes its readline on Ctrl+D (EOF on an empty line) while the
115
+ // prompt is pending: reject now, like SIGINT, so the caller can handle
116
+ // it while the process is still alive — including while a submitted
117
+ // answer is validating, which cancels that answer. Piped stdin closes
118
+ // as soon as the pipe drains, possibly mid-validation too, so there
119
+ // only clear the effect timers and let the prompt settle on its own.
120
+ // Settlement removes this listener before screen.done() closes
121
+ // readline.
122
+ const isTTY = 'isTTY' in input && input.isTTY;
123
+ const onReadlineClose = isTTY
124
+ ? () => rejectPrompt(new ExitPromptError('User force closed the prompt with EOF'))
125
+ : clearEffects;
126
+ cleanups.add(listenTo(rl, 'close', onReadlineClose));
120
127
  const startCycle = () => {
121
128
  // Re-renders only happen when the state change; but the readline cursor could
122
129
  // change position and that also requires a re-render (and a manual one because
@@ -180,7 +187,7 @@ export function createPrompt(view) {
180
187
  // render cycle starts immediately.
181
188
  //
182
189
  // @see https://github.com/SBoudrias/Inquirer.js/issues/1303
183
- if ('readableFlowing' in input && input.isTTY) {
190
+ if ('readableFlowing' in input && isTTY) {
184
191
  const immediate = nativeSetImmediate(startCycle);
185
192
  cleanups.add(() => nativeClearImmediate(immediate));
186
193
  }
@@ -1,6 +1,10 @@
1
1
  /* eslint @typescript-eslint/no-explicit-any: ["off"] */
2
2
  import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
3
3
  import { HookError, ValidationError } from './errors.js';
4
+ // Capture the real queueMicrotask at module load time so it keeps working
5
+ // when test frameworks mock timers (vi.useFakeTimers()) — a deferred paint
6
+ // must never be held hostage by a mocked clock.
7
+ const nativeQueueMicrotask = globalThis.queueMicrotask;
4
8
  const hookStorage = new AsyncLocalStorage();
5
9
  function createStore(rl) {
6
10
  const store = {
@@ -10,6 +14,7 @@ function createStore(rl) {
10
14
  hooksEffect: [],
11
15
  index: 0,
12
16
  handleChange() { },
17
+ deferredPaint: null,
13
18
  };
14
19
  return store;
15
20
  }
@@ -42,18 +47,68 @@ export function withUpdates(fn) {
42
47
  const store = getStore();
43
48
  let shouldUpdate = false;
44
49
  const oldHandleChange = store.handleChange;
45
- store.handleChange = () => {
50
+ const recordChange = () => {
46
51
  shouldUpdate = true;
47
52
  };
53
+ store.handleChange = recordChange;
48
54
  const returnValue = fn(...args);
49
55
  if (shouldUpdate) {
56
+ // Flush the merged render, recording any change made while it flushes
57
+ // into a fresh flag. A `withUpdates` wrapper started by the render
58
+ // itself (the effect runner a re-render triggers) captures the current
59
+ // recorder as its own `oldHandleChange`, so its flush records into
60
+ // `flushedUpdate` instead of rendering inside ours — nested renders
61
+ // never re-enter this flush.
62
+ let flushedUpdate = false;
63
+ store.handleChange = () => {
64
+ flushedUpdate = true;
65
+ };
50
66
  oldHandleChange();
67
+ store.handleChange = oldHandleChange;
68
+ if (flushedUpdate) {
69
+ // State changed while the render was flushing: effects triggered by
70
+ // the render set state (e.g. a search prompt flipping to `loading`
71
+ // when its term changes), and those updates were recorded after the
72
+ // single flush above already ran — nothing painted them. The
73
+ // canonical symptom is a spinner-less "idle" screen while an async
74
+ // fetch started by the last keystroke is still pending.
75
+ //
76
+ // The paint cannot run here either. Restoring `handleChange` early
77
+ // and letting the nested flush render synchronously paints
78
+ // effect-set state before the current synchronous batch of input
79
+ // events is done: a same-tick keypress then reads it (e.g. the
80
+ // `loading` status right after Tab autocompletes) and behaves as if
81
+ // the batch had been interleaved — search's tab autocomplete stops
82
+ // submitting. Defer one paint to a microtask instead: it runs after
83
+ // the current synchronous batch of updates (same-tick keypresses
84
+ // keep reading their pre-paint state) but before any next input
85
+ // event, timer or I/O. A newer render supersedes the pending paint,
86
+ // and settlement cancels it (see `effectScheduler.clearAll`).
87
+ scheduleDeferredPaint(store, oldHandleChange);
88
+ }
89
+ }
90
+ else {
91
+ store.handleChange = oldHandleChange;
51
92
  }
52
- store.handleChange = oldHandleChange;
53
93
  return returnValue;
54
94
  };
55
95
  return AsyncResource.bind(wrapped);
56
96
  }
97
+ // Schedule the single pending deferred paint of a store. Only one is ever
98
+ // needed: the paint renders the current state, so a newer request never has
99
+ // to queue a second one — keeping the slot filled is enough.
100
+ function scheduleDeferredPaint(store, paint) {
101
+ if (store.deferredPaint !== null)
102
+ return;
103
+ store.deferredPaint = AsyncResource.bind(paint);
104
+ nativeQueueMicrotask(() => {
105
+ const pending = store.deferredPaint;
106
+ if (pending === null)
107
+ return;
108
+ store.deferredPaint = null;
109
+ pending();
110
+ });
111
+ }
57
112
  export function withPointer(cb) {
58
113
  const store = getStore();
59
114
  const { index } = store;
@@ -105,5 +160,9 @@ export const effectScheduler = {
105
160
  });
106
161
  store.hooksEffect.length = 0;
107
162
  store.hooksCleanup.length = 0;
163
+ // The prompt is settling: any deferred paint scheduled by `withUpdates`
164
+ // must not run anymore, or the settled prompt would render once more
165
+ // after its screen was torn down.
166
+ store.deferredPaint = null;
108
167
  },
109
168
  };
@@ -12,6 +12,9 @@ function deepMerge(...objects) {
12
12
  const output = {};
13
13
  for (const obj of objects) {
14
14
  for (const [key, value] of Object.entries(obj)) {
15
+ // A key explicitly set to `undefined` keeps the value from the previous theme.
16
+ if (value === undefined)
17
+ continue;
15
18
  const prevValue = output[key];
16
19
  output[key] =
17
20
  isPlainObject(prevValue) && isPlainObject(value)
@@ -1,5 +1,9 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
- import { breakLines, readlineWidth } from './utils.js';
2
+ // Measures wide characters for the right-edge check below; it is the same
3
+ // package fast-wrap-ansi measures with internally, and both must stay on the
4
+ // same major so a wrapped row is never judged one column off by one side.
5
+ import stringWidth from 'fast-string-width';
6
+ import { breakLines, readlineWidth, wrapContent } from './utils.js';
3
7
  import { cursorDown, cursorLeft, cursorUp, cursorTo, cursorShow, eraseLines, } from '@inquirer/ansi';
4
8
  const height = (content) => content.split('\n').length;
5
9
  const lastLine = (content) => content.split('\n').pop() ?? '';
@@ -33,12 +37,20 @@ export default class ScreenManager {
33
37
  // SetPrompt will change cursor position, now we can get correct value
34
38
  this.cursorPos = this.rl.getCursorPos();
35
39
  const width = readlineWidth();
36
- content = breakLines(content, width);
40
+ const wrapped = wrapContent(content, width);
41
+ content = wrapped.text;
37
42
  bottomContent = breakLines(bottomContent, width);
43
+ const lastRowWidth = stringWidth(stripVTControlCharacters(wrapped.lastRow));
44
+ // `>=` rather than `===` so a degenerate 1-column terminal (where every
45
+ // row is the full width) still inserts the extra line.
46
+ const atRightEdge = lastRowWidth >= width;
38
47
  // Manually insert an extra line if we're at the end of the line.
39
48
  // This prevent the cursor from appearing at the beginning of the
40
- // current line.
41
- if (rawPromptLine.length % width === 0) {
49
+ // current line. The `rawPromptLine.length === 0` half keeps the old
50
+ // `0 % width === 0` behavior for an empty or ANSI-only prompt line,
51
+ // where `atRightEdge` alone would be false but a line break is still
52
+ // needed before the bottom content.
53
+ if (atRightEdge || rawPromptLine.length === 0) {
42
54
  content += '\n';
43
55
  }
44
56
  let output = content + (bottomContent ? '\n' + bottomContent : '');
@@ -47,7 +59,7 @@ export default class ScreenManager {
47
59
  */
48
60
  // We need to consider parts of the prompt under the cursor as part of the bottom
49
61
  // content in order to correctly cleanup and re-render.
50
- const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;
62
+ const promptLineUpDiff = wrapped.finalLineRows - 1 + Number(atRightEdge) - this.cursorPos.rows;
51
63
  const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
52
64
  // Return cursor to the input position (on top of the bottomContent)
53
65
  if (bottomContentHeight > 0)
@@ -6,6 +6,11 @@
6
6
  * @return {string}
7
7
  */
8
8
  export declare function breakLines(content: string, width: number): string;
9
+ export declare function wrapContent(content: string, width: number): {
10
+ text: string;
11
+ lastRow: string;
12
+ finalLineRows: number;
13
+ };
9
14
  /**
10
15
  * Returns the width of the active readline, or 80 as default value.
11
16
  * @returns {number}
package/dist/lib/utils.js CHANGED
@@ -9,12 +9,27 @@ import { readline } from './hook-engine.js';
9
9
  * @return {string}
10
10
  */
11
11
  export function breakLines(content, width) {
12
- return content
13
- .split('\n')
14
- .flatMap((line) => wrapAnsi(line, width, { trim: false, wordWrap: false })
12
+ return wrapContent(content, width).text;
13
+ }
14
+ // Wraps `content` and reports the geometry of its final logical line:
15
+ // `lastRow` is the last physical row of that line and `finalLineRows` is how
16
+ // many rows it spans (used by the screen manager to place the cursor back on
17
+ // the prompt line). `lastRow` is deliberately left untrimmed: readline counts
18
+ // trailing spaces when reporting the cursor position, so trimming here would
19
+ // make a line that ends exactly at the terminal edge look one column short.
20
+ export function wrapContent(content, width) {
21
+ const wrappedLines = content
15
22
  .split('\n')
16
- .map((str) => str.trimEnd()))
17
- .join('\n');
23
+ .map((line) => wrapAnsi(line, width, { trim: false, wordWrap: false }).split('\n'));
24
+ const finalLine = wrappedLines.at(-1) ?? [];
25
+ return {
26
+ text: wrappedLines
27
+ .flat()
28
+ .map((line) => line.trimEnd())
29
+ .join('\n'),
30
+ lastRow: finalLine.at(-1) ?? '',
31
+ finalLineRows: finalLine.length,
32
+ };
18
33
  }
19
34
  /**
20
35
  * Returns the width of the active readline, or 80 as default value.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "12.0.6",
3
+ "version": "12.1.1",
4
4
  "description": "Core Inquirer prompt API",
5
5
  "keywords": [
6
6
  "answer",
@@ -67,16 +67,17 @@
67
67
  "tsc": "tsc"
68
68
  },
69
69
  "dependencies": {
70
- "@inquirer/ansi": "^2.0.10",
71
- "@inquirer/figures": "^2.0.10",
72
- "@inquirer/type": "4.2.1",
70
+ "@inquirer/ansi": "^2.1.1",
71
+ "@inquirer/figures": "^2.1.1",
72
+ "@inquirer/type": "4.3.1",
73
73
  "cli-width": "^4.1.0",
74
+ "fast-string-width": "^3.0.2",
74
75
  "fast-wrap-ansi": "^0.2.0",
75
76
  "mute-stream": "^3.0.0",
76
77
  "signal-exit": "^4.1.0"
77
78
  },
78
79
  "devDependencies": {
79
- "@repo/tsconfig": "0.0.0",
80
+ "@repo/tsconfig": "0.1.0",
80
81
  "@types/mute-stream": "^0.0.4",
81
82
  "@types/node": "^26.1.1",
82
83
  "typescript": "^7.0.2"
@@ -94,5 +95,5 @@
94
95
  },
95
96
  "main": "./dist/index.js",
96
97
  "types": "./dist/index.d.ts",
97
- "gitHead": "672b77f0486388d7f5c35487d89a5ff63f4c54dd"
98
+ "gitHead": "6570b8e4d5e33a00dad2b55fa5f5fa5d148a245b"
98
99
  }