@jacebenson/jsn 5.5.10-dev.236.1 → 5.5.10-dev.237.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,282 @@
1
+ // Glue between the parser, table-scoped metadata and the five-minute cache.
2
+ // A verdict reports what was actually established. "Could not tell" is never
3
+ // rendered as "invalid" or "absent"; reads may proceed, writes never do.
4
+
5
+ import { parseEncodedQuery, CANONICAL_OPERATORS, operatorSuggestions } from './query-parse.js';
6
+ import { readTableMetadata, resolveField, QUERY_METADATA_LIMITS } from './query-metadata.js';
7
+ import { createQueryMetadataCache, DEFAULT_TTL_MS } from './query-cache.js';
8
+ import { errUsageHint } from './errors.js';
9
+
10
+ const METADATA_TABLES = new Set(['sys_db_object', 'sys_dictionary', 'sys_dictionary_override']);
11
+ const MAX_DOT_WALK = 5;
12
+ const STATE_ORDER = { invalid: 6, denied: 5, unavailable: 4, incomplete: 3, unsupported: 2, valid: 1 };
13
+
14
+ const worse = (a, b) => (STATE_ORDER[b] || 0) > (STATE_ORDER[a] || 0) ? b : a;
15
+
16
+ const LIMITS = Object.freeze({
17
+ ttl_seconds: DEFAULT_TTL_MS / 1000,
18
+ dot_walk_depth: MAX_DOT_WALK,
19
+ inheritance_depth: QUERY_METADATA_LIMITS.maxDepth,
20
+ dictionary_rows: QUERY_METADATA_LIMITS.fields,
21
+ });
22
+
23
+ function fieldSuggestions(metadata, table, element) {
24
+ const names = new Set();
25
+ for (const owner of metadata.hierarchy?.length ? metadata.hierarchy : [table]) {
26
+ for (const name of Object.keys(metadata.fields?.[owner] || {})) names.add(name);
27
+ }
28
+ const lower = String(element).toLowerCase();
29
+ return [...names]
30
+ .filter(name => name !== element)
31
+ .filter(name => name.toLowerCase().includes(lower.slice(0, 3)) || lower.includes(name.toLowerCase().slice(0, 3)))
32
+ .slice(0, 3);
33
+ }
34
+
35
+ function diagnostic(state, term, reason) {
36
+ const base = { severity: 'warning', term: term?.raw || '', state };
37
+ if (state === 'denied') {
38
+ return { ...base, code: 'metadata_denied',
39
+ message: `Table metadata for ${reason} is not visible to this identity. Hidden metadata is not proof the table or field is absent.`,
40
+ hint: 'Re-authenticate with an identity that can read sys_db_object/sys_dictionary, or narrow the filter.' };
41
+ }
42
+ if (state === 'unavailable') {
43
+ return { ...base, code: 'metadata_unavailable',
44
+ message: `Table metadata for ${reason} could not be read (network or server failure).`,
45
+ hint: 'Retry, then refresh the metadata cache; the query itself is unchanged.' };
46
+ }
47
+ return { ...base, code: 'metadata_incomplete',
48
+ message: `Table metadata for ${reason} is incomplete or truncated.`,
49
+ hint: 'Hidden or capped rows are not absence. Widen access or narrow the filter; refresh with --refresh-metadata.' };
50
+ }
51
+
52
+ /**
53
+ * Validate a user-supplied encoded query.
54
+ * @param {{sdk:object, table:string, query:string, identity?:object,
55
+ * refresh?:boolean, cache?:object}} options
56
+ */
57
+ export async function validateEncodedQuery({ sdk, table, query, identity = {}, refresh = false, cache } = {}) {
58
+ const parsed = parseEncodedQuery(query);
59
+ const metaCache = cache || createQueryMetadataCache({ identity });
60
+ if (!parsed.terms.length && !parsed.diagnostics.length) {
61
+ return { state: 'valid', table, query: parsed.original, diagnostics: [], terms: [], limits: LIMITS };
62
+ }
63
+ if (parsed.invalid) {
64
+ return { state: 'invalid', table, query: parsed.original, diagnostics: parsed.diagnostics, terms: parsed.terms, limits: LIMITS };
65
+ }
66
+ const clauses = parsed.terms.filter(term => ['clause', 'ambiguous', 'directive'].includes(term.kind));
67
+ let state = parsed.terms.some(term => term.kind === 'unsupported') ? 'unsupported' : 'valid';
68
+ const diagnostics = [...parsed.diagnostics];
69
+ const metadataByTable = new Map();
70
+ const load = async name => {
71
+ if (metadataByTable.has(name)) return metadataByTable.get(name);
72
+ if (refresh) metaCache.refresh(name);
73
+ const cached = refresh ? null : metaCache.get(name);
74
+ const metadata = cached?.payload || await readTableMetadata(sdk, name);
75
+ metadataByTable.set(name, metadata);
76
+ if (!cached && metadata.state === 'observed') metaCache.set(name, metadata);
77
+ return metadata;
78
+ };
79
+ if (!table) {
80
+ state = worse(state, 'incomplete');
81
+ diagnostics.push(diagnostic('incomplete', parsed.terms[0], 'an unresolved table target'));
82
+ } else {
83
+ for (const term of clauses) {
84
+ // A word operator inside a dotted field may hide a longer path before
85
+ // a later symbolic operator. Never approve its shorter parsed prefix.
86
+ const symbolic = term.clause?.search(/[=!<>]/) ?? -1;
87
+ if (term.field.includes('.') && /[A-Z]/.test(term.operator || '') && symbolic >= 0
88
+ && /^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)+$/.test(term.clause.slice(0, symbolic))) {
89
+ state = worse(state, 'unsupported');
90
+ diagnostics.push({ code: 'ambiguous_dot_walk_operator', severity: 'warning', state: 'unsupported', term: term.raw,
91
+ message: 'A word-operator boundary inside this dot-walk is ambiguous; its shorter prefix does not prove the full expression.',
92
+ hint: 'Use an unambiguous field/operator boundary before writing. The original read query is unchanged. See jsn records list --help.' });
93
+ continue;
94
+ }
95
+ let currentTable = table;
96
+ let metadata = await load(currentTable);
97
+ if (metadata.state !== 'observed') {
98
+ state = worse(state, metadata.state);
99
+ diagnostics.push({ ...diagnostic(metadata.state, term, currentTable), table: currentTable,
100
+ ...(metadata.suggestions?.length ? { suggestions: metadata.suggestions } : {}) });
101
+ continue;
102
+ }
103
+ // Resolve operator boundaries against accessible dictionary names, longest
104
+ // first. Uppercase fragments alone are never proof of a field boundary.
105
+ if (term.clause && !term.field.includes('.')) {
106
+ const names = metadata.hierarchy.flatMap(owner => Object.keys(metadata.fields[owner] || {}))
107
+ .sort((a, b) => b.length - a.length);
108
+ let resolved = false;
109
+ for (const name of names) {
110
+ if (!term.clause.startsWith(name)) continue;
111
+ const suffix = term.clause.slice(name.length);
112
+ const operator = CANONICAL_OPERATORS.find(op => suffix.startsWith(op));
113
+ if (operator) {
114
+ term.field = name; term.path = [name]; term.operator = operator;
115
+ term.value = suffix.slice(operator.length); term.kind = 'clause'; resolved = true; break;
116
+ }
117
+ // Only a visible field plus a close misspelling of an operator is
118
+ // demonstrably invalid. Other platform syntax stays unverified.
119
+ const token = suffix.match(/^[A-Z ]+/)?.[0] || '';
120
+ const suggestions = operatorSuggestions(token);
121
+ if (suggestions.length && token) {
122
+ state = 'invalid'; resolved = true;
123
+ diagnostics.push({ code: 'invalid_operator', severity: 'error', state: 'invalid', term: term.raw,
124
+ message: `Unrecognised operator after visible field "${name}".`, suggestions,
125
+ hint: `Use ${suggestions.join(', ')} only if intended. See jsn records list --help.` });
126
+ break;
127
+ }
128
+ }
129
+ if (term.kind === 'ambiguous' && !resolved) {
130
+ state = worse(state, 'unsupported'); continue;
131
+ }
132
+ }
133
+ if (['SAMEAS', 'NSAMEAS', 'INSTANCEOF', 'BETWEEN'].includes(term.operator)) {
134
+ state = worse(state, 'unsupported');
135
+ diagnostics.push({ code: 'unsupported_operands', severity: 'warning', state: 'unsupported', term: term.raw,
136
+ message: `${term.operator} operand semantics are not fully verified; the original query is unchanged.`,
137
+ hint: 'Use a filter whose complete operands can be verified before writing. See jsn records list --help.' });
138
+ continue;
139
+ }
140
+ const path = term.path || term.field.split('.');
141
+ if (path.length > MAX_DOT_WALK) {
142
+ state = worse(state, 'unsupported');
143
+ diagnostics.push({ code: 'dot_walk_limit', severity: 'warning', state: 'unsupported', term: term.raw,
144
+ message: `Dot-walk exceeds ${MAX_DOT_WALK} field components; the tail was not validated.`,
145
+ hint: 'Narrow the filter. See jsn records list --help.' });
146
+ continue;
147
+ }
148
+ for (let hop = 0; hop < path.length; hop++) {
149
+ const element = path[hop];
150
+ const definition = resolveField(metadata, currentTable, element);
151
+ if (!definition) {
152
+ state = worse(state, 'incomplete');
153
+ diagnostics.push({ code: 'unknown_field', severity: 'warning', state: 'incomplete', term: term.raw, field: element,
154
+ message: `Field "${element}" is not visible on ${currentTable}; it may be ACL-hidden or unknown.`,
155
+ suggestions: fieldSuggestions(metadata, currentTable, element),
156
+ hint: `Run jsn columns list --table ${currentTable}; retry with --refresh-metadata. See jsn records list --help.` });
157
+ break;
158
+ }
159
+ term.inherited = definition.inherited;
160
+ if (hop === path.length - 1) break;
161
+ if (!definition.reference) {
162
+ const complete = definition.type && definition.type !== 'unknown' && definition.type !== 'reference';
163
+ state = complete ? 'invalid' : worse(state, 'incomplete');
164
+ diagnostics.push({ code: complete ? 'invalid_dot_walk' : 'metadata_incomplete',
165
+ severity: complete ? 'error' : 'warning', state: complete ? 'invalid' : 'incomplete', term: term.raw, field: element,
166
+ message: complete ? `"${element}" on ${currentTable} is not a reference.` : `Reference metadata for "${element}" is incomplete.`,
167
+ hint: 'Dot-walks require visible reference type and target metadata. See jsn records list --help.' });
168
+ break;
169
+ }
170
+ currentTable = definition.reference;
171
+ metadata = await load(currentTable);
172
+ if (metadata.state !== 'observed') {
173
+ state = worse(state, metadata.state);
174
+ diagnostics.push({ ...diagnostic(metadata.state, term, currentTable),
175
+ ...(metadata.suggestions?.length ? { suggestions: metadata.suggestions } : {}) }); break;
176
+ }
177
+ }
178
+ }
179
+ }
180
+ return { state, table, query: parsed.original, diagnostics, terms: parsed.terms, limits: LIMITS,
181
+ identity: { principal_verified: Boolean(identity.principal), cache: metaCache.persistent ? 'disk' : 'memory' },
182
+ metadata: Object.fromEntries([...metadataByTable].map(([name, value]) => [name, { state: value.state, reason: value.reason || '' }])) };
183
+ }
184
+
185
+ function assertionMessage(verdict, action) {
186
+ const first = verdict.diagnostics.find(item => item.severity === 'error') || verdict.diagnostics[0];
187
+ return `${action} refused: encoded query validation state is ${verdict.state}${first ? ` (${first.code})` : ''}. ${first?.message || ''}`.trim();
188
+ }
189
+
190
+ /** Human-visible + JSON diagnostics attached to a successful read. */
191
+ export function queryDiagnostics(verdict) {
192
+ if (!verdict || verdict.state === 'valid') return {};
193
+ const diagnostics = verdict.diagnostics.map(item => ({
194
+ code: item.code, severity: item.severity, term: item.term,
195
+ ...(item.field ? { field: item.field } : {}), message: item.message,
196
+ ...(item.hint ? { hint: item.hint } : {}),
197
+ ...(item.suggestions?.length ? { suggestions: item.suggestions } : {}),
198
+ }));
199
+ return {
200
+ query_validation: { state: verdict.state, diagnostics, limits: verdict.limits },
201
+ warnings: diagnostics.filter(item => item.severity !== 'info')
202
+ .map(item => `Query validation ${verdict.state}: ${item.message}${item.hint ? ` ${item.hint}` : ''}`),
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Validate before a read. Demonstrably invalid syntax/schema throws; every
208
+ * unverified state returns so the caller may proceed with diagnostics and the
209
+ * original, byte-identical query.
210
+ */
211
+ export async function validateReadQuery(app, { table, query, refresh = false } = {}) {
212
+ const local = localQueryFailure(table, query);
213
+ if (local) throw validationError(local, 'Read');
214
+ if (!query || !String(query).trim()) return { state: 'valid', table, query: query || '', diagnostics: [], limits: LIMITS };
215
+ if (app.queryValidation?.table === table && app.queryValidation.query === query) return app.queryValidation;
216
+ const verdict = await validateEncodedQuery({ sdk: app.sdk, table, query, identity: await authenticatedIdentity(app), refresh });
217
+ if (verdict.state === 'invalid') throw validationError(verdict, 'Read');
218
+ return verdict;
219
+ }
220
+
221
+ /** Validate the COMPLETE original filter before any instance-record write. */
222
+ export async function assertWriteQuery(app, { table, query, refresh = false } = {}) {
223
+ const local = localQueryFailure(table, query, true);
224
+ if (local) throw validationError(local, 'Mutation');
225
+ if (app.queryValidation?.state === 'valid' && app.queryValidation.table === table && app.queryValidation.query === query) return app.queryValidation;
226
+ const verdict = await validateEncodedQuery({ sdk: app.sdk, table, query, identity: await authenticatedIdentity(app), refresh });
227
+ if (verdict.state !== 'valid') {
228
+ throw validationError(verdict, 'Mutation');
229
+ }
230
+ return verdict;
231
+ }
232
+
233
+ /** After a successful table/field mutation, drop affected cache entries. */
234
+ export function invalidateAfterMutation(app, table) {
235
+ const identity = metadataIdentity(app);
236
+ const cache = createQueryMetadataCache({ identity });
237
+ if (METADATA_TABLES.has(table)) return cache.invalidate({ all: true });
238
+ return cache.invalidate({ tables: [table] });
239
+ }
240
+
241
+ // Configuration usernames are expectations, never authenticated identity proof.
242
+ export function metadataIdentity(app) {
243
+ return { instance: app?.getEffectiveInstance?.() || '',
244
+ profile: app?.config?.activeProfile || app?.config?.defaultProfile || '', principal: '' };
245
+ }
246
+ async function authenticatedIdentity(app) {
247
+ const identity = metadataIdentity(app);
248
+ try {
249
+ // Strict provider readback on every invocation; no principal cache can outlive
250
+ // a session/account switch. Fixture SDKs without strict transport stay memory-only.
251
+ const rows = await app.sdk.listStrict('sys_user', new URLSearchParams({
252
+ sysparm_query: 'user_name=javascript:gs.getUserName()', sysparm_fields: 'sys_id,user_name',
253
+ sysparm_limit: '2', sysparm_display_value: 'false',
254
+ }));
255
+ if (rows.length === 1) {
256
+ const id = rows[0]?.sys_id?.value ?? rows[0]?.sys_id;
257
+ const name = rows[0]?.user_name?.value ?? rows[0]?.user_name;
258
+ if (/^[a-f0-9]{32}$/i.test(id) && typeof name === 'string' && name && name !== 'guest'
259
+ && (!app.sdk.username || name === app.sdk.username)) identity.principal = id;
260
+ }
261
+ } catch { /* identity unknown: persisted entries must not be read */ }
262
+ return identity;
263
+ }
264
+ function localQueryFailure(table, query, filteredWrite = false) {
265
+ const parsed = parseEncodedQuery(query);
266
+ if (parsed.invalid) return { ...parsed, table, query: parsed.original, state: 'invalid', limits: LIMITS };
267
+ if (filteredWrite && !parsed.terms.some(term => ['clause', 'ambiguous', 'unsupported'].includes(term.kind))) {
268
+ return { state: 'invalid', table, query: parsed.original, limits: LIMITS, diagnostics: [{ code: 'empty_filter', severity: 'error', term: parsed.original,
269
+ message: 'A filtered mutation requires a nonempty condition, not only ordering directives or separators.',
270
+ hint: 'Supply a complete filter. See jsn records list --help.' }] };
271
+ }
272
+ return null;
273
+ }
274
+ function validationError(verdict, action) {
275
+ const first = verdict.diagnostics.find(item => item.severity === 'error') || verdict.diagnostics[0];
276
+ const error = errUsageHint(assertionMessage(verdict, action),
277
+ `${first?.hint || 'No records were written. Refresh metadata or narrow the filter.'} See jsn records list --help.`);
278
+ error.query_validation = { state: verdict.state, query: verdict.query, limits: verdict.limits, diagnostics: verdict.diagnostics };
279
+ return error;
280
+ }
281
+
282
+ export { LIMITS as QUERY_VALIDATION_LIMITS };
package/src/sdk.js CHANGED
@@ -464,6 +464,7 @@ export class SDKClient {
464
464
  method: 'POST',
465
465
  body: JSON.stringify(data),
466
466
  });
467
+ if (['sys_db_object', 'sys_dictionary', 'sys_dictionary_override'].includes(table)) this.afterMetadataMutation?.(table);
467
468
  return result?.result || null;
468
469
  }
469
470
 
@@ -474,6 +475,7 @@ export class SDKClient {
474
475
  method: 'PUT',
475
476
  body: JSON.stringify(data),
476
477
  });
478
+ if (['sys_db_object', 'sys_dictionary', 'sys_dictionary_override'].includes(table)) this.afterMetadataMutation?.(table);
477
479
  return result?.result || null;
478
480
  }
479
481
 
@@ -481,6 +483,7 @@ export class SDKClient {
481
483
  await this._guardTableMutation(table, sysID);
482
484
  const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
483
485
  await this.request(endpoint, { method: 'DELETE' });
486
+ if (['sys_db_object', 'sys_dictionary', 'sys_dictionary_override'].includes(table)) this.afterMetadataMutation?.(table);
484
487
  }
485
488
 
486
489
  // Flow Designer actions use full Process Flow documents, not table CRUD.