@jacebenson/jsn 5.5.7 → 5.5.8

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 (63) hide show
  1. package/README.md +16 -1
  2. package/package.json +5 -6
  3. package/skills/servicenow/SKILL.md +9 -1
  4. package/src/app.js +4 -79
  5. package/src/bounded-reads.js +13 -0
  6. package/src/capabilities.js +8 -3
  7. package/src/cli-adapter.js +26 -3
  8. package/src/cli.js +13 -14
  9. package/src/command-families.js +68 -0
  10. package/src/commands/_generic.js +1 -0
  11. package/src/commands/_ticket.js +1 -1
  12. package/src/commands/actions.js +9 -4
  13. package/src/commands/approvals.js +1 -1
  14. package/src/commands/atf.js +1 -1
  15. package/src/commands/attachments.js +1 -1
  16. package/src/commands/auth.js +21 -2
  17. package/src/commands/codesearch.js +11 -2
  18. package/src/commands/compare.js +22 -0
  19. package/src/commands/customizations.js +3 -4
  20. package/src/commands/decisiontables.js +4 -0
  21. package/src/commands/docs/docs.js +5 -5
  22. package/src/commands/domains.js +1 -1
  23. package/src/commands/eval.js +11 -5
  24. package/src/commands/flows.js +24 -7
  25. package/src/commands/groupmembers.js +1 -1
  26. package/src/commands/grouproles.js +1 -1
  27. package/src/commands/groups.js +1 -1
  28. package/src/commands/midservers.js +4 -11
  29. package/src/commands/perf.js +2 -3
  30. package/src/commands/plugins.js +9 -0
  31. package/src/commands/records.js +12 -2
  32. package/src/commands/scopes.js +1 -1
  33. package/src/commands/scrapi.js +2 -2
  34. package/src/commands/setup.js +4 -34
  35. package/src/commands/skipped-updates.js +2 -3
  36. package/src/commands/store.js +4 -1
  37. package/src/commands/subscriptions.js +47 -0
  38. package/src/commands/tickets.js +1 -1
  39. package/src/commands/users.js +1 -1
  40. package/src/commands/workflows.js +3 -5
  41. package/src/config.js +1 -0
  42. package/src/context.js +8 -56
  43. package/src/docs-links.js +28 -0
  44. package/src/flow-create.js +9 -0
  45. package/src/help.js +4 -0
  46. package/src/helpers.js +17 -24
  47. package/src/instance-inventory.js +184 -0
  48. package/src/intended-context.js +68 -0
  49. package/src/mutation-context.js +69 -46
  50. package/src/output.js +1 -1
  51. package/src/paginated-search.js +146 -178
  52. package/src/picker-ui.js +20 -0
  53. package/src/prompt-engine.js +176 -0
  54. package/src/prompts.js +293 -43
  55. package/src/records/inspect.js +30 -16
  56. package/src/records-engine.js +2 -2
  57. package/src/schedule-cache.js +96 -0
  58. package/src/schedules/itom-2026-04-09.json +121 -0
  59. package/src/schedules/public-inventory.json +6224 -0
  60. package/src/sdk-batch.js +2 -1
  61. package/src/sdk.js +42 -16
  62. package/src/setup-preferences.js +2 -2
  63. package/src/subscriptions.js +176 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * A small terminal prompt engine built on node:readline keypress events.
3
+ *
4
+ * This is deliberately not a general prompt library: it exists so JSN's
5
+ * observed prompt surface (input, password, confirm, select, search,
6
+ * checkbox, editor, paginated pickers) runs on Node built-ins with no
7
+ * runtime dependency, while keeping the existing caller contract
8
+ * `prompt(config, { input, output, signal })`.
9
+ *
10
+ * Every prompt restores raw mode and removes its listener in `finally`,
11
+ * on success, Escape, Ctrl+C and thrown errors alike.
12
+ */
13
+
14
+ import readline from 'node:readline';
15
+ import { stripVTControlCharacters } from 'node:util';
16
+
17
+ export class PromptCancelled extends Error {
18
+ constructor() {
19
+ super('Cancelled.');
20
+ this.name = 'PromptCancelled';
21
+ }
22
+ }
23
+
24
+ /** Choices may be strings or { name, value, disabled }. */
25
+ export function normalizeChoices(choices = []) {
26
+ return choices.map(choice => {
27
+ if (choice && typeof choice === 'object') {
28
+ return {
29
+ name: String(choice.name ?? choice.value ?? ''),
30
+ value: 'value' in choice ? choice.value : choice.name,
31
+ disabled: Boolean(choice.disabled) || choice.type === 'separator',
32
+ ...(choice.type === 'separator' ? { separator: true } : {}),
33
+ ...(choice.section !== undefined ? { section: choice.section } : {}),
34
+ ...(choice.description !== undefined ? { description: choice.description } : {}),
35
+ checked: Boolean(choice.checked),
36
+ };
37
+ }
38
+ return { name: String(choice), value: choice, disabled: false };
39
+ });
40
+ }
41
+
42
+ export function truncate(text, width = 70) {
43
+ const value = String(text ?? '');
44
+ return value.length > width ? `${value.slice(0, width - 3)}...` : value;
45
+ }
46
+
47
+ /**
48
+ * Run one interactive prompt.
49
+ *
50
+ * @param {object} config prompt config ({ message, ... })
51
+ * @param {object} context { input, output, signal }
52
+ * @param {object} spec
53
+ * init(config, context) -> state
54
+ * key(state, key, api) -> directive | undefined | Promise<...>
55
+ * directive: { done: value } finishes, { cancel: true } throws
56
+ * PromptCancelled, { escape: true } resolves undefined.
57
+ * render(config, state) -> string | string[]
58
+ * final(config, value, state) -> string | null — the settled answer line
59
+ * (Inquirer prints `✔ <message> <answer>`). Only written on a TTY after
60
+ * the live frame is erased, so one prompt yields exactly one final line
61
+ * and piped output keeps its existing byte contract.
62
+ * escapeValue — when the caller treats Escape as "leave this screen",
63
+ * pass a sentinel produced by `escapeResult(value)`.
64
+ */
65
+ export async function runPrompt(config, context, spec) {
66
+ const input = context.input || process.stdin;
67
+ const output = context.output || process.stdout;
68
+ const canRaw = typeof input.setRawMode === 'function';
69
+ const previousRaw = canRaw ? Boolean(input.isRaw) : false;
70
+
71
+ let state;
72
+ let height = 0;
73
+ let settled = false;
74
+ let resolveDone;
75
+ let rejectDone;
76
+
77
+ const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
78
+
79
+ const draw = () => {
80
+ if (settled) return;
81
+ const rendered = spec.render(state);
82
+ const text = Array.isArray(rendered) ? rendered.join('\n') : String(rendered ?? '');
83
+ if (output.isTTY && height > 0) output.write(`\x1b[${height}A\x1b[0J`);
84
+ output.write(`${text}\n`);
85
+ // Count wrapped terminal rows as well as explicit newlines: the compact
86
+ // footer can still wrap in a narrow terminal.
87
+ const columns = output.isTTY && output.columns > 0 ? output.columns : Infinity;
88
+ height = text.split('\n').reduce((rows, line) => rows + Math.max(1, Math.ceil(Array.from(stripVTControlCharacters(line)).length / columns)), 0);
89
+ };
90
+
91
+ const finish = value => {
92
+ if (settled) return;
93
+ settled = true;
94
+ // The settled answer replaces the live frame rather than appending to it:
95
+ // rewind the frame height first so a terminal reader sees one final line.
96
+ if (spec.final && output.isTTY) {
97
+ const line = spec.final(config, value, state);
98
+ if (line) {
99
+ if (height > 0) output.write(`\x1b[${height}A\x1b[0J`);
100
+ output.write(`${line}\n`);
101
+ height = 0;
102
+ }
103
+ }
104
+ resolveDone(value);
105
+ };
106
+ const fail = error => {
107
+ if (settled) return;
108
+ settled = true;
109
+ rejectDone(error);
110
+ };
111
+
112
+ const api = { finish, fail, redraw: draw };
113
+ let queue = Promise.resolve();
114
+ const onKeypress = (_chunk, key) => {
115
+ if (!key || settled) return;
116
+ // Cancellation cannot wait behind validation or a source request.
117
+ if (key.name === 'escape') {
118
+ if (spec.escapeValue !== undefined) finish(spec.escapeValue.value);
119
+ else fail(new PromptCancelled());
120
+ return;
121
+ }
122
+ if (key.ctrl && (key.name === 'c' || key.name === 'd')) {
123
+ fail(new PromptCancelled());
124
+ return;
125
+ }
126
+ key = { ...key, text: !key.ctrl && !key.meta && typeof _chunk === 'string' && Array.from(_chunk).every(char => char.codePointAt(0) >= 32 && char.codePointAt(0) !== 127) ? _chunk : '' };
127
+ // Serialize handling: a chunk can carry several keys at once, and async
128
+ // handlers (search/load-more) must not reorder Enter ahead of arrows.
129
+ queue = queue.then(async () => {
130
+ if (settled) return;
131
+
132
+ const directive = await spec.key(state, key, api);
133
+ if (!directive || settled) return;
134
+ if ('done' in directive) finish(directive.done);
135
+ else if (directive.cancel) fail(new PromptCancelled());
136
+ else if (directive.escape) finish(undefined);
137
+ }).catch(error => fail(error));
138
+ };
139
+
140
+ const onAbort = () => fail(context.signal.reason || new PromptCancelled());
141
+ const onEnd = () => fail(new PromptCancelled());
142
+
143
+ try {
144
+ readline.emitKeypressEvents(input);
145
+ if (canRaw) input.setRawMode(true);
146
+ input.on('keypress', onKeypress);
147
+ input.on('end', onEnd);
148
+ input.on('close', onEnd);
149
+ input.on('error', fail);
150
+ if (context.signal) {
151
+ if (context.signal.aborted) onAbort();
152
+ else context.signal.addEventListener('abort', onAbort, { once: true });
153
+ }
154
+ state = spec.init(config, context);
155
+ if (input.readableEnded || input.destroyed) onEnd();
156
+ if (typeof input.resume === 'function') input.resume();
157
+ draw();
158
+ spec.onReady?.(api);
159
+ return await done;
160
+ } finally {
161
+ input.removeListener('keypress', onKeypress);
162
+ input.removeListener('end', onEnd);
163
+ input.removeListener('close', onEnd);
164
+ input.removeListener('error', fail);
165
+ if (context.signal) context.signal.removeEventListener('abort', onAbort);
166
+ if (canRaw) {
167
+ try { input.setRawMode(previousRaw); } catch { /* stream already closed */ }
168
+ }
169
+ if (typeof input.pause === 'function' && input.isTTY) input.pause();
170
+ }
171
+ }
172
+
173
+ /** Escape resolves `value` instead of cancelling (record pickers). */
174
+ export function escapeResult(value) {
175
+ return { value };
176
+ }
package/src/prompts.js CHANGED
@@ -1,35 +1,87 @@
1
- export class PromptCancelled extends Error {
2
- constructor() {
3
- super('Cancelled.');
4
- this.name = 'PromptCancelled';
5
- }
1
+ /**
2
+ * JSN's interactive prompt surface, implemented on the local engine
3
+ * (src/prompt-engine.js) instead of @inquirer/prompts.
4
+ *
5
+ * Callers use `prompt(config, { input, output, signal })`. Escape cancels
6
+ * ordinary prompts with PromptCancelled; record pickers live in
7
+ * paginated-search.js and resolve undefined instead.
8
+ */
9
+
10
+ import { pickerRows, pickerFooter } from './picker-ui.js';
11
+ import { runPrompt, normalizeChoices, PromptCancelled, escapeResult } from './prompt-engine.js';
12
+ export { PromptCancelled };
13
+
14
+ const ESC_HINT = ' (Esc to cancel)';
15
+
16
+ function withHint(config) {
17
+ const message = String(config.message ?? '');
18
+ return message.includes(ESC_HINT) ? message : `${message}${ESC_HINT}`;
6
19
  }
7
20
 
8
- /** Add Escape cancellation to an Inquirer prompt without changing its answers. */
9
- export function cancellablePrompt(prompt) {
10
- return async (config, context = {}) => {
11
- const input = context.input || process.stdin;
12
- const controller = new AbortController();
13
- const onKey = (_value, key) => {
14
- if (key?.name === 'escape') controller.abort(new PromptCancelled());
15
- };
16
- input.on('keypress', onKey);
17
- try {
18
- return await prompt({ ...config, message: `${config.message} (Esc to cancel)` }, {
19
- ...context,
20
- signal: context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal,
21
- });
22
- } catch (error) {
23
- if (controller.signal.aborted) throw controller.signal.reason;
24
- throw error;
25
- } finally {
26
- input.removeListener('keypress', onKey);
27
- }
28
- };
21
+ function applyValidate(validate, value) {
22
+ if (typeof validate !== 'function') return null;
23
+ const result = validate(value);
24
+ return result instanceof Promise ? result : result;
29
25
  }
30
26
 
31
- export const input = lazyPrompt('input');
32
- export const password = lazyPrompt('password');
27
+ async function validateAnswer(validate, value) {
28
+ const result = await applyValidate(validate, value);
29
+ if (result === true || result === undefined || result === '') return null;
30
+ return typeof result === 'string' ? result : result === false ? 'Invalid value.' : null;
31
+ }
32
+
33
+ function textPrompt({ secret = false, defaultValue = null } = {}) {
34
+ return async (config = {}, context = {}) => runPrompt({ ...config, message: withHint(config) }, context, {
35
+ init: () => ({ buffer: '', error: '' }),
36
+ async key(state, key, api) {
37
+ if (key.name === 'return' || key.name === 'enter') {
38
+ const value = state.buffer.length ? state.buffer : (config.default ?? defaultValue ?? '');
39
+ const message = await validateAnswer(config.validate, value);
40
+ if (message) { state.error = message; api.redraw(); return; }
41
+ return { done: value };
42
+ }
43
+ if (key.name === 'backspace') {
44
+ state.buffer = state.buffer.slice(0, -1);
45
+ state.error = '';
46
+ api.redraw();
47
+ return;
48
+ }
49
+ if (key.name === 'space') {
50
+ state.buffer += ' ';
51
+ state.error = '';
52
+ api.redraw();
53
+ return;
54
+ }
55
+ if (key.text) {
56
+ state.buffer += key.text;
57
+ state.error = '';
58
+ api.redraw();
59
+ return;
60
+ }
61
+ if (key.name === 'c' && key.ctrl) return { cancel: true };
62
+ api.redraw();
63
+ },
64
+ render(state) {
65
+ const label = withHint(config);
66
+ const suffix = config.default !== undefined && !secret ? ` (${config.default})` : '';
67
+ // Secrets are never echoed: the placeholder has a fixed width, so
68
+ // nothing about the typed value (characters or length) reaches stdout.
69
+ const shown = secret ? (state.buffer.length ? '******' : '') : state.buffer;
70
+ const error = state.error ? `\n ${state.error}` : '';
71
+ return `${label}${suffix}\n> ${shown}${error}`;
72
+ },
73
+ // Settled line keeps the prompt's own message (and hint) and never the
74
+ // secret value; Inquirer's `✔ message answer` shape.
75
+ final(cfg, value) {
76
+ const answer = secret || value === undefined || value === '' ? '' : ` ${value}`;
77
+ return `✔ ${withHint(cfg)}${answer}`;
78
+ },
79
+ });
80
+ }
81
+
82
+ export const input = textPrompt();
83
+
84
+ export const password = textPrompt({ secret: true });
33
85
 
34
86
  // Use the shared Escape contract and a masked prompt; codes stay ephemeral.
35
87
  export async function mfaCode(config = {}, context = {}) {
@@ -39,20 +91,218 @@ export async function mfaCode(config = {}, context = {}) {
39
91
  || 'Enter the 6-digit code from your authenticator app.',
40
92
  }, context);
41
93
  }
42
- export const select = lazyPrompt('select');
43
- export const search = lazyPrompt('search');
44
- export const confirm = lazyPrompt('confirm');
45
- export const checkbox = lazyPrompt('checkbox');
46
-
47
- // The editor prompt hands the keyboard to $EDITOR, so Escape belongs to that
48
- // editor. It lives here so every command imports prompts from one module;
49
- // cancelling an editor still uses Inquirer's Ctrl+C abort.
50
- export const editor = async (...args) => (await import('@inquirer/prompts')).editor(...args);
51
-
52
- // Load Inquirer only when a prompt is actually shown.
53
- function lazyPrompt(name) {
54
- return async (...args) => {
55
- const prompts = await import('@inquirer/prompts');
56
- return cancellablePrompt(prompts[name])(...args);
94
+
95
+ export async function confirm(config = {}, context = {}) {
96
+ const fallback = config.default === undefined ? true : Boolean(config.default);
97
+ return runPrompt({ ...config, message: withHint(config) }, context, {
98
+ init: () => ({ value: '', error: '' }),
99
+ key(state, key, api) {
100
+ if (key.name === 'return' || key.name === 'enter') {
101
+ const answer = /^y/i.test(state.value) ? true : /^n/i.test(state.value) ? false : fallback;
102
+ return { done: answer };
103
+ }
104
+ if (key.name === 'backspace') state.value = state.value.slice(0, -1);
105
+ else if (key.text) state.value += key.text;
106
+ api.redraw();
107
+ },
108
+ render(state) {
109
+ const hint = fallback ? '[Y/n]' : '[y/N]';
110
+ return `${withHint(config)} ${hint} ${state.value}`;
111
+ },
112
+ final: (cfg, value) => `✔ ${withHint(cfg)} ${value ? 'Yes' : 'No'}`,
113
+ });
114
+ }
115
+
116
+ export async function select(config = {}, context = {}) {
117
+ return localPicker(config, context);
118
+ }
119
+
120
+ async function localPicker(config, context, multiple = false) {
121
+ const choices = normalizeChoices(config.choices || []);
122
+ const state = {
123
+ term: '', choices, active: firstEnabled(choices), error: '',
124
+ picked: new Set(choices.filter(choice => choice.checked && !choice.disabled)),
57
125
  };
126
+ const defaultIndex = choices.findIndex(choice => !choice.disabled && choice.value === config.default);
127
+ if (defaultIndex >= 0) state.active = defaultIndex;
128
+ return runPrompt(config, context, {
129
+ ...(config.escapeValue ? { escapeValue: config.escapeValue } : {}),
130
+ init: () => state,
131
+ async key(_state, key, api) {
132
+ const visible = state.choices;
133
+ const choice = visible[state.active];
134
+ if (key.name === 'return' || key.name === 'enter') {
135
+ if (!multiple) {
136
+ if (choice && !choice.disabled) return { done: choice.value };
137
+ return;
138
+ }
139
+ const values = choices.filter(choice => state.picked.has(choice)).map(choice => choice.value);
140
+ state.error = config.required && !values.length ? 'Select at least one option.' : await validateAnswer(config.validate, values);
141
+ if (state.error) { api.redraw(); return; }
142
+ return { done: values };
143
+ }
144
+ if (multiple && key.name === 'space') {
145
+ if (choice && !choice.disabled) {
146
+ if (state.picked.has(choice)) state.picked.delete(choice);
147
+ else state.picked.add(choice);
148
+ state.error = '';
149
+ }
150
+ } else if (multiple && key.ctrl && key.name === 'a') {
151
+ visible.forEach(choice => { if (!choice.disabled) state.picked.add(choice); });
152
+ } else if (key.name === 'up' || key.name === 'down') {
153
+ state.active = move(visible, state.active, key.name === 'up' ? -1 : 1);
154
+ } else {
155
+ const previous = state.term;
156
+ if (key.name === 'backspace') state.term = Array.from(state.term).slice(0, -1).join('');
157
+ else if (key.text) state.term += key.text;
158
+ if (previous !== state.term) {
159
+ state.choices = state.term ? choices.filter(choice => !choice.separator && choice.name.toLocaleLowerCase().includes(state.term.toLocaleLowerCase())) : choices;
160
+ state.active = firstEnabled(state.choices);
161
+ }
162
+ }
163
+ api.redraw();
164
+ },
165
+ render() {
166
+ return [config.message ?? '', `Search: ${state.term}`, ...pickerRows(state.choices, state.active, multiple ? { picked: state.picked } : {}),
167
+ ...(!state.choices.length ? [' No matches'] : []), ...(state.error ? [` ${state.error}`] : []), ...pickerFooter({ checkbox: multiple })];
168
+ },
169
+ final: (_cfg, value) => value === undefined ? null : `✔ ${config.message ?? ''} ${multiple ? choices.filter(choice => value.includes(choice.value)).map(choice => choice.name).join(', ') : choices.find(choice => choice.value === value)?.name ?? value ?? ''}`,
170
+ });
171
+ }
172
+
173
+ export async function search(config = {}, context = {}) {
174
+ let request;
175
+ const state = { term: '', choices: [], active: 0, loading: false, token: 0, error: '' };
176
+ async function load(api) {
177
+ request?.abort();
178
+ request = new AbortController();
179
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
180
+ const token = ++state.token;
181
+ state.loading = true;
182
+ state.error = '';
183
+ state.active = 0;
184
+ api.redraw();
185
+ try {
186
+ const items = await config.source?.(state.term, { signal });
187
+ if (token !== state.token) return;
188
+ state.choices = normalizeChoices(items || []);
189
+ } catch (error) {
190
+ if (token !== state.token) return;
191
+ state.choices = [];
192
+ state.error = error?.message || String(error);
193
+ }
194
+ if (token !== state.token) return;
195
+ state.loading = false;
196
+ state.active = firstEnabled(state.choices);
197
+ api.redraw();
198
+ }
199
+ try {
200
+ return await runPrompt({ ...config, message: withHint(config) }, context, {
201
+ init: () => state,
202
+ onReady: api => { void load(api); },
203
+ key(_state, key, api) {
204
+ if (key.name === 'return' || key.name === 'enter') {
205
+ const choice = state.choices[state.active];
206
+ if (!state.loading && choice && !choice.disabled) return { done: choice.value };
207
+ return;
208
+ }
209
+ if (key.name === 'up' || key.name === 'down') {
210
+ state.active = move(state.choices, state.active, key.name === 'up' ? -1 : 1);
211
+ api.redraw();
212
+ return;
213
+ }
214
+ const previous = state.term;
215
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
216
+ else if (key.text) state.term += key.text;
217
+ if (state.term !== previous) void load(api);
218
+ },
219
+ render() {
220
+ const lines = [config.message ?? '', `Search: ${state.term}${state.loading ? ' ...' : ''}`];
221
+ if (state.error) lines.push(` ${state.error}`);
222
+ else if (!state.choices.length) lines.push(state.loading ? ' Loading...' : ' No matches');
223
+ else lines.push(...pickerRows(state.choices, state.active));
224
+ lines.push(...pickerFooter());
225
+ return lines;
226
+ },
227
+ });
228
+ } finally {
229
+ state.token += 1;
230
+ request?.abort();
231
+ }
232
+ }
233
+
234
+ export async function checkbox(config = {}, context = {}) {
235
+ return localPicker(config, context, true);
58
236
  }
237
+
238
+ function firstEnabled(choices) {
239
+ const index = choices.findIndex(choice => !choice.disabled);
240
+ return index < 0 ? 0 : index;
241
+ }
242
+
243
+ function move(choices, active, delta) {
244
+ let next = active + delta;
245
+ while (next >= 0 && next < choices.length && choices[next].disabled) next += delta;
246
+ if (next < 0 || next >= choices.length) return active;
247
+ return next;
248
+ }
249
+
250
+ /**
251
+ * Enter launches $EDITOR by default. Escape cancels before launch; once the
252
+ * editor owns the keyboard, its own controls apply.
253
+ */
254
+ export async function editor(config = {}, context = {}) {
255
+ if (config.waitForUserInput !== false) {
256
+ await runPrompt(config, context, {
257
+ init: () => ({}),
258
+ key(_state, key) {
259
+ if (key.name === 'return' || key.name === 'enter') return { done: true };
260
+ },
261
+ render: () => [withHint(config), 'Press Enter to launch your preferred editor.'],
262
+ });
263
+ } else {
264
+ (context.output || process.stdout).write(`${withHint(config)}\n`);
265
+ }
266
+ const fs = await import('node:fs');
267
+ const os = await import('node:os');
268
+ const path = await import('node:path');
269
+ const { spawn } = await import('node:child_process');
270
+
271
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'jsn-editor-'));
272
+ const file = path.join(directory, 'draft.txt');
273
+ try {
274
+ fs.writeFileSync(file, config.default ?? '', 'utf8');
275
+ const [command, ...args] = editorCommand();
276
+ await new Promise((resolve, reject) => {
277
+ const child = spawn(command, [...args, file], {
278
+ stdio: 'inherit',
279
+ signal: context.signal,
280
+ env: process.env,
281
+ });
282
+ child.on('error', reject);
283
+ child.on('exit', (code, signal) => {
284
+ if (code === 0) resolve();
285
+ else reject(new Error(`Editor exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
286
+ });
287
+ });
288
+ return fs.readFileSync(file, 'utf8');
289
+ } finally {
290
+ fs.rmSync(directory, { recursive: true, force: true });
291
+ }
292
+ }
293
+
294
+ function editorCommand() {
295
+ const spec = process.env.VISUAL || process.env.EDITOR || 'vi';
296
+ return spec.trim().split(/\s+/);
297
+ }
298
+
299
+ /**
300
+ * Kept for callers/tests that wrapped an Inquirer prompt with the Escape
301
+ * contract. The engine owns Escape now, so this is a pass-through that
302
+ * preserves the previous signature.
303
+ */
304
+ export function cancellablePrompt(prompt) {
305
+ return async (config, context = {}) => prompt(config, context);
306
+ }
307
+
308
+ export { escapeResult };
@@ -1,5 +1,7 @@
1
1
  import { isHexString, getStringField, assertSafeExactMatch } from '../helpers.js';
2
2
  import { discoverFlowContextFields, normalizeFlowContext } from '../flow-context.js';
3
+ import { tableReadParams } from '../table-read-params.js';
4
+ import { boundedReads } from '../bounded-reads.js';
3
5
 
4
6
  export async function resolveIdentifier(app, table, identifier) {
5
7
  // If it looks like a sys_id (32 hex chars), use it directly
@@ -86,24 +88,36 @@ async function resolveHistoryDisplayValues(app, table, history) {
86
88
  }
87
89
  }
88
90
 
89
- // Batch lookup choice labels
91
+ // Preserve each exact field/value query and its one-row limit. Batching
92
+ // changes HTTP envelopes, not the number or authorization of server reads.
90
93
  const choiceLabelMap = new Map();
91
- if (choiceLookups.size > 0) {
92
- for (const key of choiceLookups) {
93
- const [field, val] = key.split('|');
94
- const params = new URLSearchParams();
95
- params.set('sysparm_query', `name=${table}^element=${field}^value=${val}^language=en`);
96
- params.set('sysparm_limit', '1');
97
- params.set('sysparm_fields', 'value,label');
98
- params.set('sysparm_display_value', 'all');
99
- try {
100
- const choices = await app.sdk.list('sys_choice', params);
101
- if (choices.length > 0) {
102
- const label = choices[0].label?.display_value || choices[0].label;
103
- if (label) choiceLabelMap.set(key, label);
104
- }
105
- } catch { /* non-fatal */ }
94
+ const lookups = [...choiceLookups].map(key => {
95
+ const [field, val] = key.split('|');
96
+ return { key, params: new URLSearchParams({
97
+ sysparm_query: `name=${table}^element=${field}^value=${val}^language=en`,
98
+ sysparm_limit: '1', sysparm_fields: 'value,label', sysparm_display_value: 'all',
99
+ }) };
100
+ });
101
+ let choicesByLookup;
102
+ if (lookups.length > 1 && typeof app.sdk.batch === 'function') {
103
+ try {
104
+ const batch = await app.sdk.batch(lookups.map(({ params }, index) => ({
105
+ id: String(index), url: `/api/now/table/sys_choice?${tableReadParams(params, app.sdk)}`,
106
+ })));
107
+ choicesByLookup = batch.results.map(item => item.ok && Array.isArray(item.data?.result) ? item.data.result : []);
108
+ } catch {
109
+ // Existing policy: labels are optional. Never retry an ACL denial,
110
+ // malformed response or uncertain batch failure as individual reads.
111
+ choicesByLookup = lookups.map(() => []);
106
112
  }
113
+ } else {
114
+ choicesByLookup = await boundedReads(lookups, async ({ params }) => {
115
+ try { return await app.sdk.list('sys_choice', params); } catch { return []; }
116
+ });
117
+ }
118
+ for (const [index, choices] of choicesByLookup.entries()) {
119
+ const label = choices[0]?.label?.display_value || choices[0]?.label;
120
+ if (label) choiceLabelMap.set(lookups[index].key, label);
107
121
  }
108
122
 
109
123
  // Apply resolutions to history entries
@@ -20,10 +20,10 @@ export function recordListParams({ limit, offset, query, fields, displayValue: r
20
20
  return params;
21
21
  }
22
22
 
23
- export function listRecords(sdk, { table, params, displayValues, ...options }) {
23
+ export function listRecords(sdk, { table, params, displayValues, responseMetadata, ...options }) {
24
24
  const query = tableReadParams(params || recordListParams(options), sdk);
25
25
  if (displayValues !== undefined) query.set('sysparm_display_value', displayValue(displayValues));
26
- return sdk.list(table, query);
26
+ return responseMetadata ? sdk.list(table, query, { responseMetadata }) : sdk.list(table, query);
27
27
  }
28
28
 
29
29
  export function getRecord(sdk, options) {