@jacebenson/jsn 5.5.7 → 5.5.8-dev.219.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/README.md +16 -1
- package/package.json +5 -6
- package/skills/servicenow/SKILL.md +9 -1
- package/src/app.js +4 -79
- package/src/bounded-reads.js +13 -0
- package/src/capabilities.js +8 -3
- package/src/cli-adapter.js +26 -3
- package/src/cli.js +13 -14
- package/src/command-families.js +68 -0
- package/src/commands/_generic.js +1 -0
- package/src/commands/_ticket.js +1 -1
- package/src/commands/actions.js +9 -4
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- package/src/commands/attachments.js +1 -1
- package/src/commands/auth.js +21 -2
- package/src/commands/codesearch.js +11 -2
- package/src/commands/compare.js +22 -0
- package/src/commands/customizations.js +3 -4
- package/src/commands/decisiontables.js +4 -0
- package/src/commands/docs/docs.js +5 -5
- package/src/commands/domains.js +1 -1
- package/src/commands/eval.js +11 -5
- package/src/commands/flows.js +24 -7
- package/src/commands/groupmembers.js +1 -1
- package/src/commands/grouproles.js +1 -1
- package/src/commands/groups.js +1 -1
- package/src/commands/midservers.js +4 -11
- package/src/commands/perf.js +2 -3
- package/src/commands/plugins.js +9 -0
- package/src/commands/records.js +12 -2
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +2 -2
- package/src/commands/setup.js +4 -34
- package/src/commands/skipped-updates.js +2 -3
- package/src/commands/store.js +4 -1
- package/src/commands/subscriptions.js +47 -0
- package/src/commands/tickets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/commands/workflows.js +3 -5
- package/src/config.js +1 -0
- package/src/context.js +8 -56
- package/src/docs-links.js +28 -0
- package/src/flow-create.js +9 -0
- package/src/help.js +4 -0
- package/src/helpers.js +17 -24
- package/src/instance-inventory.js +184 -0
- package/src/intended-context.js +68 -0
- package/src/mutation-context.js +69 -46
- package/src/output.js +1 -1
- package/src/paginated-search.js +146 -178
- package/src/picker-ui.js +20 -0
- package/src/prompt-engine.js +176 -0
- package/src/prompts.js +293 -43
- package/src/records/inspect.js +30 -16
- package/src/records-engine.js +2 -2
- package/src/schedule-cache.js +96 -0
- package/src/schedules/itom-2026-04-09.json +121 -0
- package/src/schedules/public-inventory.json +6224 -0
- package/src/sdk-batch.js +2 -1
- package/src/sdk.js +42 -16
- package/src/setup-preferences.js +2 -2
- package/src/subscriptions.js +176 -0
package/src/sdk-batch.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Optional, read-only ServiceNow Batch REST transport. No ordinary SDK call is
|
|
2
2
|
// routed here implicitly; writes are deliberately outside this initial contract.
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { boundedReads } from './bounded-reads.js';
|
|
4
5
|
import { AppError, errAPI, errUsage } from './errors.js';
|
|
5
6
|
|
|
6
7
|
const UNSUPPORTED = new Set([404, 405, 501]);
|
|
@@ -121,7 +122,7 @@ export async function batchRead(sdk, requests, { fallback = true, chunkSize = 50
|
|
|
121
122
|
}
|
|
122
123
|
if (useIndividual) {
|
|
123
124
|
transports.add('individual');
|
|
124
|
-
|
|
125
|
+
results.push(...await boundedReads(chunk, request => individual(sdk, request, timeout)));
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
128
|
const successful = results.filter(item => item.ok).length;
|
package/src/sdk.js
CHANGED
|
@@ -39,15 +39,13 @@ function serializeCookies(cookieJar) {
|
|
|
39
39
|
return [...cookieJar].map(([name, value]) => `${name}=${value}`).join('; ');
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
// Basic is the exception: normal requests must first detect any TOTP challenge
|
|
50
|
-
// before a pending operation can be sent. See docs/AUTH_LIFECYCLE.md.
|
|
42
|
+
// Endpoint capability, not authentication policy: these REST surfaces can use
|
|
43
|
+
// header-only auth. OAuth now prefers the existing UI session even here because
|
|
44
|
+
// tables with ws_access=false reject Bearer while allowing the same user's UI
|
|
45
|
+
// session. JSN_ALWAYS_WARM_SESSION=0 opts OAuth out only on these paths;
|
|
46
|
+
// stateful:true, required UI endpoints and value 1 retain session precedence.
|
|
47
|
+
// Basic/TOTP, supplied token and GCK policies remain unchanged. Internal OAuth
|
|
48
|
+
// bootstrap must bypass warming to avoid recursion. See site/docs/guides/setup.md.
|
|
51
49
|
const STATELESS_REST_PREFIXES = ['/api/now/table/', '/api/now/stats/', '/api/now/v1/batch'];
|
|
52
50
|
|
|
53
51
|
export function needsUiSession(url, { stateful = false, forceSession = false } = {}) {
|
|
@@ -106,7 +104,7 @@ export class SDKClient {
|
|
|
106
104
|
this._recoveryPromise = null;
|
|
107
105
|
}
|
|
108
106
|
|
|
109
|
-
async _setAuth(req, { skipOAuthSession = false, basicSession = false } = {}) {
|
|
107
|
+
async _setAuth(req, { skipOAuthSession = false, basicSession = false, preferOAuthSession = false, oauthHeaderOnly = false } = {}) {
|
|
110
108
|
if (!this.authProvider) {
|
|
111
109
|
throw errAuth('No authentication configured');
|
|
112
110
|
}
|
|
@@ -141,14 +139,19 @@ export class SDKClient {
|
|
|
141
139
|
break;
|
|
142
140
|
case 'token':
|
|
143
141
|
case 'oauth':
|
|
144
|
-
if (!skipOAuthSession) {
|
|
142
|
+
if (!skipOAuthSession || creds.auth_method === 'oauth' && preferOAuthSession) {
|
|
145
143
|
const cookies = await this._warmSession();
|
|
146
144
|
if (cookies && this.sessionUserToken) {
|
|
145
|
+
if (creds.auth_method === 'oauth') req.headers.delete('Authorization');
|
|
147
146
|
req.headers.set('Cookie', cookies);
|
|
148
147
|
req.headers.set('X-UserToken', this.sessionUserToken);
|
|
149
148
|
break;
|
|
150
149
|
}
|
|
151
150
|
}
|
|
151
|
+
if (creds.auth_method === 'oauth' && oauthHeaderOnly) {
|
|
152
|
+
req.headers.delete('Cookie');
|
|
153
|
+
req.headers.delete('X-UserToken');
|
|
154
|
+
}
|
|
152
155
|
req.headers.set('Authorization', `Bearer ${creds.access_token}`);
|
|
153
156
|
break;
|
|
154
157
|
case 'gck':
|
|
@@ -181,14 +184,19 @@ export class SDKClient {
|
|
|
181
184
|
try {
|
|
182
185
|
const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
|
|
183
186
|
if (prepare) prepare(req);
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
+
// Endpoint requirements and Basic challenge gates are unchanged. OAuth
|
|
188
|
+
// additionally prefers the UI session on otherwise stateless REST unless
|
|
189
|
+
// explicitly opted out. Internal bootstrap bypasses both to avoid recursion.
|
|
187
190
|
const skipSession = skipOAuthSession || !needsUiSession(endpoint, {
|
|
188
191
|
stateful,
|
|
189
192
|
forceSession: process.env.JSN_ALWAYS_WARM_SESSION === '1',
|
|
190
193
|
});
|
|
191
|
-
await this._setAuth(req, {
|
|
194
|
+
await this._setAuth(req, {
|
|
195
|
+
skipOAuthSession: skipSession,
|
|
196
|
+
basicSession: !skipOAuthSession,
|
|
197
|
+
preferOAuthSession: !skipOAuthSession && process.env.JSN_ALWAYS_WARM_SESSION !== '0',
|
|
198
|
+
oauthHeaderOnly: !skipOAuthSession && skipSession && process.env.JSN_ALWAYS_WARM_SESSION === '0',
|
|
199
|
+
});
|
|
192
200
|
timer = setTimeout(() => controller.abort(), timeout);
|
|
193
201
|
const response = await fetch(req);
|
|
194
202
|
if (!skipOAuthSession && this.recovery) {
|
|
@@ -326,7 +334,7 @@ export class SDKClient {
|
|
|
326
334
|
async request(endpoint, opts = {}) {
|
|
327
335
|
// Some provider mutations are GET-shaped. Keep this local replay policy
|
|
328
336
|
// out of fetch options rather than treating their HTTP method as read-only.
|
|
329
|
-
const { timeout = this.timeout, readOnly = false, stateful = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
|
|
337
|
+
const { timeout = this.timeout, readOnly = false, stateful = false, touchLastSeen, domain = this.domain, responseMetadata, ...requestOptions } = opts;
|
|
330
338
|
if (readOnly && (requestOptions.method || 'GET').toUpperCase() !== 'GET') throw new Error('Read-only SDK requests require GET');
|
|
331
339
|
return this._withAuthenticatedRequest(endpoint, requestOptions, {
|
|
332
340
|
timeout,
|
|
@@ -342,6 +350,13 @@ export class SDKClient {
|
|
|
342
350
|
}, async (resp) => {
|
|
343
351
|
const body = await resp.text();
|
|
344
352
|
if (!resp.ok) throw errAPI(resp.status, body || resp.statusText);
|
|
353
|
+
if (responseMetadata) {
|
|
354
|
+
// Invocation-local receipt, never a cache: only accept a complete safe
|
|
355
|
+
// integer from this exact successful response (not an empty header).
|
|
356
|
+
const count = resp.headers.get('X-Total-Count');
|
|
357
|
+
responseMetadata.total = count !== null && /^\d+$/.test(count) && Number.isSafeInteger(Number(count))
|
|
358
|
+
? Number(count) : undefined;
|
|
359
|
+
}
|
|
345
360
|
if (resp.status === 204 || body === '') return null;
|
|
346
361
|
|
|
347
362
|
// Preserve read-only credential-write suppression and the existing empty-body behavior.
|
|
@@ -423,7 +438,16 @@ export class SDKClient {
|
|
|
423
438
|
return result?.result || null;
|
|
424
439
|
}
|
|
425
440
|
|
|
441
|
+
async _guardTableMutation(table, id, data) {
|
|
442
|
+
const context = this.mutationContext;
|
|
443
|
+
if (!context?.verified || context.table !== table) return;
|
|
444
|
+
const { assertMutationScope } = await import('./intended-context.js');
|
|
445
|
+
if (id) assertMutationScope(context, (await this.get(table, id))?.sys_scope, 'Record target');
|
|
446
|
+
if (data && Object.hasOwn(data, 'sys_scope')) assertMutationScope(context, data.sys_scope, 'Record payload');
|
|
447
|
+
}
|
|
448
|
+
|
|
426
449
|
async create(table, data) {
|
|
450
|
+
await this._guardTableMutation(table, null, data);
|
|
427
451
|
const endpoint = `${this.baseURL}/api/now/table/${table}`;
|
|
428
452
|
const result = await this.request(endpoint, {
|
|
429
453
|
method: 'POST',
|
|
@@ -433,6 +457,7 @@ export class SDKClient {
|
|
|
433
457
|
}
|
|
434
458
|
|
|
435
459
|
async update(table, sysID, data) {
|
|
460
|
+
await this._guardTableMutation(table, sysID, data);
|
|
436
461
|
const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
|
|
437
462
|
const result = await this.request(endpoint, {
|
|
438
463
|
method: 'PUT',
|
|
@@ -442,6 +467,7 @@ export class SDKClient {
|
|
|
442
467
|
}
|
|
443
468
|
|
|
444
469
|
async delete(table, sysID) {
|
|
470
|
+
await this._guardTableMutation(table, sysID);
|
|
445
471
|
const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
|
|
446
472
|
await this.request(endpoint, { method: 'DELETE' });
|
|
447
473
|
}
|
package/src/setup-preferences.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import * as prompts from './prompts.js';
|
|
2
2
|
const { confirm, select, input } = prompts;
|
|
3
|
-
import { ensureLocalDocumentation } from './commands/docs/local.js';
|
|
4
3
|
import { saveConfig } from './config.js';
|
|
5
|
-
import { docsServiceUrl, DEFAULT_DOCS_URL } from './commands/docs/client.js';
|
|
6
4
|
|
|
7
5
|
export function connectionPreferences(config, existing = {}, flags = {}) {
|
|
8
6
|
const saved = { read_only: false, skip_confirmations: false, include_counts: true };
|
|
@@ -32,11 +30,13 @@ export async function chooseConnectionPreferences(config, flags = {}, prompts =
|
|
|
32
30
|
}
|
|
33
31
|
|
|
34
32
|
export async function configureDocumentation(config, prompts = { input, confirm }) {
|
|
33
|
+
const { docsServiceUrl, DEFAULT_DOCS_URL } = await import('./commands/docs/client.js');
|
|
35
34
|
const current = config.docs || { source: 'hosted', url: DEFAULT_DOCS_URL };
|
|
36
35
|
const hosted = await prompts.confirm({ message: 'Use JSN-hosted documentation?', default: current.source === 'hosted' });
|
|
37
36
|
const next = { source: hosted ? 'hosted' : 'custom', url: DEFAULT_DOCS_URL };
|
|
38
37
|
if (!hosted && await prompts.confirm({ message: 'Run a local documentation server for you?', default: current.source !== 'custom' })) {
|
|
39
38
|
next.source = 'local';
|
|
39
|
+
const { ensureLocalDocumentation } = await import('./commands/docs/local.js');
|
|
40
40
|
next.url = (await ensureLocalDocumentation()).url;
|
|
41
41
|
} else if (!hosted) {
|
|
42
42
|
next.url = await prompts.input({ message: 'Docs service base URL:', default: current.source === 'custom' ? current.url : 'http://127.0.0.1:3000',
|
|
@@ -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
|
+
}
|