@jacebenson/jsn 5.5.7 → 5.5.8-dev.219.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 (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
@@ -2,73 +2,96 @@
2
2
  import process from 'node:process';
3
3
  import { collectCapabilities } from './capabilities.js';
4
4
  import { isMutationCommand } from './mutations.js';
5
- import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
6
- import { canUsePicker, getStringField, quoteShellArg } from './helpers.js';
5
+ import { canUsePicker, quoteShellArg } from './helpers.js';
7
6
  import { confirm } from './prompts.js';
8
- import { AppError, CodeConfirmationRequired, errUsageHint } from './errors.js';
7
+ import { AppError, CodeConfirmationRequired } from './errors.js';
8
+ import { contextFailure, exactContextRecord, intendedContext, readWriteContext } from './intended-context.js';
9
9
 
10
10
  export function needsMutationContext(argv) {
11
11
  if (!isMutationCommand(argv)) return false;
12
12
  const caps = collectCapabilities().get(argv._?.[0]) || {};
13
+ if (caps.mutationContext === 'operational') return false;
13
14
  if (caps.mutationContextReadMethods?.includes(String(argv.method || 'GET').toUpperCase())) return false;
14
15
  return !caps.mutationContextExemptSubcommands?.some(sub =>
15
16
  sub.split(' ').every((part, index) => argv._?.[index + 1] === part));
16
17
  }
17
18
 
18
- function diagnostic(code, message, command, severity = 'warning') {
19
- return { code, severity, message, remediation: { command } };
19
+ // Table ancestry, not a command-name heuristic, decides generic record writes.
20
+ async function isCustomizationTable(sdk, table) {
21
+ if (!table) throw contextFailure('Cannot classify a write without its table.');
22
+ const seen = new Set();
23
+ let row = await exactContextRecord(sdk, 'sys_db_object', 'name', table);
24
+ for (let depth = 0; depth < 32; depth++) {
25
+ const name = row.name?.value ?? row.name;
26
+ if (!name || seen.has(name)) throw contextFailure('Table ancestry is incomplete or cyclic.');
27
+ if (name === 'sys_metadata') return true;
28
+ seen.add(name);
29
+ if (!Object.hasOwn(row, 'super_class')) throw contextFailure('Table ancestry is unreadable.');
30
+ const parent = row.super_class?.value ?? row.super_class;
31
+ if (!parent) return false;
32
+ row = await sdk.get('sys_db_object', parent);
33
+ if (!row) throw contextFailure('Table ancestry is unreadable.');
34
+ }
35
+ throw contextFailure('Table ancestry exceeds the verification bound.');
20
36
  }
21
37
 
22
38
  export async function guardMutationContext(app, argv, { ask = confirm, rawArgs = process.argv.slice(2) } = {}) {
23
39
  if (!needsMutationContext(argv) || !app.sdk) return null;
24
- let application, updateSet;
25
- try {
26
- const user = await getCurrentUser(app.sdk);
27
- if (user?.sys_id) [application, updateSet] = await Promise.all([
28
- getCurrentApplication(app.sdk, user.sys_id, { unknownWhenMissing: true }),
29
- getCurrentUpdateSet(app.sdk, user.sys_id),
30
- ]);
31
- } catch {
32
- // Failed reads are unknown context, never evidence of Global + Default.
40
+ const caps = collectCapabilities().get(argv._?.[0]) || {};
41
+ if (caps.mutationContext === 'table' && !await isCustomizationTable(app.sdk, caps.table || argv.table)) return null;
42
+ const expected = intendedContext(app, argv);
43
+ const interactive = canUsePicker(app, argv);
44
+ if (!interactive && (!expected.scope || !expected.update_set)) throw contextFailure('Noninteractive customization writes require intended scope and update set.');
45
+ // Header application is not an established effective-domain provider contract.
46
+ if (expected.domain !== undefined || app.session?.domain || app.session?.profile?.domain_separation || app.sdk.domain) {
47
+ throw contextFailure('Effective domain cannot be proven for customization writes. X-Now-Domain propagation does not verify domain selection; domain-scoped writes are not supported by this guard.');
48
+ }
49
+ let context;
50
+ try { context = await readWriteContext(app.sdk); }
51
+ catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
52
+ if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
53
+ const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
54
+ if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
55
+ if (!['in progress', 'in_progress'].includes(context.update_set.state.toLowerCase())) fail('Selected capture update set is not in progress.');
56
+ if (expected.scope !== undefined) {
57
+ const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', expected.scope);
58
+ if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Intended scope does not match fresh selected scope.');
33
59
  }
34
- const context = { scope: application?.scope || null, application_id: application?.appSysId || null,
35
- update_set: updateSet ? { name: updateSet.name, sys_id: updateSet.sys_id, state: updateSet.state || null } : null,
36
- diagnostics: [], approval_required: false, approved: false };
37
- if (!context.scope || !updateSet) context.diagnostics.push(diagnostic('capture_context_unknown',
38
- 'Capture context could not be determined. Identify the intended scope and update set before development changes.', 'jsn updatesets list'));
39
- const appId = getStringField(updateSet || {}, 'application');
40
- const rawAppId = updateSet?.application?.value || appId;
41
- if (application?.appSysId && rawAppId && application.appSysId !== rawAppId) {
42
- context.diagnostics.push(diagnostic('update_set_scope_mismatch',
43
- `Selected scope ${context.scope} and update set ${updateSet.name} belong to different applications; changes may not be captured in this set.`,
44
- `jsn scopes set ${quoteShellArg(rawAppId)}`));
60
+ if (caps.transactionScopeOption && argv[caps.transactionScopeOption] !== undefined) {
61
+ const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', argv[caps.transactionScopeOption]);
62
+ if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Command transaction scope differs from verified intended scope.');
45
63
  }
46
- if (updateSet?.state && !['in progress', 'in_progress'].includes(updateSet.state.toLowerCase())) {
47
- context.diagnostics.push(diagnostic('update_set_not_in_progress', `Selected update set ${updateSet.name} is ${updateSet.state}; select an in-progress capture set.`, 'jsn updatesets set', 'error'));
48
- const error = errUsageHint('Selected capture update set is not in progress.', 'Run: jsn updatesets set');
49
- error.context = context; throw error;
64
+ if (expected.update_set !== undefined) {
65
+ const set = await exactContextRecord(app.sdk, 'sys_update_set', 'name', expected.update_set);
66
+ if ((set.sys_id?.value ?? set.sys_id) !== context.update_set.sys_id) fail('Intended update set does not match fresh selected update set.');
50
67
  }
51
- const globalDefault = context.scope?.toLowerCase() === 'global' && updateSet?.name?.toLowerCase() === 'default';
52
- if (globalDefault) {
53
- context.approval_required = true;
54
- context.diagnostics.push(diagnostic('global_default_update_set',
55
- 'Global scope + Default update set can capture customization in the wrong place or leave changes untracked. Select or create a dedicated update set; not all record changes are update-set tracked.',
56
- 'jsn updatesets create --name "My Feature"'));
68
+ // Never align/switch a session implicitly. Persisted and effective selections
69
+ // are independent evidence; both must agree before customization can proceed.
70
+ const [scopeResponse, setResponse] = await Promise.all([
71
+ app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/application`, { method: 'GET', readOnly: true }),
72
+ app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/updateset`, { method: 'GET', readOnly: true }),
73
+ ]);
74
+ if (scopeResponse?.result?.current !== context.application_id || setResponse?.result?.current?.sysId !== context.update_set.sys_id) fail('Effective session context is unknown or differs from the selected preferences. No context was switched.');
75
+ context.verified = true;
76
+ if (caps.mutationContext === 'table') context.table = caps.table || argv.table;
77
+ context.source = 'fresh_preferences_and_session';
78
+ context.expected = expected;
79
+ context.diagnostics = [];
80
+ context.approval_required = context.scope.toLowerCase() === 'global' && context.update_set.name.toLowerCase() === 'default';
81
+ context.approved = false;
82
+ if (interactive && (!expected.scope || !expected.update_set) && !context.approval_required) {
83
+ if (!await ask({ message: `Confirm customization in scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id})?`, default: false })) fail('Customization context was not confirmed.');
84
+ context.approved = true;
85
+ }
86
+ if (context.approval_required) {
87
+ context.diagnostics.push({ code: 'global_default_update_set', severity: 'warning', message: 'Global + Default requires approval for this exact operation.' });
57
88
  if (argv.force) context.approved = true;
58
- else if (canUsePicker(app, argv)) {
59
- context.approved = await ask({ message: `Scope: Global; update set: Default. ${context.diagnostics.at(-1).message} Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
60
- }
89
+ else if (interactive) context.approved = await ask({ message: `Scope: Global; update set: Default. Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
61
90
  if (!context.approved) {
62
- const target = app.session?.profileName ? ` --profile ${quoteShellArg(app.session.profileName)}` : '';
63
- const rerun = ['jsn', ...rawArgs.filter(arg => arg !== '--force')].map(quoteShellArg).join(' ') + (rawArgs.includes('--profile') ? '' : target);
64
- const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.',
65
- `Select a dedicated set: jsn updatesets set; or jsn updatesets create --name "My Feature". Ask the user to approve this exact operation, then rerun: ${rerun} --force`);
91
+ const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.', 'Select a dedicated set or obtain user approval for this exact operation, then rerun with --force and explicit expectations.');
66
92
  error.context = context; throw error;
67
93
  }
68
94
  }
69
- if (canUsePicker(app, argv)) {
70
- process.stderr.write(`Mutation context: scope ${context.scope || 'unknown'}; update set ${updateSet?.name || 'unknown'}${updateSet?.sys_id ? ` (${updateSet.sys_id})` : ''}.\n`);
71
- for (const item of context.diagnostics) process.stderr.write(`Warning (${item.code}): ${item.message} Run: ${item.remediation.command}\n`);
72
- }
95
+ if (interactive) process.stderr.write(`Mutation context: scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id}); user ${context.user.user_name}.\n`);
73
96
  return context;
74
97
  }
package/src/output.js CHANGED
@@ -136,7 +136,7 @@ export class OutputWriter {
136
136
  // typo looked like a successful empty result until the next tool in the
137
137
  // pipeline failed to parse it. Present null/false/0/"" still print as-is.
138
138
  if (this.jqFilter) {
139
- const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
139
+ const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
140
140
  const value = resolvePath(envelope, this.jqFilter);
141
141
  if (value === undefined) throw errExtractionNotFound(this.jqFilter);
142
142
  const indent = this.verbose && !this.raw ? 2 : undefined;
@@ -1,195 +1,163 @@
1
1
  /**
2
- * Paginated search prompt built with @inquirer/core hooks.
2
+ * Paginated, searchable record picker built on src/prompt-engine.js.
3
+ *
4
+ * Contract (unchanged from the Inquirer version):
5
+ * paginatedSearch({ message, pageSize, totalCount, source }, context?)
6
+ * source(term, offset, { signal }) -> [{ name, value }]
7
+ * Enter resolves the active choice object; Escape resolves undefined.
8
+ * Down at the last loaded row loads more while loaded < totalCount;
9
+ * a null totalCount is unknown and continues until a successful empty page.
3
10
  */
4
11
 
5
-
6
- export const paginatedSearch = async (...args) => {
7
- const { createPrompt, useState, useKeypress, usePagination, useEffect, useRef, isEnterKey, isUpKey, isDownKey } = await import('@inquirer/core');
8
- return createPrompt((config, done) => {
9
- const { message, pageSize = 10, totalCount = 0, source } = config;
10
-
11
- const [status, setStatus] = useState('loading');
12
- const [searchTerm, setSearchTerm] = useState('');
13
- const [choices, setChoices] = useState([]);
14
- const [active, setActive] = useState(0);
15
- const [loaded, setLoaded] = useState(0);
16
- const [searchMode, setSearchMode] = useState(false);
17
-
18
- // Refs for mutable state (no functional updaters — @inquirer/core doesn't support them)
19
- const choicesRef = useRef([]);
20
- const loadedRef = useRef(0);
21
- const activeRef = useRef(0);
22
- const totalCountRef = useRef(totalCount);
23
- const searchModeRef = useRef(false);
24
-
25
- const fullMessage = totalCount > 0
26
- ? `${message} (${loaded} of ${totalCount} loaded)`
27
- : message;
28
-
29
- // Load initial page
30
- useEffect(() => {
31
- const controller = new AbortController();
32
- setStatus('loading');
33
-
34
- const load = async () => {
35
- try {
36
- const items = await source(searchTerm || undefined, 0, { signal: controller.signal });
37
- if (!controller.signal.aborted) {
38
- choicesRef.current = items;
39
- loadedRef.current = items.length;
40
- activeRef.current = 0;
41
- setChoices(items);
42
- setLoaded(items.length);
43
- setActive(0);
44
- setStatus('done');
45
- }
46
- } catch {
47
- if (!controller.signal.aborted) {
48
- setStatus('done');
49
- setChoices([]);
50
- setLoaded(0);
51
- }
52
- }
53
- };
54
- load();
55
- return () => controller.abort();
56
- }, []);
57
-
58
- // Load more when scrolling past end
59
- async function loadMore() {
60
- if (loadedRef.current >= totalCountRef.current || searchModeRef.current) return;
61
- setStatus('loading');
62
- try {
63
- const newItems = await source('', loadedRef.current, { signal: new AbortController().signal });
64
- const updated = choicesRef.current.concat(newItems);
65
- choicesRef.current = updated;
66
- loadedRef.current = updated.length;
67
- setChoices([...updated]);
68
- setLoaded(updated.length);
69
- } catch (err) {
70
- console.error('Scroll load error:', err.message || err);
71
- loadedRef.current = totalCountRef.current;
72
- setLoaded(totalCountRef.current);
12
+ import { pickerRows, pickerFooter } from './picker-ui.js';
13
+ import { runPrompt, normalizeChoices, escapeResult } from './prompt-engine.js';
14
+
15
+ export const paginatedSearch = async (config = {}, context = {}) => {
16
+ const { message, pageSize = 10, totalCount = 0, source } = config;
17
+ let request;
18
+ const state = {
19
+ status: 'loading',
20
+ term: '',
21
+ choices: [],
22
+ active: 0,
23
+ loaded: 0,
24
+ searchMode: false,
25
+ token: 0,
26
+ error: '',
27
+ };
28
+
29
+ const canLoadMore = () => !state.searchMode && !state.exhausted
30
+ && (totalCount == null || state.loaded < totalCount);
31
+
32
+ // Every request gets a token. A response may only be applied while its
33
+ // token is still current, so a stale (slower) search can never replace
34
+ // newer results or be selected by a later Enter.
35
+ const isCurrent = token => token === state.token && state.status !== 'cancelled';
36
+
37
+ async function load(term, offset, { append = false } = {}) {
38
+ request?.abort();
39
+ request = new AbortController();
40
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
41
+ const token = ++state.token;
42
+ state.status = 'loading';
43
+ state.error = '';
44
+ try {
45
+ const items = normalizeChoices(await source(term || undefined, offset, { signal }) || []);
46
+ if (!isCurrent(token)) return;
47
+ state.choices = append ? state.choices.concat(items) : items;
48
+ state.loaded = state.choices.length;
49
+ state.exhausted = items.length === 0;
50
+ state.active = Math.min(state.active, Math.max(0, state.choices.length - 1));
51
+ state.status = 'done';
52
+ } catch (error) {
53
+ if (!isCurrent(token)) return;
54
+ state.status = 'done';
55
+ state.error = error?.message || String(error);
56
+ if (!append) {
57
+ state.choices = [];
58
+ state.loaded = 0;
73
59
  }
74
- setStatus('done');
60
+ // A failed load-more keeps the rows already on screen.
75
61
  }
76
-
77
- // Search when term changes
78
- useEffect(() => {
79
- if (!searchTerm) {
80
- setSearchMode(false);
81
- searchModeRef.current = false;
82
- const controller = new AbortController();
83
- setStatus('loading');
84
- source('', 0, { signal: controller.signal }).then(items => {
85
- if (!controller.signal.aborted) {
86
- choicesRef.current = items;
87
- loadedRef.current = Math.min(items.length, totalCount || Infinity);
88
- activeRef.current = 0;
89
- setChoices(items);
90
- setLoaded(items.length);
91
- setActive(0);
92
- setStatus('done');
93
- }
94
- }).catch(() => {
95
- if (!controller.signal.aborted) setStatus('done');
96
- });
97
- return () => controller.abort();
98
- }
99
-
100
- const controller = new AbortController();
101
- setStatus('loading');
102
- setSearchMode(true);
103
- searchModeRef.current = true;
104
-
105
- source(searchTerm, undefined, { signal: controller.signal }).then(items => {
106
- if (!controller.signal.aborted) {
107
- choicesRef.current = items;
108
- loadedRef.current = items.length;
109
- activeRef.current = 0;
110
- setChoices(items);
111
- setLoaded(items.length);
112
- setActive(0);
113
- setStatus('done');
114
- }
115
- }).catch(() => {
116
- if (!controller.signal.aborted) {
117
- setStatus('done');
118
- setChoices([]);
119
- }
62
+ }
63
+
64
+ let api;
65
+ const prompt = runPrompt({ ...config, message }, context, {
66
+ escapeValue: escapeResult(undefined),
67
+ init() {
68
+ // Kick off the first page. Enter is ignored while status is 'loading',
69
+ // so nothing is selectable until this resolves.
70
+ state.pending = load('', 0);
71
+ return state;
72
+ },
73
+ onReady(handle) {
74
+ api = handle;
75
+ state.pending.then(() => {
76
+ if (state.status !== 'cancelled') api.redraw();
120
77
  });
121
-
122
- return () => controller.abort();
123
- }, [searchTerm]);
124
-
125
- // Key handling
126
- useKeypress((key, rl) => {
127
- if (status === 'loading') return;
128
-
129
- if (isEnterKey(key)) {
130
- if (choicesRef.current.length > 0 && activeRef.current >= 0 && activeRef.current < choicesRef.current.length) {
131
- done(choicesRef.current[activeRef.current]);
132
- }
133
- return;
78
+ },
79
+ key(_state, key, handle) {
80
+ api = handle;
81
+ if (key.name === 'return' || key.name === 'enter') {
82
+ // No selecting a row while a request is in flight: the list on
83
+ // screen may be about to change.
84
+ if (state.status === 'loading' || !state.choices.length) return;
85
+ const choice = state.choices[state.active];
86
+ if (!choice || choice.disabled) return;
87
+ return { done: choice };
134
88
  }
135
-
136
- if (key.name === 'escape') {
137
- done(undefined);
89
+ if (key.name === 'up') {
90
+ if (state.active > 0) state.active -= 1;
91
+ api?.redraw();
138
92
  return;
139
93
  }
140
-
141
- if (isUpKey(key)) {
142
- if (activeRef.current > 0) {
143
- activeRef.current--;
144
- setActive(activeRef.current);
145
- }
146
- return;
147
- }
148
-
149
- if (isDownKey(key)) {
150
- if (activeRef.current < choicesRef.current.length - 1) {
151
- activeRef.current++;
152
- setActive(activeRef.current);
153
- } else if (!searchModeRef.current && loadedRef.current < totalCountRef.current) {
154
- loadMore().then(() => {
155
- activeRef.current++;
156
- setActive(activeRef.current);
94
+ if (key.name === 'down') {
95
+ if (state.status === 'loading') return;
96
+ if (state.active < state.choices.length - 1) {
97
+ state.active += 1;
98
+ api?.redraw();
99
+ } else if (canLoadMore()) {
100
+ const before = state.loaded;
101
+ const pending = load('', state.loaded, { append: true });
102
+ const token = state.token;
103
+ void pending.then(() => {
104
+ if (!isCurrent(token)) return;
105
+ if (state.status === 'done' && state.loaded > before) state.active = before;
106
+ api?.redraw();
157
107
  });
108
+ api?.redraw();
158
109
  }
159
110
  return;
160
111
  }
161
-
162
- // Use readline's built-in line buffer for text input
163
- const newTerm = rl.line;
164
- if (newTerm !== searchTerm) {
165
- setSearchTerm(newTerm);
112
+ const previous = state.term;
113
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
114
+ else if (key.name === 'space') state.term += ' ';
115
+ else if (key.text) state.term += key.text;
116
+ else return;
117
+ if (state.term === previous) return;
118
+
119
+ if (!state.term) {
120
+ state.searchMode = false;
121
+ state.active = 0;
122
+ void load('', 0).then(() => api?.redraw());
123
+ api?.redraw();
124
+ return;
166
125
  }
167
- });
168
-
169
- // Paginated rendering
170
- const page = usePagination({
171
- items: Array.isArray(choices) ? choices : [],
172
- active,
173
- pageSize,
174
- renderItem: ({ item, isActive }) => {
175
- const prefix = isActive ? '\x1b[7m' : ' ';
176
- const suffix = isActive ? '\x1b[0m' : '';
177
- const name = item.name || String(item.value || item);
178
- const display = name.length > 70 ? name.slice(0, 67) + '...' : name;
179
- return ` ${prefix}${display}${suffix}`;
180
- },
181
- loop: false,
182
- });
183
-
184
- const helpText = loaded < totalCount && !searchMode
185
- ? '(scroll to load more, type to search, Esc to cancel)'
186
- : '(type to search, Esc to cancel)';
187
-
188
- return [
189
- `${fullMessage} Search: ${searchTerm}${status === 'loading' ? ' ...' : ''}`,
190
- `${page}\n\n${helpText}`,
191
- ];
192
- })(...args);
126
+ state.searchMode = true;
127
+ state.active = 0;
128
+ void load(state.term, undefined).then(() => api?.redraw());
129
+ api?.redraw();
130
+ },
131
+ render() {
132
+ const pages = Math.max(1, Math.ceil(state.choices.length / pageSize));
133
+ const current = Math.min(pages - 1, Math.floor(state.active / pageSize));
134
+ const start = current * pageSize;
135
+ const visible = state.choices.slice(start, start + pageSize);
136
+ const header = totalCount > 0 && !state.searchMode
137
+ ? `${message} (${state.loaded} of ${totalCount} loaded)`
138
+ : message;
139
+ const lines = [header ?? '', `Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
140
+ if (state.error) lines.push(` ${state.error}`);
141
+ else if (!state.choices.length) lines.push(state.status === 'loading' ? ' Loading...' : ' No matches');
142
+ lines.push(...pickerRows(visible, state.active - start));
143
+ lines.push(...pickerFooter({ more: canLoadMore() }));
144
+ return lines;
145
+ },
146
+ });
147
+
148
+ return prompt.then(value => {
149
+ // Mark the prompt so an in-flight source response cannot redraw or
150
+ // apply after the picker closed.
151
+ state.status = 'cancelled';
152
+ state.token += 1;
153
+ request?.abort();
154
+ return value;
155
+ }, error => {
156
+ state.status = 'cancelled';
157
+ state.token += 1;
158
+ request?.abort();
159
+ throw error;
160
+ }).then(value => value);
193
161
  };
194
162
 
195
163
  export default paginatedSearch;
@@ -0,0 +1,20 @@
1
+ export const PICKER_HELP = '↑↓ navigate • ⏎ select • type to search • Esc cancel';
2
+
3
+ export function pickerRows(choices, active, { picked } = {}) {
4
+ const lines = [];
5
+ choices.forEach((choice, index) => {
6
+ if (choice.section && choice.section !== choices[index - 1]?.section) {
7
+ if (index) lines.push('');
8
+ lines.push(` ${choice.section}`);
9
+ }
10
+ if (choice.separator) { lines.push(` ${choice.name}`); return; }
11
+ const check = picked ? `[${picked.has(choice) ? 'x' : ' '}] ` : '';
12
+ lines.push(`${index === active ? '❯' : ' '} ${check}${choice.name}${choice.disabled ? ' (disabled)' : ''}`);
13
+ if (index === active && choice.description) lines.push(` ${choice.description}`);
14
+ });
15
+ return lines;
16
+ }
17
+
18
+ export function pickerFooter({ checkbox = false, more = false } = {}) {
19
+ return ['', `${PICKER_HELP}${checkbox ? ' • Space toggle' : ''}${more ? ' • ↓ load more' : ''}`];
20
+ }