@jacebenson/jsn 5.5.6 → 5.5.7-dev.212.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.
Files changed (43) hide show
  1. package/README.md +16 -1
  2. package/package.json +9 -8
  3. package/src/amb.js +15 -0
  4. package/src/app.js +4 -15
  5. package/src/auth/credential-store.js +131 -32
  6. package/src/auth/oauth.js +4 -28
  7. package/src/auth/transport.js +22 -0
  8. package/src/auth.js +23 -2
  9. package/src/cli-adapter.js +18 -1
  10. package/src/cli.js +0 -3
  11. package/src/commands/auth.js +21 -5
  12. package/src/commands/codesearch.js +11 -2
  13. package/src/commands/docs/community.js +1 -1
  14. package/src/commands/docs/db.js +38 -4
  15. package/src/commands/docs/docs.js +14 -13
  16. package/src/commands/docs/index.js +2 -1
  17. package/src/commands/docs/refresh.js +2 -1
  18. package/src/commands/docs/releases.js +1 -1
  19. package/src/commands/docs/replace.js +1 -1
  20. package/src/commands/docs/service-snapshot.js +1 -1
  21. package/src/commands/docs/snapshot.js +2 -1
  22. package/src/commands/docs/sync-service.js +5 -3
  23. package/src/commands/flows.js +7 -2
  24. package/src/commands/setup.js +28 -31
  25. package/src/commands/skill.js +3 -8
  26. package/src/commands/version.js +5 -1
  27. package/src/config.js +93 -18
  28. package/src/docs-links.js +28 -0
  29. package/src/help.js +4 -0
  30. package/src/midserver-install.js +3 -0
  31. package/src/paginated-search.js +146 -178
  32. package/src/perf.js +1 -1
  33. package/src/prompt-engine.js +169 -0
  34. package/src/prompts.js +304 -42
  35. package/src/sdk.js +10 -44
  36. package/src/session.js +6 -1
  37. package/src/sqlite.js +94 -0
  38. package/src/commands/docs/public/index.html +0 -178
  39. package/src/commands/docs/public/vendor/marked.min.js +0 -69
  40. package/src/commands/docs/public/vendor/purify.min.js +0 -3
  41. package/src/commands/docs/serve.js +0 -287
  42. package/src/commands/history.js +0 -57
  43. package/src/mutation-history.js +0 -75
@@ -0,0 +1,169 @@
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
+
16
+ export class PromptCancelled extends Error {
17
+ constructor() {
18
+ super('Cancelled.');
19
+ this.name = 'PromptCancelled';
20
+ }
21
+ }
22
+
23
+ /** Choices may be strings or { name, value, disabled }. */
24
+ export function normalizeChoices(choices = []) {
25
+ return choices.map(choice => {
26
+ if (choice && typeof choice === 'object') {
27
+ return {
28
+ name: String(choice.name ?? choice.value ?? ''),
29
+ value: 'value' in choice ? choice.value : choice.name,
30
+ disabled: Boolean(choice.disabled),
31
+ checked: Boolean(choice.checked),
32
+ };
33
+ }
34
+ return { name: String(choice), value: choice, disabled: false };
35
+ });
36
+ }
37
+
38
+ export function truncate(text, width = 70) {
39
+ const value = String(text ?? '');
40
+ return value.length > width ? `${value.slice(0, width - 3)}...` : value;
41
+ }
42
+
43
+ /**
44
+ * Run one interactive prompt.
45
+ *
46
+ * @param {object} config prompt config ({ message, ... })
47
+ * @param {object} context { input, output, signal }
48
+ * @param {object} spec
49
+ * init(config, context) -> state
50
+ * key(state, key, api) -> directive | undefined | Promise<...>
51
+ * directive: { done: value } finishes, { cancel: true } throws
52
+ * PromptCancelled, { escape: true } resolves undefined.
53
+ * render(config, state) -> string | string[]
54
+ * final(config, value, state) -> string | null — the settled answer line
55
+ * (Inquirer prints `✔ <message> <answer>`). Only written on a TTY after
56
+ * the live frame is erased, so one prompt yields exactly one final line
57
+ * and piped output keeps its existing byte contract.
58
+ * escapeValue — when the caller treats Escape as "leave this screen",
59
+ * pass a sentinel produced by `escapeResult(value)`.
60
+ */
61
+ export async function runPrompt(config, context, spec) {
62
+ const input = context.input || process.stdin;
63
+ const output = context.output || process.stdout;
64
+ const canRaw = typeof input.setRawMode === 'function';
65
+ const previousRaw = canRaw ? Boolean(input.isRaw) : false;
66
+
67
+ let state;
68
+ let height = 0;
69
+ let settled = false;
70
+ let resolveDone;
71
+ let rejectDone;
72
+
73
+ const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
74
+
75
+ const draw = () => {
76
+ if (settled) return;
77
+ const rendered = spec.render(state);
78
+ const text = Array.isArray(rendered) ? rendered.join('\n') : String(rendered ?? '');
79
+ if (output.isTTY && height > 0) output.write(`\x1b[${height}A\x1b[0J`);
80
+ output.write(`${text}\n`);
81
+ height = text.split('\n').length;
82
+ };
83
+
84
+ const finish = value => {
85
+ if (settled) return;
86
+ settled = true;
87
+ // The settled answer replaces the live frame rather than appending to it:
88
+ // rewind the frame height first so a terminal reader sees one final line.
89
+ if (spec.final && output.isTTY) {
90
+ const line = spec.final(config, value, state);
91
+ if (line) {
92
+ if (height > 0) output.write(`\x1b[${height}A\x1b[0J`);
93
+ output.write(`${line}\n`);
94
+ height = 0;
95
+ }
96
+ }
97
+ resolveDone(value);
98
+ };
99
+ const fail = error => {
100
+ if (settled) return;
101
+ settled = true;
102
+ rejectDone(error);
103
+ };
104
+
105
+ const api = { finish, fail, redraw: draw };
106
+ let queue = Promise.resolve();
107
+ const onKeypress = (_chunk, key) => {
108
+ if (!key || settled) return;
109
+ // Cancellation cannot wait behind validation or a source request.
110
+ if (key.name === 'escape') {
111
+ if (spec.escapeValue !== undefined) finish(spec.escapeValue.value);
112
+ else fail(new PromptCancelled());
113
+ return;
114
+ }
115
+ if (key.ctrl && (key.name === 'c' || key.name === 'd')) {
116
+ fail(new PromptCancelled());
117
+ return;
118
+ }
119
+ key = { ...key, text: !key.ctrl && !key.meta && typeof _chunk === 'string' && Array.from(_chunk).every(char => char.codePointAt(0) >= 32 && char.codePointAt(0) !== 127) ? _chunk : '' };
120
+ // Serialize handling: a chunk can carry several keys at once, and async
121
+ // handlers (search/load-more) must not reorder Enter ahead of arrows.
122
+ queue = queue.then(async () => {
123
+ if (settled) return;
124
+
125
+ const directive = await spec.key(state, key, api);
126
+ if (!directive || settled) return;
127
+ if ('done' in directive) finish(directive.done);
128
+ else if (directive.cancel) fail(new PromptCancelled());
129
+ else if (directive.escape) finish(undefined);
130
+ }).catch(error => fail(error));
131
+ };
132
+
133
+ const onAbort = () => fail(context.signal.reason || new PromptCancelled());
134
+ const onEnd = () => fail(new PromptCancelled());
135
+
136
+ try {
137
+ readline.emitKeypressEvents(input);
138
+ if (canRaw) input.setRawMode(true);
139
+ input.on('keypress', onKeypress);
140
+ input.on('end', onEnd);
141
+ input.on('close', onEnd);
142
+ input.on('error', fail);
143
+ if (context.signal) {
144
+ if (context.signal.aborted) onAbort();
145
+ else context.signal.addEventListener('abort', onAbort, { once: true });
146
+ }
147
+ state = spec.init(config, context);
148
+ if (input.readableEnded || input.destroyed) onEnd();
149
+ if (typeof input.resume === 'function') input.resume();
150
+ draw();
151
+ spec.onReady?.(api);
152
+ return await done;
153
+ } finally {
154
+ input.removeListener('keypress', onKeypress);
155
+ input.removeListener('end', onEnd);
156
+ input.removeListener('close', onEnd);
157
+ input.removeListener('error', fail);
158
+ if (context.signal) context.signal.removeEventListener('abort', onAbort);
159
+ if (canRaw) {
160
+ try { input.setRawMode(previousRaw); } catch { /* stream already closed */ }
161
+ }
162
+ if (typeof input.pause === 'function' && input.isTTY) input.pause();
163
+ }
164
+ }
165
+
166
+ /** Escape resolves `value` instead of cancelling (record pickers). */
167
+ export function escapeResult(value) {
168
+ return { value };
169
+ }
package/src/prompts.js CHANGED
@@ -1,35 +1,86 @@
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 { runPrompt, normalizeChoices, truncate, PromptCancelled, escapeResult } from './prompt-engine.js';
11
+ export { PromptCancelled };
12
+
13
+ const ESC_HINT = ' (Esc to cancel)';
14
+
15
+ function withHint(config) {
16
+ const message = String(config.message ?? '');
17
+ return message.includes(ESC_HINT) ? message : `${message}${ESC_HINT}`;
6
18
  }
7
19
 
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
- };
20
+ function applyValidate(validate, value) {
21
+ if (typeof validate !== 'function') return null;
22
+ const result = validate(value);
23
+ return result instanceof Promise ? result : result;
24
+ }
25
+
26
+ async function validateAnswer(validate, value) {
27
+ const result = await applyValidate(validate, value);
28
+ if (result === true || result === undefined || result === '') return null;
29
+ return typeof result === 'string' ? result : result === false ? 'Invalid value.' : null;
29
30
  }
30
31
 
31
- export const input = lazyPrompt('input');
32
- export const password = lazyPrompt('password');
32
+ function textPrompt({ secret = false, defaultValue = null } = {}) {
33
+ return async (config = {}, context = {}) => runPrompt({ ...config, message: withHint(config) }, context, {
34
+ init: () => ({ buffer: '', error: '' }),
35
+ async key(state, key, api) {
36
+ if (key.name === 'return' || key.name === 'enter') {
37
+ const value = state.buffer.length ? state.buffer : (config.default ?? defaultValue ?? '');
38
+ const message = await validateAnswer(config.validate, value);
39
+ if (message) { state.error = message; api.redraw(); return; }
40
+ return { done: value };
41
+ }
42
+ if (key.name === 'backspace') {
43
+ state.buffer = state.buffer.slice(0, -1);
44
+ state.error = '';
45
+ api.redraw();
46
+ return;
47
+ }
48
+ if (key.name === 'space') {
49
+ state.buffer += ' ';
50
+ state.error = '';
51
+ api.redraw();
52
+ return;
53
+ }
54
+ if (key.text) {
55
+ state.buffer += key.text;
56
+ state.error = '';
57
+ api.redraw();
58
+ return;
59
+ }
60
+ if (key.name === 'c' && key.ctrl) return { cancel: true };
61
+ api.redraw();
62
+ },
63
+ render(state) {
64
+ const label = withHint(config);
65
+ const suffix = config.default !== undefined && !secret ? ` (${config.default})` : '';
66
+ // Secrets are never echoed: the placeholder has a fixed width, so
67
+ // nothing about the typed value (characters or length) reaches stdout.
68
+ const shown = secret ? (state.buffer.length ? '******' : '') : state.buffer;
69
+ const error = state.error ? `\n ${state.error}` : '';
70
+ return `${label}${suffix}\n> ${shown}${error}`;
71
+ },
72
+ // Settled line keeps the prompt's own message (and hint) and never the
73
+ // secret value; Inquirer's `✔ message answer` shape.
74
+ final(cfg, value) {
75
+ const answer = secret || value === undefined || value === '' ? '' : ` ${value}`;
76
+ return `✔ ${withHint(cfg)}${answer}`;
77
+ },
78
+ });
79
+ }
80
+
81
+ export const input = textPrompt();
82
+
83
+ export const password = textPrompt({ secret: true });
33
84
 
34
85
  // Use the shared Escape contract and a masked prompt; codes stay ephemeral.
35
86
  export async function mfaCode(config = {}, context = {}) {
@@ -39,20 +90,231 @@ export async function mfaCode(config = {}, context = {}) {
39
90
  || 'Enter the 6-digit code from your authenticator app.',
40
91
  }, context);
41
92
  }
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
93
 
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);
94
+ export async function confirm(config = {}, context = {}) {
95
+ const fallback = config.default === undefined ? true : Boolean(config.default);
96
+ return runPrompt({ ...config, message: withHint(config) }, context, {
97
+ init: () => ({ value: '', error: '' }),
98
+ key(state, key, api) {
99
+ if (key.name === 'return' || key.name === 'enter') {
100
+ const answer = /^y/i.test(state.value) ? true : /^n/i.test(state.value) ? false : fallback;
101
+ return { done: answer };
102
+ }
103
+ if (key.name === 'backspace') state.value = state.value.slice(0, -1);
104
+ else if (key.text) state.value += key.text;
105
+ api.redraw();
106
+ },
107
+ render(state) {
108
+ const hint = fallback ? '[Y/n]' : '[y/N]';
109
+ return `${withHint(config)} ${hint} ${state.value}`;
110
+ },
111
+ final: (cfg, value) => `✔ ${withHint(cfg)} ${value ? 'Yes' : 'No'}`,
112
+ });
113
+ }
51
114
 
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);
57
- };
115
+ export async function select(config = {}, context = {}) {
116
+ const choices = normalizeChoices(config.choices || []);
117
+ return runPrompt({ ...config, message: withHint(config) }, context, {
118
+ init: () => ({ active: Math.max(firstEnabled(choices), choices.findIndex(choice => !choice.disabled && choice.value === config.default)) }),
119
+ key(state, key, api) {
120
+ if (key.name === 'return' || key.name === 'enter') {
121
+ const choice = choices[state.active];
122
+ if (!choice || choice.disabled) return;
123
+ return { done: choice.value };
124
+ }
125
+ if (key.name === 'up') { state.active = move(choices, state.active, -1); api.redraw(); return; }
126
+ if (key.name === 'down') { state.active = move(choices, state.active, 1); api.redraw(); return; }
127
+ if (key.name === 'k') { state.active = move(choices, state.active, -1); api.redraw(); return; }
128
+ if (key.name === 'j') { state.active = move(choices, state.active, 1); api.redraw(); return; }
129
+ },
130
+ render(state) {
131
+ const lines = [withHint(config)];
132
+ choices.forEach((choice, index) => {
133
+ const marker = index === state.active ? '>' : ' ';
134
+ lines.push(`${marker} ${choice.disabled ? `(disabled) ${choice.name}` : choice.name}`);
135
+ });
136
+ lines.push('', ' Use arrow keys, Enter to select.');
137
+ return lines;
138
+ },
139
+ final(cfg, value) {
140
+ const chosen = choices.find(choice => choice.value === value);
141
+ return `✔ ${withHint(cfg)} ${chosen ? chosen.name : value}`;
142
+ },
143
+ });
58
144
  }
145
+
146
+ export async function search(config = {}, context = {}) {
147
+ let request;
148
+ const state = { term: '', choices: [], active: 0, loading: false, token: 0, error: '' };
149
+ async function load(api) {
150
+ request?.abort();
151
+ request = new AbortController();
152
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
153
+ const token = ++state.token;
154
+ state.loading = true;
155
+ state.error = '';
156
+ state.active = 0;
157
+ api.redraw();
158
+ try {
159
+ const items = await config.source?.(state.term, { signal });
160
+ if (token !== state.token) return;
161
+ state.choices = normalizeChoices(items || []);
162
+ } catch (error) {
163
+ if (token !== state.token) return;
164
+ state.choices = [];
165
+ state.error = error?.message || String(error);
166
+ }
167
+ if (token !== state.token) return;
168
+ state.loading = false;
169
+ state.active = firstEnabled(state.choices);
170
+ api.redraw();
171
+ }
172
+ try {
173
+ return await runPrompt({ ...config, message: withHint(config) }, context, {
174
+ init: () => state,
175
+ onReady: api => { void load(api); },
176
+ key(_state, key, api) {
177
+ if (key.name === 'return' || key.name === 'enter') {
178
+ const choice = state.choices[state.active];
179
+ if (!state.loading && choice && !choice.disabled) return { done: choice.value };
180
+ return;
181
+ }
182
+ if (key.name === 'up' || key.name === 'down') {
183
+ state.active = move(state.choices, state.active, key.name === 'up' ? -1 : 1);
184
+ api.redraw();
185
+ return;
186
+ }
187
+ const previous = state.term;
188
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
189
+ else if (key.text) state.term += key.text;
190
+ if (state.term !== previous) void load(api);
191
+ },
192
+ render() {
193
+ const lines = [`${withHint(config)} Search: ${state.term}${state.loading ? ' ...' : ''}`];
194
+ if (state.error) lines.push(` ${state.error}`);
195
+ else if (!state.choices.length) lines.push(state.loading ? ' Loading...' : ' No matches');
196
+ else state.choices.forEach((choice, index) => lines.push(`${index === state.active ? '>' : ' '} ${truncate(choice.name)}`));
197
+ lines.push('', ' Type to filter, arrows to move, Enter to select.');
198
+ return lines;
199
+ },
200
+ });
201
+ } finally {
202
+ state.token += 1;
203
+ request?.abort();
204
+ }
205
+ }
206
+
207
+ export async function checkbox(config = {}, context = {}) {
208
+ const choices = normalizeChoices(config.choices || []);
209
+ return runPrompt({ ...config, message: withHint(config) }, context, {
210
+ init: () => ({ active: firstEnabled(choices), picked: new Set(choices.flatMap((choice, index) => choice.checked && !choice.disabled ? [index] : [])), error: '' }),
211
+ key(state, key, api) {
212
+ if (key.name === 'return' || key.name === 'enter') {
213
+ const values = choices.filter((_choice, index) => state.picked.has(index)).map(choice => choice.value);
214
+ if (config.required && values.length === 0) {
215
+ state.error = 'Select at least one option.';
216
+ api.redraw();
217
+ return;
218
+ }
219
+ return { done: values };
220
+ }
221
+ if (key.name === 'space') {
222
+ if (choices[state.active] && !choices[state.active].disabled) {
223
+ if (state.picked.has(state.active)) state.picked.delete(state.active);
224
+ else state.picked.add(state.active);
225
+ state.error = '';
226
+ api.redraw();
227
+ }
228
+ return;
229
+ }
230
+ if (key.name === 'a' && key.ctrl) {
231
+ choices.forEach((choice, index) => { if (!choice.disabled) state.picked.add(index); });
232
+ api.redraw();
233
+ return;
234
+ }
235
+ if (key.name === 'up') { state.active = move(choices, state.active, -1); api.redraw(); return; }
236
+ if (key.name === 'down') { state.active = move(choices, state.active, 1); api.redraw(); return; }
237
+ },
238
+ render(state) {
239
+ const lines = [withHint(config)];
240
+ choices.forEach((choice, index) => {
241
+ lines.push(`${index === state.active ? '>' : ' '} [${state.picked.has(index) ? 'x' : ' '}] ${choice.name}`);
242
+ });
243
+ if (state.error) lines.push(` ${state.error}`);
244
+ lines.push('', ' Space toggles, arrows move, Enter confirms.');
245
+ return lines;
246
+ },
247
+ });
248
+ }
249
+
250
+ function firstEnabled(choices) {
251
+ const index = choices.findIndex(choice => !choice.disabled);
252
+ return index < 0 ? 0 : index;
253
+ }
254
+
255
+ function move(choices, active, delta) {
256
+ let next = active + delta;
257
+ while (next >= 0 && next < choices.length && choices[next].disabled) next += delta;
258
+ if (next < 0 || next >= choices.length) return active;
259
+ return next;
260
+ }
261
+
262
+ /**
263
+ * Enter launches $EDITOR by default. Escape cancels before launch; once the
264
+ * editor owns the keyboard, its own controls apply.
265
+ */
266
+ export async function editor(config = {}, context = {}) {
267
+ if (config.waitForUserInput !== false) {
268
+ await runPrompt(config, context, {
269
+ init: () => ({}),
270
+ key(_state, key) {
271
+ if (key.name === 'return' || key.name === 'enter') return { done: true };
272
+ },
273
+ render: () => [withHint(config), 'Press Enter to launch your preferred editor.'],
274
+ });
275
+ } else {
276
+ (context.output || process.stdout).write(`${withHint(config)}\n`);
277
+ }
278
+ const fs = await import('node:fs');
279
+ const os = await import('node:os');
280
+ const path = await import('node:path');
281
+ const { spawn } = await import('node:child_process');
282
+
283
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'jsn-editor-'));
284
+ const file = path.join(directory, 'draft.txt');
285
+ try {
286
+ fs.writeFileSync(file, config.default ?? '', 'utf8');
287
+ const [command, ...args] = editorCommand();
288
+ await new Promise((resolve, reject) => {
289
+ const child = spawn(command, [...args, file], {
290
+ stdio: 'inherit',
291
+ signal: context.signal,
292
+ env: process.env,
293
+ });
294
+ child.on('error', reject);
295
+ child.on('exit', (code, signal) => {
296
+ if (code === 0) resolve();
297
+ else reject(new Error(`Editor exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
298
+ });
299
+ });
300
+ return fs.readFileSync(file, 'utf8');
301
+ } finally {
302
+ fs.rmSync(directory, { recursive: true, force: true });
303
+ }
304
+ }
305
+
306
+ function editorCommand() {
307
+ const spec = process.env.VISUAL || process.env.EDITOR || 'vi';
308
+ return spec.trim().split(/\s+/);
309
+ }
310
+
311
+ /**
312
+ * Kept for callers/tests that wrapped an Inquirer prompt with the Escape
313
+ * contract. The engine owns Escape now, so this is a pass-through that
314
+ * preserves the previous signature.
315
+ */
316
+ export function cancellablePrompt(prompt) {
317
+ return async (config, context = {}) => prompt(config, context);
318
+ }
319
+
320
+ export { escapeResult };
package/src/sdk.js CHANGED
@@ -4,6 +4,7 @@ import { batchRead } from './sdk-batch.js';
4
4
  import { tableReadParams } from './table-read-params.js';
5
5
  import { gunzipSync } from 'node:zlib';
6
6
  import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
7
+ import { assertCredentialTransport, assertCredentialDestination } from './auth/transport.js';
7
8
  import { canPrompt, getStringField } from './helpers.js';
8
9
  import { errMfaRequired, errMfaRejected, isTerminalAuthError } from './errors.js';
9
10
  import { buildMfaVerificationBody, extractMfaFormTokens, normalizeTotpCode, parseLoginStatus } from './auth/mfa.js';
@@ -82,7 +83,6 @@ export class SDKClient {
82
83
  this.baseURL = baseURL.replace(/\/$/, '');
83
84
  this.authProvider = authProvider;
84
85
  this.recovery = opts.recovery;
85
- this.onMutation = opts.onMutation;
86
86
  this.timeout = opts.timeout || DEFAULT_TIMEOUT;
87
87
  this.domain = opts.domain || '';
88
88
  this.includeReferenceLinks = opts.includeReferenceLinks === true;
@@ -163,49 +163,14 @@ export class SDKClient {
163
163
  // Keep the timeout alive through body consumption for text/JSON requests.
164
164
  // Raw-response callers retain their existing timeout boundary at headers.
165
165
  async _withAuthenticatedRequest(endpoint, opts, settings, consume = (response) => response) {
166
- const url = new URL(endpoint);
167
- const match = url.pathname.match(/^\/api\/now\/table\/([^/]+)(?:\/([^/]+))?\/?$/);
168
- const operation = { POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete' }[(opts.method || 'GET').toUpperCase()];
169
- const event = match && operation && this.onMutation ? {
170
- table: decodeURIComponent(match[1]), sys_id: match[2] ? decodeURIComponent(match[2]) : null, operation,
171
- } : null;
172
- let result;
173
- try {
174
- result = await this._performAuthenticatedRequest(endpoint, opts, settings, async response => {
175
- if (event) event.http_status = response.status;
176
- const value = await consume(response);
177
- if (event && value instanceof Response && response.ok && operation === 'create') {
178
- try { event.sys_id = (await response.clone().json())?.result?.sys_id || null; } catch { /* ID remains unknown. */ }
179
- }
180
- return value;
181
- });
182
- } catch (error) {
183
- if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
184
- ? 'failed' : 'unknown', http_status: error.status || null });
185
- throw error;
186
- }
187
- if (event) {
188
- let body = result;
189
- if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }
190
- const id = body?.result?.sys_id;
191
- if (typeof id === 'string') event.sys_id = id;
192
- else if (typeof id?.value === 'string') event.sys_id = id.value;
193
- await this._reportMutation({ ...event, outcome: event.http_status >= 400
194
- ? (event.http_status < 500 && event.http_status !== 408 ? 'failed' : 'unknown')
195
- : (event.sys_id ? 'succeeded' : 'unknown') });
196
- }
197
- return result;
198
- }
199
-
200
- async _reportMutation(event) {
201
- // History failures must never change the outcome of a completed remote write.
202
- try { await this.onMutation(event); } catch { /* App callback reports local storage failures. */ }
166
+ return this._performAuthenticatedRequest(endpoint, opts, settings, consume);
203
167
  }
204
168
 
205
169
  async _performAuthenticatedRequest(endpoint, opts, {
206
170
  timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
207
171
  allowMutationReplay = false, stateful = false,
208
172
  }, consume = (response) => response) {
173
+ assertCredentialDestination(endpoint, this.baseURL);
209
174
  const method = String(opts.method || 'GET').toUpperCase();
210
175
  for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
211
176
  // Headers for this attempt belong to the session as it is right now.
@@ -214,7 +179,7 @@ export class SDKClient {
214
179
  let timer;
215
180
  let rejection;
216
181
  try {
217
- const req = new Request(endpoint, { ...opts, signal: controller.signal });
182
+ const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
218
183
  if (prepare) prepare(req);
219
184
  // Header-authenticated REST skips UI warming for OAuth/token/GCK.
220
185
  // Basic must still check for TOTP before dispatch; internal bootstrap
@@ -297,6 +262,7 @@ export class SDKClient {
297
262
  * that they still belong to the selected identity.
298
263
  */
299
264
  async _verifyRecoveredSession() {
265
+ assertCredentialTransport(this.baseURL);
300
266
  const params = new URLSearchParams({
301
267
  sysparm_query: 'user_name=javascript:gs.getUserName()',
302
268
  sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
@@ -972,7 +938,6 @@ export class SDKClient {
972
938
  form.set('sysparm_upload_prefix', '');
973
939
  form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
974
940
  form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
975
- let outcome = 'unknown';
976
941
  try {
977
942
  await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
978
943
  headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
@@ -998,12 +963,9 @@ export class SDKClient {
998
963
  const member = actual.get(expected.sys_id);
999
964
  return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
1000
965
  })) throw new Error('Uploaded update set members did not match the XML export');
1001
- outcome = 'succeeded';
1002
966
  return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
1003
967
  } catch (error) {
1004
968
  throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying. No automatic retry was attempted.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
1005
- } finally {
1006
- if (this.onMutation) await this._reportMutation({ table: 'sys_remote_update_set', sys_id: id, operation: 'create', outcome });
1007
969
  }
1008
970
  }
1009
971
 
@@ -1183,6 +1145,7 @@ export class SDKClient {
1183
1145
  * is an actionable error, never a silent fallback.
1184
1146
  */
1185
1147
  async ambSession() {
1148
+ assertCredentialTransport(this.baseURL);
1186
1149
  if (!this.authProvider) throw errAuth('No authentication configured');
1187
1150
  const creds = await this.authProvider.getCredentials();
1188
1151
  if (!creds) throw errAuth('No valid credentials');
@@ -1222,19 +1185,21 @@ export class SDKClient {
1222
1185
  }
1223
1186
 
1224
1187
  async _initializeSession() {
1188
+ assertCredentialTransport(this.baseURL);
1225
1189
  let challenged = false;
1226
1190
  try {
1227
1191
  const creds = await this.authProvider.getCredentials();
1228
1192
  if (creds.auth_method === 'oauth') {
1229
1193
  const cookieJar = new Map();
1230
1194
  const login = `${this.baseURL}/angular.do?sysparm_type=get_user`;
1231
- collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST' })));
1195
+ collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST', redirect: 'error' })));
1232
1196
  const scopeEndpoint = `${this.baseURL}/api/now/table/sys_scope?sysparm_fields=sys_id%2Csys_class_name&sysparm_limit=1`;
1233
1197
  collectSetCookies(cookieJar, await this._fetchWithAuth(scopeEndpoint, {
1234
1198
  method: 'GET',
1235
1199
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1236
1200
  }));
1237
1201
  const finalLogin = await fetch(new Request(login, {
1202
+ redirect: 'error',
1238
1203
  method: 'POST',
1239
1204
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1240
1205
  }));
@@ -1284,6 +1249,7 @@ export class SDKClient {
1284
1249
  // Each network exchange, including its body, has a deadline independent of
1285
1250
  // human code entry. The race also bounds streams that do not honor abort.
1286
1251
  async _mfaExchange(path, options, cookieJar, consume = response => response) {
1252
+ assertCredentialTransport(this.baseURL);
1287
1253
  const controller = new AbortController();
1288
1254
  let timer;
1289
1255
  const deadline = new Promise((resolve, reject) => {