@jacebenson/jsn 5.5.10 → 5.5.11-dev.241.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 +25 -0
- package/package.json +1 -1
- package/src/access-analyzer.js +92 -0
- package/src/app.js +5 -0
- package/src/auth/credential-store.js +3 -3
- package/src/auth/windows-credential-store.ps1 +1 -1
- package/src/cli-adapter.js +53 -3
- package/src/cli.js +17 -3
- package/src/command-audience.js +3 -1
- package/src/command-families.js +10 -3
- package/src/commands/_generic.js +15 -5
- package/src/commands/_simple.js +14 -1
- package/src/commands/_ticket.js +7 -1
- package/src/commands/access-analyzer.js +37 -0
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- package/src/commands/auth.js +6 -0
- package/src/commands/cases.js +3 -0
- package/src/commands/catalog.js +1 -1
- package/src/commands/cmdb.js +3 -0
- package/src/commands/decisiontables.js +1 -1
- package/src/commands/discover.js +108 -8
- package/src/commands/document.js +31 -0
- package/src/commands/domains.js +1 -1
- package/src/commands/graphql.js +1 -1
- package/src/commands/groupmembers.js +1 -1
- package/src/commands/grouproles.js +1 -1
- package/src/commands/groups.js +1 -1
- package/src/commands/logs.js +3 -0
- package/src/commands/records.js +21 -0
- package/src/commands/rest.js +1 -1
- package/src/commands/scan.js +40 -5
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +1 -1
- package/src/commands/table-behavior.js +5 -0
- package/src/commands/tickets.js +9 -1
- package/src/commands/transactions.js +3 -0
- package/src/commands/updatesets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/context.js +19 -0
- package/src/help.js +3 -1
- package/src/instance-documentation.js +237 -0
- package/src/intended-context.js +30 -3
- package/src/output.js +15 -3
- package/src/query-cache.js +187 -0
- package/src/query-metadata.js +189 -0
- package/src/query-parse.js +201 -0
- package/src/query-validate.js +282 -0
- package/src/scan.js +92 -17
- package/src/sdk.js +3 -0
- package/src/table-behavior.js +1 -1
package/src/context.js
CHANGED
|
@@ -122,6 +122,25 @@ export async function readEffectiveUpdateSet(sdk) {
|
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
/**
|
|
126
|
+
* Read the application this authenticated session has selected.
|
|
127
|
+
*
|
|
128
|
+
* The platform stores the Global selection as the *absence* of the
|
|
129
|
+
* `apps.current_app` preference, so that preference alone can never prove
|
|
130
|
+
* Global. This endpoint reports the session's effective picker selection; a
|
|
131
|
+
* response without a readable `result.current` proves nothing and must never
|
|
132
|
+
* be interpreted as Global.
|
|
133
|
+
*/
|
|
134
|
+
export async function readEffectiveApplication(sdk) {
|
|
135
|
+
const endpoint = `${sdk.baseURL}/api/now/ui/concoursepicker/application`;
|
|
136
|
+
const response = await sdk.request(endpoint, { method: 'GET', readOnly: true });
|
|
137
|
+
const current = response?.result?.current;
|
|
138
|
+
if (typeof current !== 'string' || !current) {
|
|
139
|
+
throw new Error('Invalid application picker response: expected result.current.');
|
|
140
|
+
}
|
|
141
|
+
return { sys_id: current };
|
|
142
|
+
}
|
|
143
|
+
|
|
125
144
|
/** Verify capture consistency without ever changing the session. */
|
|
126
145
|
export async function alignUpdateSetCapture(sdk, intended) {
|
|
127
146
|
const effective = await readEffectiveUpdateSet(sdk);
|
package/src/help.js
CHANGED
|
@@ -93,6 +93,7 @@ const AUTOMATION_COMMANDS = [
|
|
|
93
93
|
];
|
|
94
94
|
|
|
95
95
|
const ACCESS_COMMANDS = [
|
|
96
|
+
{ name: 'access-analyzer', desc: 'Saved access analysis evidence (read-only)' },
|
|
96
97
|
{ name: 'acls', alias: 'acl', desc: 'Access controls' },
|
|
97
98
|
{ name: 'b4rules', alias: 'b4r', desc: 'Before-query business rules (see also Automation)' },
|
|
98
99
|
{ name: 'roles', alias: 'role', desc: 'Roles' },
|
|
@@ -171,6 +172,7 @@ const DEVELOPER_COMMANDS = [
|
|
|
171
172
|
{ name: 'graphql', desc: 'GraphQL queries' },
|
|
172
173
|
{ name: 'codesearch', desc: 'Search code across ServiceNow artifacts' },
|
|
173
174
|
{ name: 'docs', desc: 'Local ServiceNow documentation search' },
|
|
175
|
+
{ name: 'document', desc: 'Read-only instance configuration documentation' },
|
|
174
176
|
{ name: 'diff', desc: 'Compare records across configured profiles' },
|
|
175
177
|
{ name: 'perf', desc: 'Read-only performance capture and comparison' },
|
|
176
178
|
{ name: 'skill', desc: 'AI agent skill file (show, fetch, install)' },
|
|
@@ -276,7 +278,7 @@ function renderConciseHelp(config, registry, width) {
|
|
|
276
278
|
`\nCOMMON COMMANDS\n${renderRows(common.map((command) => ({ label: command.name, description: command.desc })), { width, indent: 2 })}`,
|
|
277
279
|
'',
|
|
278
280
|
'ALL COMMANDS BY GROUP',
|
|
279
|
-
...wrapText('
|
|
281
|
+
...wrapText('jsn --all-commands --help for details', { width }),
|
|
280
282
|
renderRows(groups, { width, indent: 2 }),
|
|
281
283
|
'',
|
|
282
284
|
'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/intended-context.js
CHANGED
|
@@ -1,13 +1,35 @@
|
|
|
1
1
|
// Intent comes from the task, never from the current provider preferences.
|
|
2
2
|
import { assertSafeExactMatch, getStringField } from './helpers.js';
|
|
3
3
|
import { errUsageHint } from './errors.js';
|
|
4
|
-
import { readEffectiveUpdateSet } from './context.js';
|
|
4
|
+
import { readEffectiveApplication, readEffectiveUpdateSet } from './context.js';
|
|
5
5
|
|
|
6
6
|
const CONTEXT_HINT = 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.';
|
|
7
|
+
const GLOBAL_APPLICATION = 'global';
|
|
7
8
|
|
|
8
9
|
export function contextFailure(message, hint = CONTEXT_HINT) {
|
|
9
10
|
return errUsageHint(message, hint);
|
|
10
11
|
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Prove Global from the live session when `apps.current_app` is absent.
|
|
15
|
+
*
|
|
16
|
+
* ServiceNow represents the Global application selection as the absence of the
|
|
17
|
+
* preference row, so a missing row is only *evidence* of Global when a fresh
|
|
18
|
+
* read of the session application picker says so. Anything else — a picker
|
|
19
|
+
* reporting another application, or a picker that cannot be read — is reported
|
|
20
|
+
* back as a `note` so the caller refuses instead of silently assuming Global
|
|
21
|
+
* and capturing the write into the wrong application.
|
|
22
|
+
*/
|
|
23
|
+
async function globalFromSession(sdk) {
|
|
24
|
+
try {
|
|
25
|
+
const effective = await readEffectiveApplication(sdk);
|
|
26
|
+
if (effective.sys_id === GLOBAL_APPLICATION) return { value: GLOBAL_APPLICATION };
|
|
27
|
+
return { note: `\nThe session application picker reports ${effective.sys_id}, not Global, and no apps.current_app preference is persisted for this user — the selection cannot be treated as Global.` };
|
|
28
|
+
} catch (error) {
|
|
29
|
+
return { note: `\nThe session application picker could not be read (${error.message}), so Global cannot be confirmed.` };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
11
33
|
const raw = (record, key) => record?.[key]?.value ?? record?.[key];
|
|
12
34
|
export async function exactContextRecord(sdk, table, field, identifier) {
|
|
13
35
|
if (typeof identifier !== 'string' || !identifier.trim()) throw contextFailure(`Missing intended ${table} identifier.`);
|
|
@@ -40,7 +62,7 @@ export async function readWriteContext(sdk) {
|
|
|
40
62
|
* branch below says what is actually wrong and names the command that fixes
|
|
41
63
|
* it.
|
|
42
64
|
*/
|
|
43
|
-
async function preference({ key, label, remediation, sessionTruth }) {
|
|
65
|
+
async function preference({ key, label, remediation, sessionTruth, sessionFallback }) {
|
|
44
66
|
let rows;
|
|
45
67
|
try {
|
|
46
68
|
rows = await sdk.list('sys_user_preference', new URLSearchParams({
|
|
@@ -53,8 +75,12 @@ export async function readWriteContext(sdk) {
|
|
|
53
75
|
);
|
|
54
76
|
}
|
|
55
77
|
if (rows.length === 0) {
|
|
78
|
+
// Only the documented Global representation (absent row + session picker
|
|
79
|
+
// reporting Global) may recover here; an unproven scope still fails.
|
|
80
|
+
const fallback = sessionFallback ? await sessionFallback() : null;
|
|
81
|
+
if (fallback?.value) return fallback.value;
|
|
56
82
|
throw contextFailure(
|
|
57
|
-
`No ${label} is selected for ${user.user_name}, so there is no capture context to verify this write against.${await sessionNote(sessionTruth)}`,
|
|
83
|
+
`No ${label} is selected for ${user.user_name}, so there is no capture context to verify this write against.${fallback?.note || ''}${await sessionNote(sessionTruth)}`,
|
|
58
84
|
`Select one first, then rerun the same command: ${remediation}. --expect-scope and --expect-update-set assert an existing selection; they cannot create one.`,
|
|
59
85
|
);
|
|
60
86
|
}
|
|
@@ -89,6 +115,7 @@ export async function readWriteContext(sdk) {
|
|
|
89
115
|
preference({
|
|
90
116
|
key: 'apps.current_app', label: 'application scope',
|
|
91
117
|
remediation: 'jsn scopes set "<scope value or name>"',
|
|
118
|
+
sessionFallback: () => globalFromSession(sdk),
|
|
92
119
|
}),
|
|
93
120
|
preference({
|
|
94
121
|
key: 'sys_update_set', label: 'update set',
|
package/src/output.js
CHANGED
|
@@ -126,7 +126,20 @@ 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 = {}) {
|
|
140
|
+
if (!['json', 'quiet'].includes(this.effectiveFormat()) && !this.jqFilter) {
|
|
141
|
+
for (const warning of (data?.query_validation ? data.warnings : opts.meta?.warnings) || [] ) this.errorWriter.write(`Warning: ${warning}\n`);
|
|
142
|
+
}
|
|
130
143
|
// --get extractor: resolve against the JSON envelope and print just that
|
|
131
144
|
// value as JSON. Takes precedence over styling/table formats — a path
|
|
132
145
|
// extract is inherently scriptable, not presentational.
|
|
@@ -136,9 +149,7 @@ export class OutputWriter {
|
|
|
136
149
|
// typo looked like a successful empty result until the next tool in the
|
|
137
150
|
// pipeline failed to parse it. Present null/false/0/"" still print as-is.
|
|
138
151
|
if (this.jqFilter) {
|
|
139
|
-
const
|
|
140
|
-
const value = resolvePath(envelope, this.jqFilter);
|
|
141
|
-
if (value === undefined) throw errExtractionNotFound(this.jqFilter);
|
|
152
|
+
const value = this.validateExtraction(data, opts);
|
|
142
153
|
const indent = this.verbose && !this.raw ? 2 : undefined;
|
|
143
154
|
const text = this.raw && typeof value === 'string' ? value : JSON.stringify(value, null, indent);
|
|
144
155
|
this.writer.write(text + '\n');
|
|
@@ -168,6 +179,7 @@ export class OutputWriter {
|
|
|
168
179
|
const format = this.effectiveFormat();
|
|
169
180
|
const e = error.code ? error : { code: 'unknown', message: String(error), hint: '' };
|
|
170
181
|
const resp = { ok: false, error: e.message, code: e.code, hint: e.hint || '' };
|
|
182
|
+
if (e.query_validation) resp.query_validation = e.query_validation;
|
|
171
183
|
if (e.resolution) resp.resolution = e.resolution;
|
|
172
184
|
if (e.context) resp.context = e.context;
|
|
173
185
|
if (e.status === 401 || e.status === 403) resp.status = e.status;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Five-minute metadata cache, isolated by instance + profile + authenticated
|
|
2
|
+
// principal + table. Only fully observed metadata is persisted; denied,
|
|
3
|
+
// unavailable and incomplete reads are never cached as fact.
|
|
4
|
+
//
|
|
5
|
+
// The cache is a latency tradeoff, not authorization: an ACL or schema change
|
|
6
|
+
// inside the TTL is not reflected, so every diagnostic says so.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { cacheDir } from './config.js';
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_TTL_MS = 300_000;
|
|
14
|
+
const VERSION = 3;
|
|
15
|
+
export const QUERY_CACHE_LIMITS = Object.freeze({ entries: 64, entryBytes: 262144, bytes: 8388608 });
|
|
16
|
+
const TABLE = /^[a-zA-Z0-9_]+$/;
|
|
17
|
+
|
|
18
|
+
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
19
|
+
|
|
20
|
+
export function identityKey(identity = {}, table = '') {
|
|
21
|
+
return digest([identity.instance || '', identity.profile || '', identity.principal || '', table].join('\n'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validIdentity(identity) {
|
|
25
|
+
return Boolean(identity && identity.instance && identity.principal && identity.principal !== 'guest');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function validPayload(payload) {
|
|
29
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)
|
|
30
|
+
|| payload.complete !== true || payload.source !== 'table-api'
|
|
31
|
+
|| !Number.isSafeInteger(payload.total) || payload.total <= 0 || payload.total >= 1000) return false;
|
|
32
|
+
if (payload.state !== 'observed') return false;
|
|
33
|
+
if (!Array.isArray(payload.hierarchy) || !payload.hierarchy.length || !payload.hierarchy.every(name => TABLE.test(name))) return false;
|
|
34
|
+
if (!payload.fields || typeof payload.fields !== 'object' || Array.isArray(payload.fields)) return false;
|
|
35
|
+
let count = 0;
|
|
36
|
+
for (const [owner, fields] of Object.entries(payload.fields)) {
|
|
37
|
+
if (!payload.hierarchy.includes(owner) || !fields || typeof fields !== 'object' || Array.isArray(fields)) return false;
|
|
38
|
+
for (const [element, definition] of Object.entries(fields)) {
|
|
39
|
+
if (!TABLE.test(element) || !definition || typeof definition !== 'object') return false;
|
|
40
|
+
if (typeof definition.type !== 'string' || !definition.type || definition.type === 'unknown'
|
|
41
|
+
|| (definition.type === 'reference' && !definition.reference)) return false;
|
|
42
|
+
if (typeof definition.reference !== 'string' || (definition.reference && !TABLE.test(definition.reference))) return false;
|
|
43
|
+
count++;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return count === payload.total;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {{identity:{instance:string,profile:string,principal:string},
|
|
51
|
+
* ttlMs?:number, dir?:string}} options
|
|
52
|
+
*/
|
|
53
|
+
export function createQueryMetadataCache({ identity = {}, ttlMs = DEFAULT_TTL_MS, dir = '', platform = process.platform } = {}) {
|
|
54
|
+
identity = { ...identity };
|
|
55
|
+
ttlMs = Math.min(DEFAULT_TTL_MS, Math.max(0, ttlMs));
|
|
56
|
+
const memory = new Map();
|
|
57
|
+
// Match flow-search policy: Node mode bits cannot prove Windows private DACLs.
|
|
58
|
+
const persist = platform !== 'win32' && validIdentity(identity);
|
|
59
|
+
const root = dir || path.join(cacheDir(), 'query-metadata');
|
|
60
|
+
const keyFor = table => identityKey(identity, table);
|
|
61
|
+
const fileFor = key => path.join(root, `${key}.json`);
|
|
62
|
+
function boundMemory() {
|
|
63
|
+
let bytes = 0;
|
|
64
|
+
for (const [table, entry] of [...memory].reverse()) {
|
|
65
|
+
bytes += Buffer.byteLength(JSON.stringify(entry.payload));
|
|
66
|
+
if (bytes > QUERY_CACHE_LIMITS.bytes) memory.delete(table);
|
|
67
|
+
}
|
|
68
|
+
while (memory.size > QUERY_CACHE_LIMITS.entries) memory.delete(memory.keys().next().value);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
function readFile(table) {
|
|
73
|
+
if (!persist) return null;
|
|
74
|
+
const key = keyFor(table);
|
|
75
|
+
const file = fileFor(key);
|
|
76
|
+
try {
|
|
77
|
+
const parent = fs.lstatSync(root);
|
|
78
|
+
if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return null;
|
|
79
|
+
const stat = fs.lstatSync(file);
|
|
80
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > QUERY_CACHE_LIMITS.entryBytes
|
|
81
|
+
|| (process.getuid && stat.uid !== process.getuid()) || (stat.mode & 0o077) !== 0) return null; // foreign permissions: refuse
|
|
82
|
+
const entry = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
83
|
+
if (!entry || entry.version !== VERSION || entry.key !== key) return null;
|
|
84
|
+
if (entry.instance !== identity.instance || entry.profile !== (identity.profile || '')
|
|
85
|
+
|| entry.principal !== identity.principal || entry.table !== table) return null;
|
|
86
|
+
if (!Number.isSafeInteger(entry.fetched_at) || entry.fetched_at > Date.now() || Date.now() - entry.fetched_at >= ttlMs) return null;
|
|
87
|
+
if (!validPayload(entry.payload) || entry.payload.hierarchy[0] !== table) return null;
|
|
88
|
+
return { payload: entry.payload, fetched_at: entry.fetched_at };
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function writeFile(table, payload) {
|
|
95
|
+
if (!persist || !validPayload(payload)) return;
|
|
96
|
+
const key = keyFor(table);
|
|
97
|
+
const file = fileFor(key);
|
|
98
|
+
const temp = path.join(root, `.${key}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`);
|
|
99
|
+
try {
|
|
100
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
101
|
+
const parent = fs.lstatSync(root);
|
|
102
|
+
if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return;
|
|
103
|
+
const body = JSON.stringify({
|
|
104
|
+
version: VERSION, key,
|
|
105
|
+
instance: identity.instance, profile: identity.profile || '',
|
|
106
|
+
principal: identity.principal, table, fetched_at: Date.now(), payload,
|
|
107
|
+
});
|
|
108
|
+
if (Buffer.byteLength(body) > QUERY_CACHE_LIMITS.entryBytes) return;
|
|
109
|
+
fs.writeFileSync(temp, body, { mode: 0o600, flag: 'wx' });
|
|
110
|
+
fs.renameSync(temp, file);
|
|
111
|
+
const files = fs.readdirSync(root).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
|
|
112
|
+
.map(name => ({ name, stat: fs.lstatSync(path.join(root, name)) }))
|
|
113
|
+
.filter(item => item.stat.isFile()).sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
114
|
+
let bytes = 0;
|
|
115
|
+
for (const [index, item] of files.entries()) {
|
|
116
|
+
bytes += item.stat.size;
|
|
117
|
+
if (index >= QUERY_CACHE_LIMITS.entries || bytes > QUERY_CACHE_LIMITS.bytes) fs.unlinkSync(path.join(root, item.name));
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
try { fs.unlinkSync(temp); } catch { /* best effort */ }
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
identity,
|
|
126
|
+
persistent: persist,
|
|
127
|
+
get(table) {
|
|
128
|
+
const hit = memory.get(table);
|
|
129
|
+
if (hit && hit.fetched_at <= Date.now() && Date.now() - hit.fetched_at < ttlMs) return hit;
|
|
130
|
+
if (hit) memory.delete(table);
|
|
131
|
+
const disk = readFile(table);
|
|
132
|
+
if (disk) { memory.set(table, disk); boundMemory(); }
|
|
133
|
+
return disk;
|
|
134
|
+
},
|
|
135
|
+
set(table, payload) {
|
|
136
|
+
if (!validPayload(payload) || payload.hierarchy[0] !== table
|
|
137
|
+
|| Buffer.byteLength(JSON.stringify(payload)) > QUERY_CACHE_LIMITS.entryBytes - 2048) return null;
|
|
138
|
+
const entry = { payload, fetched_at: Date.now() };
|
|
139
|
+
memory.set(table, entry);
|
|
140
|
+
boundMemory();
|
|
141
|
+
writeFile(table, payload);
|
|
142
|
+
return entry;
|
|
143
|
+
},
|
|
144
|
+
/** Explicit refresh: forget this table before the next read. */
|
|
145
|
+
refresh(table) { memory.delete(table); if (persist) { try { fs.unlinkSync(fileFor(keyFor(table))); } catch { /* absent */ } } },
|
|
146
|
+
/**
|
|
147
|
+
* Invalidate entries affected by a table/field mutation. When the affected
|
|
148
|
+
* scope is uncertain, clearing this identity's cache is the safe choice.
|
|
149
|
+
*/
|
|
150
|
+
invalidate({ tables = [], all = false } = {}) {
|
|
151
|
+
const affected = new Set(tables.filter(Boolean));
|
|
152
|
+
memory.clear();
|
|
153
|
+
if (platform === 'win32') return { removed: 0 };
|
|
154
|
+
// With unknown principal, clear this instance/profile to avoid stale privileged reuse.
|
|
155
|
+
let removed = 0;
|
|
156
|
+
let entries;
|
|
157
|
+
try {
|
|
158
|
+
const parent = fs.lstatSync(root);
|
|
159
|
+
if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return { removed: 0 };
|
|
160
|
+
entries = fs.readdirSync(root);
|
|
161
|
+
} catch { return { removed: 0 }; }
|
|
162
|
+
for (const name of entries) {
|
|
163
|
+
if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
|
|
164
|
+
const file = path.join(root, name);
|
|
165
|
+
let entry;
|
|
166
|
+
try {
|
|
167
|
+
const stat = fs.lstatSync(file);
|
|
168
|
+
if (!stat.isFile() || stat.size > QUERY_CACHE_LIMITS.entryBytes || (stat.mode & 0o077)) continue;
|
|
169
|
+
entry = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
170
|
+
} catch { continue; }
|
|
171
|
+
if (entry?.instance !== identity.instance || entry?.profile !== (identity.profile || '')
|
|
172
|
+
|| (persist && entry?.principal !== identity.principal)) continue;
|
|
173
|
+
const related = entry?.payload?.hierarchy || [];
|
|
174
|
+
const references = Object.values(entry?.payload?.fields || {}).flatMap(fields =>
|
|
175
|
+
Object.values(fields || {}).map(definition => definition?.reference).filter(Boolean));
|
|
176
|
+
const touch = all || !affected.size
|
|
177
|
+
|| affected.has(entry.table) || related.some(name => affected.has(name))
|
|
178
|
+
|| references.some(name => affected.has(name));
|
|
179
|
+
if (!touch) continue;
|
|
180
|
+
try { fs.unlinkSync(file); removed++; } catch { /* best effort */ }
|
|
181
|
+
}
|
|
182
|
+
return { removed };
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export { digest as queryCacheDigest };
|