@jacebenson/jsn 5.5.10-dev.233.1 → 5.5.10-dev.234.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 +1 -1
- package/src/cli.js +2 -0
- package/src/commands/document.js +31 -0
- package/src/help.js +2 -1
- package/src/instance-documentation.js +237 -0
- package/src/output.js +11 -3
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -42,6 +42,7 @@ import { platformCmd } from './commands/platform.js';
|
|
|
42
42
|
import { codesearchCmd } from './commands/codesearch.js';
|
|
43
43
|
import { versionCmd } from './commands/version.js';
|
|
44
44
|
import { upgradeCmd } from './commands/upgrade.js';
|
|
45
|
+
import { documentCmd } from './commands/document.js';
|
|
45
46
|
import { skillCmd, checkSkill } from './commands/skill.js';
|
|
46
47
|
import { getVersion, checkLatest, getReleaseChannel, getInstallCommand } from './commands/version.js';
|
|
47
48
|
|
|
@@ -456,6 +457,7 @@ export function buildCLI() {
|
|
|
456
457
|
.command(docsCmd(wrap))
|
|
457
458
|
.command(versionCmd(wrap))
|
|
458
459
|
.command(upgradeCmd(wrap))
|
|
460
|
+
.command(documentCmd(wrap))
|
|
459
461
|
.command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
|
|
460
462
|
.demandCommand(1, 'You must specify a command')
|
|
461
463
|
.onParentDiscovery((argv, { path, subcommands }) => {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { declareCapabilities } from '../capabilities.js';
|
|
2
|
+
import { DOCUMENT_BUDGETS, collectInstanceDocumentation, renderInstanceDocumentation, writeDocumentFile } from '../instance-documentation.js';
|
|
3
|
+
|
|
4
|
+
declareCapabilities('document', { mutationSubcommands: [], skipDailyChecks: true });
|
|
5
|
+
|
|
6
|
+
export function documentCmd(wrap) {
|
|
7
|
+
return {
|
|
8
|
+
command: 'document',
|
|
9
|
+
describe: 'Create bounded read-only instance configuration documentation',
|
|
10
|
+
builder: y => y.command({
|
|
11
|
+
command: 'instance',
|
|
12
|
+
describe: 'Generate deterministic Markdown/Mermaid from safe metadata. Requires --profile.',
|
|
13
|
+
builder: child => {
|
|
14
|
+
child.option('output', { type: 'string', describe: 'New Markdown file; never overwrites. POSIX mode 0600; Windows inherits directory ACLs; use a private directory.' });
|
|
15
|
+
for (const [name, [fallback, min, max]] of Object.entries(DOCUMENT_BUDGETS)) {
|
|
16
|
+
const flag = name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
|
|
17
|
+
child.option(flag, { type: 'number', default: fallback, describe: `${name} budget (${min}–${max})` });
|
|
18
|
+
}
|
|
19
|
+
return child;
|
|
20
|
+
},
|
|
21
|
+
handler: wrap(async (argv, app) => {
|
|
22
|
+
const data = await collectInstanceDocumentation(argv, app);
|
|
23
|
+
data.markdown = renderInstanceDocumentation(data);
|
|
24
|
+
app.output.validateExtraction(data);
|
|
25
|
+
if (argv.output) writeDocumentFile(argv.output, data.markdown);
|
|
26
|
+
const human = !app.output.jqFilter && ['styled', 'markdown'].includes(app.output.effectiveFormat());
|
|
27
|
+
app.output.ok(human ? data.markdown : data);
|
|
28
|
+
}),
|
|
29
|
+
}).demandCommand(1),
|
|
30
|
+
};
|
|
31
|
+
}
|
package/src/help.js
CHANGED
|
@@ -171,6 +171,7 @@ const DEVELOPER_COMMANDS = [
|
|
|
171
171
|
{ name: 'graphql', desc: 'GraphQL queries' },
|
|
172
172
|
{ name: 'codesearch', desc: 'Search code across ServiceNow artifacts' },
|
|
173
173
|
{ name: 'docs', desc: 'Local ServiceNow documentation search' },
|
|
174
|
+
{ name: 'document', desc: 'Read-only instance configuration documentation' },
|
|
174
175
|
{ name: 'diff', desc: 'Compare records across configured profiles' },
|
|
175
176
|
{ name: 'perf', desc: 'Read-only performance capture and comparison' },
|
|
176
177
|
{ name: 'skill', desc: 'AI agent skill file (show, fetch, install)' },
|
|
@@ -276,7 +277,7 @@ function renderConciseHelp(config, registry, width) {
|
|
|
276
277
|
`\nCOMMON COMMANDS\n${renderRows(common.map((command) => ({ label: command.name, description: command.desc })), { width, indent: 2 })}`,
|
|
277
278
|
'',
|
|
278
279
|
'ALL COMMANDS BY GROUP',
|
|
279
|
-
...wrapText('names only; jsn --all-commands --help
|
|
280
|
+
...wrapText('names only; jsn --all-commands --help for details', { width }),
|
|
280
281
|
renderRows(groups, { width, indent: 2 }),
|
|
281
282
|
'',
|
|
282
283
|
'EXAMPLES',
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { errUsage } from './errors.js';
|
|
4
|
+
|
|
5
|
+
const identity = /^[0-9a-f]{32}$/i;
|
|
6
|
+
const tableName = /^[a-z][a-z0-9_]*$/;
|
|
7
|
+
const common = ['sys_id', 'sys_scope', 'sys_package', 'sys_updated_on'];
|
|
8
|
+
const fields = {
|
|
9
|
+
sys_scope: ['sys_id', 'name', 'scope', 'sys_class_name', 'sys_updated_on'],
|
|
10
|
+
sys_db_object: [...common, 'name', 'label', 'super_class'],
|
|
11
|
+
sys_dictionary: [...common, 'name', 'element', 'column_label', 'internal_type', 'reference', 'mandatory', 'read_only'],
|
|
12
|
+
sys_script: [...common, 'name', 'collection', 'active', 'when', 'order', 'action_insert', 'action_update', 'action_delete', 'action_query'],
|
|
13
|
+
sys_script_client: [...common, 'name', 'table', 'active', 'type', 'field', 'applies_extended'],
|
|
14
|
+
sys_ui_policy: [...common, 'short_description', 'table', 'active', 'on_load', 'reverse_if_false'],
|
|
15
|
+
sys_ui_action: [...common, 'name', 'table', 'active', 'action_name', 'client', 'form_button', 'list_button'],
|
|
16
|
+
sys_script_include: [...common, 'name', 'api_name', 'access', 'active', 'client_callable'],
|
|
17
|
+
sys_hub_flow: [...common, 'name', 'active'],
|
|
18
|
+
sp_page: [...common, 'id', 'title'],
|
|
19
|
+
sp_widget: [...common, 'id', 'name'],
|
|
20
|
+
sp_container: [...common, 'name', 'sp_page', 'order'],
|
|
21
|
+
sp_row: [...common, 'sp_container', 'order'],
|
|
22
|
+
sp_column: [...common, 'sp_row', 'order'],
|
|
23
|
+
sp_instance: [...common, 'title', 'sp_column', 'sp_widget', 'order'],
|
|
24
|
+
sys_rest_message: [...common, 'name', 'active'],
|
|
25
|
+
sys_soap_message: [...common, 'name', 'active'],
|
|
26
|
+
sysauto_script: [...common, 'name', 'active', 'run_type'],
|
|
27
|
+
};
|
|
28
|
+
const labels = { sys_db_object: 'Tables', sys_dictionary: 'Fields', sys_script: 'Business rules', sys_script_client: 'Client scripts', sys_ui_policy: 'UI policies', sys_ui_action: 'UI actions', sys_script_include: 'Script Includes', sys_hub_flow: 'Flows', sp_page: 'Portal pages', sp_widget: 'Portal widgets', sp_container: 'Portal containers', sp_row: 'Portal rows', sp_column: 'Portal columns', sp_instance: 'Widget instances', sys_rest_message: 'REST integrations', sys_soap_message: 'SOAP integrations', sysauto_script: 'Scheduled automation' };
|
|
29
|
+
export const DOCUMENT_BUDGETS = {
|
|
30
|
+
pageSize: [25, 1, 100], discoveryPages: [2, 1, 5], applications: [3, 1, 6], detailPages: [1, 1, 3], maxRequests: [96, 1, 200],
|
|
31
|
+
};
|
|
32
|
+
const raw = input => {
|
|
33
|
+
const value = input && typeof input === 'object' ? input.value : input;
|
|
34
|
+
return ['string', 'number', 'boolean'].includes(typeof value) ? String(value).slice(0, 512) : null;
|
|
35
|
+
};
|
|
36
|
+
const sort = rows => rows.sort((a, b) => String(a.sys_id).localeCompare(String(b.sys_id), 'en'));
|
|
37
|
+
const safeIds = rows => [...new Set(rows.map(row => row.sys_id).filter(value => identity.test(value || '')))];
|
|
38
|
+
|
|
39
|
+
export function validateDocument(argv) {
|
|
40
|
+
if (typeof argv.profile !== 'string' || !argv.profile.trim()) throw errUsage('Instance documentation requires explicit --profile.');
|
|
41
|
+
if (argv.instance) throw errUsage('Use --profile without --instance for instance documentation.');
|
|
42
|
+
const budgets = {};
|
|
43
|
+
for (const [name, [fallback, min, max]] of Object.entries(DOCUMENT_BUDGETS)) {
|
|
44
|
+
const n = argv[name] ?? fallback;
|
|
45
|
+
if (!Number.isInteger(n) || n < min || n > max) throw errUsage(`Invalid ${name}: use an integer from ${min} to ${max}.`);
|
|
46
|
+
budgets[name] = n;
|
|
47
|
+
}
|
|
48
|
+
if (argv.output !== undefined) {
|
|
49
|
+
if (typeof argv.output !== 'string' || !argv.output.trim()) throw errUsage('--output must name a new file.');
|
|
50
|
+
try { fs.lstatSync(argv.output); throw errUsage('--output already exists; refusing to overwrite.'); }
|
|
51
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
52
|
+
if (!fs.statSync(path.dirname(path.resolve(argv.output))).isDirectory()) throw errUsage('--output parent must be a directory.');
|
|
53
|
+
}
|
|
54
|
+
return budgets;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A namespace string never establishes ownership. Missing/unknown references stay unresolved. */
|
|
58
|
+
export function documentOwner(row, candidates) {
|
|
59
|
+
const ownership = [row.sys_scope, row.sys_package];
|
|
60
|
+
if (!Object.hasOwn(row, 'sys_scope') || !Object.hasOwn(row, 'sys_package') || ownership.some(ref => typeof ref !== 'string' || !ref.trim())) return { kind: 'unresolved', reason: 'missing_ownership_fields' };
|
|
61
|
+
const refs = ownership.filter(ref => ref !== 'global');
|
|
62
|
+
if (refs.some(ref => !candidates.some(c => c.identity === ref))) return { kind: 'unresolved', reason: 'unknown_ownership_reference' };
|
|
63
|
+
if (new Set(refs).size > 1) return { kind: 'unresolved', reason: 'conflicting_ownership_references' };
|
|
64
|
+
return refs.length ? { kind: 'application', identity: refs[0] } : { kind: 'unassigned-global' };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function collectInstanceDocumentation(argv, app) {
|
|
68
|
+
const budgets = validateDocument(argv);
|
|
69
|
+
app.requireInstance();
|
|
70
|
+
const evidence = { schema_version: 1, profile: argv.profile, observed_at: new Date().toISOString(), status: 'incomplete',
|
|
71
|
+
release_identity: 'unknown', customization_evidence: 'not_collected', budgets, requests_used: 0,
|
|
72
|
+
candidates: [], applications: [], global_candidates: [], global_details: [], unresolved: [], sources: [], portal_relations: [],
|
|
73
|
+
limitations: ['Bounded configuration metadata, not execution, customer authorship, baseline differences or effective access.',
|
|
74
|
+
'Completeness is unknown. No provider count was collected; short or empty pages do not prove absence.',
|
|
75
|
+
'Scripts, conditions, defaults, URLs, credentials, bodies, business records and execution telemetry are not collected.',
|
|
76
|
+
'Instance release/build identity and existing customization evidence were not collected.',
|
|
77
|
+
'Inherited behavior, flow internals, nested portal rows, catalog configuration and standalone/OOTB changes remain gaps.'] };
|
|
78
|
+
// Every Table API call, including schema discovery, passes this budget and strict reader.
|
|
79
|
+
async function read(table, query, pages = budgets.detailPages, requestedFields = fields[table]) {
|
|
80
|
+
const rows = [], seen = new Set();
|
|
81
|
+
for (let page = 0; page < pages; page++) {
|
|
82
|
+
const source = { id: `source-${evidence.sources.length + 1}`, resource: `/api/now/table/${table}`, table, method: 'GET',
|
|
83
|
+
fields: [...requestedFields], query, observed_at: new Date().toISOString(),
|
|
84
|
+
bounds: { limit: budgets.pageSize, offset: page * budgets.pageSize, page: page + 1, max_pages: pages },
|
|
85
|
+
count: null, continuation: 'unknown', completeness: 'unknown', status: 'not_collected', reasons: [], records: [] };
|
|
86
|
+
evidence.sources.push(source);
|
|
87
|
+
if (evidence.requests_used >= budgets.maxRequests) { source.status = 'truncated'; source.reasons.push('request_budget'); break; }
|
|
88
|
+
evidence.requests_used++;
|
|
89
|
+
try {
|
|
90
|
+
const result = await app.sdk.listStrict(table, new URLSearchParams({ sysparm_fields: requestedFields.join(','), sysparm_query: query,
|
|
91
|
+
sysparm_limit: String(budgets.pageSize), sysparm_offset: String(source.bounds.offset), sysparm_display_value: 'false' }));
|
|
92
|
+
source.count = result.length;
|
|
93
|
+
source.continuation = result.length >= budgets.pageSize ? 'possible' : 'unknown';
|
|
94
|
+
source.status = 'observed';
|
|
95
|
+
if (result.length >= budgets.pageSize && page + 1 === pages) { source.status = 'truncated'; source.reasons.push('page_budget'); }
|
|
96
|
+
if (result.length > budgets.pageSize) source.reasons.push('provider_over_return');
|
|
97
|
+
const missing = new Set();
|
|
98
|
+
for (const input of result.slice(0, budgets.pageSize)) {
|
|
99
|
+
const row = Object.fromEntries(requestedFields.filter(field => {
|
|
100
|
+
if (!Object.hasOwn(input || {}, field)) { missing.add(field); return false; } return true;
|
|
101
|
+
}).map(field => [field, raw(input[field])]));
|
|
102
|
+
source.records.push(row);
|
|
103
|
+
if (!row.sys_id || seen.has(row.sys_id)) { source.reasons.push(row.sys_id ? 'duplicate_record' : 'missing_record_identity'); continue; }
|
|
104
|
+
seen.add(row.sys_id); rows.push({ ...row, source: source.id });
|
|
105
|
+
}
|
|
106
|
+
source.missing_fields = [...missing].sort();
|
|
107
|
+
if (missing.size) { source.reasons.push('missing_fields'); if (source.status === 'observed') source.status = 'missing-fields'; }
|
|
108
|
+
if (!result.length) source.reasons.push('empty_page_not_completeness_proof');
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error.status === 403) { source.status = 'denied'; source.reasons.push('http_403'); }
|
|
111
|
+
else if (error.status === 404 || error.code === 'malformed_response') { source.status = 'unavailable'; source.reasons.push(error.status === 404 ? 'http_404' : 'malformed_response'); }
|
|
112
|
+
else throw error;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return sort(rows);
|
|
117
|
+
}
|
|
118
|
+
const hierarchy = await read('sys_db_object', 'nameINsys_app,sys_scope,sys_package^ORDERBYsys_id');
|
|
119
|
+
const ownership = await read('sys_dictionary', 'name=sys_metadata^elementINsys_scope,sys_package^ORDERBYsys_id', 1, ['sys_id', 'name', 'element', 'reference']);
|
|
120
|
+
const scopeClass = hierarchy.find(r => r.name === 'sys_scope'), packageClass = hierarchy.find(r => r.name === 'sys_package');
|
|
121
|
+
const validIdentitySchema = scopeClass && packageClass && hierarchy.some(r => r.name === 'sys_app' && r.super_class === scopeClass.sys_id)
|
|
122
|
+
&& scopeClass.super_class === packageClass.sys_id && [['sys_scope', 'sys_scope'], ['sys_package', 'sys_package']].every(([element, reference]) => ownership.some(r => r.element === element && r.reference === reference));
|
|
123
|
+
if (!validIdentitySchema) { evidence.limitations.push('Identity schema not established; dependent application and Global discovery refused.'); return evidence; }
|
|
124
|
+
const discovered = await read('sys_scope', 'ORDERBYsys_id', budgets.discoveryPages);
|
|
125
|
+
evidence.candidates = discovered.filter(row => identity.test(row.sys_id || '')).map(row => ({ identity: row.sys_id, name: row.name || 'Unnamed application', namespace: row.scope ?? 'unknown', class: row.sys_class_name ?? 'unknown', source: row.source, selected: false,
|
|
126
|
+
provenance: 'Observed application record; class and Store status do not prove customer authorship.' }));
|
|
127
|
+
const globalApps = evidence.candidates.filter(c => c.namespace === 'global'), scopedApps = evidence.candidates.filter(c => c.namespace !== 'global');
|
|
128
|
+
const selected = [...globalApps.slice(0, 1), ...scopedApps.slice(0, 1), ...evidence.candidates].filter((c, index, list) => list.findIndex(x => x.identity === c.identity) === index).slice(0, budgets.applications);
|
|
129
|
+
for (const candidate of selected) candidate.selected = true;
|
|
130
|
+
const classify = (records, expected, allowDirect = false) => records.filter(record => {
|
|
131
|
+
const owner = documentOwner(record, evidence.candidates);
|
|
132
|
+
if (owner.kind === 'unresolved') { evidence.unresolved.push({ record, ...owner }); return false; }
|
|
133
|
+
return expected ? owner.identity === expected || allowDirect && owner.kind === 'unassigned-global' : owner.kind === 'unassigned-global';
|
|
134
|
+
});
|
|
135
|
+
const portalSchema = await read('sys_dictionary', 'nameINsp_container,sp_row,sp_column,sp_instance^ORDERBYsys_id', 1, ['sys_id', 'name', 'element', 'reference']);
|
|
136
|
+
const portalContracts = [['sp_container', 'sp_page', 'sp_page'], ['sp_row', 'sp_container', 'sp_container'], ['sp_column', 'sp_row', 'sp_row'], ['sp_instance', 'sp_column', 'sp_column'], ['sp_instance', 'sp_widget', 'sp_widget']];
|
|
137
|
+
const portalVerified = portalContracts.every(([name, element, reference]) => portalSchema.some(r => r.name === name && r.element === element && r.reference === reference));
|
|
138
|
+
if (!portalVerified) evidence.limitations.push('Portal reference schema not established; composition collection refused.');
|
|
139
|
+
for (const candidate of selected) {
|
|
140
|
+
const application = { ...candidate, sections: {}, portal_relations: [] };
|
|
141
|
+
evidence.applications.push(application);
|
|
142
|
+
const query = `sys_scope=${candidate.identity}^ORsys_package=${candidate.identity}`;
|
|
143
|
+
const tables = classify(await read('sys_db_object', `${query}^ORDERBYsys_id`), candidate.identity);
|
|
144
|
+
application.sections.sys_db_object = tables;
|
|
145
|
+
const names = [...new Set(tables.map(t => t.name).filter(n => tableName.test(n || '')))];
|
|
146
|
+
for (const table of ['sys_script', 'sys_script_client', 'sys_ui_policy', 'sys_ui_action', 'sys_script_include', 'sys_hub_flow', 'sp_page', 'sp_widget', 'sys_rest_message', 'sys_soap_message', 'sysauto_script']) {
|
|
147
|
+
const target = table === 'sys_script' ? 'collection' : ['sys_script_client', 'sys_ui_policy', 'sys_ui_action'].includes(table) ? 'table' : null;
|
|
148
|
+
const selector = target && names.length ? `${query}^OR${target}IN${names.join(',')}` : query;
|
|
149
|
+
const records = classify(await read(table, `${selector}^ORDERBYsys_id`), candidate.identity, Boolean(target));
|
|
150
|
+
application.sections[table] = records.filter(row => !target || documentOwner(row, evidence.candidates).identity === candidate.identity || names.includes(row[target]));
|
|
151
|
+
}
|
|
152
|
+
application.sections.sys_dictionary = names.length ? classify(await read('sys_dictionary', `nameIN${names.join(',')}^ORDERBYsys_id`), candidate.identity, true) : [];
|
|
153
|
+
if (portalVerified && application.sections.sp_page.length) {
|
|
154
|
+
let parents = application.sections.sp_page;
|
|
155
|
+
for (const [table, field] of portalContracts.slice(0, 4)) {
|
|
156
|
+
const ids = safeIds(parents);
|
|
157
|
+
const records = ids.length ? classify(await read(table, `${field}IN${ids.join(',')}^ORDERBYsys_id`), candidate.identity, true).filter(r => ids.includes(r[field])) : [];
|
|
158
|
+
application.sections[table] = records; parents = records;
|
|
159
|
+
}
|
|
160
|
+
const widgetIds = [...new Set((application.sections.sp_instance || []).map(r => r.sp_widget).filter(v => identity.test(v || '')))];
|
|
161
|
+
if (widgetIds.length) {
|
|
162
|
+
const endpoints = classify(await read('sp_widget', `sys_idIN${widgetIds.join(',')}^ORDERBYsys_id`), candidate.identity, true).filter(r => widgetIds.includes(r.sys_id));
|
|
163
|
+
// Endpoint reads supplement the independent inventory, never replace it.
|
|
164
|
+
// Retain each original row's source, including when the follow-up is denied.
|
|
165
|
+
const widgets = new Map(application.sections.sp_widget.map(row => [row.sys_id, row]));
|
|
166
|
+
for (const endpoint of endpoints) if (!widgets.has(endpoint.sys_id)) widgets.set(endpoint.sys_id, endpoint);
|
|
167
|
+
application.sections.sp_widget = sort([...widgets.values()]);
|
|
168
|
+
}
|
|
169
|
+
for (const instance of application.sections.sp_instance || []) {
|
|
170
|
+
const column = application.sections.sp_column.find(r => r.sys_id === instance.sp_column);
|
|
171
|
+
const row = application.sections.sp_row.find(r => r.sys_id === column?.sp_row);
|
|
172
|
+
const container = application.sections.sp_container.find(r => r.sys_id === row?.sp_container);
|
|
173
|
+
const page = application.sections.sp_page.find(r => r.sys_id === container?.sp_page);
|
|
174
|
+
const widget = application.sections.sp_widget.find(r => r.sys_id === instance.sp_widget);
|
|
175
|
+
if (page && widget) {
|
|
176
|
+
const relation = { application: candidate.identity, page: page.sys_id, widget: widget.sys_id,
|
|
177
|
+
page_title: page.title || page.id, widget_name: widget.name || widget.id,
|
|
178
|
+
path: [page, container, row, column, instance, widget].map(r => ({ sys_id: r.sys_id, source: r.source })), schema_sources: [...new Set(portalSchema.map(r => r.source))] };
|
|
179
|
+
evidence.portal_relations.push(relation); application.portal_relations.push(relation);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const leads = await read('sys_db_object', 'sys_scope=global^nameSTARTSWITHu_^ORDERBYsys_id');
|
|
185
|
+
evidence.global_candidates = classify(leads).filter(r => r.name?.startsWith('u_'));
|
|
186
|
+
for (const lead of evidence.global_candidates.slice(0, 2)) {
|
|
187
|
+
if (!tableName.test(lead.name)) continue;
|
|
188
|
+
const detail = { table: lead, sections: {} };
|
|
189
|
+
evidence.global_details.push(detail);
|
|
190
|
+
for (const [table, field] of [['sys_dictionary', 'name'], ['sys_script', 'collection'], ['sys_script_client', 'table'], ['sys_ui_policy', 'table'], ['sys_ui_action', 'table']]) detail.sections[table] = classify(await read(table, `${field}=${lead.name}^ORDERBYsys_id`)).filter(r => r[field] === lead.name);
|
|
191
|
+
}
|
|
192
|
+
return evidence;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Numeric entities prevent Markdown/HTML/autolink syntax from metadata labels.
|
|
196
|
+
const md = value => String(value ?? 'unknown').replace(/[^\p{L}\p{N} \n]/gu, char => `&#${char.codePointAt(0)};`).replace(/[\r\n]/g, ' ');
|
|
197
|
+
// Mermaid uses only generated identifiers and an inert, bounded label alphabet.
|
|
198
|
+
const mermaid = value => String(value ?? 'unknown').replace(/[^\p{L}\p{N} ]/gu, ' ').slice(0, 100);
|
|
199
|
+
export function renderInstanceDocumentation(evidence) {
|
|
200
|
+
const lines = ['# Instance configuration documentation', '', `Profile: ${md(evidence.profile)}. Observed: ${md(evidence.observed_at)}.`, '',
|
|
201
|
+
'Release/build identity: unknown. Coverage: incomplete.', '', ...evidence.limitations.map(text => `- ${md(text)}`), '', '## Application discovery', '',
|
|
202
|
+
'| Application | Namespace | Exact identity | Detail |', '| --- | --- | --- | --- |'];
|
|
203
|
+
for (const c of evidence.candidates) lines.push(`| ${md(c.name)} | ${md(c.namespace)} | ${md(c.identity)} | ${c.selected ? 'selected' : 'deferred by budget'} |`);
|
|
204
|
+
const section = (table, rows) => {
|
|
205
|
+
lines.push(`### ${labels[table] || table}`, '');
|
|
206
|
+
if (!rows.length) { lines.push('No rows established in this bounded collection. See source receipts.', ''); return; }
|
|
207
|
+
const columns = fields[table].filter(f => !['sys_scope', 'sys_package'].includes(f));
|
|
208
|
+
lines.push(`| ${columns.join(' | ')} | Source |`, `| ${columns.map(() => '---').join(' | ')} | --- |`);
|
|
209
|
+
for (const row of rows) lines.push(`| ${columns.map(c => md(row[c])).join(' | ')} | ${md(row.source)} |`);
|
|
210
|
+
lines.push('');
|
|
211
|
+
};
|
|
212
|
+
for (const app of evidence.applications) {
|
|
213
|
+
lines.push(`## ${md(app.name)} ${app.namespace === 'global' ? 'Global application' : 'application'}`, '',
|
|
214
|
+
'Exact ownership and configured target metadata only. No execution or customer-authorship claim.', '');
|
|
215
|
+
for (const [table, rows] of Object.entries(app.sections)) section(table, rows);
|
|
216
|
+
if (app.portal_relations.length) {
|
|
217
|
+
lines.push('### Verified portal page to widget references', '', '```mermaid', 'flowchart LR');
|
|
218
|
+
app.portal_relations.slice(0, 20).forEach((r, i) => lines.push(` p${i}["${mermaid(r.page_title)}"] -->|configured composition| w${i}["${mermaid(r.widget_name)}"]`));
|
|
219
|
+
lines.push('```', '', 'Collapsed exact-reference paths only. Layout children remain in supporting tables. At most 20 relations drawn.', '');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
lines.push('## Unassigned Global development candidates', '', 'Custom-named table leads only, not proof of customer authorship or baseline changes. Named Global applications are separate.', '');
|
|
223
|
+
section('sys_db_object', evidence.global_candidates);
|
|
224
|
+
for (const detail of evidence.global_details) { lines.push(`### ${md(detail.table.label || detail.table.name)}`, ''); for (const [table, rows] of Object.entries(detail.sections)) section(table, rows); }
|
|
225
|
+
lines.push('## Unresolved ownership', '', `${evidence.unresolved.length} returned records have unresolved ownership. Full projected references and reasons remain in JSON.`, '', '## Source receipts', '',
|
|
226
|
+
`Table requests used: ${evidence.requests_used}/${evidence.budgets.maxRequests}. Provider counts not collected. Completeness unknown.`, '');
|
|
227
|
+
for (const source of evidence.sources) lines.push(`### ${source.id}`, '',
|
|
228
|
+
`Resource: ${md(source.resource)}. Method: GET. Status: ${source.status}. Reasons: ${md(source.reasons.join(', ') || 'none')}.`,
|
|
229
|
+
`Fields: ${md(source.fields.join(', '))}. Query: ${md(source.query)}.`,
|
|
230
|
+
`Observed: ${md(source.observed_at)}. Limit: ${source.bounds.limit}, offset: ${source.bounds.offset}, count: ${source.count ?? 'unknown'}, continuation: ${source.continuation}. Completeness unknown.`, '');
|
|
231
|
+
return lines.join('\n') + '\n';
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function writeDocumentFile(destination, markdown) {
|
|
235
|
+
const fd = fs.openSync(destination, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600);
|
|
236
|
+
try { fs.writeFileSync(fd, markdown, 'utf8'); } finally { fs.closeSync(fd); }
|
|
237
|
+
}
|
package/src/output.js
CHANGED
|
@@ -126,6 +126,16 @@ export class OutputWriter {
|
|
|
126
126
|
return this.format;
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
+
// Export callers can preflight exactly the extraction that ok() will emit,
|
|
130
|
+
// before creating a local file or performing another irreversible side effect.
|
|
131
|
+
validateExtraction(data, opts = {}) {
|
|
132
|
+
if (!this.jqFilter) return undefined;
|
|
133
|
+
const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
|
|
134
|
+
const value = resolvePath(envelope, this.jqFilter);
|
|
135
|
+
if (value === undefined) throw errExtractionNotFound(this.jqFilter);
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
|
|
129
139
|
ok(data, opts = {}) {
|
|
130
140
|
// --get extractor: resolve against the JSON envelope and print just that
|
|
131
141
|
// value as JSON. Takes precedence over styling/table formats — a path
|
|
@@ -136,9 +146,7 @@ export class OutputWriter {
|
|
|
136
146
|
// typo looked like a successful empty result until the next tool in the
|
|
137
147
|
// pipeline failed to parse it. Present null/false/0/"" still print as-is.
|
|
138
148
|
if (this.jqFilter) {
|
|
139
|
-
const
|
|
140
|
-
const value = resolvePath(envelope, this.jqFilter);
|
|
141
|
-
if (value === undefined) throw errExtractionNotFound(this.jqFilter);
|
|
149
|
+
const value = this.validateExtraction(data, opts);
|
|
142
150
|
const indent = this.verbose && !this.raw ? 2 : undefined;
|
|
143
151
|
const text = this.raw && typeof value === 'string' ? value : JSON.stringify(value, null, indent);
|
|
144
152
|
this.writer.write(text + '\n');
|