@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
package/src/config.js CHANGED
@@ -5,6 +5,13 @@ import path from 'node:path';
5
5
  import os from 'node:os';
6
6
 
7
7
  const APP_NAME = 'servicenow';
8
+ // Persistence provenance is private: project JSON cannot forge it.
9
+ const persistence = new WeakMap();
10
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11
+ const fields = ['instanceURL', 'defaultProfile', 'format', 'connectionDefaults', 'docs'];
12
+ function snapshot(cfg) {
13
+ return structuredClone(Object.fromEntries([...fields, 'profiles'].map(key => [key, cfg[key]])));
14
+ }
8
15
 
9
16
  export function globalConfigDir() {
10
17
  const xdg = process.env.XDG_CONFIG_HOME;
@@ -101,6 +108,13 @@ export function loadConfig(overrides = {}) {
101
108
  const cfg = createConfig();
102
109
 
103
110
  loadFromFile(cfg, globalConfigPath(), 'global');
111
+ const global = snapshot(cfg);
112
+ // Preserve provenance outside the serializable/user-controlled config shape.
113
+ // A project can select an origin, but cannot authorize ambient secrets for it.
114
+ Object.defineProperty(cfg, 'credentialTrust', { value: {
115
+ profiles: structuredClone(cfg.profiles),
116
+ origin: normalizeInstanceURL(getEffectiveInstance(cfg)),
117
+ } });
104
118
  loadFromFile(cfg, localConfigPath(), 'local');
105
119
  loadFromEnv(cfg);
106
120
 
@@ -120,37 +134,98 @@ export function loadConfig(overrides = {}) {
120
134
  }
121
135
  }
122
136
 
137
+ persistence.set(cfg, { global, effective: snapshot(cfg) });
123
138
  return cfg;
124
139
  }
125
140
 
126
- export function saveConfig(cfg) {
141
+ export function isTrustedCredentialDestination(cfg, instance, explicitInstance = '', explicitProfile = '') {
142
+ const origin = normalizeInstanceURL(instance);
143
+ // Hand-built configs are a programmatic API, not project-file input.
144
+ if (!cfg?.credentialTrust) return true;
145
+ const selectedProfile = explicitProfile && Object.hasOwn(cfg.credentialTrust.profiles, explicitProfile)
146
+ ? cfg.credentialTrust.profiles[explicitProfile]?.instance_url : '';
147
+ // Bind ambient secrets to the global default, not every saved account.
148
+ // Only explicit process selectors may opt into another saved origin.
149
+ const binding = explicitInstance || selectedProfile || process.env.SERVICENOW_INSTANCE_URL || cfg.credentialTrust.origin;
150
+ return Boolean(binding) && normalizeInstanceURL(binding) === origin;
151
+ }
152
+
153
+ export function saveConfig(cfg, { approvedProfile = '', approveDefault = false } = {}) {
154
+ const state = persistence.get(cfg);
155
+ const next = state ? structuredClone(state.global) : snapshot(cfg);
156
+ const changedProfiles = new Set();
157
+ const changedFields = new Set();
158
+ const refuse = () => {
159
+ const error = new Error('Project configuration cannot be promoted to global trust. Edit the global profile outside this project, or explicitly approve the destination with auth login <URL>.');
160
+ error.code = 'usage_error';
161
+ throw error;
162
+ };
163
+ if (state) {
164
+ for (const name of new Set([...Object.keys(state.effective.profiles), ...Object.keys(cfg.profiles)])) {
165
+ if (name !== approvedProfile && same(cfg.profiles[name], state.effective.profiles[name])) continue;
166
+ // A changed project-derived profile must not be copied wholesale, even
167
+ // when the user only changed an innocuous preference on that profile.
168
+ if (name !== approvedProfile && cfg.profiles[name] !== undefined
169
+ && !same(state.effective.profiles[name], state.global.profiles[name])) refuse();
170
+ if (cfg.profiles[name] === undefined) delete next.profiles[name];
171
+ else next.profiles[name] = structuredClone(cfg.profiles[name]);
172
+ changedProfiles.add(name);
173
+ }
174
+ for (const key of fields) {
175
+ if (same(cfg[key], state.effective[key]) && !(approveDefault && ['instanceURL', 'defaultProfile'].includes(key))) continue;
176
+ // Removing a locally selected profile must not clear an unrelated global
177
+ // default. The caller explicitly removed that profile, not this one.
178
+ if (key === 'defaultProfile' && !cfg[key] && !approveDefault
179
+ && state.effective.defaultProfile !== state.global.defaultProfile) {
180
+ changedFields.add(key);
181
+ continue;
182
+ }
183
+ if (key === 'instanceURL' && !approveDefault && cfg[key]) {
184
+ // Switching is selection, not authorization of a project origin.
185
+ const name = cfg.defaultProfile;
186
+ if (name && (!same(cfg.profiles[name], next.profiles[name]) || !next.profiles[name])) refuse();
187
+ }
188
+ if (key === 'defaultProfile' && cfg[key] && !approveDefault
189
+ && (!next.profiles[cfg[key]] || !same(cfg.profiles[cfg[key]], next.profiles[cfg[key]]))) refuse();
190
+ next[key] = structuredClone(cfg[key]);
191
+ changedFields.add(key);
192
+ }
193
+ }
127
194
  const dir = globalConfigDir();
128
195
  fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
129
196
  const payload = {
130
- connection_defaults: cfg.connectionDefaults || undefined,
131
- docs: cfg.docs || undefined,
132
- instance_url: cfg.instanceURL || undefined,
133
- profiles: Object.keys(cfg.profiles).length > 0 ? cfg.profiles : undefined,
134
- default_profile: cfg.defaultProfile || undefined,
135
- format: cfg.format || undefined,
197
+ connection_defaults: next.connectionDefaults || undefined,
198
+ docs: next.docs || undefined,
199
+ instance_url: next.instanceURL || undefined,
200
+ profiles: Object.keys(next.profiles).length > 0 ? next.profiles : undefined,
201
+ default_profile: next.defaultProfile || undefined,
202
+ format: next.format || undefined,
136
203
  };
137
204
  fs.writeFileSync(globalConfigPath(), JSON.stringify(payload, null, 2), { mode: 0o600 });
138
205
 
139
- // Sync managed fields to local config if it exists, so profile operations
140
- // (use, remove, create, auth login) aren't silently reverted on next load.
141
- if (fs.existsSync(localConfigPath())) {
206
+ // Synchronize only authored changes. Never replace the project's entire
207
+ // profile map with the effective (or global) map.
208
+ if (state && fs.existsSync(localConfigPath())) {
142
209
  try {
143
- const localData = JSON.parse(fs.readFileSync(localConfigPath(), 'utf-8'));
144
- const merged = { ...localData };
145
- if (payload.profiles !== undefined) merged.profiles = payload.profiles;
146
- if (payload.default_profile !== undefined) merged.default_profile = payload.default_profile;
147
- if (payload.instance_url !== undefined) merged.instance_url = payload.instance_url;
148
- if (payload.format !== undefined) merged.format = payload.format;
149
- fs.writeFileSync(localConfigPath(), JSON.stringify(merged, null, 2), { mode: 0o600 });
210
+ const local = JSON.parse(fs.readFileSync(localConfigPath(), 'utf-8'));
211
+ for (const name of changedProfiles) {
212
+ local.profiles ||= {};
213
+ if (next.profiles[name] === undefined) delete local.profiles[name];
214
+ else local.profiles[name] = next.profiles[name];
215
+ }
216
+ const keys = { instanceURL: 'instance_url', defaultProfile: 'default_profile', format: 'format' };
217
+ for (const key of changedFields) if (keys[key]) {
218
+ if (next[key]) local[keys[key]] = next[key];
219
+ else delete local[keys[key]];
220
+ }
221
+ if (changedProfiles.size || [...changedFields].some(key => keys[key])) {
222
+ fs.writeFileSync(localConfigPath(), JSON.stringify(local, null, 2), { mode: 0o600 });
223
+ }
150
224
  } catch {
151
- // Local config unreadable — skip sync, global save already succeeded
225
+ // Local config unreadable — skip sync, global save already succeeded.
152
226
  }
153
227
  }
228
+ if (state) persistence.set(cfg, { global: next, effective: snapshot(cfg) });
154
229
  }
155
230
 
156
231
  export function saveLocalConfig(cfg) {
@@ -0,0 +1,28 @@
1
+ // GENERATED FILENAME: keep in sync with site/config/docs-links.json.
2
+ // The npm package ships only cli/, so this projection is checked in and verified
3
+ // by site/test/docs_links_test.rb. Edit the registry, then regenerate this file.
4
+ export const SITE_ORIGIN = 'https://jsn.jace.pro';
5
+ export const ROOT_DOC_LINK = '/docs/';
6
+ export const DOC_LINKS = Object.freeze({
7
+ codesearch: '/features/servicenow-code-search-cli/',
8
+ docs: '/docs/cli-guide/#jsn-cli-guide',
9
+ flows: '/docs/flows/#flow-definition-search',
10
+ records: '/docs/records/#watching-a-servicenow-record',
11
+ updatesets: '/docs/updatesets/#transfer-an-update-set',
12
+ midservers: '/docs/midservers/#remote-mid-management-over-ssh',
13
+ setup: '/docs/setup/#connect-an-instance',
14
+ auth: '/docs/setup/#authentication-lifecycle-review',
15
+ skill: '/docs/agents/#use-jsn-with-ai-agents',
16
+ });
17
+
18
+ /** Absolute documentation URL for one registered command family, or null when
19
+ * the family has no migrated guide. Callers decide how to render a miss. */
20
+ export function resolveDocLink(name) {
21
+ const path = DOC_LINKS[name];
22
+ return path ? `${SITE_ORIGIN}${path}` : null;
23
+ }
24
+
25
+ /** Absolute documentation URL for one registered command family. */
26
+ export function docLink(name) {
27
+ return resolveDocLink(name) || `${SITE_ORIGIN}${ROOT_DOC_LINK}`;
28
+ }
package/src/help.js CHANGED
@@ -10,6 +10,8 @@
10
10
  // (`approvals`, `cmdb`, `docs`, `perf`, `platform`, … were missing from the
11
11
  // hand-written list while being fully registered).
12
12
 
13
+ import { SITE_ORIGIN, ROOT_DOC_LINK } from './docs-links.js';
14
+
13
15
  const COMMON_COMMANDS = [
14
16
  'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
15
17
  ];
@@ -23,6 +25,7 @@ const CONCISE_EXAMPLES = [
23
25
  ];
24
26
 
25
27
  const CONCISE_MORE = [
28
+ { label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: install, setup, safety, output, agents and feature references' },
26
29
  { label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
27
30
  { label: 'jsn discover <word>', description: 'Find commands by task words' },
28
31
  { label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
@@ -289,6 +292,7 @@ TIPS
289
292
  "jsn --json" prints the registered command surface as JSON for scripts and agents
290
293
 
291
294
  LEARN MORE
295
+ Documentation and feature references: https://jsn.jace.pro/docs/
292
296
  Some list commands offer a picker in an interactive terminal with automatic output.
293
297
  Arrow keys browse (10 visible items); type to search; scroll to load more; Enter selects; Esc cancels.
294
298
  Picker eligibility and search fields vary by command. Explicit output formats (including --json) skip pickers.
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { execFileSync } from 'node:child_process';
6
+ import { assertCredentialDestination } from './auth/transport.js';
6
7
 
7
8
  const INSTALL_HOST = 'install.service-now.com';
8
9
 
@@ -41,9 +42,11 @@ export function buildMidRecipeUrl(releaseName) {
41
42
  export async function validateMidCredentials(instanceURL, username, password, fetchImpl = fetch) {
42
43
  if (!username || !password) throw new Error('MID Server username and password are required');
43
44
  const endpoint = `${String(instanceURL).replace(/\/$/, '')}/api/now/table/sys_properties?sysparm_query=name=mid.version&sysparm_fields=value&sysparm_limit=1`;
45
+ assertCredentialDestination(endpoint, instanceURL);
44
46
  let response;
45
47
  try {
46
48
  response = await fetchImpl(endpoint, {
49
+ redirect: 'error',
47
50
  headers: {
48
51
  Accept: 'application/json',
49
52
  Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
@@ -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.
3
9
  */
4
10
 
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);
11
+ import { runPrompt, normalizeChoices, truncate, escapeResult } from './prompt-engine.js';
12
+
13
+ export const paginatedSearch = async (config = {}, context = {}) => {
14
+ const { message, pageSize = 10, totalCount = 0, source } = config;
15
+ let request;
16
+ const state = {
17
+ status: 'loading',
18
+ term: '',
19
+ choices: [],
20
+ active: 0,
21
+ loaded: 0,
22
+ searchMode: false,
23
+ token: 0,
24
+ error: '',
25
+ };
26
+
27
+ // Every request gets a token. A response may only be applied while its
28
+ // token is still current, so a stale (slower) search can never replace
29
+ // newer results or be selected by a later Enter.
30
+ const isCurrent = token => token === state.token && state.status !== 'cancelled';
31
+
32
+ async function load(term, offset, { append = false } = {}) {
33
+ request?.abort();
34
+ request = new AbortController();
35
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
36
+ const token = ++state.token;
37
+ state.status = 'loading';
38
+ state.error = '';
39
+ try {
40
+ const items = normalizeChoices(await source(term || undefined, offset, { signal }) || []);
41
+ if (!isCurrent(token)) return;
42
+ state.choices = append ? state.choices.concat(items) : items;
43
+ state.loaded = state.choices.length;
44
+ state.active = Math.min(state.active, Math.max(0, state.choices.length - 1));
45
+ state.status = 'done';
46
+ } catch (error) {
47
+ if (!isCurrent(token)) return;
48
+ state.status = 'done';
49
+ state.error = error?.message || String(error);
50
+ if (!append) {
51
+ state.choices = [];
52
+ state.loaded = 0;
73
53
  }
74
- setStatus('done');
54
+ // A failed load-more keeps the rows already on screen.
75
55
  }
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
- }
56
+ }
57
+
58
+ let api;
59
+ const prompt = runPrompt({ ...config, message }, context, {
60
+ escapeValue: escapeResult(undefined),
61
+ init() {
62
+ // Kick off the first page. Enter is ignored while status is 'loading',
63
+ // so nothing is selectable until this resolves.
64
+ state.pending = load('', 0);
65
+ return state;
66
+ },
67
+ onReady(handle) {
68
+ api = handle;
69
+ state.pending.then(() => {
70
+ if (state.status !== 'cancelled') api.redraw();
120
71
  });
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;
134
- }
135
-
136
- if (key.name === 'escape') {
137
- done(undefined);
138
- return;
72
+ },
73
+ key(_state, key, handle) {
74
+ api = handle;
75
+ if (key.name === 'return' || key.name === 'enter') {
76
+ // No selecting a row while a request is in flight: the list on
77
+ // screen may be about to change.
78
+ if (state.status === 'loading' || !state.choices.length) return;
79
+ const choice = state.choices[state.active];
80
+ if (!choice) return;
81
+ return { done: choice };
139
82
  }
140
-
141
- if (isUpKey(key)) {
142
- if (activeRef.current > 0) {
143
- activeRef.current--;
144
- setActive(activeRef.current);
145
- }
83
+ if (key.name === 'up') {
84
+ if (state.active > 0) state.active -= 1;
85
+ api?.redraw();
146
86
  return;
147
87
  }
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);
88
+ if (key.name === 'down') {
89
+ if (state.status === 'loading') return;
90
+ if (state.active < state.choices.length - 1) {
91
+ state.active += 1;
92
+ api?.redraw();
93
+ } else if (!state.searchMode && state.loaded < totalCount) {
94
+ const before = state.loaded;
95
+ const pending = load('', state.loaded, { append: true });
96
+ const token = state.token;
97
+ void pending.then(() => {
98
+ if (!isCurrent(token)) return;
99
+ if (state.status === 'done' && state.loaded > before) state.active = before;
100
+ api?.redraw();
157
101
  });
102
+ api?.redraw();
158
103
  }
159
104
  return;
160
105
  }
161
-
162
- // Use readline's built-in line buffer for text input
163
- const newTerm = rl.line;
164
- if (newTerm !== searchTerm) {
165
- setSearchTerm(newTerm);
106
+ const previous = state.term;
107
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
108
+ else if (key.name === 'space') state.term += ' ';
109
+ else if (key.text) state.term += key.text;
110
+ else return;
111
+ if (state.term === previous) return;
112
+
113
+ if (!state.term) {
114
+ state.searchMode = false;
115
+ state.active = 0;
116
+ void load('', 0).then(() => api?.redraw());
117
+ api?.redraw();
118
+ return;
166
119
  }
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);
120
+ state.searchMode = true;
121
+ state.active = 0;
122
+ void load(state.term, undefined).then(() => api?.redraw());
123
+ api?.redraw();
124
+ },
125
+ render() {
126
+ const pages = Math.max(1, Math.ceil(state.choices.length / pageSize));
127
+ const current = Math.min(pages - 1, Math.floor(state.active / pageSize));
128
+ const start = current * pageSize;
129
+ const visible = state.choices.slice(start, start + pageSize);
130
+ const header = totalCount > 0 && !state.searchMode
131
+ ? `${message} (${state.loaded} of ${totalCount} loaded)`
132
+ : message;
133
+ const lines = [`${header} Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
134
+ if (state.error) lines.push(` ${state.error}`);
135
+ else if (!state.choices.length) lines.push(state.status === 'loading' ? ' Loading...' : ' No matches');
136
+ visible.forEach((choice, index) => {
137
+ const absolute = start + index;
138
+ lines.push(`${absolute === state.active ? '>' : ' '} ${truncate(choice.name)}`);
139
+ });
140
+ const help = state.loaded < totalCount && !state.searchMode
141
+ ? '(scroll to load more, type to search, Esc to cancel)'
142
+ : '(type to search, Esc to cancel)';
143
+ lines.push('', help);
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;
package/src/perf.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
- import Database from 'better-sqlite3';
5
+ import Database from './sqlite.js';
6
6
  import { getVersion } from './commands/version.js';
7
7
  import { capturePerformance } from './perf-capture.js';
8
8