lambdajson-js 2.0.0 → 3.1.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/README.md CHANGED
@@ -22,4 +22,27 @@ lint({ $str: ['\\ needless escape'] }); // => [{ severity: 'warning', code: 'nee
22
22
  ```
23
23
 
24
24
  `compile` throws a `LambdaJSONError` (with `code` and a JSON Pointer `path`) for a malformed program.
25
- See the language documentation for the full reference and the migration notes from 1.x.
25
+ Problems found while a program runs throw a `LambdaJSONRuntimeError` (also with `code` and `path`).
26
+ See the language documentation for the full reference and the migration notes.
27
+
28
+ ## Type inference
29
+
30
+ `infer(program, { input, vars, primitives })` returns `{ type, problems }`: the JSON Schema type of the result
31
+ and the errors and warnings (impossible paths, possibly missing operands, mismatched arguments, impossible
32
+ comparisons, unbound variables) found from the type of the input, without running the program.
33
+ See the language documentation.
34
+
35
+ ## Changes in 3.1
36
+
37
+ * `infer(program, { input, vars, primitives })`: type inference with errors and warnings before a program runs.
38
+ * `typed(primitive, signature, infer?)` accepts JSON Schema types as well as notation.
39
+
40
+ ## Changes in 3.0
41
+
42
+ * **Breaking:** arithmetic (`$sum`, `$subtract`, `$multiply`, `$divide`) and ordering (`$lt`, `$lte`, `$gt`, `$gte`)
43
+ throw `LambdaJSONRuntimeError` (`missing-operand`) on a `null` or `undefined` operand instead of passing it on.
44
+ * **Breaking:** `$eq` and `$neq` compare deeply, by value.
45
+ * Functions with named parameters: `{ "$let": { "$f": { "$fn": { "as": ["a", "b"], "body": … } } }, "$f": [1, 2] }`;
46
+ `#` in the body stays the caller's input.
47
+ * New primitives: `$round`, `$min`, `$max`, `$count`, `$find`, `$unique`, `$pick`, `$omit`, `$lower`, `$upper`, `$trim`, `$isNil`.
48
+ * `signatureOf(name)` returns the declared types of a primitive; `typed(primitive, { takes, returns })` declares them for custom ones.
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "lambdajson-js",
3
- "version": "2.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "LambdaJSON to JavaScript function compiler",
5
5
  "type": "module",
6
6
  "main": "./src/js-compiler.js",
7
7
  "module": "./src/js-compiler.js",
8
8
  "files": [
9
9
  "src",
10
- "src/README.md",
11
10
  "LICENSE"
12
11
  ],
13
12
  "exports": {
@@ -34,7 +33,8 @@
34
33
  "license": "MIT",
35
34
  "author": "Benjamin Batistic",
36
35
  "scripts": {
37
- "test": "mocha"
36
+ "test": "mocha",
37
+ "prepublishOnly": "npm test"
38
38
  },
39
39
  "dependencies": {
40
40
  "fast-printf": "^1.6.10",
@@ -46,5 +46,11 @@
46
46
  "esbuild": "^0.27.0",
47
47
  "globals": "^16.5.0",
48
48
  "mocha": "^11.7.5"
49
+ },
50
+ "engines": {
51
+ "node": ">=18"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
49
55
  }
50
56
  }
package/src/infer.js ADDED
@@ -0,0 +1,420 @@
1
+ import { isArray, isEqual, isPlainObject, isString, mapValues, toPath } from 'lodash-es';
2
+ import { primitives as builtins } from './primitives.js';
3
+ import { lint } from './js-compiler.js';
4
+ import {
5
+ ANY, ARRAY, BOOLEAN, FUNCTION, NULL, NUMBER, OBJECT, STRING,
6
+ arrayOf, describe, disjoint, isAny, isNullable, itemOf, literalType, members, nonNull, normalize,
7
+ nullable, objectOf, orAny, toType, tuple, union, valueOf, walkPath
8
+ } from './types.js';
9
+
10
+ const LET = '$let';
11
+ const pointer = (path, ...keys) => keys.reduce((p, key) => `${p}/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`, path);
12
+ const NUMBER_OR_STRING = union(NUMBER, STRING);
13
+ const isTuple = t => t.type === 'array' && t.items === false && t.prefixItems !== undefined;
14
+
15
+ /**
16
+ * Infers the type of the result of a program from the type of its input, and reports the
17
+ * problems that are certain (errors) or possible (warnings) before it runs.
18
+ * @param {any} program
19
+ * @param {{ input?: object, vars?: object, primitives?: object }} options types as JSON Schema
20
+ * @returns {{ type: object, problems: { severity: 'error' | 'warning', code: string, path: string, message: string }[] }}
21
+ */
22
+ export function infer(program, { input = {}, vars = {}, primitives: extended = {} } = {}) {
23
+ const problems = lint(program, extended);
24
+ if (problems.some(p => p.severity === 'error')) return { type: ANY, problems };
25
+ const seen = new Set(problems.map(p => JSON.stringify(p)));
26
+ const report = (severity, code, path, message) => {
27
+ const problem = { severity, code, path, message };
28
+ const key = JSON.stringify(problem);
29
+ if (!seen.has(key)) {
30
+ seen.add(key);
31
+ problems.push(problem);
32
+ }
33
+ };
34
+ const engine = createEngine({ ...builtins, ...extended }, report);
35
+ const env = { input: toType(input), vars: mapValues(vars, toType), funcs: new Map() };
36
+ return { type: engine.tree(env, program, ''), problems };
37
+ }
38
+
39
+ function createEngine(prims, report) {
40
+ const active = new Set();
41
+
42
+ const error = (code, path, message) => report('error', code, path, message);
43
+ const warning = (code, path, message) => report('warning', code, path, message);
44
+
45
+ function tree(env, node, path) {
46
+ if (isString(node)) return string(env, node, path);
47
+ if (isArray(node)) return tuple(node.map((n, i) => tree(env, n, pointer(path, i))));
48
+ if (isPlainObject(node)) {
49
+ return Object.keys(node).some(k => k.startsWith('$')) ? call(env, node, path) : object(env, node, path);
50
+ }
51
+ return literalType(node);
52
+ }
53
+
54
+ function object(env, node, path) {
55
+ const properties = {};
56
+ for (const key of Object.keys(node)) {
57
+ properties[key.startsWith('\\') ? key.slice(1) : key] = tree(env, node[key], pointer(path, key));
58
+ }
59
+ return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false };
60
+ }
61
+
62
+ function string(env, node, path) {
63
+ if (node.startsWith('\\')) return literalType(node.slice(1));
64
+ if (node === '#') return env.input;
65
+ const fail = message => error('unknown-path', path, message);
66
+ if (node.startsWith('#')) {
67
+ let p = node.slice(1);
68
+ p = /^\d/.test(p) ? `[${p[0]}]` + p.slice(1) : p;
69
+ p = p.startsWith('.') ? p.slice(1) : p;
70
+ return walkPath(env.input, toPath(p), fail);
71
+ }
72
+ if (node.startsWith('@')) {
73
+ const [name, ...rest] = toPath(node.slice(1));
74
+ if (name === undefined || !Object.prototype.hasOwnProperty.call(env.vars, name)) {
75
+ error('unknown-variable', path, `'${name ?? ''}' is not bound by an enclosing '${LET}' or 'as'`);
76
+ return ANY;
77
+ }
78
+ return walkPath(env.vars[name], rest, fail);
79
+ }
80
+ return literalType(node);
81
+ }
82
+
83
+ function call(env, node, path) {
84
+ const keys = Object.keys(node);
85
+ const key = keys.find(k => k !== LET);
86
+ if (!keys.includes(LET)) return head(env, key, node[key], path);
87
+
88
+ const letPath = pointer(path, LET);
89
+ const declarations = node[LET];
90
+ const funcs = new Map(env.funcs);
91
+ const inner = { ...env, funcs, vars: { ...env.vars } };
92
+ for (const name of Object.keys(declarations)) {
93
+ if (name.startsWith('$')) funcs.set(name, { tree: declarations[name], path: pointer(letPath, name), funcs });
94
+ }
95
+ for (const name of Object.keys(declarations)) {
96
+ if (!name.startsWith('$')) inner.vars[name] = tree(inner, declarations[name], pointer(letPath, name));
97
+ }
98
+ return head(inner, key, node[key], path);
99
+ }
100
+
101
+ function head(env, key, value, path) {
102
+ const argPath = pointer(path, key);
103
+ const prim = prims[key];
104
+ return prim !== undefined ? primitive(env, key, prim, value, argPath) : functionCall(env, key, value, argPath);
105
+ }
106
+
107
+ function functionCall(env, key, value, path) {
108
+ const arg = tree(env, value, path);
109
+ const decl = env.funcs.get(key);
110
+ if (!decl || active.has(decl)) return ANY;
111
+ active.add(decl);
112
+ try {
113
+ const fn = isPlainObject(decl.tree) && Object.keys(decl.tree).length === 1 ? decl.tree.$fn : undefined;
114
+ if (fn === undefined) return tree({ input: arg, vars: env.vars, funcs: decl.funcs }, decl.tree, decl.path);
115
+ const vars = { ...env.vars, ...bindParameters(fn.as, arg, path) };
116
+ return tree({ input: env.input, vars, funcs: decl.funcs }, fn.body, pointer(decl.path, '$fn', 'body'));
117
+ } finally {
118
+ active.delete(decl);
119
+ }
120
+ }
121
+
122
+ function bindParameters(as, arg, path) {
123
+ if (!isArray(as)) return { [as]: arg };
124
+ if (disjoint(arg, ARRAY)) {
125
+ error('type-mismatch', path, `the function takes ${as.length} arguments as an array, got ${describe(arg)}`);
126
+ return Object.fromEntries(as.map(name => [name, ANY]));
127
+ }
128
+ const argument = nonNull(arg);
129
+ if (isTuple(argument)) {
130
+ if (argument.prefixItems.length !== as.length) {
131
+ error('wrong-argument-count', path, `the function takes ${as.length} arguments, got ${argument.prefixItems.length}`);
132
+ return Object.fromEntries(as.map(name => [name, ANY]));
133
+ }
134
+ return Object.fromEntries(as.map((name, i) => [name, argument.prefixItems[i]]));
135
+ }
136
+ const item = itemOf(argument);
137
+ return Object.fromEntries(as.map(name => [name, item]));
138
+ }
139
+
140
+ function primitive(env, key, prim, value, path) {
141
+ const builtin = prim === builtins[key];
142
+ if (builtin && FORMS[key]) return FORMS[key](env, value, path);
143
+ if (prim.params) return named(env, key, prim, value, path, builtin);
144
+ if (typeof prim !== 'function') return returnsOf(prim.signature, ANY);
145
+ return positional(env, key, prim, value, path, builtin);
146
+ }
147
+
148
+ const returnsOf = (signature, argument) => {
149
+ if (signature === undefined) return ANY;
150
+ if (signature.infer) return normalize(signature.infer(argument, {}));
151
+ return signature.returns === undefined ? ANY : toType(signature.returns);
152
+ };
153
+
154
+ function positional(env, key, prim, value, path, builtin) {
155
+ const arg = tree(env, value, path);
156
+ const signature = prim.signature;
157
+ if (signature?.takes !== undefined) checkTakes(toType(signature.takes), arg, value, path);
158
+ if (builtin && RESULTS[key]) return RESULTS[key](arg, path);
159
+ return returnsOf(signature, arg);
160
+ }
161
+
162
+ /** The operands of an argument that is an array: [{ type, path }]. */
163
+ function operands(value, arg, path) {
164
+ const array = nonNull(arg);
165
+ if (array.prefixItems) {
166
+ const list = array.prefixItems.map((type, i) => ({ type, path: isArray(value) ? pointer(path, i) : path }));
167
+ return array.items === false ? list : [...list, { type: array.items ?? ANY, path }];
168
+ }
169
+ return [{ type: itemOf(array), path }];
170
+ }
171
+
172
+ function check(expected, actual, path, what) {
173
+ if (disjoint(actual, expected)) {
174
+ error('type-mismatch', path, `${what} is ${describe(actual)}, expected ${describe(expected)}`);
175
+ }
176
+ }
177
+
178
+ function checkTakes(expected, arg, value, path) {
179
+ if (expected.type === 'array' && expected.items && expected.items !== false) {
180
+ check(ARRAY, arg, path, 'the argument');
181
+ if (disjoint(arg, ARRAY)) return;
182
+ for (const operand of operands(value, arg, path)) check(expected.items, operand.type, operand.path, 'an item');
183
+ } else {
184
+ check(expected, arg, path, 'the argument');
185
+ }
186
+ }
187
+
188
+ function named(env, key, prim, value, path, builtin) {
189
+ const signature = prim.signature;
190
+ const takes = isPlainObject(signature?.takes) ? signature.takes : {};
191
+ const rule = builtin ? NAMED[key] : undefined;
192
+ const types = {};
193
+ const lambdas = {};
194
+ for (const [k, v] of Object.entries(value)) {
195
+ const argPath = pointer(path, k);
196
+ if (k === 'as') continue;
197
+ if (takes[k] === 'function') {
198
+ lambdas[k] = [v, argPath];
199
+ continue;
200
+ }
201
+ types[k] = tree(env, v, argPath);
202
+ if (takes[k] !== undefined) check(toType(takes[k]), types[k], argPath, `'${k}'`);
203
+ }
204
+ for (const spec of prim.params) {
205
+ const name = spec.replace(/(=#|\?)$/, '');
206
+ if (spec.endsWith('=#') && !(name in types) && !(name in lambdas)) {
207
+ types[name] = env.input;
208
+ if (takes[name] !== undefined) check(toType(takes[name]), env.input, path, `the input`);
209
+ }
210
+ }
211
+ const as = value.as === undefined ? undefined : isArray(value.as) ? value.as : [value.as];
212
+ const bodies = {};
213
+ for (const k of Object.keys(lambdas)) {
214
+ const run = (args, input) => lambda(env, lambdas[k], as, args, input);
215
+ bodies[k] = rule?.fns?.[k] ? rule.fns[k](types, run) : run([], ANY);
216
+ }
217
+ if (rule?.result) return rule.result(types, bodies, path);
218
+ return returnsOf(signature, types);
219
+ }
220
+
221
+ function lambda(env, [node, path], as, args, input = args[0] ?? ANY) {
222
+ const scope = as === undefined
223
+ ? { ...env, input }
224
+ : { ...env, vars: { ...env.vars, ...Object.fromEntries(as.map((name, i) => [name, args[i] ?? ANY])) } };
225
+ return tree(scope, node, path);
226
+ }
227
+
228
+ /** Arithmetic and ordering fail at run time on a missing operand. */
229
+ const strict = accepted => (env, value, path) => {
230
+ const arg = tree(env, value, path);
231
+ if (disjoint(arg, ARRAY)) {
232
+ error('type-mismatch', path, `the argument is ${describe(arg)}, expected an array of operands`);
233
+ } else {
234
+ if (isNullable(arg)) warning('possibly-missing-operand', path, 'the operands may be missing');
235
+ for (const operand of operands(value, arg, path)) {
236
+ if (disjoint(operand.type, accepted)) {
237
+ error('type-mismatch', operand.path, `an operand is ${describe(operand.type)}, expected ${describe(accepted)}`);
238
+ } else if (isNullable(operand.type)) {
239
+ warning('possibly-missing-operand', operand.path, `an operand may be missing: ${describe(operand.type)}`);
240
+ }
241
+ }
242
+ }
243
+ };
244
+ const arithmetic = strict(NUMBER);
245
+ const ordering = strict(NUMBER_OR_STRING);
246
+
247
+ const truthyConst = t => 'const' in t && !!t.const;
248
+ const args = (env, value, path) => value.map((v, i) => tree(env, v, pointer(path, i)));
249
+
250
+ const FORMS = {
251
+ $literal: (env, value) => literalType(value),
252
+ $: (env, value, path) => {
253
+ tree({ ...env, input: ANY }, value, path);
254
+ return FUNCTION;
255
+ },
256
+ $if: (env, value, path) => {
257
+ const [, then, otherwise] = args(env, value, path);
258
+ return otherwise ? union(then, otherwise) : nullable(then);
259
+ },
260
+ $cond: (env, value, path) => {
261
+ const results = value.map((clause, i) => [tree(env, clause[0], pointer(path, i, 0)), tree(env, clause[1], pointer(path, i, 1))]);
262
+ const last = results[results.length - 1];
263
+ const total = last && !isAny(last[0]) && members(last[0]).every(truthyConst);
264
+ return orAny(union(...results.map(r => r[1]), ...(total ? [] : [NULL])));
265
+ },
266
+ $and: (env, value, path) => logic(env, value, path, true),
267
+ $or: (env, value, path) => logic(env, value, path, false),
268
+ };
269
+ for (const key of ['$sum', '$subtract', '$multiply', '$divide']) {
270
+ FORMS[key] = (env, value, path) => { arithmetic(env, value, path); return NUMBER; };
271
+ }
272
+ for (const key of ['$lt', '$lte', '$gt', '$gte']) {
273
+ FORMS[key] = (env, value, path) => { ordering(env, value, path); return BOOLEAN; };
274
+ }
275
+
276
+ function logic(env, value, path, empty) {
277
+ const types = isArray(value) ? args(env, value, path) : [itemOf(tree(env, value, path))];
278
+ return orAny(union(...types, ...(types.length === 0 ? [literalType(empty)] : [])));
279
+ }
280
+
281
+ const mergeObjects = types => {
282
+ const objects = types.map(nonNull);
283
+ if (!objects.every(t => t.type === 'object')) return OBJECT;
284
+ const properties = {};
285
+ const required = new Set();
286
+ let closed = true;
287
+ for (const t of objects) {
288
+ for (const [k, p] of Object.entries(t.properties ?? {})) {
289
+ const previous = properties[k];
290
+ properties[k] = previous && nonNull(previous).type === 'object' && nonNull(p).type === 'object' ? mergeObjects([previous, p]) : p;
291
+ }
292
+ (t.required ?? []).forEach(k => required.add(k));
293
+ closed = closed && t.additionalProperties === false;
294
+ }
295
+ return { type: 'object', properties, required: [...required], ...(closed ? { additionalProperties: false } : {}) };
296
+ };
297
+
298
+ const literalKeys = t => {
299
+ const list = nonNull(t);
300
+ return isTuple(list) && list.prefixItems.every(m => typeof m.const === 'string') ? list.prefixItems.map(m => m.const) : null;
301
+ };
302
+
303
+ const restrict = (object, keep) => {
304
+ const o = nonNull(object);
305
+ if (o.type !== 'object') return OBJECT;
306
+ const result = { ...o };
307
+ if (o.properties) result.properties = Object.fromEntries(Object.entries(o.properties).filter(([k]) => keep(k)));
308
+ if (o.required) result.required = o.required.filter(keep);
309
+ return result;
310
+ };
311
+
312
+ const RESULTS = {
313
+ $in: a => a,
314
+ $return: a => a,
315
+ $eq: (a, path) => compared(a, path),
316
+ $neq: (a, path) => compared(a, path),
317
+ $head: a => {
318
+ const list = nonNull(a);
319
+ if (list.prefixItems?.length > 0) return list.prefixItems[0];
320
+ return isTuple(list) ? NULL : nullable(itemOf(list));
321
+ },
322
+ $tail: a => arrayOf(itemOf(a)),
323
+ $unique: a => arrayOf(itemOf(a)),
324
+ $concat: a => arrayOf(orAny(union(...operands(undefined, a, '').map(o => itemOf(o.type))))),
325
+ $keys: a => {
326
+ const o = nonNull(a);
327
+ const keys = o.type === 'object' && o.additionalProperties === false ? Object.keys(o.properties ?? {}) : null;
328
+ return arrayOf(keys && keys.length > 0 ? { type: 'string', enum: keys } : STRING);
329
+ },
330
+ $values: a => arrayOf(valueOf(a)),
331
+ $merge: a => mergeObjects(operands(undefined, a, '').map(o => o.type)),
332
+ $coalesce: a => {
333
+ const list = nonNull(a);
334
+ if (!isTuple(list)) return nullable(itemOf(list));
335
+ const result = [];
336
+ for (const type of list.prefixItems) {
337
+ result.push(nonNull(type));
338
+ if (!isNullable(type)) return orAny(union(...result));
339
+ }
340
+ return orAny(union(...result, NULL));
341
+ },
342
+ $match: () => nullable(arrayOf(STRING)),
343
+ $parseInt: () => nullable(NUMBER),
344
+ $parseFloat: () => nullable(NUMBER),
345
+ };
346
+
347
+ function compared(a, path) {
348
+ const list = nonNull(a);
349
+ if (list.prefixItems?.length >= 2 && disjoint(list.prefixItems[0], list.prefixItems[1])) {
350
+ warning('impossible-comparison', path, `${describe(list.prefixItems[0])} and ${describe(list.prefixItems[1])} are never equal`);
351
+ }
352
+ return BOOLEAN;
353
+ }
354
+
355
+ const over = (collection, fn, result, argsOf = item => [item, NUMBER]) => ({
356
+ fns: { [fn]: (t, run) => run(argsOf(itemOf(t[collection]))) },
357
+ result: (t, b) => result(b, itemOf(t[collection])),
358
+ });
359
+ const sequenceItems = sequences => {
360
+ const list = nonNull(sequences);
361
+ return isTuple(list) && list.prefixItems.length === 2
362
+ ? list.prefixItems.map(itemOf)
363
+ : [itemOf(itemOf(list)), itemOf(itemOf(list))];
364
+ };
365
+
366
+ const NAMED = {
367
+ $map: over('over', 'fn', b => arrayOf(b.fn)),
368
+ $filter: over('collection', 'predicate', (b, item) => arrayOf(item)),
369
+ $any: over('collection', 'predicate', () => BOOLEAN),
370
+ $all: over('collection', 'predicate', () => BOOLEAN),
371
+ $find: over('collection', 'predicate', (b, item) => nullable(item)),
372
+ $count: over('collection', 'predicate', () => NUMBER),
373
+ $group: over('collection', 'by', (b, item) => objectOf(arrayOf(item)), item => [item]),
374
+ $toDictionary: over('collection', 'by', (b, item) => objectOf(item), item => [item]),
375
+ $ascending: over('collection', 'by', (b, item) => arrayOf(item), item => [item]),
376
+ $descending: over('collection', 'by', (b, item) => arrayOf(item), item => [item]),
377
+ $take: over('from', 'while', (b, item) => arrayOf(item), item => [item]),
378
+ $mapValues: {
379
+ fns: { fn: (t, run) => run([valueOf(t.of), STRING]) },
380
+ result: (t, b) => objectOf(b.fn),
381
+ },
382
+ $apply: {
383
+ fns: { fn: (t, run) => run([t.to]) },
384
+ result: (t, b) => b.fn,
385
+ },
386
+ $zip: {
387
+ fns: { with: (t, run) => { const pair = sequenceItems(t.sequences); return run(pair, tuple(pair)); } },
388
+ result: (t, b) => arrayOf('with' in b ? b.with : tuple(sequenceItems(t.sequences))),
389
+ },
390
+ $fold: {
391
+ fns: {
392
+ with: (t, run) => {
393
+ const item = itemOf(t.collection);
394
+ let accumulator = t.init ?? item;
395
+ for (let pass = 0; pass < 2; pass++) {
396
+ const next = union(accumulator, run([accumulator, item], tuple([accumulator, item])));
397
+ if (isEqual(next, accumulator)) break;
398
+ accumulator = next;
399
+ }
400
+ return accumulator;
401
+ }
402
+ },
403
+ result: (t, b) => b.with,
404
+ },
405
+ $get: {
406
+ result: (t, b, path) => {
407
+ const literal = t.path && 'const' in t.path && typeof t.path.const === 'string';
408
+ return literal ? walkPath(t.object, toPath(t.path.const), message => error('unknown-path', pointer(path, 'path'), message)) : ANY;
409
+ },
410
+ },
411
+ $pick: {
412
+ result: t => { const keys = literalKeys(t.keys); return keys ? restrict(t.object, k => keys.includes(k)) : OBJECT; },
413
+ },
414
+ $omit: {
415
+ result: t => { const keys = literalKeys(t.keys); return keys ? restrict(t.object, k => !keys.includes(k)) : nonNull(t.object).type === 'object' ? nonNull(t.object) : OBJECT; },
416
+ },
417
+ };
418
+
419
+ return { tree };
420
+ }
@@ -1,12 +1,14 @@
1
- import { get, isArray, isPlainObject, isString, map, mapValues } from 'lodash-es'
2
- import { primitives } from './primitives.js';
1
+ import { get, isArray, isPlainObject, isString, map, mapValues, zipObject } from 'lodash-es'
2
+ import { primitives, LambdaJSONRuntimeError } from './primitives.js';
3
3
 
4
4
  export {
5
5
  compile,
6
6
  lint,
7
+ signatureOf,
7
8
  LambdaJSONError
8
9
  }
9
- export { primitives, named, special, call } from './primitives.js';
10
+ export { primitives, named, special, call, typed, LambdaJSONRuntimeError } from './primitives.js';
11
+ export { infer } from './infer.js';
10
12
 
11
13
  /**
12
14
  * A problem in the structure of a program, found while compiling it.
@@ -22,6 +24,7 @@ class LambdaJSONError extends Error {
22
24
  }
23
25
 
24
26
  const LET = '$let';
27
+ const FN = '$fn';
25
28
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
26
29
 
27
30
  /**
@@ -55,6 +58,15 @@ function lint(program, extendedPrimitives = {}) {
55
58
  return problems;
56
59
  }
57
60
 
61
+ /**
62
+ * The declared types of a primitive: `{ takes, returns }`, or undefined when it declares none.
63
+ * @param {string} name
64
+ * @param {object} extendedPrimitives
65
+ */
66
+ function signatureOf(name, extendedPrimitives = {}) {
67
+ return ({ ...primitives, ...extendedPrimitives })[name]?.signature;
68
+ }
69
+
58
70
  function compileProgram(program, extendedPrimitives, warn) {
59
71
  const scope = {
60
72
  primitives: { ...primitives, ...extendedPrimitives },
@@ -204,7 +216,7 @@ function parseAs(value, path) {
204
216
 
205
217
  function compileFunctionCall(scope, key, value, path) {
206
218
  const arg = compileTree(scope, value, path);
207
- return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }) });
219
+ return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }), outer: input });
208
220
  }
209
221
 
210
222
  function compileArray(scope, tree, path) {
@@ -212,8 +224,34 @@ function compileArray(scope, tree, path) {
212
224
  return x => map(funks, f => f(x));
213
225
  }
214
226
 
227
+ /**
228
+ * `{ "$fn": { "as": names, "body": expression } }` declares a function with named parameters.
229
+ * The call's argument is bound to the name, or its items to the names of an array; `#` in the
230
+ * body stays the input of the caller.
231
+ */
232
+ function compileFunction(scope, tree, path) {
233
+ const fnPath = pointer(path, FN);
234
+ const spec = tree[FN];
235
+ if (!isPlainObject(spec) || Object.keys(spec).some(k => k !== 'as' && k !== 'body') || !('as' in spec) || !('body' in spec)) {
236
+ fail('invalid-function', fnPath, `'${FN}' is an object { as, body }`);
237
+ }
238
+ const names = parseAs(spec.as, pointer(fnPath, 'as'));
239
+ const body = compileTree(scope, spec.body, pointer(fnPath, 'body'));
240
+ return ({ vars, input, outer }) => {
241
+ const args = isArray(spec.as) ? input : [input];
242
+ if (args.length !== names.length) {
243
+ throw new LambdaJSONRuntimeError('wrong-argument-count', fnPath, `the function takes ${names.length} argument(s), got ${args.length}`);
244
+ }
245
+ return body({ vars: { ...vars, ...zipObject(names, args) }, input: outer });
246
+ };
247
+ }
248
+
249
+ const isFunctionDeclaration = tree => isPlainObject(tree) && Object.keys(tree).length === 1 && FN in tree;
250
+
215
251
  function compileVars(scope, obj, path) {
216
- const funks = mapValues(obj, (n, k) => compileTree(scope, n, pointer(path, k)));
252
+ const funks = mapValues(obj, (n, k) => k.startsWith('$') && isFunctionDeclaration(n)
253
+ ? compileFunction(scope, n, pointer(path, k))
254
+ : compileTree(scope, n, pointer(path, k)));
217
255
  return ({ vars, input }) => {
218
256
  const localVars = {};
219
257
  const extendedVars = { ...vars };
package/src/primitives.js CHANGED
@@ -1,6 +1,19 @@
1
1
  import { printf } from 'fast-printf';
2
- import { concat, divide, eq, every, filter, first, get, groupBy, gt, gte, includes, isArray, join, keyBy, keys, lt, lte, map, mapValues, merge, multiply,
3
- orderBy, reduce, some, split, subtract, sum, tail, take, takeWhile, values, zipObject, zipWith } from 'lodash-es'
2
+ import { concat, divide, every, filter, find, first, get, groupBy, gt, gte, includes, isArray, isEqual, isNil, join, keyBy, keys, lt, lte, map, mapValues, max, merge, min, multiply,
3
+ omit, orderBy, pick, reduce, round, some, split, subtract, sum, tail, take, takeWhile, uniqWith, values, zipObject, zipWith } from 'lodash-es'
4
+
5
+ /**
6
+ * A problem found while a program runs, e.g. an operand that is missing.
7
+ * `path` is a JSON Pointer to the offending node of the program, `code` a stable identifier.
8
+ */
9
+ export class LambdaJSONRuntimeError extends Error {
10
+ constructor(code, path, message) {
11
+ super(`${message} (at ${path || '/'})`);
12
+ this.name = 'LambdaJSONRuntimeError';
13
+ this.code = code;
14
+ this.path = path;
15
+ }
16
+ }
4
17
 
5
18
  /**
6
19
  * Primitives come in three shapes:
@@ -44,10 +57,27 @@ const variadic = (name, empty, decides) => special((args, { compile }) => {
44
57
  };
45
58
  }, { description: `${name}: [a, b, …], short-circuits` });
46
59
 
60
+ /**
61
+ * Arithmetic and ordering need values: an operand that is null or undefined (typically a path
62
+ * missing in the input) fails with the path of the call instead of flowing on silently.
63
+ */
64
+ const strict = (name, impl) => special((args, { compile, path }) => {
65
+ const f = compile(args);
66
+ return x => {
67
+ const operands = f(x);
68
+ const missing = isArray(operands) ? operands.findIndex(isNil) : isNil(operands) ? 0 : -1;
69
+ if (missing >= 0) {
70
+ throw new LambdaJSONRuntimeError('missing-operand', path,
71
+ `${name} got ${operands?.[missing] === null ? 'null' : 'undefined'} as ${isArray(operands) ? `operand ${missing}` : 'its operand'}; a path in the input is probably missing`);
72
+ }
73
+ return impl(operands);
74
+ };
75
+ });
76
+
47
77
  const sort = direction => named(['by?', 'collection=#', 'as?'], ({ by, collection, as }) => x =>
48
78
  orderBy(collection(x), by ? [v => call(by, as, x, [v])] : undefined, [direction]));
49
79
 
50
- export const primitives = {
80
+ const primitiveTable = {
51
81
  $let: true,
52
82
  $literal: special(value => () => value),
53
83
  $: f => x => v => f({ ...x, input: v }),
@@ -78,17 +108,17 @@ export const primitives = {
78
108
  $not: f => x => !f(x),
79
109
  $negate: f => x => !f(x),
80
110
 
81
- $eq: f => x => eq(...f(x)),
82
- $neq: f => x => !eq(...f(x)),
83
- $lt: f => x => lt(...f(x)),
84
- $lte: f => x => lte(...f(x)),
85
- $gt: f => x => gt(...f(x)),
86
- $gte: f => x => gte(...f(x)),
111
+ $eq: f => x => isEqual(...f(x)),
112
+ $neq: f => x => !isEqual(...f(x)),
113
+ $lt: strict('$lt', v => lt(...v)),
114
+ $lte: strict('$lte', v => lte(...v)),
115
+ $gt: strict('$gt', v => gt(...v)),
116
+ $gte: strict('$gte', v => gte(...v)),
87
117
 
88
- $sum: f => x => sum(f(x)),
89
- $subtract: f => x => subtract(...f(x)),
90
- $multiply: f => x => multiply(...f(x)),
91
- $divide: f => x => divide(...f(x)),
118
+ $sum: strict('$sum', v => sum(v)),
119
+ $subtract: strict('$subtract', v => subtract(...v)),
120
+ $multiply: strict('$multiply', v => multiply(...v)),
121
+ $divide: strict('$divide', v => divide(...v)),
92
122
 
93
123
  $map: named(['fn', 'over=#', 'as?'], ({ fn, over, as }) => x => map(over(x), lambda(fn, as, x))),
94
124
  $mapValues: named(['fn', 'of=#', 'as?'], ({ fn, of, as }) => x => mapValues(of(x), lambda(fn, as, x))),
@@ -136,6 +166,85 @@ export const primitives = {
136
166
  return string(x).replace(p, substitute(x));
137
167
  }),
138
168
  $printf: named(['template', 'args=#'], ({ template, args }) => x => printf(template(x), ...args(x))),
169
+ $round: named(['value=#', 'digits?'], ({ value, digits }) => x => round(value(x), digits?.(x))),
170
+ $min: f => x => min(f(x)),
171
+ $max: f => x => max(f(x)),
172
+ $count: named(['predicate?', 'collection=#', 'as?'], ({ predicate, collection, as }) => x =>
173
+ predicate ? filter(collection(x), lambda(predicate, as, x)).length : collection(x).length),
174
+ $find: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => find(collection(x), lambda(predicate, as, x))),
175
+ $unique: f => x => uniqWith(f(x), isEqual),
176
+ $pick: named(['keys', 'object=#'], ({ keys, object }) => x => pick(object(x), keys(x))),
177
+ $omit: named(['keys', 'object=#'], ({ keys, object }) => x => omit(object(x), keys(x))),
178
+ $lower: f => x => toStr(f(x)).toLowerCase(),
179
+ $upper: f => x => toStr(f(x)).toUpperCase(),
180
+ $trim: f => x => toStr(f(x)).trim(),
181
+ $isNil: f => x => isNil(f(x)),
139
182
  $parseInt: f => x => { const n = parseInt(f(x), 10); return isNaN(n) ? undefined : n; },
140
183
  $parseFloat: f => x => { const n = parseFloat(f(x)); return isNaN(n) ? undefined : n; },
141
184
  }
185
+
186
+ /**
187
+ * Types of the primitives, so that tools can infer what a program takes and returns.
188
+ * `takes` is the type of the expression argument, or an object of parameter types for
189
+ * named parameters; `returns` the type of the result. Types: `any`, `number`, `string`,
190
+ * `boolean`, `object`, `function` (a lambda), `names` (the `as` parameter), `array` or `array<T>`.
191
+ * A type (JSON Schema) is accepted wherever a notation is. A custom primitive declares its own with
192
+ * `typed(primitive, signature, infer?)`; `infer(argumentTypes, context)` computes the result type from the
193
+ * type of the argument (an object of parameter types for named parameters).
194
+ */
195
+ export const typed = (primitive, signature, infer) => {
196
+ const declared = infer ? { ...signature, infer } : signature;
197
+ return typeof primitive === 'function' ? Object.assign(primitive, { signature: declared }) : { ...primitive, signature: declared };
198
+ };
199
+
200
+ const sig = (takes, returns) => ({ takes, returns });
201
+ const over = (fn, collection, returns, extra = {}) => sig({ [fn]: 'function', [collection]: collection === 'of' ? 'object' : 'array', ...extra, as: 'names' }, returns);
202
+ const numbers = 'array<number>';
203
+
204
+ const signatures = {
205
+ $literal: sig('any', 'any'), $: sig('any', 'function'), $in: sig('any', 'any'), $return: sig('any', 'any'),
206
+ $apply: sig({ fn: 'function', to: 'any', as: 'names' }, 'any'),
207
+ $pipeline: sig('array<function>', 'any'),
208
+ $if: sig('array', 'any'), $cond: sig('array', 'any'), $and: sig('array', 'any'), $or: sig('array', 'any'),
209
+ $not: sig('any', 'boolean'), $negate: sig('any', 'boolean'),
210
+ $eq: sig('array', 'boolean'), $neq: sig('array', 'boolean'),
211
+ $lt: sig(numbers, 'boolean'), $lte: sig(numbers, 'boolean'), $gt: sig(numbers, 'boolean'), $gte: sig(numbers, 'boolean'),
212
+ $sum: sig(numbers, 'number'), $subtract: sig(numbers, 'number'), $multiply: sig(numbers, 'number'), $divide: sig(numbers, 'number'),
213
+ $map: over('fn', 'over', 'array'),
214
+ $mapValues: over('fn', 'of', 'object'),
215
+ $filter: over('predicate', 'collection', 'array'),
216
+ $any: over('predicate', 'collection', 'boolean'),
217
+ $all: over('predicate', 'collection', 'boolean'),
218
+ $group: over('by', 'collection', 'object'),
219
+ $toDictionary: over('by', 'collection', 'object'),
220
+ $ascending: over('by', 'collection', 'array'),
221
+ $descending: over('by', 'collection', 'array'),
222
+ $take: sig({ while: 'function', count: 'number', from: 'array', as: 'names' }, 'array'),
223
+ $zip: sig({ with: 'function', sequences: 'array<array>', as: 'names' }, 'array'),
224
+ $fold: sig({ with: 'function', init: 'any', collection: 'array', as: 'names' }, 'any'),
225
+ $head: sig('array', 'any'), $tail: sig('array', 'array'), $concat: sig('array<array>', 'array'),
226
+ $keys: sig('object', 'array<string>'), $values: sig('object', 'array'), $merge: sig('array<object>', 'object'),
227
+ $coalesce: sig('array', 'any'),
228
+ $get: sig({ object: 'object', path: 'string' }, 'any'),
229
+ $includes: sig({ collection: 'array', value: 'any' }, 'boolean'),
230
+ $str: sig('any', 'string'),
231
+ $join: sig({ separator: 'string', strings: 'array' }, 'string'),
232
+ $split: sig({ separator: 'string', string: 'string' }, 'array<string>'),
233
+ $match: sig({ pattern: 'string', string: 'string' }, 'array'),
234
+ $isMatch: sig({ pattern: 'string', string: 'string' }, 'boolean'),
235
+ $replace: sig({ regex: 'string', substitute: 'string', string: 'string', global: 'boolean' }, 'string'),
236
+ $printf: sig({ template: 'string', args: 'array' }, 'string'),
237
+ $round: sig({ value: 'number', digits: 'number' }, 'number'),
238
+ $min: sig(numbers, 'number'), $max: sig(numbers, 'number'),
239
+ $count: over('predicate', 'collection', 'number'),
240
+ $find: over('predicate', 'collection', 'any'),
241
+ $unique: sig('array', 'array'),
242
+ $pick: sig({ keys: 'array<string>', object: 'object' }, 'object'),
243
+ $omit: sig({ keys: 'array<string>', object: 'object' }, 'object'),
244
+ $lower: sig('string', 'string'), $upper: sig('string', 'string'), $trim: sig('string', 'string'),
245
+ $isNil: sig('any', 'boolean'),
246
+ $parseInt: sig('string', 'number'), $parseFloat: sig('string', 'number'),
247
+ };
248
+
249
+ export const primitives = Object.fromEntries(Object.entries(primitiveTable).map(([name, primitive]) =>
250
+ [name, signatures[name] ? typed(primitive, signatures[name]) : primitive]));
package/src/types.js ADDED
@@ -0,0 +1,293 @@
1
+ import { isArray, isEqual, isPlainObject, isString, mapValues } from 'lodash-es';
2
+
3
+ /**
4
+ * Types are JSON Schema objects restricted to: `type`, `const`, `enum`, `items`, `prefixItems`,
5
+ * `properties`, `required`, `additionalProperties` and `anyOf`, plus the non-standard
6
+ * `{ type: 'function' }`. `{}` is any value; a missing value is `{ type: 'null' }`.
7
+ */
8
+ export const ANY = {};
9
+ export const NULL = { type: 'null' };
10
+ export const NUMBER = { type: 'number' };
11
+ export const STRING = { type: 'string' };
12
+ export const BOOLEAN = { type: 'boolean' };
13
+ export const FUNCTION = { type: 'function' };
14
+ export const ARRAY = { type: 'array' };
15
+ export const OBJECT = { type: 'object' };
16
+ export const NEVER = { enum: [] };
17
+
18
+ export const arrayOf = items => ({ type: 'array', items });
19
+ export const objectOf = additionalProperties => ({ type: 'object', additionalProperties });
20
+ export const tuple = prefixItems => ({ type: 'array', prefixItems, items: false });
21
+
22
+ export const isAny = t => Object.keys(t).length === 0;
23
+ export const members = t => t.anyOf ?? [t];
24
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
25
+
26
+ /**
27
+ * Reduces a JSON Schema (or a signature notation, see `toType`) to the supported subset.
28
+ */
29
+ export function normalize(t) {
30
+ if (t === false) return NEVER;
31
+ if (!isPlainObject(t)) return ANY;
32
+ if (isArray(t.anyOf)) return union(...t.anyOf.map(normalize));
33
+ if (isArray(t.type)) return union(...t.type.map(type => normalize({ ...t, type })));
34
+ const out = {};
35
+ if (isString(t.type)) out.type = t.type === 'integer' ? 'number' : t.type;
36
+ if ('const' in t) out.const = t.const;
37
+ if (isArray(t.enum)) out.enum = t.enum;
38
+ if (t.items !== undefined) out.items = t.items === false ? false : normalize(t.items);
39
+ if (isArray(t.prefixItems)) out.prefixItems = t.prefixItems.map(normalize);
40
+ if (isPlainObject(t.properties)) out.properties = mapValues(t.properties, normalize);
41
+ if (isArray(t.required)) out.required = t.required;
42
+ if (t.additionalProperties === false) out.additionalProperties = false;
43
+ else if (isPlainObject(t.additionalProperties)) out.additionalProperties = normalize(t.additionalProperties);
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Notation of a signature: `any`, `number`, `string`, `boolean`, `object`, `array`, `array<T>`,
49
+ * `function`; anything else that is an object is a type.
50
+ */
51
+ export function toType(notation) {
52
+ if (isString(notation)) {
53
+ const generic = /^array<(.+)>$/.exec(notation);
54
+ if (generic) return arrayOf(toType(generic[1]));
55
+ return { number: NUMBER, string: STRING, boolean: BOOLEAN, object: OBJECT, array: ARRAY, function: FUNCTION }[notation] ?? ANY;
56
+ }
57
+ return normalize(notation);
58
+ }
59
+
60
+ export function literalType(value) {
61
+ if (value === null) return { type: 'null', const: null };
62
+ if (isArray(value)) return tuple(value.map(literalType));
63
+ if (isPlainObject(value)) {
64
+ return { type: 'object', properties: mapValues(value, literalType), required: Object.keys(value), additionalProperties: false };
65
+ }
66
+ return { type: typeof value, const: value };
67
+ }
68
+
69
+ const valuesOf = m => 'const' in m ? [m.const] : m.enum ?? null;
70
+
71
+ const kindOfValue = v => v === null ? 'null' : isArray(v) ? 'array' : typeof v;
72
+
73
+ function kindsOf(m) {
74
+ if (m.type !== undefined) return [m.type];
75
+ const values = valuesOf(m);
76
+ return values === null ? null : [...new Set(values.map(kindOfValue))];
77
+ }
78
+
79
+ export function valueMatches(v, t) {
80
+ return members(t).some(m => matchOne(v, m));
81
+ }
82
+
83
+ function matchOne(v, m) {
84
+ if (isAny(m)) return true;
85
+ if (m.type !== undefined && m.type !== kindOfValue(v)) return false;
86
+ const values = valuesOf(m);
87
+ if (values && !values.some(x => isEqual(x, v))) return false;
88
+ if (isArray(v)) {
89
+ return v.every((item, i) => {
90
+ const target = m.prefixItems?.[i] ?? (m.items === false ? null : m.items);
91
+ return target === null ? false : target === undefined || valueMatches(item, target);
92
+ });
93
+ }
94
+ if (isPlainObject(v)) {
95
+ if ((m.required ?? []).some(k => !own(v, k))) return false;
96
+ return Object.entries(v).every(([k, item]) => {
97
+ const target = own(m.properties ?? {}, k) ? m.properties[k] : m.additionalProperties;
98
+ return target === false ? false : target === undefined || valueMatches(item, target);
99
+ });
100
+ }
101
+ return true;
102
+ }
103
+
104
+ /** Every value of `s` is a value of `t`; conservative: false when it can't be shown. */
105
+ export function assignable(s, t) {
106
+ return members(s).every(a => members(t).some(b => assignableOne(a, b)));
107
+ }
108
+
109
+ function assignableOne(a, b) {
110
+ if (isAny(b)) return true;
111
+ if (isAny(a)) return false;
112
+ const values = valuesOf(a);
113
+ if (values) return values.every(v => matchOne(v, b));
114
+ if (a.type === undefined || a.type !== b.type || valuesOf(b)) return false;
115
+ if (a.type === 'array') return arrayAssignable(a, b);
116
+ if (a.type === 'object') return objectAssignable(a, b);
117
+ return true;
118
+ }
119
+
120
+ function arrayAssignable(a, b) {
121
+ const aPrefix = a.prefixItems ?? [];
122
+ const bPrefix = b.prefixItems ?? [];
123
+ for (let i = 0; i < aPrefix.length; i++) {
124
+ const target = bPrefix[i] ?? (b.items === false ? null : b.items ?? ANY);
125
+ if (!target || !assignable(aPrefix[i], target)) return false;
126
+ }
127
+ if (a.items === false) return true;
128
+ if (b.items === false) return false;
129
+ const rest = a.items ?? ANY;
130
+ return assignable(rest, b.items ?? ANY) && bPrefix.slice(aPrefix.length).every(t => assignable(rest, t));
131
+ }
132
+
133
+ function objectAssignable(a, b) {
134
+ const aProps = a.properties ?? {};
135
+ const bProps = b.properties ?? {};
136
+ const aRequired = a.required ?? [];
137
+ for (const [k, target] of Object.entries(bProps)) {
138
+ if (own(aProps, k)) {
139
+ if (!assignable(aProps[k], target)) return false;
140
+ } else if ((b.required ?? []).includes(k) || (a.additionalProperties !== false && !assignable(a.additionalProperties ?? ANY, target))) {
141
+ return false;
142
+ }
143
+ }
144
+ if ((b.required ?? []).some(k => !aRequired.includes(k))) return false;
145
+ const extra = Object.keys(aProps).filter(k => !own(bProps, k));
146
+ if (b.additionalProperties === false) return a.additionalProperties === false && extra.length === 0;
147
+ if (b.additionalProperties !== undefined) {
148
+ return (a.additionalProperties === false || assignable(a.additionalProperties ?? ANY, b.additionalProperties))
149
+ && extra.every(k => assignable(aProps[k], b.additionalProperties));
150
+ }
151
+ return true;
152
+ }
153
+
154
+ /** No value is both `s` and `t`. */
155
+ export function disjoint(s, t) {
156
+ return members(s).every(a => members(t).every(b => disjointOne(a, b)));
157
+ }
158
+
159
+ function disjointOne(a, b) {
160
+ if (isAny(a) || isAny(b)) return false;
161
+ const ka = kindsOf(a);
162
+ const kb = kindsOf(b);
163
+ if (ka && kb && !ka.some(k => kb.includes(k))) return true;
164
+ const va = valuesOf(a);
165
+ const vb = valuesOf(b);
166
+ if (va && vb) return !va.some(x => vb.some(y => isEqual(x, y)));
167
+ if (va) return !va.some(v => matchOne(v, b));
168
+ if (vb) return !vb.some(v => matchOne(v, a));
169
+ return false;
170
+ }
171
+
172
+ /** The union of types, normalized: flat, without duplicates or members assignable to another. */
173
+ export function union(...types) {
174
+ const result = [];
175
+ for (const t of types) {
176
+ if (isAny(t)) return ANY;
177
+ for (const m of members(t)) {
178
+ if (result.some(r => assignableOne(m, r))) continue;
179
+ for (let i = result.length - 1; i >= 0; i--) {
180
+ if (assignableOne(result[i], m)) result.splice(i, 1);
181
+ }
182
+ result.push(m);
183
+ }
184
+ }
185
+ if (result.length === 0) return NEVER;
186
+ return result.length === 1 ? result[0] : { anyOf: result };
187
+ }
188
+
189
+ export const orAny = t => isEqual(t, NEVER) ? ANY : t;
190
+
191
+ export function isNullable(t) {
192
+ return !isAny(t) && members(t).some(m => kindsOf(m)?.includes('null'));
193
+ }
194
+
195
+ export function nonNull(t) {
196
+ return union(...members(t).map(m => {
197
+ if (m.enum) return { enum: m.enum.filter(v => v !== null) };
198
+ return kindsOf(m)?.length === 1 && kindsOf(m)[0] === 'null' ? NEVER : m;
199
+ }));
200
+ }
201
+
202
+ export const nullable = t => union(t, NULL);
203
+
204
+ /** The type of an element of an array type. */
205
+ export function itemOf(t) {
206
+ const items = members(nonNull(t)).map(m => {
207
+ if (m.type !== 'array') return ANY;
208
+ if (m.prefixItems === undefined && m.items === undefined) return ANY;
209
+ return union(...(m.prefixItems ?? []), ...(m.items === false ? [] : [m.items ?? ANY]));
210
+ });
211
+ return orAny(union(...items));
212
+ }
213
+
214
+ /** The type of a value of an object type. */
215
+ export function valueOf(t) {
216
+ const values = members(nonNull(t)).map(m => {
217
+ if (m.type !== 'object') return ANY;
218
+ const add = m.additionalProperties;
219
+ return union(...Object.values(m.properties ?? {}), ...(add === false ? [] : [add ?? ANY]));
220
+ });
221
+ return orAny(union(...values));
222
+ }
223
+
224
+ const expand = m => {
225
+ if (m.type !== undefined) return [m];
226
+ if ('const' in m) return [literalType(m.const)];
227
+ return m.enum ? m.enum.map(literalType) : [m];
228
+ };
229
+
230
+ const describeKeys = props => Object.keys(props).join(', ') || 'none';
231
+
232
+ function walkMember(m, k) {
233
+ if (isAny(m)) return { type: ANY };
234
+ const numeric = /^\d+$/.test(k);
235
+ switch (m.type) {
236
+ case 'object': {
237
+ const props = m.properties ?? {};
238
+ if (own(props, k)) return { type: (m.required ?? []).includes(k) ? props[k] : nullable(props[k]) };
239
+ if (m.additionalProperties === false) {
240
+ return { error: `'${k}' is not a property of the object (declared: ${describeKeys(props)})` };
241
+ }
242
+ return { type: nullable(m.additionalProperties ?? ANY) };
243
+ }
244
+ case 'array': {
245
+ if (numeric) {
246
+ const prefix = m.prefixItems ?? [];
247
+ if (Number(k) < prefix.length) return { type: prefix[Number(k)] };
248
+ if (m.items === false) return { error: `index ${k} is beyond the tuple of ${prefix.length}` };
249
+ return { type: nullable(m.items ?? ANY) };
250
+ }
251
+ return k === 'length' ? { type: NUMBER } : { error: `an array has no '${k}'` };
252
+ }
253
+ case 'string':
254
+ if (k === 'length') return { type: NUMBER };
255
+ return numeric ? { type: nullable(STRING) } : { error: `a string has no '${k}'` };
256
+ default:
257
+ return { error: `a ${m.type} has no '${k}'` };
258
+ }
259
+ }
260
+
261
+ /** Walks one segment: `{ type }`, or `{ error }` when the segment can't exist. */
262
+ export function walkSegment(t, k) {
263
+ const results = members(t).flatMap(expand).map(m => kindsOf(m)?.[0] === 'null' && kindsOf(m).length === 1
264
+ ? { type: NULL, isNull: true }
265
+ : walkMember(m, k));
266
+ const real = results.filter(r => !r.isNull);
267
+ if (real.length > 0 && real.every(r => r.error)) return { error: real[0].error };
268
+ return { type: union(...results.filter(r => !r.error).map(r => r.type)) };
269
+ }
270
+
271
+ /** Walks a path; calls `fail(message)` at the first impossible segment and continues with null. */
272
+ export function walkPath(t, segments, fail) {
273
+ let current = t;
274
+ for (const segment of segments) {
275
+ const step = walkSegment(current, segment);
276
+ if (step.error) {
277
+ fail(step.error);
278
+ return NULL;
279
+ }
280
+ current = step.type;
281
+ }
282
+ return current;
283
+ }
284
+
285
+ export function describe(t) {
286
+ if (isAny(t)) return 'any';
287
+ return members(t).map(m => {
288
+ if ('const' in m) return JSON.stringify(m.const);
289
+ if (m.enum) return m.enum.map(v => JSON.stringify(v)).join(' | ') || 'never';
290
+ if (m.type === 'array' && m.items && m.items !== false) return `array<${describe(m.items)}>`;
291
+ return m.type ?? 'any';
292
+ }).join(' | ');
293
+ }