@altopelago/sansa 0.9.0
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/CHANGELOG.md +41 -0
- package/CODE_OF_CONDUCT.md +28 -0
- package/CONTRIBUTING.md +52 -0
- package/GOVERNANCE.md +35 -0
- package/LICENSE +21 -0
- package/README.md +146 -0
- package/SECURITY.md +38 -0
- package/docs/api-contract.md +788 -0
- package/docs/capabilities.json +80 -0
- package/docs/query-tool.md +228 -0
- package/docs/releasing.md +37 -0
- package/fixtures/address-v1.json +316 -0
- package/fixtures/query-inventory.aeon +69 -0
- package/fixtures/query-inventory.json +671 -0
- package/fixtures/query-params-single.json +10 -0
- package/package.json +70 -0
- package/scripts/cts-address.mjs +107 -0
- package/scripts/cts-query.mjs +271 -0
- package/scripts/cts-resolve.mjs +151 -0
- package/scripts/cts-value-semantics.mjs +83 -0
- package/scripts/query-web.mjs +145 -0
- package/scripts/query.mjs +579 -0
- package/scripts/stress-addresses.mjs +65 -0
- package/src/index.d.ts +575 -0
- package/src/index.js +3389 -0
- package/stress-tests/README.md +19 -0
- package/stress-tests/address/invalid.sansa-cases +60 -0
- package/stress-tests/address/valid.sansa-cases +76 -0
- package/tools/query-web/app.js +266 -0
- package/tools/query-web/examples.mjs +478 -0
- package/tools/query-web/index.html +117 -0
- package/tools/query-web/runtime.mjs +796 -0
- package/tools/query-web/styles.css +251 -0
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { evaluateQuery, parseQuery } from '../src/index.js';
|
|
6
|
+
import { namespaceFromAeonSource } from '../tools/query-web/runtime.mjs';
|
|
7
|
+
|
|
8
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const root = resolve(here, '..');
|
|
10
|
+
const defaultFixturePath = resolve(root, 'fixtures', 'query-inventory.json');
|
|
11
|
+
const QUERY_VALUE_METADATA_PROPERTY = '__sansaQueryValueMetadata';
|
|
12
|
+
const QUERY_OBJECT_FIELD_METADATA_PROPERTY = '__sansaObjectFieldMetadata';
|
|
13
|
+
|
|
14
|
+
const args = parseArgs(process.argv.slice(2));
|
|
15
|
+
|
|
16
|
+
if (args.help) {
|
|
17
|
+
printHelp();
|
|
18
|
+
process.exit(0);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const querySource = readQuerySource(args);
|
|
22
|
+
if (!querySource.trim()) {
|
|
23
|
+
console.error('SANSA Query tool error: expected query source via --query, --query-file, or stdin.');
|
|
24
|
+
process.exit(2);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const mode = args.mode ?? 'evaluate';
|
|
28
|
+
const format = args.format ?? 'text';
|
|
29
|
+
const fixturePath = resolve(args.fixture ?? defaultFixturePath);
|
|
30
|
+
const policy = parsePolicy(args.policy);
|
|
31
|
+
const budget = parseBudgetArgs(args);
|
|
32
|
+
const evaluateOptions = buildEvaluateOptions({ policy, transformEnabled: args.disableTransform !== true, budget });
|
|
33
|
+
|
|
34
|
+
if (!['evaluate', 'parse'].includes(mode)) {
|
|
35
|
+
console.error(`SANSA Query tool error: unsupported --mode '${mode}'. Expected 'evaluate' or 'parse'.`);
|
|
36
|
+
process.exit(2);
|
|
37
|
+
}
|
|
38
|
+
if (!['text', 'json'].includes(format)) {
|
|
39
|
+
console.error(`SANSA Query tool error: unsupported --format '${format}'. Expected 'text' or 'json'.`);
|
|
40
|
+
process.exit(2);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let result;
|
|
44
|
+
if (mode === 'parse') {
|
|
45
|
+
result = parseQuery(querySource);
|
|
46
|
+
} else {
|
|
47
|
+
const loaded = await readNamespaceFixture(fixturePath, args.fixtureKind);
|
|
48
|
+
if (!loaded.ok) process.exit(2);
|
|
49
|
+
|
|
50
|
+
const paramsBinding = readParamsBinding(args);
|
|
51
|
+
if (paramsBinding) {
|
|
52
|
+
mountParamsLocalSpace(loaded.namespace.root, paramsBinding);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
result = evaluateQuery(querySource, loaded.namespace, evaluateOptions);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (format === 'json') {
|
|
59
|
+
console.log(JSON.stringify(formatJsonResult(result, mode, fixturePath), null, 2));
|
|
60
|
+
} else {
|
|
61
|
+
printTextResult(result, mode, fixturePath);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
process.exit(result.ok ? 0 : 1);
|
|
65
|
+
|
|
66
|
+
function parseArgs(raw) {
|
|
67
|
+
const output = {};
|
|
68
|
+
for (let index = 0; index < raw.length; index += 1) {
|
|
69
|
+
const arg = raw[index];
|
|
70
|
+
if (arg === '--help' || arg === '-h') {
|
|
71
|
+
output.help = true;
|
|
72
|
+
} else if (arg === '--query' || arg === '-q') {
|
|
73
|
+
output.query = requireValue(raw, ++index, arg);
|
|
74
|
+
} else if (arg === '--query-file') {
|
|
75
|
+
output.queryFile = requireValue(raw, ++index, arg);
|
|
76
|
+
} else if (arg === '--fixture' || arg === '-f') {
|
|
77
|
+
output.fixture = requireValue(raw, ++index, arg);
|
|
78
|
+
} else if (arg === '--fixture-kind') {
|
|
79
|
+
output.fixtureKind = requireValue(raw, ++index, arg);
|
|
80
|
+
} else if (arg === '--params') {
|
|
81
|
+
output.params = requireValue(raw, ++index, arg);
|
|
82
|
+
} else if (arg === '--params-file') {
|
|
83
|
+
output.paramsFile = requireValue(raw, ++index, arg);
|
|
84
|
+
} else if (arg === '--format') {
|
|
85
|
+
output.format = requireValue(raw, ++index, arg);
|
|
86
|
+
} else if (arg === '--mode') {
|
|
87
|
+
output.mode = requireValue(raw, ++index, arg);
|
|
88
|
+
} else if (arg === '--policy') {
|
|
89
|
+
output.policy = requireValue(raw, ++index, arg);
|
|
90
|
+
} else if (arg === '--disable-transform') {
|
|
91
|
+
output.disableTransform = true;
|
|
92
|
+
} else if (arg === '--max-from-bindings') {
|
|
93
|
+
output.maxFromBindings = requireValue(raw, ++index, arg);
|
|
94
|
+
} else if (arg === '--max-where-candidates') {
|
|
95
|
+
output.maxWhereCandidates = requireValue(raw, ++index, arg);
|
|
96
|
+
} else if (arg === '--max-order-candidates') {
|
|
97
|
+
output.maxOrderCandidates = requireValue(raw, ++index, arg);
|
|
98
|
+
} else if (arg === '--max-result-records') {
|
|
99
|
+
output.maxResultRecords = requireValue(raw, ++index, arg);
|
|
100
|
+
} else {
|
|
101
|
+
console.error(`SANSA Query tool error: unknown argument '${arg}'.`);
|
|
102
|
+
process.exit(2);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return output;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parsePolicy(value) {
|
|
109
|
+
if (value === undefined) return undefined;
|
|
110
|
+
if (value === 'validation') return value;
|
|
111
|
+
console.error(`SANSA Query tool error: unsupported --policy '${value}'. Expected 'validation'.`);
|
|
112
|
+
process.exit(2);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function parseBudgetArgs(options) {
|
|
116
|
+
const budget = {};
|
|
117
|
+
for (const [flag, key] of [
|
|
118
|
+
['--max-from-bindings', 'maxFromBindings'],
|
|
119
|
+
['--max-where-candidates', 'maxWhereCandidates'],
|
|
120
|
+
['--max-order-candidates', 'maxOrderCandidates'],
|
|
121
|
+
['--max-result-records', 'maxResultRecords'],
|
|
122
|
+
]) {
|
|
123
|
+
if (options[key] === undefined) continue;
|
|
124
|
+
budget[key] = parseBudgetLimit(options[key], flag);
|
|
125
|
+
}
|
|
126
|
+
return Object.keys(budget).length === 0 ? undefined : budget;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function parseBudgetLimit(value, flag) {
|
|
130
|
+
if (!/^(0|[1-9][0-9]*)$/.test(value)) {
|
|
131
|
+
console.error(`SANSA Query tool error: ${flag} expects a non-negative integer.`);
|
|
132
|
+
process.exit(2);
|
|
133
|
+
}
|
|
134
|
+
const parsed = Number(value);
|
|
135
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
136
|
+
console.error(`SANSA Query tool error: ${flag} exceeds the JavaScript safe integer range.`);
|
|
137
|
+
process.exit(2);
|
|
138
|
+
}
|
|
139
|
+
return parsed;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function buildEvaluateOptions({ policy, transformEnabled, budget }) {
|
|
143
|
+
return {
|
|
144
|
+
...(policy ? { policy } : {}),
|
|
145
|
+
...(transformEnabled ? {} : { extensions: { transform: false } }),
|
|
146
|
+
...(budget ? { budget } : {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function requireValue(raw, index, flag) {
|
|
151
|
+
const value = raw[index];
|
|
152
|
+
if (!value || value.startsWith('--')) {
|
|
153
|
+
console.error(`SANSA Query tool error: ${flag} expects a value.`);
|
|
154
|
+
process.exit(2);
|
|
155
|
+
}
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function readQuerySource(options) {
|
|
160
|
+
if (typeof options.query === 'string') return options.query;
|
|
161
|
+
if (typeof options.queryFile === 'string') return readFileSync(resolve(options.queryFile), 'utf8');
|
|
162
|
+
if (!process.stdin.isTTY) return readFileSync(0, 'utf8');
|
|
163
|
+
return '';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function readNamespaceFixture(path, explicitKind) {
|
|
167
|
+
const kind = inferFixtureKind(path, explicitKind);
|
|
168
|
+
let source;
|
|
169
|
+
try {
|
|
170
|
+
source = readFileSync(path, 'utf8');
|
|
171
|
+
} catch (error) {
|
|
172
|
+
console.error(`SANSA Query tool error: could not read fixture '${path}': ${error.message}`);
|
|
173
|
+
return { ok: false };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (kind === 'json') {
|
|
177
|
+
try {
|
|
178
|
+
return { ok: true, namespace: buildNamespace(JSON.parse(source)) };
|
|
179
|
+
} catch (error) {
|
|
180
|
+
console.error(`SANSA Query tool error: could not parse JSON fixture '${path}': ${error.message}`);
|
|
181
|
+
return { ok: false };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const result = await namespaceFromAeonSource(source);
|
|
186
|
+
if (!result.ok) {
|
|
187
|
+
console.error(`SANSA Query tool error: could not compile AEON fixture '${path}':`);
|
|
188
|
+
console.error(result.text);
|
|
189
|
+
return { ok: false };
|
|
190
|
+
}
|
|
191
|
+
return { ok: true, namespace: result.namespace };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function inferFixtureKind(path, explicitKind) {
|
|
195
|
+
if (explicitKind !== undefined) {
|
|
196
|
+
if (explicitKind === 'json' || explicitKind === 'aeon') return explicitKind;
|
|
197
|
+
console.error(`SANSA Query tool error: unsupported --fixture-kind '${explicitKind}'. Expected 'json' or 'aeon'.`);
|
|
198
|
+
process.exit(2);
|
|
199
|
+
}
|
|
200
|
+
if (path.endsWith('.json')) return 'json';
|
|
201
|
+
if (path.endsWith('.aeon')) return 'aeon';
|
|
202
|
+
console.error(`SANSA Query tool error: could not infer fixture kind from '${path}'. Use --fixture-kind json or --fixture-kind aeon.`);
|
|
203
|
+
process.exit(2);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function readParamsBinding(options) {
|
|
207
|
+
if (typeof options.params === 'string' && typeof options.paramsFile === 'string') {
|
|
208
|
+
console.error('SANSA Query tool error: use either --params or --params-file, not both.');
|
|
209
|
+
process.exit(2);
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
const source = typeof options.params === 'string'
|
|
213
|
+
? options.params
|
|
214
|
+
: typeof options.paramsFile === 'string'
|
|
215
|
+
? readFileSync(resolve(options.paramsFile), 'utf8')
|
|
216
|
+
: undefined;
|
|
217
|
+
if (source === undefined) return undefined;
|
|
218
|
+
return normalizeParamsPayload(JSON.parse(source));
|
|
219
|
+
} catch (error) {
|
|
220
|
+
const origin = typeof options.paramsFile === 'string'
|
|
221
|
+
? ` from '${resolve(options.paramsFile)}'`
|
|
222
|
+
: '';
|
|
223
|
+
console.error(`SANSA Query tool error: could not read params${origin}: ${error.message}`);
|
|
224
|
+
process.exit(2);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function normalizeParamsPayload(payload) {
|
|
229
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
230
|
+
throw new Error('expected a JSON object.');
|
|
231
|
+
}
|
|
232
|
+
if (Array.isArray(payload.children)) {
|
|
233
|
+
return normalizeFixtureBinding(payload, '$.<"params">');
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
address: '$.<"params">',
|
|
237
|
+
representationKind: 'object',
|
|
238
|
+
children: Object.entries(payload).map(([name, value]) => normalizeParamEntry(name, value)),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function normalizeParamEntry(name, value) {
|
|
243
|
+
const address = `$.<"params">.${renderParamMember(name)}`;
|
|
244
|
+
if (isSansaAddressLiteralValue(value)) {
|
|
245
|
+
return {
|
|
246
|
+
name,
|
|
247
|
+
address,
|
|
248
|
+
semanticType: 'sansa',
|
|
249
|
+
representationKind: 'sansa',
|
|
250
|
+
value,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
if (value && typeof value === 'object' && !Array.isArray(value) && isFixtureBindingShape(value)) {
|
|
254
|
+
return normalizeFixtureBinding({ ...value, name: value.name ?? name }, address);
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
name,
|
|
258
|
+
address,
|
|
259
|
+
semanticType: semanticTypeForParamValue(value),
|
|
260
|
+
representationKind: representationKindForParamValue(value),
|
|
261
|
+
value,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function normalizeFixtureBinding(binding, fallbackAddress) {
|
|
266
|
+
if (!binding || typeof binding !== 'object' || Array.isArray(binding)) {
|
|
267
|
+
throw new Error('expected params binding objects.');
|
|
268
|
+
}
|
|
269
|
+
const normalized = {
|
|
270
|
+
...binding,
|
|
271
|
+
address: binding.address ?? fallbackAddress,
|
|
272
|
+
};
|
|
273
|
+
if (Array.isArray(binding.children)) {
|
|
274
|
+
normalized.children = binding.children.map((child, index) => {
|
|
275
|
+
const childAddress = child && typeof child === 'object' && typeof child.name === 'string'
|
|
276
|
+
? `${normalized.address}.${renderParamMember(child.name)}`
|
|
277
|
+
: child && typeof child === 'object' && Number.isInteger(child.index)
|
|
278
|
+
? `${normalized.address}[${child.index}]`
|
|
279
|
+
: `${normalized.address}[${index}]`;
|
|
280
|
+
const explicitAddress = child && typeof child === 'object' && !Array.isArray(child)
|
|
281
|
+
? child.address
|
|
282
|
+
: undefined;
|
|
283
|
+
return normalizeFixtureBinding(child, explicitAddress ?? childAddress);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
return normalized;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function isFixtureBindingShape(value) {
|
|
290
|
+
return (
|
|
291
|
+
Object.hasOwn(value, 'value') ||
|
|
292
|
+
Object.hasOwn(value, 'scalar') ||
|
|
293
|
+
Object.hasOwn(value, 'children') ||
|
|
294
|
+
Object.hasOwn(value, 'attributeSpace') ||
|
|
295
|
+
Object.hasOwn(value, 'attributes') ||
|
|
296
|
+
Object.hasOwn(value, 'localSpaces') ||
|
|
297
|
+
Object.hasOwn(value, 'semanticType') ||
|
|
298
|
+
Object.hasOwn(value, 'representationKind')
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function isSansaAddressLiteralValue(value) {
|
|
303
|
+
return (
|
|
304
|
+
value &&
|
|
305
|
+
typeof value === 'object' &&
|
|
306
|
+
!Array.isArray(value) &&
|
|
307
|
+
value.type === 'SansaAddressLiteral' &&
|
|
308
|
+
typeof value.address === 'string'
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function renderParamMember(name) {
|
|
313
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)
|
|
314
|
+
? name
|
|
315
|
+
: `[${JSON.stringify(name)}]`;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function semanticTypeForParamValue(value) {
|
|
319
|
+
if (value === null) return 'null';
|
|
320
|
+
if (typeof value === 'string') return 'string';
|
|
321
|
+
if (typeof value === 'number') return 'number';
|
|
322
|
+
if (typeof value === 'boolean') return 'boolean';
|
|
323
|
+
if (Array.isArray(value)) return 'list';
|
|
324
|
+
return 'object';
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function representationKindForParamValue(value) {
|
|
328
|
+
return semanticTypeForParamValue(value);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function mountParamsLocalSpace(rootBinding, paramsBinding) {
|
|
332
|
+
if (!rootBinding || typeof rootBinding !== 'object') {
|
|
333
|
+
console.error('SANSA Query tool error: params require a fixture root binding object.');
|
|
334
|
+
process.exit(2);
|
|
335
|
+
}
|
|
336
|
+
rootBinding.localSpaces = {
|
|
337
|
+
...(rootBinding.localSpaces ?? {}),
|
|
338
|
+
params: paramsBinding,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function buildNamespace(fixture) {
|
|
343
|
+
const rootBinding = fixture.root ?? fixture;
|
|
344
|
+
return {
|
|
345
|
+
root: rootBinding,
|
|
346
|
+
children: (binding) => binding.children ?? [],
|
|
347
|
+
attributeSpace: (binding) => binding.attributeSpace ?? binding.attributes,
|
|
348
|
+
localSpace: (binding, name) => binding.localSpaces?.[name],
|
|
349
|
+
value: valueFromBinding,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function formatJsonResult(result, mode, fixturePath) {
|
|
354
|
+
if (!result.ok) {
|
|
355
|
+
return {
|
|
356
|
+
ok: false,
|
|
357
|
+
mode,
|
|
358
|
+
fixture: fixturePath,
|
|
359
|
+
errors: result.errors,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
if (mode === 'parse') {
|
|
363
|
+
return {
|
|
364
|
+
ok: true,
|
|
365
|
+
mode,
|
|
366
|
+
fixture: fixturePath,
|
|
367
|
+
query: summarizeQuery(result.query),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
ok: true,
|
|
372
|
+
mode,
|
|
373
|
+
fixture: fixturePath,
|
|
374
|
+
count: result.results.length,
|
|
375
|
+
results: result.results.map((entry) => ({
|
|
376
|
+
type: entry.type,
|
|
377
|
+
...(entry.address === undefined ? {} : { address: entry.address }),
|
|
378
|
+
binding: summarizeBinding(entry.binding),
|
|
379
|
+
value: sanitizeJsonValue(summarizeQueryValue(entry.value)),
|
|
380
|
+
})),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function printTextResult(result, mode, fixturePath) {
|
|
385
|
+
if (!result.ok) {
|
|
386
|
+
console.error(`SANSA Query ${mode} failed (${fixturePath})`);
|
|
387
|
+
for (const error of result.errors) {
|
|
388
|
+
const location = Number.isInteger(error.index)
|
|
389
|
+
? ` at index ${error.index}`
|
|
390
|
+
: Number.isInteger(error.selectorIndex)
|
|
391
|
+
? ` at selector ${error.selectorIndex}`
|
|
392
|
+
: '';
|
|
393
|
+
const phase = typeof error.phase === 'string' ? ` [${error.phase}]` : '';
|
|
394
|
+
const candidate = typeof error.candidateAddress === 'string' ? ` at ${error.candidateAddress}` : '';
|
|
395
|
+
console.error(`${error.code}${phase}${candidate}${location}: ${error.message}`);
|
|
396
|
+
}
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (mode === 'parse') {
|
|
401
|
+
console.log(result.query.canonical);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (result.results.length === 0) {
|
|
406
|
+
console.log('(no results)');
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
for (const entry of result.results) {
|
|
411
|
+
for (const line of renderQueryValueLines(entry.value, entry.binding)) {
|
|
412
|
+
console.log(line);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function renderQueryValueLines(value, sourceBinding) {
|
|
418
|
+
switch (value.type) {
|
|
419
|
+
case 'scalar':
|
|
420
|
+
return [`${sourceBinding.address ?? '<binding>'} = ${renderAeonValue(value.value, value[QUERY_VALUE_METADATA_PROPERTY])}`];
|
|
421
|
+
case 'object':
|
|
422
|
+
return [`${sourceBinding.address ?? '<binding>'} = ${renderAeonValue(value.value, undefined, value.value?.[QUERY_OBJECT_FIELD_METADATA_PROPERTY])}`];
|
|
423
|
+
case 'bindingSet':
|
|
424
|
+
if (value.bindings.length === 0) return [`${sourceBinding.address ?? '<binding>'} -> (empty)`];
|
|
425
|
+
return value.bindings.map((binding) => {
|
|
426
|
+
const scalar = scalarFromBinding(binding);
|
|
427
|
+
return scalar.ok
|
|
428
|
+
? `${binding.address ?? '<binding>'} = ${renderAeonValue(scalar.value, scalarMetadataFromBinding(binding))}`
|
|
429
|
+
: `${binding.address ?? '<binding>'}`;
|
|
430
|
+
});
|
|
431
|
+
default:
|
|
432
|
+
return [`${sourceBinding.address ?? '<binding>'} = ${renderAeonValue(value)}`];
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function renderAeonValue(value, metadata, fieldMetadata) {
|
|
437
|
+
if ((metadata?.kind === 'null' || value === null) && typeof metadata?.nullReason === 'string') {
|
|
438
|
+
return `!${metadata.nullReason}`;
|
|
439
|
+
}
|
|
440
|
+
if (metadata?.kind === 'nan' || (typeof value === 'number' && Number.isNaN(value))) return 'NaN';
|
|
441
|
+
if (metadata?.kind === 'infinity' || value === Infinity) return 'Infinity';
|
|
442
|
+
if (value === -Infinity) return '-Infinity';
|
|
443
|
+
if (value === null) return 'null';
|
|
444
|
+
if (typeof value === 'string') return JSON.stringify(value);
|
|
445
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
446
|
+
if (Array.isArray(value)) {
|
|
447
|
+
return `[${value.map((entry) => renderAeonValue(entry)).join(',')}]`;
|
|
448
|
+
}
|
|
449
|
+
if (value && typeof value === 'object') {
|
|
450
|
+
return `{${Object.entries(value).map(([key, entry]) => (
|
|
451
|
+
`${JSON.stringify(key)}:${renderAeonValue(entry, fieldMetadata?.[key])}`
|
|
452
|
+
)).join(',')}}`;
|
|
453
|
+
}
|
|
454
|
+
return JSON.stringify(value);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function scalarMetadataFromBinding(binding) {
|
|
458
|
+
const metadata = {};
|
|
459
|
+
const kind = binding.scalarKind ?? binding.valueKind ?? binding.literalKind ?? binding.representationKind ?? binding.kind ?? binding.type;
|
|
460
|
+
if (typeof kind === 'string') metadata.kind = lowerFirst(kind);
|
|
461
|
+
if (binding.nullReason !== undefined) metadata.nullReason = binding.nullReason;
|
|
462
|
+
return Object.keys(metadata).length > 0 ? metadata : undefined;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function lowerFirst(value) {
|
|
466
|
+
return value ? value[0].toLowerCase() + value.slice(1) : value;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function summarizeQueryValue(value) {
|
|
470
|
+
switch (value.type) {
|
|
471
|
+
case 'bindingSet':
|
|
472
|
+
return {
|
|
473
|
+
type: value.type,
|
|
474
|
+
bindings: value.bindings.map(summarizeBinding),
|
|
475
|
+
};
|
|
476
|
+
case 'scalar':
|
|
477
|
+
case 'object':
|
|
478
|
+
return value;
|
|
479
|
+
default:
|
|
480
|
+
return value;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function valueFromBinding(binding) {
|
|
485
|
+
if (binding.scalarKind === 'nan') return Number.NaN;
|
|
486
|
+
if (binding.scalarKind === 'infinity') {
|
|
487
|
+
return binding.value === '-Infinity' || binding.scalar === '-Infinity' ? -Infinity : Infinity;
|
|
488
|
+
}
|
|
489
|
+
if (Object.hasOwn(binding, 'value')) return binding.value;
|
|
490
|
+
if (Object.hasOwn(binding, 'scalar')) return binding.scalar;
|
|
491
|
+
return undefined;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function sanitizeJsonValue(value) {
|
|
495
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return String(value);
|
|
496
|
+
if (Array.isArray(value)) return value.map(sanitizeJsonValue);
|
|
497
|
+
if (value && typeof value === 'object') {
|
|
498
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, sanitizeJsonValue(entry)]));
|
|
499
|
+
}
|
|
500
|
+
return value;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function summarizeQuery(query) {
|
|
504
|
+
return {
|
|
505
|
+
canonical: query.canonical,
|
|
506
|
+
clauses: query.clauses,
|
|
507
|
+
from: summarizeQueryFrom(query.from),
|
|
508
|
+
...(query.where ? { where: query.where.expression } : {}),
|
|
509
|
+
...(query.orderBy ? {
|
|
510
|
+
orderBy: query.orderBy.keys.map((key) => ({
|
|
511
|
+
expression: key.expression,
|
|
512
|
+
direction: key.direction,
|
|
513
|
+
})),
|
|
514
|
+
} : {}),
|
|
515
|
+
...(query.offset ? { offset: query.offset.value } : {}),
|
|
516
|
+
...(query.limit ? { limit: query.limit.value } : {}),
|
|
517
|
+
select: query.select.expression,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function summarizeQueryFrom(from) {
|
|
522
|
+
return from.source === 'expression'
|
|
523
|
+
? from.expression
|
|
524
|
+
: from.address.canonical;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function summarizeBinding(binding) {
|
|
528
|
+
const scalar = scalarFromBinding(binding);
|
|
529
|
+
return {
|
|
530
|
+
...(binding.address === undefined ? {} : { address: binding.address }),
|
|
531
|
+
...(binding.name === undefined ? {} : { name: binding.name }),
|
|
532
|
+
...(binding.index === undefined ? {} : { index: binding.index }),
|
|
533
|
+
...(binding.semanticType === undefined ? {} : { semanticType: binding.semanticType }),
|
|
534
|
+
...(binding.representationKind === undefined ? {} : { representationKind: binding.representationKind }),
|
|
535
|
+
...(binding.scalarKind === undefined ? {} : { scalarKind: binding.scalarKind }),
|
|
536
|
+
...(binding.nullReason === undefined ? {} : { nullReason: binding.nullReason }),
|
|
537
|
+
...(scalar.ok ? { value: sanitizeJsonValue(scalar.value) } : {}),
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function scalarFromBinding(binding) {
|
|
542
|
+
const value = valueFromBinding(binding);
|
|
543
|
+
if (value !== undefined) return { ok: true, value };
|
|
544
|
+
if (Object.hasOwn(binding, 'value')) return { ok: true, value: binding.value };
|
|
545
|
+
if (Object.hasOwn(binding, 'scalar')) return { ok: true, value: binding.scalar };
|
|
546
|
+
return { ok: false };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function printHelp() {
|
|
550
|
+
console.log(`SANSA Query tool
|
|
551
|
+
|
|
552
|
+
Usage:
|
|
553
|
+
npm run query -- --query "from $.inventory.items.*\\nselect .sku"
|
|
554
|
+
npm run query -- --query-file query.sansaq --fixture fixture.aeon
|
|
555
|
+
npm run query -- --query-file query.sansaq --fixture fixture.json
|
|
556
|
+
npm run query -- --mode parse --query "from $.inventory.items.*\\nselect .sku"
|
|
557
|
+
|
|
558
|
+
Options:
|
|
559
|
+
-q, --query <source> Query source.
|
|
560
|
+
--query-file <path> Read query source from a file.
|
|
561
|
+
-f, --fixture <path> AEON or JSON namespace fixture. Defaults to fixtures/query-inventory.json.
|
|
562
|
+
--fixture-kind <kind> Force fixture kind: aeon or json. Inferred from extension by default.
|
|
563
|
+
--params <json> Mount JSON params at $.<"params">.
|
|
564
|
+
--params-file <path> Read JSON params and mount them at $.<"params">.
|
|
565
|
+
--mode <mode> evaluate or parse. Defaults to evaluate.
|
|
566
|
+
--format <format> text or json. Defaults to text.
|
|
567
|
+
--policy <policy> Optional query policy: validation.
|
|
568
|
+
--disable-transform Disable experimental SANSA.Transform helpers.
|
|
569
|
+
--max-from-bindings <n>
|
|
570
|
+
Fail if the from source resolves more than n bindings.
|
|
571
|
+
--max-where-candidates <n>
|
|
572
|
+
Fail if where would evaluate more than n candidates.
|
|
573
|
+
--max-order-candidates <n>
|
|
574
|
+
Fail if order by would sort more than n candidates.
|
|
575
|
+
--max-result-records <n>
|
|
576
|
+
Fail if select would produce more than n result records.
|
|
577
|
+
-h, --help Show this help.
|
|
578
|
+
`);
|
|
579
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { parseAddress } from '../src/index.js';
|
|
6
|
+
|
|
7
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const root = resolve(here, '..');
|
|
9
|
+
|
|
10
|
+
const suites = [
|
|
11
|
+
{
|
|
12
|
+
name: 'valid',
|
|
13
|
+
file: resolve(root, 'stress-tests/address/valid.sansa-cases'),
|
|
14
|
+
shouldParse: true,
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: 'invalid',
|
|
18
|
+
file: resolve(root, 'stress-tests/address/invalid.sansa-cases'),
|
|
19
|
+
shouldParse: false,
|
|
20
|
+
},
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
let failures = 0;
|
|
24
|
+
let total = 0;
|
|
25
|
+
|
|
26
|
+
for (const suite of suites) {
|
|
27
|
+
const cases = readCases(suite.file);
|
|
28
|
+
for (const testCase of cases) {
|
|
29
|
+
total += 1;
|
|
30
|
+
const result = parseAddress(testCase.source);
|
|
31
|
+
if (suite.shouldParse && !result.ok) {
|
|
32
|
+
failures += 1;
|
|
33
|
+
const first = result.errors[0];
|
|
34
|
+
console.error(`[FAIL] ${suite.name} case ${testCase.index}: expected parse success`);
|
|
35
|
+
console.error(` source: ${JSON.stringify(testCase.source)}`);
|
|
36
|
+
console.error(` error: ${first.code} ${first.message}`);
|
|
37
|
+
}
|
|
38
|
+
if (!suite.shouldParse && result.ok) {
|
|
39
|
+
failures += 1;
|
|
40
|
+
console.error(`[FAIL] ${suite.name} case ${testCase.index}: expected parse failure`);
|
|
41
|
+
console.error(` source: ${JSON.stringify(testCase.source)}`);
|
|
42
|
+
console.error(` canonical: ${result.address.canonical}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (failures > 0) {
|
|
48
|
+
console.error(`SANSA address stress failed: ${failures}/${total} cases failed`);
|
|
49
|
+
process.exit(1);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
console.log(`SANSA address stress passed: ${total} cases`);
|
|
53
|
+
|
|
54
|
+
function readCases(file) {
|
|
55
|
+
const raw = readFileSync(file, 'utf8');
|
|
56
|
+
return raw
|
|
57
|
+
.split(/^---[ \t]*$/m)
|
|
58
|
+
.map((chunk) => chunk
|
|
59
|
+
.split(/\r?\n/)
|
|
60
|
+
.filter((line) => !line.trimStart().startsWith('//'))
|
|
61
|
+
.join('\n')
|
|
62
|
+
.trim())
|
|
63
|
+
.filter((source) => source.length > 0)
|
|
64
|
+
.map((source, index) => ({ source, index: index + 1 }));
|
|
65
|
+
}
|