@jacebenson/jsn 5.5.7-dev.213.1 → 5.5.7-dev.214.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.214.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
+ });
@@ -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
+ });
@@ -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'),
@@ -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
+ });