@jacebenson/jsn 5.5.10-dev.235.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,201 @@
1
+ // Encoded-query tokenizer. This module classifies; it never rewrites,
2
+ // re-encodes, substitutes or drops any part of the caller's string.
3
+ //
4
+ // The parser understands the surface jsn users type, not the whole platform:
5
+ // ^-separated clauses, ^OR / ^NQ / ^EQ connectors, ORDERBY / ORDERBYDESC,
6
+ // symbolic and canonical word operators, and dot-walk paths. Anything dynamic
7
+ // (`javascript:`, `js:`) or otherwise outside that surface is reported as
8
+ // unsupported, never invalid — the platform may accept it.
9
+
10
+ const SYMBOLIC = ['>=', '<=', '!=', '=', '>', '<'];
11
+ const WORD = ['ISNOTEMPTY', 'INSTANCEOF', 'STARTSWITH', 'ENDSWITH', 'NOTLIKE',
12
+ 'NOT LIKE', 'NOT IN', 'BETWEEN', 'NSAMEAS', 'SAMEAS', 'ISEMPTY', 'NOTIN', 'LIKE', 'IN'];
13
+ const CANONICAL = new Set([...SYMBOLIC, ...WORD]);
14
+ const NO_VALUE = new Set(['ISEMPTY', 'ISNOTEMPTY']);
15
+ const CONNECTOR = /^(OR(?!DERBY)|NQ|EQ|AND)/;
16
+
17
+ const raw = value => String(value && typeof value === 'object' ? value.value ?? '' : value ?? '');
18
+
19
+ function levenshtein(a, b) {
20
+ const rows = Array.from({ length: a.length + 1 }, (_, i) => [i]);
21
+ for (let j = 1; j <= b.length; j++) rows[0][j] = j;
22
+ for (let i = 1; i <= a.length; i++) {
23
+ for (let j = 1; j <= b.length; j++) {
24
+ rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1,
25
+ rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
26
+ }
27
+ }
28
+ return rows[a.length][b.length];
29
+ }
30
+
31
+ /** Close canonical operators for an unrecognised term (labels only). */
32
+ export function operatorSuggestions(token) {
33
+ const upper = String(token || '').toUpperCase();
34
+ if (!upper) return [];
35
+ return [...CANONICAL]
36
+ .map(op => ({ op, distance: levenshtein(upper, op) }))
37
+ .filter(item => item.distance <= Math.max(2, Math.floor(upper.length / 3)))
38
+ .sort((a, b) => a.distance - b.distance) // closest first, labels only
39
+ .slice(0, 3)
40
+ .map(item => item.op);
41
+ }
42
+
43
+ // Scan every suffix window so `nameSTARTWITHfoo` still suggests STARTSWITH
44
+ // without guessing where the field ends.
45
+ function closestOperators(clause) {
46
+ const upper = clause.toUpperCase();
47
+ const found = new Map();
48
+ for (const op of CANONICAL) {
49
+ for (let start = 1; start + op.length <= upper.length + 2; start++) {
50
+ const window = upper.slice(start, start + op.length);
51
+ const distance = levenshtein(window, op);
52
+ if (distance > 2 || distance >= op.length) continue;
53
+ const previous = found.get(op);
54
+ if (previous === undefined || distance < previous) found.set(op, distance);
55
+ }
56
+ }
57
+ return [...found].sort((a, b) => a[1] - b[1] || b[0].length - a[0].length).slice(0, 3).map(([op]) => op);
58
+ }
59
+
60
+ function splitClauses(query) {
61
+ const clauses = [];
62
+ let current = '';
63
+ let escaped = false;
64
+ for (let i = 0; i < query.length; i++) {
65
+ const char = query[i];
66
+ if (char === '^') {
67
+ if (query[i + 1] === '^') { current += '^^'; i++; continue; }
68
+ clauses.push(current); current = ''; continue;
69
+ }
70
+ if (escaped) { current += char; escaped = false; continue; }
71
+ current += char;
72
+ }
73
+ clauses.push(current);
74
+ return clauses;
75
+ }
76
+
77
+ function findOperator(clause) {
78
+ let symbol = -1;
79
+ for (let i = 0; i < clause.length && symbol < 0; i++) {
80
+ for (const op of SYMBOLIC) {
81
+ if (clause.startsWith(op, i)) { symbol = i; break; }
82
+ }
83
+ }
84
+ let word = -1;
85
+ let wordOp = '';
86
+ for (const op of WORD) {
87
+ for (let i = 1; i + op.length <= clause.length; i++) {
88
+ const token = clause.slice(i, i + op.length);
89
+ if (token !== op) continue; // canonical uppercase only: `caller_in` stays a field
90
+ const next = clause[i + op.length];
91
+ if (next && /[=!<>]/.test(next)) continue; // `caller_in=x` is a field, not IN
92
+ if (word < 0 || i < word || (i === word && op.length > wordOp.length)) { word = i; wordOp = op; }
93
+ break;
94
+ }
95
+ }
96
+ const at = symbol >= 0 && (word < 0 || symbol < word) ? symbol : word;
97
+ if (at < 0) return null;
98
+ if (at === symbol) {
99
+ const op = SYMBOLIC.find(candidate => clause.startsWith(candidate, at));
100
+ return { field: clause.slice(0, at), operator: op, value: clause.slice(at + op.length).replaceAll('^^', '^'), index: at };
101
+ }
102
+ return { field: clause.slice(0, word), operator: wordOp, value: clause.slice(word + wordOp.length).replaceAll('^^', '^'), index: word };
103
+ }
104
+
105
+ /**
106
+ * Parse an encoded query.
107
+ * @returns {{original: string, terms: object[], diagnostics: object[],
108
+ * unsupported: boolean, invalid: boolean}}
109
+ */
110
+ export function parseEncodedQuery(query) {
111
+ const original = typeof query === 'string' ? query : '';
112
+ const terms = [];
113
+ const diagnostics = [];
114
+ if (!original.trim()) return { original, terms, diagnostics, unsupported: false, invalid: false };
115
+
116
+ for (const rawClause of splitClauses(original)) {
117
+ if (rawClause === '') continue;
118
+ let clause = rawClause;
119
+ let connector = '';
120
+
121
+ // Directives are checked before connector stripping: ORDERBY starts with OR.
122
+ if (/^ORDERBYDESC/i.test(clause) || /^ORDERBY/i.test(clause)) {
123
+ const match = clause.match(/^ORDERBY(?:DESC)?([a-z0-9_]+(?:\.[a-z0-9_]+)*)$/i);
124
+ if (match) {
125
+ terms.push({ kind: 'directive', raw: rawClause, connector, directive: /^ORDERBYDESC/i.test(clause) ? 'ORDERBYDESC' : 'ORDERBY', field: match[1] });
126
+ continue;
127
+ }
128
+ diagnostics.push({ code: 'malformed_directive', severity: 'error', term: rawClause,
129
+ message: `"${rawClause}" is not a valid ORDERBY directive.`,
130
+ hint: 'Use ORDERBYfield or ORDERBYDESCfield.' });
131
+ continue;
132
+ }
133
+
134
+ const connected = clause.match(CONNECTOR);
135
+ if (connected) { connector = connected[1]; clause = clause.slice(connected[0].length); }
136
+ if (clause.trim() === '') {
137
+ if (connector !== 'EQ') {
138
+ terms.push({ kind: 'invalid', raw: rawClause, connector });
139
+ diagnostics.push({ code: 'empty_branch', severity: 'error', term: rawClause,
140
+ message: `${connector} requires a complete query term.`, hint: 'Supply a condition after every OR, NQ or AND branch. See jsn records list --help.' });
141
+ }
142
+ continue;
143
+ }
144
+
145
+ if (/^(?:javascript|js):/i.test(clause) || /(?:javascript|js):/i.test(clause)
146
+ || /^(?:RLQUERY|ENDRLQUERY|GROUPBY|HAVING)/.test(clause)
147
+ || /(?:NOTON|ON|RELATIVE[A-Z]*|DYNAMIC)/.test(clause.split(/[=!<>]/, 1)[0])) {
148
+ terms.push({ kind: 'unsupported', raw: rawClause, connector, reason: 'dynamic_script' });
149
+ diagnostics.push({ code: 'unsupported_dynamic_query', severity: 'warning', term: rawClause,
150
+ message: 'This term uses platform dynamic/script syntax, which jsn does not evaluate.',
151
+ hint: 'The query is left byte-identical; validation is unverified for this term.' });
152
+ continue;
153
+ }
154
+
155
+ const found = findOperator(clause);
156
+ if (!found) {
157
+ const suggestions = closestOperators(clause);
158
+ terms.push({ kind: 'ambiguous', raw: rawClause, clause, connector, code: 'missing_operator', field: clause });
159
+ diagnostics.push({ code: 'missing_operator', severity: 'warning', term: rawClause,
160
+ message: `"${rawClause}" has no recognised operator.`,
161
+ ...(suggestions.length ? { suggestions } : {}),
162
+ hint: suggestions.length ? `Did you mean a canonical operator such as ${suggestions.join(', ')}?` : 'Use fieldOPERATORvalue, for example active=true.' });
163
+ continue;
164
+ }
165
+
166
+ const field = found.field.trim();
167
+ if (!field) {
168
+ terms.push({ kind: 'invalid', raw: rawClause, connector, code: 'empty_field', operator: found.operator });
169
+ diagnostics.push({ code: 'empty_field', severity: 'error', term: rawClause,
170
+ message: `"${rawClause}" has an operator but no field name.` });
171
+ continue;
172
+ }
173
+ if (!/^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*$/.test(field)) {
174
+ terms.push({ kind: 'invalid', raw: rawClause, connector, code: 'invalid_field_syntax', field, operator: found.operator });
175
+ diagnostics.push({ code: 'invalid_field_syntax', severity: 'error', term: rawClause,
176
+ message: `"${field}" is not a valid field path.`,
177
+ hint: 'Field paths contain letters, numbers, underscores and dots (for reference walks).' });
178
+ continue;
179
+ }
180
+ if (!NO_VALUE.has(found.operator) && found.value === '') {
181
+ diagnostics.push({ code: 'empty_value', severity: 'warning', term: rawClause, field,
182
+ message: `"${rawClause}" supplies an empty value for ${found.operator}.`,
183
+ hint: 'The query is unchanged; confirm this is intentional.' });
184
+ }
185
+ terms.push({
186
+ kind: 'clause', raw: rawClause, clause, connector, field, operator: found.operator, value: found.value,
187
+ path: field.split('.'), inherited: false,
188
+ });
189
+ }
190
+
191
+ if (!terms.length) diagnostics.push({ code: 'empty_filter', severity: 'error', term: original,
192
+ message: 'A nonempty encoded query must contain a condition or directive, not only separators or connectors.',
193
+ hint: 'Supply a complete filter. See jsn records list --help.' });
194
+
195
+ const invalid = terms.some(term => term.kind === 'invalid') || diagnostics.some(d => d.severity === 'error');
196
+ const unsupported = terms.some(term => term.kind === 'unsupported' || term.kind === 'ambiguous');
197
+ return { original, terms, diagnostics, unsupported, invalid };
198
+ }
199
+
200
+ export const CANONICAL_OPERATORS = Object.freeze([...CANONICAL]);
201
+ export { raw as rawFieldValue };
@@ -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.