@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.
@@ -0,0 +1,176 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { cachedSchedules } from './schedule-cache.js';
3
+ import { AppError } from './errors.js';
4
+
5
+ export function scheduleSnapshot({ bundled = false } = {}) {
6
+ const cached = !bundled && cachedSchedules();
7
+ if (cached) return cached;
8
+ const current = JSON.parse(readFileSync(new URL('./schedules/itom-2026-04-09.json', import.meta.url), 'utf8'));
9
+ const inventory = JSON.parse(readFileSync(new URL('./schedules/public-inventory.json', import.meta.url), 'utf8'));
10
+ return {
11
+ schedules: [{ ...current, product: 'ITOM', measurement: 'illustrative-population', normalization_status: 'normalized', skus: [] }, ...inventory],
12
+ provenance: { source: 'bundled', stale: true, freshness: 'bundled fallback; no network freshness check' },
13
+ };
14
+ }
15
+ export function scheduleCatalog({ product, sku, id, bundled = false, snapshot } = {}) {
16
+ return (snapshot || scheduleSnapshot({ bundled })).schedules
17
+ .filter(s => (!product || s.product.toUpperCase() === product.toUpperCase()) && (!sku || (s.skus || []).includes(sku)) && (!id || s.id === id));
18
+ }
19
+ export function formatSchedule(schedule) {
20
+ const lines = [];
21
+ const label = key => key.replaceAll('_', ' ');
22
+ const render = (value, indent = '') => {
23
+ if (Array.isArray(value)) return value.flatMap(item => typeof item === 'object' && item !== null ? [`${indent}-`, ...render(item, `${indent} `)] : [`${indent}- ${item}`]);
24
+ if (value && typeof value === 'object') return Object.entries(value).flatMap(([key, item]) => item && typeof item === 'object' ? [`${indent}${label(key)}:`, ...render(item, `${indent} `)] : [`${indent}${label(key)}: ${item ?? 'not specified'}`]);
25
+ return [`${indent}${value ?? 'not specified'}`];
26
+ };
27
+ for (const [key, value] of Object.entries(schedule)) {
28
+ if (key === 'definitions' && Array.isArray(value)) {
29
+ lines.push('DEFINITIONS', ...value.map(d => `- ${d.term}: ${d.definition} [${d.source_sections?.join('; ') || schedule.source_sections?.join('; ') || 'see source'}]`));
30
+ } else if (key === 'meter') {
31
+ lines.push('METER', ...render(Object.fromEntries(Object.entries(value).filter(([k]) => k !== 'rules'))));
32
+ if (value.rules) lines.push('USAGE RULES', ...value.rules.map(rule => {
33
+ const name = rule.skill || rule.capability;
34
+ const action = rule.action || rule.usage;
35
+ const rate = rule.assists !== undefined ? (rule.assists === null ? rule.rate_reference || 'conditional; see conditions' : `${rule.assists} Assist`) : `${rule.credits} Credit`;
36
+ const detail = Object.fromEntries(Object.entries(rule).filter(([k]) => !['skill', 'capability', 'action', 'usage', 'assists', 'credits'].includes(k)));
37
+ return `- ${name}: ${action} — ${rate}${Object.keys(detail).length ? `; ${render(detail).join('; ')}` : ''}`;
38
+ }));
39
+ } else {
40
+ lines.push(label(key).toUpperCase(), ...render(value));
41
+ }
42
+ }
43
+ return lines.join('\n');
44
+ }
45
+
46
+ export function loadSchedule(id = 'itom-2026-04-09') {
47
+ const selected = scheduleCatalog({ id, bundled: true });
48
+ if (selected.length !== 1) throw new AppError('unsupported_schedule', 'No bundled schedule for this selection.', 'Run jsn subscriptions schedules for exact IDs.');
49
+ return selected[0];
50
+ }
51
+ const malformed = () => new AppError('malformed', 'Source response is incomplete or malformed.');
52
+ async function read(sdk, kind, table, params) {
53
+ return sdk.request(`${sdk.baseURL}/api/now/${kind}/${table}?${new URLSearchParams(params)}`, { method: 'GET', readOnly: true });
54
+ }
55
+ async function count(sdk, table, query) {
56
+ const body = await read(sdk, 'stats', table, { sysparm_count: 'true', sysparm_query: query });
57
+ const value = body?.result?.stats?.count;
58
+ if (!/^(0|[1-9]\d*)$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw malformed();
59
+ return Number(value);
60
+ }
61
+ async function rows(sdk, table, query, fields, cap, offset = 0) {
62
+ const body = await read(sdk, 'table', table, { sysparm_query: query, sysparm_fields: fields, sysparm_limit: String(cap), sysparm_offset: String(offset), sysparm_display_value: 'false', sysparm_exclude_reference_link: 'true' });
63
+ if (!Array.isArray(body?.result)) throw malformed();
64
+ return body.result;
65
+ }
66
+ function status(error) {
67
+ if (error.status === 403 || error.code === 'forbidden') return 'forbidden';
68
+ if (error.status === 404) return 'missing-or-hidden';
69
+ return ['malformed', 'schema_unavailable'].includes(error.code) ? error.code : 'unavailable';
70
+ }
71
+
72
+ export async function estimateSubscription(sdk, product, { schedule, assumeEligible = false } = {}) {
73
+ if (String(product).toUpperCase() !== 'ITOM') {
74
+ if (scheduleCatalog({ product }).length) throw new AppError('measurement_unavailable', 'Known catalog product; measurement is unimplemented.', 'Inspect subscriptions schedules --product with this product. No role or CI population is substituted.');
75
+ throw new AppError('unsupported_product', 'No verified product meter is bundled for this selection.', 'Run jsn subscriptions schedules. HRSD eligible population and contractual meter remain unverified; role counts are not billable seats.');
76
+ }
77
+ const selected = loadSchedule(schedule);
78
+ if (selected.product !== 'ITOM' || selected.measurement !== 'illustrative-population') throw new AppError('measurement_unavailable', 'This exact schedule is catalog-only; its measurement adapter is unimplemented.', 'Inspect subscriptions schedules --id with this schedule ID. No current ITOM ratios are substituted.');
79
+ const report = {
80
+ product: 'ITOM', captured_at: new Date().toISOString(), schedule: selected,
81
+ applicability: schedule ? 'explicit schedule selection; contractual SKU applicability unverified' : 'provisional April 9, 2026 schedule assumption; product name does not prove SKU applicability',
82
+ eligibility_assumption: assumeEligible ? 'Hypothetically all visible mapped populations are ITOM-managed and meet component/product requirements; exclusions remain unevaluated.' : 'No eligibility assumed; units withheld. Use --assume-eligible only for an illustrative activation scenario.',
83
+ status: 'incomplete', total_units: null, authoritative: false, categories: [],
84
+ };
85
+ let definitions, byId, byName;
86
+ report.coverage = { metadata_status: 'unavailable', visible_definitions: null, provider_count: null, skipped_ancestries: 0, semantics: 'Provider-visible exact-class aggregate counts only; ACL-hidden rows and concurrent changes remain unknown.' };
87
+ try {
88
+ // Include scoped/custom descendants, whose names need not start with cmdb_ci.
89
+ const available = await count(sdk, 'sys_db_object', '');
90
+ report.coverage.provider_count = available;
91
+ definitions = [];
92
+ const ids = new Set();
93
+ let ordered = true;
94
+ let previous;
95
+ let pages = 0;
96
+ let offset = 0;
97
+ // Offset addresses provider windows, including rows omitted by visibility.
98
+ // Short pages are not exhaustion; stable counts and unique rows are required.
99
+ while (offset < available && offset < 20000 && pages < 200) {
100
+ const limit = Math.min(1000, available - offset, 20000 - offset);
101
+ const page = await rows(sdk, 'sys_db_object', 'ORDERBYsys_id', 'sys_id,name,super_class', limit, offset);
102
+ offset += limit;
103
+ pages++;
104
+ if (page.length > limit) throw malformed();
105
+ if (!page.length) break;
106
+ for (const d of page) {
107
+ if (!d || typeof d.sys_id !== 'string' || !d.sys_id.trim() || ids.has(d.sys_id)) throw malformed();
108
+ if (previous !== undefined && d.sys_id <= previous) ordered = false;
109
+ previous = d.sys_id;
110
+ ids.add(d.sys_id);
111
+ }
112
+ definitions.push(...page);
113
+ }
114
+ const after = await count(sdk, 'sys_db_object', '');
115
+ report.coverage.provider_count_after = after;
116
+ report.coverage.metadata_pages = pages;
117
+ report.coverage.visible_definitions = definitions.length;
118
+ report.coverage.metadata_status = ordered && available === after && definitions.length === available ? 'provider-count-matched' : 'partial';
119
+ byId = new Map(definitions.map(d => [d.sys_id, d]));
120
+ byName = new Map(definitions.map(d => [d.name, d]));
121
+ if (byId.size !== definitions.length || byName.size !== definitions.length || !byName.has('cmdb_ci') || definitions.some(d => typeof d.name !== 'string' || typeof d.super_class !== 'string')) throw malformed();
122
+ const dictionary = await rows(sdk, 'sys_dictionary', 'name=cmdb_ci^element=sys_class_name', 'name,element,internal_type', 2);
123
+ if (dictionary.length !== 1 || dictionary[0].name !== 'cmdb_ci' || dictionary[0].element !== 'sys_class_name' || !['sys_class_name', 'string'].includes(dictionary[0].internal_type)) throw new AppError('schema_unavailable', 'Class discriminator schema unavailable.');
124
+ } catch (error) {
125
+ report.categories = selected.categories.map(c => ({ category: c.id, resources_per_su: c.resources_per_su, status: status(error), population: null, illustrative_units: null }));
126
+ return report;
127
+ }
128
+ const assigned = new Map(selected.categories.map(c => [c.id, []]));
129
+ const ambiguous = new Set();
130
+ for (const definition of definitions) {
131
+ const ancestry = new Set();
132
+ let current = definition;
133
+ while (current) {
134
+ if (ancestry.has(current.name)) throw malformed();
135
+ ancestry.add(current.name);
136
+ if (!current.super_class) break;
137
+ current = byId.get(current.super_class);
138
+ if (!current) { report.coverage.skipped_ancestries++; break; }
139
+ }
140
+ if (!current || !ancestry.has('cmdb_ci') || !/^[a-zA-Z0-9_]+$/.test(definition.name)) continue;
141
+ let matches = selected.categories.filter(c => c.classes.some(name => ancestry.has(name)));
142
+ if (matches.length > 1) matches = matches.filter(c => c.id !== 'end_user_device');
143
+ if (matches.length > 1) { matches.forEach(c => ambiguous.add(c.id)); continue; }
144
+ if (matches.length === 1) assigned.get(matches[0].id).push(definition.name);
145
+ }
146
+ for (const category of selected.categories) {
147
+ const item = { category: category.id, resources_per_su: category.resources_per_su, population: null, illustrative_units: null, status: 'unsupported', missing_classes: category.classes.filter(n => !byName.has(n)), mapping_complete: false };
148
+ const classes = assigned.get(category.id);
149
+ item.mapping_complete = report.coverage.metadata_status === 'provider-count-matched' && report.coverage.skipped_ancestries === 0 && !item.missing_classes.length && category.id !== 'paas' && category.id !== 'unresolved_object' && !ambiguous.has(category.id);
150
+ if (ambiguous.has(category.id)) item.status = 'ambiguous-overlap';
151
+ else if (classes.length) {
152
+ try {
153
+ item.population = await count(sdk, 'cmdb_ci', `sys_class_nameIN${classes.sort().join(',')}`);
154
+ item.status = item.mapping_complete ? 'visible-population' : 'partial-mapping';
155
+ if (assumeEligible) item.illustrative_units = item.population / category.resources_per_su;
156
+ } catch (error) { item.status = status(error); }
157
+ } else item.status = category.id === 'unresolved_object' ? 'unsupported-source-schema' : 'missing-or-hidden';
158
+ report.categories.push(item);
159
+ }
160
+ return report;
161
+ }
162
+
163
+ export function formatEstimate(report) {
164
+ return [
165
+ 'ITOM illustrative population comparison: INCOMPLETE, no authoritative total',
166
+ `Schedule: ${report.schedule.id}. ${report.applicability}`,
167
+ `Source: ${report.schedule.source_url}`,
168
+ `Metadata: ${report.coverage.metadata_status}, ${report.coverage.visible_definitions ?? '?'} definitions / ${report.coverage.provider_count ?? '?'} provider count; ${report.coverage.skipped_ancestries} unresolved ancestries`,
169
+ report.coverage.semantics,
170
+ report.eligibility_assumption,
171
+ 'CATEGORY | VISIBLE POPULATION | RESOURCES/SU | ILLUSTRATIVE SU | COVERAGE',
172
+ ...report.categories.map(c => `${c.category} | ${c.population ?? '?'} | ${c.resources_per_su} | ${c.illustrative_units ?? '?'} | ${c.status}`),
173
+ report.schedule.unresolved_mapping,
174
+ ...report.schedule.limitations,
175
+ ].join('\n');
176
+ }