@jacebenson/jsn 5.5.7-dev.213.1 → 5.5.7-dev.215.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.7-dev.213.1",
3
+ "version": "5.5.7-dev.215.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -79,6 +79,8 @@ import { b4rulesCmd } from './commands/b4rules.js';
79
79
  import { atfCmd } from './commands/atf.js';
80
80
  import { scanCmd } from './commands/scan.js';
81
81
  import { storeCmd } from './commands/store.js';
82
+ import { pluginsCmd } from './commands/plugins.js';
83
+ import { compareCmd } from './commands/compare.js';
82
84
  import { subscriptionsCmd } from './commands/subscriptions.js';
83
85
  import { approvalsCmd } from './commands/approvals.js';
84
86
  import { perfCmd } from './commands/perf.js';
@@ -445,6 +447,8 @@ export function buildCLI() {
445
447
  .command(atfCmd(wrap))
446
448
  .command(scanCmd(wrap))
447
449
  .command(storeCmd(wrap))
450
+ .command(pluginsCmd(wrap))
451
+ .command(compareCmd(wrap))
448
452
  .command(subscriptionsCmd(wrap))
449
453
  .command(approvalsCmd(wrap))
450
454
  .command(skippedUpdatesCmd(wrap))
@@ -0,0 +1,22 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { inventoryCompareCommand, compareInstanceInventory } from '../instance-inventory.js';
3
+
4
+ declareCapabilities('compare', { skipContextHeader: true });
5
+ export const compareCmd = wrap => ({
6
+ ...inventoryCompareCommand(wrap, 'plugins'),
7
+ command: 'compare',
8
+ describe: 'Compare plugins AND Store apps; report how to align --target to desired --source (read-only)',
9
+ handler: wrap(async (argv, app) => {
10
+ const plugins = await compareInstanceInventory(argv, app, 'plugins', false);
11
+ const store = await compareInstanceInventory(argv, app, 'store', false);
12
+ const data = {
13
+ source: plugins.source, target: plugins.target, complete: plugins.complete && store.complete,
14
+ inventories: { plugins, store },
15
+ counts: Object.fromEntries(Object.keys(plugins.counts).map(key => [key, plugins.counts[key] + store.counts[key]])),
16
+ caveat: 'Distinct plugin and Store inventories can overlap. Counts are unique within each inventory, not a deduplicated product count. Recommendations are review guidance, never executable remediation.',
17
+ };
18
+ Object.defineProperty(data, '_formatted', { value: `${plugins._formatted}\n\n${store._formatted}\n\n${data.caveat}`, enumerable: false });
19
+ app.ok(data, { summary: 'Align target to source: plugins and Store applications' });
20
+ if (!data.complete) process.exitCode = 1;
21
+ }),
22
+ });
@@ -302,12 +302,7 @@ async function promptMidCredentials(app, argv) {
302
302
  const validation = await validateMidCredentials(app.getEffectiveInstance(), username, password);
303
303
  return { username, password, releaseName: validation.releaseName };
304
304
  } catch (error) {
305
- const answer = await input({ message: `${error.message}. Press Enter to retry or Q to quit:` });
306
- if (answer.trim().toLowerCase() === 'q') {
307
- const quit = new Error('MID Server installation cancelled');
308
- quit.code = 'cancelled';
309
- throw quit;
310
- }
305
+ await input({ message: `${error.message}. Press Enter to retry or Esc to cancel:` });
311
306
  username = argv.username || '';
312
307
  }
313
308
  }
@@ -0,0 +1,9 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { inventoryCompareCommand } from '../instance-inventory.js';
3
+
4
+ declareCapabilities('plugins', { skipContextHeader: true });
5
+ export const pluginsCmd = wrap => ({
6
+ command: 'plugins', describe: 'Inspect platform plugin differences across instances',
7
+ builder: p => p.command(inventoryCompareCommand(wrap, 'plugins')),
8
+ handler: wrap(async (_argv, app) => app.ok({ commands: ['compare'] }, { summary: 'Use jsn compare --source pdi --target vendor for both inventories; jsn plugins compare --source pdi --target vendor for plugins only' })),
9
+ });
@@ -41,37 +41,10 @@ const setupHelp = () => [
41
41
  'Configure settings directly: jsn setup --configure-defaults or jsn setup --configure-docs.',
42
42
  ].join('\n');
43
43
 
44
- /** The setup hub prompt; q and Escape resolve with no selected action. */
44
+ /** The setup hub shares searchable local menus; Escape leaves the hub. */
45
45
  export const authHubPrompt = async (config = {}, context = {}) => {
46
- const { runPrompt, escapeResult } = await import('../prompt-engine.js');
47
- const choices = config.choices || [];
48
- const state = { active: 0 };
49
- return runPrompt(config, context, {
50
- escapeValue: escapeResult(undefined),
51
- init: () => state,
52
- key(_state, key, api) {
53
- if (key.name === 'q') return { done: undefined };
54
- if (key.name === 'return' || key.name === 'enter') {
55
- const choice = choices[state.active];
56
- if (choice) return { done: choice.value };
57
- return;
58
- }
59
- if (key.name === 'up' && state.active > 0) { state.active -= 1; api.redraw(); return; }
60
- if (key.name === 'down' && state.active < choices.length - 1) { state.active += 1; api.redraw(); }
61
- },
62
- render() {
63
- // Section headings are rendered inline; the pagination budget the
64
- // Inquirer version needed no longer applies to a local renderer.
65
- const lines = [config.message];
66
- choices.forEach((choice, index) => {
67
- const heading = choices[index - 1]?.section !== choice.section ? `${index ? '\n' : ''} ${choice.section}` : null;
68
- if (heading) lines.push(heading);
69
- lines.push(`${index === state.active ? '❯' : ' '} ${choice.name}`);
70
- });
71
- lines.push('', '↑↓ navigate • ⏎ select • q/Esc exit');
72
- return lines;
73
- },
74
- });
46
+ const { select, escapeResult } = await import('../prompts.js');
47
+ return select({ ...config, escapeValue: escapeResult(undefined) }, context);
75
48
  };
76
49
 
77
50
  /** Interactive hub: what do you want to do? Returns an action or undefined on exit. */
@@ -1,3 +1,4 @@
1
+ import { inventoryCompareCommand } from '../instance-inventory.js';
1
2
  import { confirmDelete, quoteShellArg, truncateString } from '../helpers.js';
2
3
  import { declareCapabilities } from '../capabilities.js';
3
4
  import { AppError, errUsage } from '../errors.js';
@@ -16,6 +17,7 @@ import {
16
17
  // App Client, which writes installed-application state rather than capturing
17
18
  // metadata into the selected application/update set.
18
19
  declareCapabilities('store', {
20
+ skipContextHeaderSubcommands: ['compare'],
19
21
  mutationSubcommands: ['install', 'update'],
20
22
  mutationContextExemptSubcommands: ['install', 'update'],
21
23
  });
@@ -229,6 +231,7 @@ export function storeCmd(wrap) {
229
231
  command: 'store [subcommand]',
230
232
  describe: 'Discover ServiceNow Store applications, inspect versions and entitlement, and request explicit installs/updates',
231
233
  builder: y => y
234
+ .command(inventoryCompareCommand(wrap, 'store'))
232
235
  .command({
233
236
  command: 'list',
234
237
  describe: 'List Store applications for a tab (read-only)',
@@ -302,7 +305,7 @@ export function storeCmd(wrap) {
302
305
  handler: wrap(async (argv, app) => runLifecycle(argv, app, 'update')),
303
306
  }),
304
307
  handler: wrap(async (argv, app) => {
305
- report(app, argv, { commands: ['search', 'list', 'show', 'status', 'install', 'update'] }, {
308
+ report(app, argv, { commands: ['compare', 'search', 'list', 'show', 'status', 'install', 'update'] }, {
306
309
  summary: 'ServiceNow Store applications',
307
310
  breadcrumbs: [hint('list', 'jsn store list --tab installed', 'List installed applications'),
308
311
  hint('search', 'jsn store search "<term>"', 'Search applications available to this instance'),
package/src/helpers.js CHANGED
@@ -448,31 +448,24 @@ export async function interactiveList({ app, table, singular, columns, limit = 5
448
448
 
449
449
  // Paginated source adapter: (term, offset, { signal }) => choices[]
450
450
  async function serverSource(term, offset, { signal: _signal } = {}) {
451
- try {
452
- const params = new URLSearchParams();
453
- params.set('sysparm_limit', String(limit));
454
- params.set('sysparm_display_value', 'all');
455
- if (pickerFields) params.set('sysparm_fields', pickerFields);
456
- if (term) {
457
- params.set('sysparm_query', `${baseQuery}${labelField}LIKE${term}^ORDERBYDESCsys_updated_on`);
458
- } else {
459
- params.set('sysparm_query', baseQuery + 'ORDERBYDESCsys_updated_on');
460
- params.set('sysparm_offset', String(offset));
461
- }
462
- const records = await app.sdk.list(table, params);
463
- if (!Array.isArray(records)) {
464
- console.error('SDK non-array:', typeof records);
465
- return [];
466
- }
467
- return records.map(r => ({
468
- name: formatLabel ? formatLabel(r) : (getStringField(r, labelField) || getStringField(r, 'sys_id')),
469
- value: formatValue ? formatValue(r) : r,
470
- }));
471
- } catch (err) {
472
- if (isTerminalAuthError(err)) throw err;
473
- console.error('serverSource error:', err.message || err);
474
- return [];
451
+ const params = new URLSearchParams();
452
+ params.set('sysparm_limit', String(limit));
453
+ params.set('sysparm_display_value', 'all');
454
+ if (pickerFields) params.set('sysparm_fields', pickerFields);
455
+ if (term) {
456
+ params.set('sysparm_query', `${baseQuery}${labelField}LIKE${term}^ORDERBYDESCsys_updated_on`);
457
+ } else {
458
+ params.set('sysparm_query', baseQuery + 'ORDERBYDESCsys_updated_on');
459
+ params.set('sysparm_offset', String(offset));
475
460
  }
461
+ // Only a successful empty page means exhausted. Let the picker render
462
+ // failures and retry this offset; preserve terminal auth errors unchanged.
463
+ const records = await app.sdk.list(table, params);
464
+ if (!Array.isArray(records)) throw new Error(`Could not list ${table}: list returned a non-array result`);
465
+ return records.map(r => ({
466
+ name: formatLabel ? formatLabel(r) : (getStringField(r, labelField) || getStringField(r, 'sys_id')),
467
+ value: formatValue ? formatValue(r) : r,
468
+ }));
476
469
  }
477
470
 
478
471
  const selected = await prompt({
@@ -0,0 +1,184 @@
1
+ import { resolveSession } from './session.js';
2
+ import { errUsage } from './errors.js';
3
+ import { listApplications } from './store.js';
4
+
5
+ export async function readObservedStoreApps(sdk, maxPages, tableFailure) {
6
+ const items = new Map(), localIds = new Set();
7
+ const coverage = { table: 'sn_appclient/appmanager/apps', tab: 'installed', status: 'unknown', fetched: 0, total: null, reason: 'no_provider_total', table_failure: tableFailure, observed_items_usable: true, exhaustion: 'not_reached' };
8
+ try {
9
+ for (let page = 0; page < maxPages; page++) {
10
+ // Reuse the production Store discovery transport. Its page_full is a
11
+ // client heuristic, NOT provider has_more or an exhaustiveness guarantee.
12
+ const result = await listApplications(sdk, { tab: 'installed', limit: 200, offset: coverage.fetched });
13
+ if (!result.apps.length) { coverage.exhaustion = 'empty_page_observed'; return { items, coverage }; }
14
+ if (result.apps.length > 200) throw Object.assign(new Error(), { code: 'invalid_page_size' });
15
+ for (const row of result.apps) {
16
+ if (!row.scope?.trim() || !row.sys_id?.trim() || !row.name?.trim() || !row.version?.trim()) throw Object.assign(new Error(), { code: 'missing_fields' });
17
+ if (items.has(row.scope) || localIds.has(row.sys_id)) throw Object.assign(new Error(), { code: 'duplicate_or_invalid_identity' });
18
+ localIds.add(row.sys_id);
19
+ items.set(row.scope, { id: row.scope, name: row.name, version: row.version, available_version: row.latest_version, active: null, installed: true, installation_evidence: 'appclient_installed_tab', observation_verified: true });
20
+ coverage.fetched++;
21
+ }
22
+ }
23
+ coverage.reason = 'page_limit_no_provider_total';
24
+ } catch (error) {
25
+ coverage.reason = error.status === 403 ? 'forbidden' : error.code || 'unreadable_source';
26
+ coverage.observed_items_usable = false;
27
+ }
28
+ return { items, coverage };
29
+ }
30
+
31
+
32
+ // Separate inventories: a Store application may also expose platform plugins.
33
+ // Neither inventory is a substitute for the other; custom sys_app rows are excluded.
34
+ export const inventorySources = {
35
+ plugins: { table: 'v_plugin', key: 'id', fields: ['sys_id', 'id', 'name', 'version', 'active'] },
36
+ store: { table: 'sys_store_app', key: 'scope', fields: ['sys_id', 'scope', 'name', 'version', 'active', 'install_date'] },
37
+ };
38
+ const text = value => {
39
+ const raw = value && typeof value === 'object' ? value.value : value;
40
+ return typeof raw === 'string' ? raw : typeof raw === 'boolean' ? String(raw) : null;
41
+ };
42
+
43
+ export async function readInventory(sdk, kind, maxPages = 30) {
44
+ const source = inventorySources[kind];
45
+ if (!source) throw errUsage('Unknown inventory kind');
46
+ if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100) throw errUsage('--max-pages must be an integer from 1 to 100');
47
+ const coverage = { table: source.table, status: 'unknown', fetched: 0, total: null, reason: null };
48
+ const items = new Map();
49
+ const seen = new Set();
50
+ const countParams = new URLSearchParams({ sysparm_count: 'true' });
51
+ const count = async () => {
52
+ const response = await sdk.request(`${sdk.baseURL}/api/now/stats/${source.table}?${countParams}`, { method: 'GET', ...(kind === 'store' ? { stateful: true } : {}) });
53
+ const value = response?.result?.stats?.count;
54
+ if (value == null || !/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw Object.assign(new Error(), { code: 'unreadable_count' });
55
+ return Number(value);
56
+ };
57
+ try {
58
+ coverage.total = await count();
59
+ for (let page = 0; coverage.fetched < coverage.total && page < maxPages; page++) {
60
+ const rows = await sdk.listStrict(source.table, {
61
+ sysparm_fields: [...source.fields, ...(kind === 'store' ? ['latest_version'] : [])].join(','), sysparm_query: 'ORDERBYsys_id',
62
+ sysparm_display_value: 'false', sysparm_exclude_reference_link: 'true',
63
+ sysparm_limit: 200, sysparm_offset: coverage.fetched,
64
+ }, kind === 'store' ? { stateful: true } : {});
65
+ if (!Array.isArray(rows) || !rows.length || rows.length > 200) throw Object.assign(new Error(), { code: 'unstable_pagination' });
66
+ for (const row of rows) {
67
+ if (!row || source.fields.some(field => !Object.hasOwn(row, field) || text(row[field]) === null)) throw Object.assign(new Error(), { code: 'missing_fields' });
68
+ const key = text(row[source.key]);
69
+ const id = text(row.sys_id);
70
+ if (!key?.trim() || !id?.trim() || seen.has(id) || items.has(key)) throw Object.assign(new Error(), { code: 'duplicate_or_invalid_identity' });
71
+ seen.add(id);
72
+ const active = text(row.active);
73
+ const allowed = kind === 'plugins' ? ['active', 'inactive'] : ['true', 'false'];
74
+ if (!allowed.includes(active)) throw Object.assign(new Error(), { code: 'unknown_state' });
75
+ items.set(key, { id: key, name: text(row.name), version: text(row.version) || null, active: kind === 'plugins' ? active === 'active' : active === 'true', ...(kind === 'store' ? { installed: text(row.version) && text(row.install_date) ? true : null, installation_evidence: text(row.version) && text(row.install_date) ? 'local_version_and_install_date' : 'unknown', available_version: text(row.latest_version) || null } : {}) });
76
+ coverage.fetched++;
77
+ }
78
+ }
79
+ if (coverage.fetched !== coverage.total) throw Object.assign(new Error(), { code: 'page_limit_or_count_mismatch' });
80
+ if (await count() !== coverage.total) throw Object.assign(new Error(), { code: 'count_changed' });
81
+ coverage.status = 'complete';
82
+ } catch (error) {
83
+ // Never include provider text, hostnames or credentials in a comparison report.
84
+ coverage.reason = error.status === 403 ? 'forbidden' : error.status === 401 ? 'auth_error' : error.code || 'unreadable_source';
85
+ }
86
+ if (kind === 'store' && coverage.reason === 'forbidden') return readObservedStoreApps(sdk, maxPages, coverage.reason);
87
+ return { items, coverage };
88
+ }
89
+
90
+ export function recommendAlignment(before, after, reliable, kind) {
91
+ if (!reliable) return [{ action: 'investigate_access', message: 'Investigate source/target access and incomplete coverage before planning changes.' }];
92
+ if (!before) return [{ action: 'review_target_only', message: 'Review or retain target-only item; no automatic removal recommended.' }];
93
+ if (!after) {
94
+ if (kind === 'store' && before.installed === true) return [{ action: 'install', message: `Install Store application on target at source installed version ${before.version}; verify entitlement and compatibility first.` }];
95
+ if (kind === 'plugins' && before.active === true) return [{ action: 'activate', message: `Locate and activate plugin on target to match source; verify availability and dependencies first (source version ${before.version ?? 'unknown'}).` }];
96
+ return [{ action: 'review_presence', message: 'Review source-only item and its installation/activation evidence before planning changes.' }];
97
+ }
98
+ if (kind === 'store' && (before.installed == null || after.installed == null)) return [{ action: 'investigate_installation', message: `Investigate installation evidence before alignment (source local version ${before.version ?? 'unknown'}; target local version ${after.version ?? 'unknown'}). An empty version or install date does not prove not installed.` }];
99
+ const actions = [];
100
+ if (kind === 'store' && before.installed === true && after.installed === false) actions.push({ action: 'install', message: `Install Store application on target at source version ${before.version}; verify entitlement and compatibility first.` });
101
+ if (before.active === true && after.active === false) actions.push({ action: kind === 'plugins' ? 'activate' : 'review_activation', message: kind === 'plugins' ? 'Activate plugin on target to match active source; verify prerequisites first.' : 'Review application activation on target to match active source.' });
102
+ if (before.active === false && after.active === true) actions.push({ action: 'review_activation', message: 'Target is active while source is inactive; review impact rather than automatically deactivating.' });
103
+ if (before.version !== after.version) {
104
+ const parse = value => typeof value === 'string' && /^\d+(?:\.\d+)*$/.test(value) ? value.split('.').map(BigInt) : null;
105
+ const a = parse(before.version), b = parse(after.version);
106
+ let order = 0;
107
+ if (a && b) for (let i = 0; i < Math.max(a.length, b.length); i++) { if ((b[i] ?? 0n) !== (a[i] ?? 0n)) { order = (b[i] ?? 0n) > (a[i] ?? 0n) ? 1 : -1; break; } }
108
+ const versions = `target ${after.version ?? 'unknown'}; source ${before.version ?? 'unknown'}`;
109
+ actions.push({ action: !a || !b || order >= 0 ? 'review_version' : 'align_version', message: !a || !b ? `Review version alignment (${versions}); provider version order is unknown, do not assume downgrade support.` : order > 0 ? `Review newer target version (${versions}); no downgrade recommended.` : order === 0 ? `Review equivalent numeric versions with different provider labels (${versions}).` : `Align target to source version after verifying supported upgrade availability (${versions}).` });
110
+ }
111
+ if (kind === 'store' && before.installed === false && after.installed === true) actions.push({ action: 'review_installation', message: 'Review or retain target installation; no automatic uninstall recommended.' });
112
+ if (!actions.length && (!before.version || !after.version)) actions.push({ action: 'investigate_version', message: 'Investigate missing installed-version evidence.' });
113
+ return actions.length ? actions : [{ action: 'none', message: kind === 'store' && (before.active == null || after.active == null) ? 'Observed installed versions match; no version action needed. Activation is unreported.' : 'No action needed; observed versions and states match.' }];
114
+ }
115
+
116
+ export function compareInventories(source, destination, kind = 'plugins') {
117
+ return [...new Set([...source.items.keys(), ...destination.items.keys()])].sort().map(id => {
118
+ const before = source.items.get(id) || null;
119
+ const after = destination.items.get(id) || null;
120
+ const inventoriesComplete = source.coverage.status === 'complete' && destination.coverage.status === 'complete';
121
+ const observedPair = kind === 'store' && before && after && (source.coverage.status === 'complete' || before.observation_verified === true && source.coverage.observed_items_usable) && (destination.coverage.status === 'complete' || after.observation_verified === true && destination.coverage.observed_items_usable);
122
+ const reliable = inventoriesComplete || observedPair;
123
+ let status = 'unknown';
124
+ const changes = [];
125
+ if (reliable) {
126
+ if (!before) status = 'target_only';
127
+ else if (!after) status = 'source_only';
128
+ else {
129
+ for (const field of ['version', 'active', 'installed']) {
130
+ if (field === 'active' && (before.active == null || after.active == null)) continue;
131
+ if (before[field] !== after[field]) changes.push(field);
132
+ }
133
+ status = kind === 'store' && (before.installed == null || after.installed == null) || before.version === null || after.version === null ? 'unknown' : changes.length ? 'different' : 'matching';
134
+ }
135
+ }
136
+ return { id, name: before?.name || after?.name || id, status, evidence: inventoriesComplete ? 'complete_inventory' : observedPair ? 'observed_pair' : 'incomplete_inventory', changes, before, after, recommendations: recommendAlignment(before, after, reliable, kind) };
137
+ });
138
+ }
139
+
140
+ export function formatInventoryComparison(data, verbose = false) {
141
+ const lines = [`${data.kind}: ${data.source} -> ${data.target} (align TARGET ${data.target} to SOURCE ${data.source})`, data.complete ? 'Complete visible inventories' : 'INCOMPLETE inventory: absences unknown; verified observed pairs can still be compared',
142
+ ...Object.entries(data.coverage).map(([side, c]) => `${side}: ${c.status}, ${c.fetched}/${c.total ?? '?'} rows${c.reason ? ` (${c.reason})` : ''}`),
143
+ `${data.records.length} identities; ${Object.entries(data.counts).map(([key, value]) => `${value} ${key}`).join(', ')}`,
144
+ 'ID | STATUS | SOURCE -> TARGET | WHAT TO DO ON TARGET'];
145
+ const value = item => item ? `${item.version ?? 'version unknown'}, ${item.active === null ? 'activation unknown' : item.active ? 'active' : 'inactive'}${Object.hasOwn(item, 'installed') ? `, ${item.installed == null ? 'installation unknown' : item.installed ? 'installed' : 'not installed'}, available ${item.available_version ?? 'unknown'}` : ''}` : 'not observed';
146
+ const differences = data.records.filter(row => row.status !== 'matching');
147
+ const shown = verbose ? differences : differences.slice(0, 50);
148
+ for (const row of shown) lines.push(`${row.name || row.id} [${row.id}] | ${row.status} | ${value(row.before)} -> ${value(row.after)} | ${row.recommendations.map(item => item.message).join(' ')}`);
149
+ if (shown.length < differences.length) lines.push(`${differences.length - shown.length} additional rows omitted; --verbose shows all differences.`);
150
+ lines.push('Matching rows need no action and are omitted; --json includes all rows. Read-only visible inventory, not entitlement or Store connectivity.');
151
+ return lines.join('\n');
152
+ }
153
+
154
+ export async function compareInstanceInventory(argv, app, kind, emit = true) {
155
+ const targetName = argv.target || argv.destination;
156
+ if (!argv.source || !targetName) throw errUsage('Provide --source and --target profile names');
157
+ const sdk = name => {
158
+ const s = resolveSession({ profile: name }, app.config);
159
+ if (s.unknownProfile || !s.profile || !s.instance) throw errUsage(`Unknown or unconfigured profile: ${name}`);
160
+ return app.getSDKForProfile(s.instance, { profileName: name, profile: s.profile, username: s.username, authMethod: s.profile.auth_method, domain: s.domain });
161
+ };
162
+ // Resolve both profiles before making any request. Sequential bounded reads.
163
+ const sourceSDK = sdk(argv.source), destinationSDK = sdk(targetName);
164
+ const source = await readInventory(sourceSDK, kind, argv.maxPages);
165
+ const destination = await readInventory(destinationSDK, kind, argv.maxPages);
166
+ const records = compareInventories(source, destination, kind);
167
+ const counts = Object.fromEntries(['matching', 'different', 'source_only', 'target_only', 'unknown'].map(status => [status, records.filter(row => row.status === status).length]));
168
+ const data = { kind, source: argv.source, target: targetName, complete: source.coverage.status === 'complete' && destination.coverage.status === 'complete', coverage: { source: source.coverage, target: destination.coverage }, counts, records };
169
+ Object.defineProperty(data, '_formatted', { value: formatInventoryComparison(data, argv.verbose), enumerable: false });
170
+ if (emit) {
171
+ app.ok(data, { summary: `${kind} comparison${data.complete ? '' : ' (incomplete)'}` });
172
+ if (!data.complete) process.exitCode = 1;
173
+ }
174
+ return data;
175
+ }
176
+
177
+ export const inventoryCompareCommand = (wrap, kind) => ({
178
+ command: 'compare', describe: `Compare ${kind === 'store' ? 'Store application' : 'plugin'} inventories across explicit profiles (read-only)`,
179
+ builder: p => p.option('source', { type: 'string', demandOption: true, describe: 'Source profile alias, desired baseline for --target' })
180
+ .option('target', { alias: 'destination', type: 'string', demandOption: true, describe: 'Target profile to align to the desired --source baseline' })
181
+ .option('max-pages', { type: 'number', default: 30, describe: 'Per-side page budget, 200 rows/page (1–100); limits remain incomplete' })
182
+ .epilogue('Align target to source without changing either instance:\njsn compare --source pdi --target vendor\njsn compare --source pdi --target vendor --json\njsn compare --source pdi --target vendor --get data.inventories.store.coverage\nIncomplete coverage exits 1 and recommends investigating access, not installing or removing. Numeric versions are ordered conservatively; newer target versions require review, never automatic downgrade.'),
183
+ handler: wrap((argv, app) => compareInstanceInventory(argv, app, kind)),
184
+ });
@@ -5,10 +5,12 @@
5
5
  * paginatedSearch({ message, pageSize, totalCount, source }, context?)
6
6
  * source(term, offset, { signal }) -> [{ name, value }]
7
7
  * Enter resolves the active choice object; Escape resolves undefined.
8
- * Down at the last loaded row loads more while loaded < totalCount.
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.
9
10
  */
10
11
 
11
- import { runPrompt, normalizeChoices, truncate, escapeResult } from './prompt-engine.js';
12
+ import { pickerRows, pickerFooter } from './picker-ui.js';
13
+ import { runPrompt, normalizeChoices, escapeResult } from './prompt-engine.js';
12
14
 
13
15
  export const paginatedSearch = async (config = {}, context = {}) => {
14
16
  const { message, pageSize = 10, totalCount = 0, source } = config;
@@ -24,6 +26,9 @@ export const paginatedSearch = async (config = {}, context = {}) => {
24
26
  error: '',
25
27
  };
26
28
 
29
+ const canLoadMore = () => !state.searchMode && !state.exhausted
30
+ && (totalCount == null || state.loaded < totalCount);
31
+
27
32
  // Every request gets a token. A response may only be applied while its
28
33
  // token is still current, so a stale (slower) search can never replace
29
34
  // newer results or be selected by a later Enter.
@@ -41,6 +46,7 @@ export const paginatedSearch = async (config = {}, context = {}) => {
41
46
  if (!isCurrent(token)) return;
42
47
  state.choices = append ? state.choices.concat(items) : items;
43
48
  state.loaded = state.choices.length;
49
+ state.exhausted = items.length === 0;
44
50
  state.active = Math.min(state.active, Math.max(0, state.choices.length - 1));
45
51
  state.status = 'done';
46
52
  } catch (error) {
@@ -77,7 +83,7 @@ export const paginatedSearch = async (config = {}, context = {}) => {
77
83
  // screen may be about to change.
78
84
  if (state.status === 'loading' || !state.choices.length) return;
79
85
  const choice = state.choices[state.active];
80
- if (!choice) return;
86
+ if (!choice || choice.disabled) return;
81
87
  return { done: choice };
82
88
  }
83
89
  if (key.name === 'up') {
@@ -90,7 +96,7 @@ export const paginatedSearch = async (config = {}, context = {}) => {
90
96
  if (state.active < state.choices.length - 1) {
91
97
  state.active += 1;
92
98
  api?.redraw();
93
- } else if (!state.searchMode && state.loaded < totalCount) {
99
+ } else if (canLoadMore()) {
94
100
  const before = state.loaded;
95
101
  const pending = load('', state.loaded, { append: true });
96
102
  const token = state.token;
@@ -130,17 +136,11 @@ export const paginatedSearch = async (config = {}, context = {}) => {
130
136
  const header = totalCount > 0 && !state.searchMode
131
137
  ? `${message} (${state.loaded} of ${totalCount} loaded)`
132
138
  : message;
133
- const lines = [`${header} Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
139
+ const lines = [header ?? '', `Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
134
140
  if (state.error) lines.push(` ${state.error}`);
135
141
  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);
142
+ lines.push(...pickerRows(visible, state.active - start));
143
+ lines.push(...pickerFooter({ more: canLoadMore() }));
144
144
  return lines;
145
145
  },
146
146
  });
@@ -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
+ }
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import readline from 'node:readline';
15
+ import { stripVTControlCharacters } from 'node:util';
15
16
 
16
17
  export class PromptCancelled extends Error {
17
18
  constructor() {
@@ -27,7 +28,10 @@ export function normalizeChoices(choices = []) {
27
28
  return {
28
29
  name: String(choice.name ?? choice.value ?? ''),
29
30
  value: 'value' in choice ? choice.value : choice.name,
30
- disabled: Boolean(choice.disabled),
31
+ disabled: Boolean(choice.disabled) || choice.type === 'separator',
32
+ ...(choice.type === 'separator' ? { separator: true } : {}),
33
+ ...(choice.section !== undefined ? { section: choice.section } : {}),
34
+ ...(choice.description !== undefined ? { description: choice.description } : {}),
31
35
  checked: Boolean(choice.checked),
32
36
  };
33
37
  }
@@ -78,7 +82,10 @@ export async function runPrompt(config, context, spec) {
78
82
  const text = Array.isArray(rendered) ? rendered.join('\n') : String(rendered ?? '');
79
83
  if (output.isTTY && height > 0) output.write(`\x1b[${height}A\x1b[0J`);
80
84
  output.write(`${text}\n`);
81
- height = text.split('\n').length;
85
+ // Count wrapped terminal rows as well as explicit newlines: the compact
86
+ // footer can still wrap in a narrow terminal.
87
+ const columns = output.isTTY && output.columns > 0 ? output.columns : Infinity;
88
+ height = text.split('\n').reduce((rows, line) => rows + Math.max(1, Math.ceil(Array.from(stripVTControlCharacters(line)).length / columns)), 0);
82
89
  };
83
90
 
84
91
  const finish = value => {
package/src/prompts.js CHANGED
@@ -7,7 +7,8 @@
7
7
  * paginated-search.js and resolve undefined instead.
8
8
  */
9
9
 
10
- import { runPrompt, normalizeChoices, truncate, PromptCancelled, escapeResult } from './prompt-engine.js';
10
+ import { pickerRows, pickerFooter } from './picker-ui.js';
11
+ import { runPrompt, normalizeChoices, PromptCancelled, escapeResult } from './prompt-engine.js';
11
12
  export { PromptCancelled };
12
13
 
13
14
  const ESC_HINT = ' (Esc to cancel)';
@@ -113,33 +114,59 @@ export async function confirm(config = {}, context = {}) {
113
114
  }
114
115
 
115
116
  export async function select(config = {}, context = {}) {
117
+ return localPicker(config, context);
118
+ }
119
+
120
+ async function localPicker(config, context, multiple = false) {
116
121
  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) {
122
+ const state = {
123
+ term: '', choices, active: firstEnabled(choices), error: '',
124
+ picked: new Set(choices.filter(choice => choice.checked && !choice.disabled)),
125
+ };
126
+ const defaultIndex = choices.findIndex(choice => !choice.disabled && choice.value === config.default);
127
+ if (defaultIndex >= 0) state.active = defaultIndex;
128
+ return runPrompt(config, context, {
129
+ ...(config.escapeValue ? { escapeValue: config.escapeValue } : {}),
130
+ init: () => state,
131
+ async key(_state, key, api) {
132
+ const visible = state.choices;
133
+ const choice = visible[state.active];
120
134
  if (key.name === 'return' || key.name === 'enter') {
121
- const choice = choices[state.active];
122
- if (!choice || choice.disabled) return;
123
- return { done: choice.value };
135
+ if (!multiple) {
136
+ if (choice && !choice.disabled) return { done: choice.value };
137
+ return;
138
+ }
139
+ const values = choices.filter(choice => state.picked.has(choice)).map(choice => choice.value);
140
+ state.error = config.required && !values.length ? 'Select at least one option.' : await validateAnswer(config.validate, values);
141
+ if (state.error) { api.redraw(); return; }
142
+ return { done: values };
124
143
  }
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;
144
+ if (multiple && key.name === 'space') {
145
+ if (choice && !choice.disabled) {
146
+ if (state.picked.has(choice)) state.picked.delete(choice);
147
+ else state.picked.add(choice);
148
+ state.error = '';
149
+ }
150
+ } else if (multiple && key.ctrl && key.name === 'a') {
151
+ visible.forEach(choice => { if (!choice.disabled) state.picked.add(choice); });
152
+ } else if (key.name === 'up' || key.name === 'down') {
153
+ state.active = move(visible, state.active, key.name === 'up' ? -1 : 1);
154
+ } else {
155
+ const previous = state.term;
156
+ if (key.name === 'backspace') state.term = Array.from(state.term).slice(0, -1).join('');
157
+ else if (key.text) state.term += key.text;
158
+ if (previous !== state.term) {
159
+ state.choices = state.term ? choices.filter(choice => !choice.separator && choice.name.toLocaleLowerCase().includes(state.term.toLocaleLowerCase())) : choices;
160
+ state.active = firstEnabled(state.choices);
161
+ }
162
+ }
163
+ api.redraw();
138
164
  },
139
- final(cfg, value) {
140
- const chosen = choices.find(choice => choice.value === value);
141
- return `✔ ${withHint(cfg)} ${chosen ? chosen.name : value}`;
165
+ render() {
166
+ return [config.message ?? '', `Search: ${state.term}`, ...pickerRows(state.choices, state.active, multiple ? { picked: state.picked } : {}),
167
+ ...(!state.choices.length ? [' No matches'] : []), ...(state.error ? [` ${state.error}`] : []), ...pickerFooter({ checkbox: multiple })];
142
168
  },
169
+ final: (_cfg, value) => value === undefined ? null : `✔ ${config.message ?? ''} ${multiple ? choices.filter(choice => value.includes(choice.value)).map(choice => choice.name).join(', ') : choices.find(choice => choice.value === value)?.name ?? value ?? ''}`,
143
170
  });
144
171
  }
145
172
 
@@ -190,11 +217,11 @@ export async function search(config = {}, context = {}) {
190
217
  if (state.term !== previous) void load(api);
191
218
  },
192
219
  render() {
193
- const lines = [`${withHint(config)} Search: ${state.term}${state.loading ? ' ...' : ''}`];
220
+ const lines = [config.message ?? '', `Search: ${state.term}${state.loading ? ' ...' : ''}`];
194
221
  if (state.error) lines.push(` ${state.error}`);
195
222
  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.');
223
+ else lines.push(...pickerRows(state.choices, state.active));
224
+ lines.push(...pickerFooter());
198
225
  return lines;
199
226
  },
200
227
  });
@@ -205,46 +232,7 @@ export async function search(config = {}, context = {}) {
205
232
  }
206
233
 
207
234
  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
- });
235
+ return localPicker(config, context, true);
248
236
  }
249
237
 
250
238
  function firstEnabled(choices) {