@jacebenson/jsn 5.5.10-dev.236.1 → 5.5.10-dev.238.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/app.js +5 -0
- package/src/auth/credential-store.js +3 -3
- package/src/cli.js +12 -1
- package/src/command-families.js +3 -3
- package/src/commands/_generic.js +6 -0
- package/src/commands/_ticket.js +7 -1
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- 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/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 +17 -0
- package/src/commands/rest.js +1 -1
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +1 -1
- package/src/commands/tickets.js +4 -1
- package/src/commands/transactions.js +3 -0
- package/src/commands/updatesets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/output.js +4 -0
- 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/sdk.js +3 -0
|
@@ -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 };
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// On-demand, table-scoped metadata for encoded-query validation.
|
|
2
|
+
//
|
|
3
|
+
// A bounded sys_db_object ancestry walk and one sys_dictionary request cover
|
|
4
|
+
// visible ancestors. Unresolved tables allow one bounded name-candidate lookup. Nothing here dumps a
|
|
5
|
+
// whole instance schema, and nothing here treats a hidden row as absence.
|
|
6
|
+
|
|
7
|
+
const FIELD_LIMIT = 1000;
|
|
8
|
+
const MAX_DEPTH = 8;
|
|
9
|
+
|
|
10
|
+
const raw = value => String(value && typeof value === 'object' ? value.value ?? '' : value ?? '');
|
|
11
|
+
const isName = value => typeof value === 'string' && /^[a-zA-Z0-9_]+$/.test(value);
|
|
12
|
+
|
|
13
|
+
function params(query, fields, limit) {
|
|
14
|
+
return new URLSearchParams({
|
|
15
|
+
sysparm_query: query,
|
|
16
|
+
sysparm_fields: fields,
|
|
17
|
+
sysparm_limit: String(limit),
|
|
18
|
+
sysparm_display_value: 'false',
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function classifyFailure(error) {
|
|
23
|
+
const status = Number(error?.status);
|
|
24
|
+
if (status === 401 || status === 403 || error?.code === 'auth_error') return 'denied';
|
|
25
|
+
return 'unavailable';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readList(sdk, table, searchParams) {
|
|
29
|
+
try {
|
|
30
|
+
const responseMetadata = {};
|
|
31
|
+
const read = sdk.listStrict || sdk.list;
|
|
32
|
+
const rows = await read.call(sdk, table, searchParams, { responseMetadata });
|
|
33
|
+
if (!Array.isArray(rows)) return { state: 'unavailable', reason: 'Metadata response was not an array' };
|
|
34
|
+
return { rows, total: responseMetadata.total };
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return { state: classifyFailure(error), reason: 'Metadata read failed or returned an invalid envelope' };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// One prefix-bounded, ACL-scoped candidate read, never a schema inventory.
|
|
41
|
+
// Suggestions are labels only and are never cached or substituted into queries.
|
|
42
|
+
async function tableSuggestions(sdk, table, requests) {
|
|
43
|
+
if (!isName(table) || table.length < 3) return [];
|
|
44
|
+
const prefix = table.slice(0, 3);
|
|
45
|
+
const query = `nameSTARTSWITH${prefix}^ORDERBYname`;
|
|
46
|
+
requests.push({ table: 'sys_db_object', query, fields: 'name', limit: 20 });
|
|
47
|
+
const result = await readList(sdk, 'sys_db_object', params(query, 'name', 20));
|
|
48
|
+
if (!result.rows || result.rows.length > 20) return [];
|
|
49
|
+
const distance = (a, b) => {
|
|
50
|
+
let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
51
|
+
for (let i = 1; i <= a.length; i++) {
|
|
52
|
+
const next = [i];
|
|
53
|
+
for (let j = 1; j <= b.length; j++) next[j] = Math.min(next[j - 1] + 1, previous[j] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
54
|
+
previous = next;
|
|
55
|
+
}
|
|
56
|
+
return previous[b.length];
|
|
57
|
+
};
|
|
58
|
+
return [...new Set(result.rows.map(row => raw(row?.name)))]
|
|
59
|
+
.filter(name => isName(name) && name.length <= 160 && name !== table && name.startsWith(prefix))
|
|
60
|
+
.map(name => ({ name, distance: distance(table.slice(0, 160), name) }))
|
|
61
|
+
.filter(candidate => candidate.distance <= Math.max(2, Math.floor(table.length / 4)))
|
|
62
|
+
.sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name))
|
|
63
|
+
.slice(0, 3).map(candidate => candidate.name);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Read table + ancestor field metadata as visible to the caller's own ACLs.
|
|
68
|
+
* States: observed | denied | unavailable | incomplete.
|
|
69
|
+
* `incomplete` is never absence: callers must not treat missing fields as
|
|
70
|
+
* definitively unknown-to-the-platform.
|
|
71
|
+
*/
|
|
72
|
+
export async function readTableMetadata(sdk, table, { maxDepth = MAX_DEPTH, limit = FIELD_LIMIT } = {}) {
|
|
73
|
+
if (!isName(table)) {
|
|
74
|
+
return { state: 'unavailable', table, hierarchy: [], fields: {}, reason: 'Invalid table name', requests: [] };
|
|
75
|
+
}
|
|
76
|
+
const requests = [];
|
|
77
|
+
const hierarchy = [];
|
|
78
|
+
const visited = new Set();
|
|
79
|
+
let next = { query: `name=${table}`, fields: 'sys_id,name,super_class', limit: 2 };
|
|
80
|
+
let state = 'observed';
|
|
81
|
+
let reason = '';
|
|
82
|
+
|
|
83
|
+
for (let depth = 0; next && depth < maxDepth; depth++) {
|
|
84
|
+
const search = params(next.query, next.fields, next.limit);
|
|
85
|
+
requests.push({ table: 'sys_db_object', query: next.query, fields: next.fields, limit: next.limit });
|
|
86
|
+
const result = await readList(sdk, 'sys_db_object', search);
|
|
87
|
+
if (!result.rows) {
|
|
88
|
+
return { state: result.state, table, hierarchy: hierarchy.map(item => item.name), fields: {}, reason: result.reason, requests,
|
|
89
|
+
suggestions: depth === 0 ? await tableSuggestions(sdk, table, requests) : [] };
|
|
90
|
+
}
|
|
91
|
+
if (result.rows.length !== 1) {
|
|
92
|
+
// First hop: the table is not visible (may not exist, may be ACL-hidden).
|
|
93
|
+
// Deeper hop: an ancestor is hidden or the chain is malformed.
|
|
94
|
+
state = depth === 0 ? 'denied' : 'incomplete';
|
|
95
|
+
reason = depth === 0
|
|
96
|
+
? `Table ${table} is not visible to this identity; it may not exist or may be ACL-hidden`
|
|
97
|
+
: `Ancestor metadata above ${hierarchy.at(-1)?.name || table} is not visible`;
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
const row = result.rows[0];
|
|
101
|
+
const name = raw(row?.name);
|
|
102
|
+
const id = raw(row?.sys_id);
|
|
103
|
+
if (!row || typeof row !== 'object' || !isName(name) || visited.has(name)
|
|
104
|
+
|| (depth === 0 ? name !== table : id !== next.query.slice(7))) {
|
|
105
|
+
state = 'incomplete';
|
|
106
|
+
reason = 'Malformed or cyclic sys_db_object ancestry';
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
visited.add(name);
|
|
110
|
+
hierarchy.push({ name, sys_id: id });
|
|
111
|
+
if (!Object.hasOwn(row, 'super_class')) {
|
|
112
|
+
state = 'incomplete';
|
|
113
|
+
reason = 'Parent metadata is not visible; inheritance coverage is incomplete';
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
const parentValue = row.super_class;
|
|
117
|
+
const readableParent = typeof parentValue === 'string'
|
|
118
|
+
|| (parentValue && typeof parentValue === 'object' && !Array.isArray(parentValue)
|
|
119
|
+
&& Object.hasOwn(parentValue, 'value') && typeof parentValue.value === 'string');
|
|
120
|
+
if (!readableParent) {
|
|
121
|
+
state = 'incomplete';
|
|
122
|
+
reason = 'Parent reference has no readable raw value; inheritance coverage is incomplete';
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
const parent = raw(row.super_class);
|
|
126
|
+
if (!parent) { next = null; break; }
|
|
127
|
+
if (!/^[a-f0-9]{32}$/i.test(parent)) {
|
|
128
|
+
state = 'incomplete';
|
|
129
|
+
reason = 'Malformed parent reference in sys_db_object';
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
next = { query: `sys_id=${parent}`, fields: 'sys_id,name,super_class', limit: 2 };
|
|
133
|
+
}
|
|
134
|
+
if (next && hierarchy.length >= maxDepth) {
|
|
135
|
+
state = state === 'observed' ? 'incomplete' : state;
|
|
136
|
+
reason ||= `Table inheritance depth limit ${maxDepth} reached`;
|
|
137
|
+
}
|
|
138
|
+
if (!hierarchy.length) {
|
|
139
|
+
return { state, table, hierarchy: [], fields: {}, reason, requests, suggestions: await tableSuggestions(sdk, table, requests) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const names = hierarchy.map(item => item.name);
|
|
143
|
+
const query = `nameIN${names.join(',')}^elementISNOTEMPTY`;
|
|
144
|
+
requests.push({ table: 'sys_dictionary', query, fields: 'sys_id,name,element,internal_type,reference', limit });
|
|
145
|
+
const dictionary = await readList(sdk, 'sys_dictionary', params(query, 'sys_id,name,element,internal_type,reference', limit));
|
|
146
|
+
if (!dictionary.rows) {
|
|
147
|
+
return { state: dictionary.state, table, hierarchy: names, fields: {}, reason: dictionary.reason, requests };
|
|
148
|
+
}
|
|
149
|
+
const fields = {};
|
|
150
|
+
for (const row of dictionary.rows) {
|
|
151
|
+
const owner = raw(row?.name);
|
|
152
|
+
const element = raw(row?.element);
|
|
153
|
+
if (!isName(owner) || !isName(element) || !names.includes(owner)) {
|
|
154
|
+
state = state === 'observed' ? 'incomplete' : state;
|
|
155
|
+
reason ||= 'Ignored a malformed or out-of-scope sys_dictionary row';
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (!Object.hasOwn(row, 'internal_type') || !raw(row.internal_type)
|
|
159
|
+
|| !Object.hasOwn(row, 'reference')
|
|
160
|
+
|| (raw(row.internal_type) === 'reference' && !isName(raw(row.reference)))) {
|
|
161
|
+
state = state === 'observed' ? 'incomplete' : state;
|
|
162
|
+
reason ||= 'Field type or reference metadata is not visible';
|
|
163
|
+
}
|
|
164
|
+
fields[owner] ||= {};
|
|
165
|
+
fields[owner][element] = {
|
|
166
|
+
type: raw(row.internal_type) || 'unknown',
|
|
167
|
+
reference: isName(raw(row.reference)) ? raw(row.reference) : '',
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
if (!dictionary.rows.length || !Number.isSafeInteger(dictionary.total)
|
|
171
|
+
|| dictionary.total !== dictionary.rows.length || dictionary.rows.length >= limit) {
|
|
172
|
+
state = state === 'observed' ? 'incomplete' : state;
|
|
173
|
+
reason ||= `sys_dictionary limit ${limit} reached; field coverage is incomplete`;
|
|
174
|
+
}
|
|
175
|
+
return { state, table, hierarchy: names, fields, reason, requests,
|
|
176
|
+
complete: state === 'observed', source: 'table-api', total: dictionary.total };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Resolve one field through the dictionary, marking where it was inherited. */
|
|
180
|
+
export function resolveField(metadata, table, element) {
|
|
181
|
+
const owners = metadata.hierarchy?.length ? metadata.hierarchy : [table];
|
|
182
|
+
for (const owner of owners) {
|
|
183
|
+
const definition = metadata.fields?.[owner]?.[element];
|
|
184
|
+
if (definition) return { ...definition, owner, inherited: owner !== table };
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export const QUERY_METADATA_LIMITS = Object.freeze({ maxDepth: MAX_DEPTH, fields: FIELD_LIMIT });
|
|
@@ -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 };
|