@jacebenson/jsn 5.5.7-dev.212.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.212.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,9 @@ 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';
84
+ import { subscriptionsCmd } from './commands/subscriptions.js';
82
85
  import { approvalsCmd } from './commands/approvals.js';
83
86
  import { perfCmd } from './commands/perf.js';
84
87
  import { customizationsCmd } from './commands/customizations.js';
@@ -444,6 +447,9 @@ export function buildCLI() {
444
447
  .command(atfCmd(wrap))
445
448
  .command(scanCmd(wrap))
446
449
  .command(storeCmd(wrap))
450
+ .command(pluginsCmd(wrap))
451
+ .command(compareCmd(wrap))
452
+ .command(subscriptionsCmd(wrap))
447
453
  .command(approvalsCmd(wrap))
448
454
  .command(skippedUpdatesCmd(wrap))
449
455
  .command(perfCmd(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,47 @@
1
+ import { refreshSchedules } from '../schedule-cache.js';
2
+ import { declareCapabilities } from '../capabilities.js';
3
+ import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
+
5
+ declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
6
+ export function subscriptionsCmd(wrap) {
7
+ const local = (argv, app) => {
8
+ const snapshot = scheduleSnapshot();
9
+ const schedules = scheduleCatalog({ product: argv.product, sku: argv.sku, id: argv.id, snapshot });
10
+ const data = { provenance: snapshot.provenance, schedules, coverage: { index_documents: new Set(snapshot.schedules.map(s => s.source_url)).size, archive: 'unavailable', sku_mapping: 'only explicitly normalized codes; empty results do not establish absence of rights' } };
11
+ Object.defineProperty(data, '_formatted', { value: [
12
+ `Local catalog snapshot (${data.provenance.source}; ${data.provenance.freshness}; revision ${data.provenance.revision || 'bundled'}; retrieved ${data.provenance.retrieved_at || 'bundled'}; stale ${data.provenance.stale}); contractual applicability unverified. Archive unavailable.`,
13
+ ...schedules.flatMap(s => [
14
+ `${s.id} | ${s.product} | ${s.effective_date || s.source_version || 'date unverified'} | ${s.normalization_status || 'not specified'}`,
15
+ s.source_url,
16
+ `Measurement: ${s.measurement || 'not specified; inspection only'}. SKU mapping: ${(s.skus || []).join(', ') || 'unverified'}`,
17
+ ...(s.unknowns || s.limitations || []),
18
+ ...(argv.id ? [formatSchedule(s)] : []),
19
+ ]),
20
+ ].join('\n') });
21
+ app.ok(data, { summary: 'Local dated metering schedules, not purchased rights' });
22
+ };
23
+ return {
24
+ command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
25
+ builder: y => y.command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
+ const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
+ const manifest = argv.manifestUrl || process.env.JSN_SCHEDULES_MANIFEST_URL || app.config?.docs?.schedule_manifest_url || (origin ? new URL('/subscription-schedules/v1/manifest.json', origin).href : undefined);
28
+ const provenance = await refreshSchedules(manifest);
29
+ app.ok({ provenance }, { summary: 'Validated schedule cache refreshed' });
30
+ }) }).command({ command: 'schedules', describe: 'Inspect validated cache or bundled source-backed schedules offline', builder: b => b.option('product', { type: 'string' }).option('sku', { type: 'string' }).option('id', { type: 'string' }), handler: wrap(local) })
31
+ .command({ command: 'estimate <product>', describe: 'Read-only ITOM population comparison, not billing or a 90-day meter',
32
+ builder: b => b.positional('product', { type: 'string', describe: 'ITOM; arbitrary SKUs and HRSD unsupported' })
33
+ .option('schedule', { type: 'string', describe: 'Explicit dated schedule ID from subscriptions schedules' })
34
+ .option('assume-eligible', { type: 'boolean', default: false, describe: 'Hypothetically treat mapped populations as managed and component-eligible, exclusions unknown' }),
35
+ handler: wrap(async (argv, app) => {
36
+ // Validate unsupported selections before requesting an instance.
37
+ const selected = loadSchedule(argv.schedule);
38
+ if (String(argv.product).toUpperCase() !== 'ITOM' || selected.measurement !== 'illustrative-population') await estimateSubscription(null, argv.product, { schedule: argv.schedule });
39
+ app.requireInstance();
40
+ const report = await estimateSubscription(app.sdk, argv.product, { schedule: argv.schedule, assumeEligible: argv.assumeEligible });
41
+ Object.defineProperty(report, '_formatted', { value: formatEstimate(report) });
42
+ app.ok(report, { summary: 'Incomplete illustrative ITOM population comparison; no authoritative total' });
43
+ }),
44
+ }),
45
+ handler: wrap(local),
46
+ };
47
+ }
@@ -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
+ });
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { cacheDir } from './config.js';
5
+ import { AppError } from './errors.js';
6
+
7
+ const MAX = 4 * 1024 * 1024;
8
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
9
+ const fail = message => { throw new AppError('invalid_catalog', message); };
10
+ const file = () => path.join(cacheDir(), 'subscription-schedules-v1.json');
11
+ const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
12
+ export function validateCatalog(catalog) {
13
+ const checkDepth = (value, depth = 0) => {
14
+ if (depth > 32) fail('Catalog nesting exceeds schema limit.');
15
+ if (value && typeof value === 'object') for (const child of Object.values(value)) checkDepth(child, depth + 1);
16
+ };
17
+ checkDepth(catalog);
18
+ if (catalog?.schema_version !== 1 || !hash(catalog.revision) || !Array.isArray(catalog.schedules) || !catalog.schedules.length) fail('Invalid catalog schema.');
19
+ const ids = new Set();
20
+ for (const r of catalog.schedules) {
21
+ if (!r || typeof r.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(r.id) || ids.has(r.id) || typeof r.product !== 'string' || !r.product.trim()) fail('Invalid or duplicate schedule ID/product.');
22
+ ids.add(r.id);
23
+ for (const key of ['title', 'source_version', 'effective_date', 'applicability', 'measurement', 'normalization_status']) {
24
+ if (r[key] !== undefined && r[key] !== null && typeof r[key] !== 'string') fail(`Invalid record ${key}.`);
25
+ }
26
+ for (const key of ['source_sections', 'skus', 'unknowns', 'exceptions', 'limitations']) {
27
+ if (r[key] !== undefined && (!Array.isArray(r[key]) || r[key].some(v => typeof v !== 'string'))) fail(`Invalid record ${key}.`);
28
+ }
29
+ if (r.definitions !== undefined && (!r.definitions || typeof r.definitions !== 'object')) fail('Invalid definitions.');
30
+ if (Array.isArray(r.definitions) && r.definitions.some(d => !d || typeof d.term !== 'string' || typeof d.definition !== 'string' || !Array.isArray(d.source_sections) || d.source_sections.some(v => typeof v !== 'string'))) fail('Invalid definition provenance.');
31
+ if (r.meter !== undefined && (!r.meter || typeof r.meter !== 'object' || Array.isArray(r.meter))) fail('Invalid meter.');
32
+ if (r.meter?.rules !== undefined && (!Array.isArray(r.meter.rules) || r.meter.rules.some(v => !v || typeof v !== 'object' || Array.isArray(v)))) fail('Invalid meter rules.');
33
+ for (const key of ['packages', 'entitlements', 'section_coverage', 'capability_lists']) {
34
+ if (r[key] !== undefined && (!r[key] || typeof r[key] !== 'object')) fail(`Invalid record ${key}.`);
35
+ }
36
+ let source;
37
+ try { source = new URL(r.source_url); } catch { fail('Missing source provenance.'); }
38
+ if (source.protocol !== 'https:' || source.hostname !== 'www.servicenow.com' || source.username || source.password || !source.pathname.endsWith('.pdf') || !Number.isFinite(Date.parse(r.retrieved_at || r.fetched_at))) fail('Unsafe or missing source provenance.');
39
+ if (r.id !== 'itom-2026-04-09' && (!Array.isArray(r.source_sections) || !r.source_sections.length || !Array.isArray(r.skus) || !['normalized', 'partial'].includes(r.normalization_status))) fail('Invalid normalized record schema.');
40
+ }
41
+ return catalog;
42
+ }
43
+ function safeURL(value, origin) {
44
+ let u;
45
+ try { u = new URL(value); } catch { fail('Invalid catalog URL.'); }
46
+ if (u.username || u.password || u.hash || (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(u.hostname))) || (origin && u.origin !== origin)) fail('Catalog URL must use HTTPS and the approved manifest origin (explicit loopback HTTP is allowed).');
47
+ return u;
48
+ }
49
+ async function download(url, cap) {
50
+ const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(10000), credentials: 'omit' });
51
+ if (!response.ok) fail(`Catalog HTTP ${response.status}.`);
52
+ if (Number(response.headers.get('content-length')) > cap) fail('Catalog exceeds size cap.');
53
+ const chunks = []; let size = 0;
54
+ for await (const chunk of response.body) {
55
+ size += chunk.length;
56
+ if (size > cap) { fail('Catalog exceeds size cap.'); }
57
+ chunks.push(chunk);
58
+ }
59
+ return Buffer.concat(chunks);
60
+ }
61
+ export async function refreshSchedules(manifestURL) {
62
+ if (!manifestURL) fail('Specify --manifest-url or configure JSN_DOCS_URL / global docs.url.');
63
+ const url = safeURL(manifestURL);
64
+ const manifest = JSON.parse(await download(url, 16384));
65
+ if (manifest.schema_version !== 1 || !hash(manifest.revision) || !hash(manifest.sha256) || !Number.isSafeInteger(manifest.bytes) || manifest.bytes < 1 || manifest.bytes > MAX || !Number.isFinite(Date.parse(manifest.published_at))) fail('Invalid manifest schema or size.');
66
+ const artifactURL = safeURL(manifest.catalog_url, url.origin);
67
+ const bytes = await download(artifactURL, MAX);
68
+ if (bytes.length !== manifest.bytes || digest(bytes) !== manifest.sha256) fail('Catalog byte length or SHA256 mismatch.');
69
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
70
+ const catalog = validateCatalog(JSON.parse(text));
71
+ if (catalog.revision !== manifest.revision) fail('Catalog revision mismatch.');
72
+ const entry = { manifest, manifest_url: url.href, retrieved_at: new Date().toISOString(), artifact: text };
73
+ const serialized = JSON.stringify(entry);
74
+ if (Buffer.byteLength(serialized) > MAX * 2) fail('Serialized cache exceeds size cap.');
75
+ fs.mkdirSync(path.dirname(file()), { recursive: true, mode: 0o700 });
76
+ const temp = `${file()}.${randomUUID()}.tmp`;
77
+ try { fs.writeFileSync(temp, serialized, { mode: 0o600, flag: 'wx' }); fs.renameSync(temp, file()); }
78
+ finally { fs.rmSync(temp, { force: true }); }
79
+ return cachedSchedules().provenance;
80
+ }
81
+ export function cachedSchedules() {
82
+ try {
83
+ if (fs.statSync(file()).size > MAX * 2) return null;
84
+ const entry = JSON.parse(fs.readFileSync(file(), 'utf8'));
85
+ const m = entry.manifest;
86
+ if (m?.schema_version !== 1 || !hash(m.revision) || !hash(m.sha256) || !Number.isSafeInteger(m.bytes) || m.bytes < 1 || m.bytes > MAX || !Number.isFinite(Date.parse(m.published_at))) return null;
87
+ const approved = safeURL(entry.manifest_url);
88
+ safeURL(m.catalog_url, approved.origin);
89
+ if (typeof entry.artifact !== 'string') return null;
90
+ const bytes = Buffer.from(entry.artifact);
91
+ if (bytes.length > MAX || bytes.length !== entry.manifest.bytes || digest(bytes) !== entry.manifest.sha256) return null;
92
+ const catalog = validateCatalog(JSON.parse(bytes));
93
+ if (catalog.revision !== entry.manifest.revision || !Number.isFinite(Date.parse(entry.retrieved_at))) return null;
94
+ return { schedules: catalog.schedules, provenance: { source: 'validated-cache', revision: catalog.revision, sha256: entry.manifest.sha256, retrieved_at: entry.retrieved_at, manifest_url: entry.manifest_url, stale: Date.now() - Date.parse(entry.retrieved_at) > 86400000, freshness: 'last-good snapshot; no network freshness check' } };
95
+ } catch { return null; }
96
+ }
@@ -0,0 +1,121 @@
1
+ {
2
+ "id": "itom-2026-04-09",
3
+ "product": "ITOM",
4
+ "effective_for_skus_introduced": "2026-04-09",
5
+ "source_url": "https://www.servicenow.com/content/dam/servicenow-assets/public/en-us/doc-type/legal/it-operations-management-itom-servicenow-subscription-unit-overview.pdf",
6
+ "source_version": "Effective for SKUs introduced on April 9, 2026; sections 1.1 and 1.2",
7
+ "fetched_at": "2026-11-19T07:47:54.276651+00:00",
8
+ "retrieval": "Independent web_extract PDF text retrieval; direct download returned 403. Binary hash unavailable.",
9
+ "categories": [
10
+ {
11
+ "id": "server",
12
+ "resources_per_su": 1,
13
+ "classes": [
14
+ "cmdb_ci_server",
15
+ "cmdb_ci_vm_instance",
16
+ "cmdb_ci_ucs_rack_unit",
17
+ "cmdb_ci_ucs_blade",
18
+ "cmdb_ci_mainframe_hardware"
19
+ ]
20
+ },
21
+ {
22
+ "id": "paas",
23
+ "resources_per_su": 3,
24
+ "classes": [
25
+ "cmdb_ci_cloud_appserver",
26
+ "cmdb_ci_could_database",
27
+ "cmdb_ci_dynamodb_table",
28
+ "cmdb_ci_cloud_directory",
29
+ "cmdb_ci_cloud_gateway",
30
+ "cmdb_ci_cloud_messaging_service",
31
+ "cmdb_ci_cloud_webserver"
32
+ ]
33
+ },
34
+ {
35
+ "id": "container",
36
+ "resources_per_su": 10,
37
+ "classes": [
38
+ "cmdb_ci_oslv_container"
39
+ ]
40
+ },
41
+ {
42
+ "id": "image",
43
+ "resources_per_su": 3,
44
+ "classes": [
45
+ "cmdb_ci_oslv_image",
46
+ "cmdb_ci_oslv_local_image",
47
+ "cmdb_ci_openshift_images"
48
+ ]
49
+ },
50
+ {
51
+ "id": "end_user_device",
52
+ "resources_per_su": 4,
53
+ "classes": [
54
+ "cmdb_ci_computer"
55
+ ]
56
+ },
57
+ {
58
+ "id": "faas",
59
+ "resources_per_su": 20,
60
+ "classes": [
61
+ "cmdb_ci_cloud_function"
62
+ ]
63
+ },
64
+ {
65
+ "id": "gpu",
66
+ "resources_per_su": 1,
67
+ "classes": [
68
+ "cmdb_ci_gpu"
69
+ ]
70
+ },
71
+ {
72
+ "id": "api",
73
+ "resources_per_su": 1,
74
+ "classes": [
75
+ "cmdb_ci_api"
76
+ ]
77
+ },
78
+ {
79
+ "id": "ai_agent",
80
+ "resources_per_su": 3,
81
+ "classes": [
82
+ "cmdb_ci_function_ai"
83
+ ]
84
+ },
85
+ {
86
+ "id": "service_instance",
87
+ "resources_per_su": 1,
88
+ "classes": [
89
+ "cmdb_ci_service_auto"
90
+ ]
91
+ },
92
+ {
93
+ "id": "unresolved_object",
94
+ "resources_per_su": 4,
95
+ "classes": []
96
+ }
97
+ ],
98
+ "definitions": {
99
+ "provenance": "Paraphrases of section 1.1, not independent eligibility rules. All CI resource types must be represented in the listed classes or descendants and managed by an ITOM application.",
100
+ "server": "Physical or virtual server.",
101
+ "paas": "Cloud-based platform service.",
102
+ "container": "Operating system-level virtualization.",
103
+ "image": "Operating system-level virtualization image.",
104
+ "end_user_device": "Physical or virtual computing device not defined as another Managed IT Resource Type, with an ITOM component such as Agent Client Collector installed.",
105
+ "faas": "Serverless compute function-as-a-service instance.",
106
+ "gpu": "Graphics Processing Unit.",
107
+ "api": "Application programming interface.",
108
+ "ai_agent": "Service for machine learning, data processing and AI-driven tasks.",
109
+ "service_instance": "Interconnected applications and IT resources configured to offer a digital service.",
110
+ "unresolved_object": "IT resource receiving an ITOM event, performance metric or log, not represented as a CMDB CI; recorded in em_unique_nodes with type=unknown. Counting this source is unsupported in this slice."
111
+ },
112
+ "unresolved_mapping": "cmdb_ci_could_database is literal source text; no corrected mapping is assumed.",
113
+ "limitations": [
114
+ "CMDB populations are not managed or billable counts, nor a ceiling.",
115
+ "Managed-by-ITOM eligibility and product scope are unverified.",
116
+ "End-user devices require an installed ITOM component and exclusion of other resource types.",
117
+ "Container/image relationship exclusions are not evaluated.",
118
+ "Rounding and contract applicability are unknown.",
119
+ "Observed 90-day usage and purchased entitlements are not implemented."
120
+ ]
121
+ }