@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.
- package/README.md +16 -1
- package/package.json +5 -6
- package/skills/servicenow/SKILL.md +9 -1
- package/src/app.js +4 -79
- package/src/bounded-reads.js +13 -0
- package/src/capabilities.js +8 -3
- package/src/cli-adapter.js +26 -3
- package/src/cli.js +13 -14
- package/src/command-families.js +68 -0
- package/src/commands/_generic.js +1 -0
- package/src/commands/_ticket.js +1 -1
- package/src/commands/actions.js +9 -4
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- package/src/commands/attachments.js +1 -1
- package/src/commands/auth.js +21 -2
- package/src/commands/codesearch.js +11 -2
- package/src/commands/compare.js +22 -0
- package/src/commands/customizations.js +3 -4
- package/src/commands/decisiontables.js +4 -0
- package/src/commands/docs/docs.js +5 -5
- package/src/commands/domains.js +1 -1
- package/src/commands/eval.js +11 -5
- package/src/commands/flows.js +24 -7
- package/src/commands/groupmembers.js +1 -1
- package/src/commands/grouproles.js +1 -1
- package/src/commands/groups.js +1 -1
- package/src/commands/midservers.js +4 -11
- package/src/commands/perf.js +2 -3
- package/src/commands/plugins.js +9 -0
- package/src/commands/records.js +12 -2
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +2 -2
- package/src/commands/setup.js +4 -34
- package/src/commands/skipped-updates.js +2 -3
- package/src/commands/store.js +4 -1
- package/src/commands/subscriptions.js +47 -0
- package/src/commands/tickets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/commands/workflows.js +3 -5
- package/src/config.js +1 -0
- package/src/context.js +8 -56
- package/src/docs-links.js +28 -0
- package/src/flow-create.js +9 -0
- package/src/help.js +4 -0
- package/src/helpers.js +17 -24
- package/src/instance-inventory.js +184 -0
- package/src/intended-context.js +68 -0
- package/src/mutation-context.js +69 -46
- package/src/output.js +1 -1
- package/src/paginated-search.js +146 -178
- package/src/picker-ui.js +20 -0
- package/src/prompt-engine.js +176 -0
- package/src/prompts.js +293 -43
- package/src/records/inspect.js +30 -16
- package/src/records-engine.js +2 -2
- package/src/schedule-cache.js +96 -0
- package/src/schedules/itom-2026-04-09.json +121 -0
- package/src/schedules/public-inventory.json +6224 -0
- package/src/sdk-batch.js +2 -1
- package/src/sdk.js +42 -16
- package/src/setup-preferences.js +2 -2
- package/src/subscriptions.js +176 -0
package/src/mutation-context.js
CHANGED
|
@@ -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 {
|
|
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
|
|
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
|
-
|
|
19
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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 (
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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 (
|
|
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
|
|
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 (
|
|
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;
|
package/src/paginated-search.js
CHANGED
|
@@ -1,195 +1,163 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Paginated
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
60
|
+
// A failed load-more keeps the rows already on screen.
|
|
75
61
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
137
|
-
|
|
89
|
+
if (key.name === 'up') {
|
|
90
|
+
if (state.active > 0) state.active -= 1;
|
|
91
|
+
api?.redraw();
|
|
138
92
|
return;
|
|
139
93
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
if (
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
-
|
|
163
|
-
|
|
164
|
-
if (
|
|
165
|
-
|
|
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
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
pageSize
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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;
|
package/src/picker-ui.js
ADDED
|
@@ -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
|
+
}
|