trilean 1.12.0 → 1.13.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.
@@ -4,7 +4,7 @@ import { parseArgs } from "node:util";
4
4
  import { z } from "zod";
5
5
  import { RegexParseError, compilePattern } from "trilean-regex";
6
6
  //#region package.json
7
- var version = "1.12.0";
7
+ var version = "1.13.1";
8
8
  //#endregion
9
9
  //#region src/computed-value.ts
10
10
  /** Dimension symbol -\> exponent, e.g. `{ m: 1, s: -1 }` for metres per second. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`. */
@@ -133,27 +133,6 @@ function createEvaluationBudget(maxNodes, maxNestingDepth) {
133
133
  } };
134
134
  }
135
135
  //#endregion
136
- //#region src/complex.ts
137
- const complexFromPolar = (magnitude, phase, unit) => ({
138
- kind: "complex",
139
- re: magnitude * Math.cos(phase),
140
- im: magnitude * Math.sin(phase),
141
- unit
142
- });
143
- /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
144
- const complexMagnitude = (value) => ({
145
- kind: "number",
146
- value: Math.hypot(value.re, value.im),
147
- unit: value.unit
148
- });
149
- /**
150
- * arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
151
- */
152
- const complexPhase = (value) => ({
153
- kind: "number",
154
- value: Math.atan2(value.im + 0, value.re + 0)
155
- });
156
- //#endregion
157
136
  //#region src/evaluator-effect.ts
158
137
  /**
159
138
  * Suspends until `value` is available. The driver resumes the task with exactly that value (awaited, in the async driver), and the generator's own "next" type is `T`, so the result is typed without an assertion.
@@ -176,6 +155,13 @@ function* all(tasks) {
176
155
  function isThenable(value) {
177
156
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
178
157
  }
158
+ /**
159
+ * The synchronous driver's rule for a resolver result: it is returned as it is, or, when it is a promise, the evaluation throws a `TypeError`, since a synchronous evaluator has nothing to do with one. Shared by `runSync` and by every other synchronous evaluation path, so they cannot disagree about what a promise from a resolver means.
160
+ */
161
+ function settleSync(value) {
162
+ if (isThenable(value)) throw new TypeError("a resolver supplied to a synchronous evaluator returned a promise; use the asynchronous evaluator for asynchronous resolvers");
163
+ return value;
164
+ }
179
165
  /** Runs a task to completion, awaiting each suspension and running an `all` group's tasks concurrently. */
180
166
  async function runAsync(task) {
181
167
  let step = task.next();
@@ -187,17 +173,13 @@ async function runAsync(task) {
187
173
  return step.value;
188
174
  }
189
175
  /**
190
- * Runs a task to completion without awaiting anything: an `all` group's tasks run one after another, and a `wait` on a promise throws, since a synchronous evaluator has nothing to do with one.
176
+ * Runs a task to completion without awaiting anything: an `all` group's tasks run one after another, and a `wait` on a promise throws (see `settleSync`).
191
177
  */
192
178
  function runSync(task) {
193
179
  let step = task.next();
194
180
  while (step.done !== true) {
195
181
  const suspension = step.value;
196
- let result;
197
- if (suspension.kind === "wait") {
198
- if (isThenable(suspension.value)) throw new TypeError("a resolver supplied to a synchronous evaluator returned a promise; use the asynchronous evaluator for asynchronous resolvers");
199
- result = suspension.value;
200
- } else result = suspension.tasks.map(runSync);
182
+ const result = suspension.kind === "wait" ? settleSync(suspension.value) : suspension.tasks.map(runSync);
201
183
  step = task.next(result);
202
184
  }
203
185
  return step.value;
@@ -799,6 +781,67 @@ function invokeRegisteredFunction(functions, fnName, args) {
799
781
  return definite(outcome);
800
782
  }
801
783
  //#endregion
784
+ //#region src/complex.ts
785
+ const complexFromPolar = (magnitude, phase, unit) => ({
786
+ kind: "complex",
787
+ re: magnitude * Math.cos(phase),
788
+ im: magnitude * Math.sin(phase),
789
+ unit
790
+ });
791
+ /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
792
+ const complexMagnitude = (value) => ({
793
+ kind: "number",
794
+ value: Math.hypot(value.re, value.im),
795
+ unit: value.unit
796
+ });
797
+ /**
798
+ * arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
799
+ */
800
+ const complexPhase = (value) => ({
801
+ kind: "number",
802
+ value: Math.atan2(value.im + 0, value.re + 0)
803
+ });
804
+ //#endregion
805
+ //#region src/evaluator-literals.ts
806
+ /**
807
+ * The `ComputedValue` a literal node denotes, as a new object on every call. Whichever authoring form a `complexLiteral` used (see the "Complex values" section of README.md), it is normalised here to the single rectangular `ComputedValue`, so nothing downstream (arithmetic, compare, memberOf, negate) ever sees a polar-authored value. Shared by the interpreter and the compiled path so a literal means one thing in both.
808
+ */
809
+ function literalValue(node) {
810
+ switch (node.kind) {
811
+ case "numberLiteral": return {
812
+ kind: "number",
813
+ value: node.value,
814
+ unit: node.unit
815
+ };
816
+ case "textLiteral": return {
817
+ kind: "text",
818
+ value: node.value
819
+ };
820
+ case "booleanLiteral": return {
821
+ kind: "boolean",
822
+ value: node.value
823
+ };
824
+ case "instantLiteral": return {
825
+ kind: "instant",
826
+ value: node.value
827
+ };
828
+ case "durationLiteral": return {
829
+ kind: "duration",
830
+ value: node.value,
831
+ unit: node.unit
832
+ };
833
+ case "complexLiteral":
834
+ if ("re" in node) return {
835
+ kind: "complex",
836
+ re: node.re,
837
+ im: node.im,
838
+ unit: node.unit
839
+ };
840
+ return complexFromPolar(node.magnitude, node.phase, node.unit);
841
+ default: throw new Error("unreachable literal node kind");
842
+ }
843
+ }
844
+ //#endregion
802
845
  //#region src/json-value.ts
803
846
  const JsonValueSchema = z.lazy(() => z.union([
804
847
  z.string(),
@@ -973,7 +1016,7 @@ const DurationLiteralNodeSchema = z.object({
973
1016
  /**
974
1017
  * The wire-format literal accepts either of the two authoring forms real-world complex data arrives in, discriminated structurally rather than by a `form` tag: rectangular (`re`/`im`), matching the `complex` computed-value kind's own single canonical representation exactly (see the "Complex values" section of README.md), or polar (`magnitude`/`phase`, in radians), for the domains that reason that way natively and would otherwise have to hand-compute the conversion before ever constructing the tree. `strictObject` on both members is what makes the two forms mutually exclusive on the wire -- a plain `object` would silently strip an unrecognised field rather than reject a payload that mixes both.
975
1018
  *
976
- * The evaluator normalises whichever form was authored into the single rectangular `ComputedValue` immediately on evaluation (see the `complexLiteral` case in evaluator.ts), so nothing downstream of that -- arithmetic, `compare`, `memberOf`, `negate` -- ever sees a polar value; they keep consuming the one canonical `complex` shape unchanged.
1019
+ * The evaluator normalises whichever form was authored into the single rectangular `ComputedValue` immediately on evaluation (see `literalValue` in evaluator-literals.ts), so nothing downstream of that -- arithmetic, `compare`, `memberOf`, `negate` -- ever sees a polar value; they keep consuming the one canonical `complex` shape unchanged.
977
1020
  */
978
1021
  const ComplexRectangularLiteralNodeSchema = z.strictObject({
979
1022
  kind: z.literal("complexLiteral"),
@@ -1207,36 +1250,12 @@ function* evaluateValueInternal(node, context, resolvers, accumulator, functions
1207
1250
  }
1208
1251
  return invokeRegisteredFunction(functions, node.fn, args);
1209
1252
  }
1210
- case "numberLiteral": return definite({
1211
- kind: "number",
1212
- value: node.value,
1213
- unit: node.unit
1214
- });
1215
- case "textLiteral": return definite({
1216
- kind: "text",
1217
- value: node.value
1218
- });
1219
- case "booleanLiteral": return definite({
1220
- kind: "boolean",
1221
- value: node.value
1222
- });
1223
- case "instantLiteral": return definite({
1224
- kind: "instant",
1225
- value: node.value
1226
- });
1227
- case "durationLiteral": return definite({
1228
- kind: "duration",
1229
- value: node.value,
1230
- unit: node.unit
1231
- });
1232
- case "complexLiteral":
1233
- if ("re" in node) return definite({
1234
- kind: "complex",
1235
- re: node.re,
1236
- im: node.im,
1237
- unit: node.unit
1238
- });
1239
- return definite(complexFromPolar(node.magnitude, node.phase, node.unit));
1253
+ case "numberLiteral":
1254
+ case "textLiteral":
1255
+ case "booleanLiteral":
1256
+ case "instantLiteral":
1257
+ case "durationLiteral":
1258
+ case "complexLiteral": return definite(literalValue(node));
1240
1259
  case "arithmetic": {
1241
1260
  const [left, right] = yield* all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1242
1261
  if (left.status === "indeterminate") return left;
@@ -1342,6 +1361,305 @@ function* evaluateValueInternal(node, context, resolvers, accumulator, functions
1342
1361
  }
1343
1362
  }
1344
1363
  //#endregion
1364
+ //#region src/evaluator-compiled.ts
1365
+ /** Never charged: handed to the nodes of a tree compiled without budget counting, none of which reads it. */
1366
+ const UNLIMITED_BUDGET = { checkNode: () => void 0 };
1367
+ /** The `visitedTreeKeys` of a call that has not entered any `treeReference`; the interpreter copies it rather than mutating it, so one instance serves every call. */
1368
+ const NO_TREE_KEYS = /* @__PURE__ */ new Set();
1369
+ /** The message for the `accumulator` node outside a fold's `combine`, which is everywhere a compiled node can sit. */
1370
+ const ACCUMULATOR_OUTSIDE_FOLD = "accumulator used outside a reduce fold's combine expression";
1371
+ /** Compiles the nodes of one tree, for one setting of `counted`. */
1372
+ var NodeCompiler = class {
1373
+ functions;
1374
+ maxNestingDepth;
1375
+ counted;
1376
+ /** The number of nodes compiled natively so far; an upper bound on the nodes one evaluation can visit, because every compiled node is visited at most once per call. */
1377
+ nodesCompiled = 0;
1378
+ /** Whether any node was left to the interpreter. */
1379
+ interpreted = false;
1380
+ /**
1381
+ * `functions` is the registry `call` nodes resolve against. A node at `maxNestingDepth` or deeper is left to the interpreter, so compilation never descends further than an evaluation would. `counted` says whether every compiled node charges the call's `EvaluationBudget` before doing its own work, exactly as the interpreter does; a tree that can never exhaust its budget is compiled with it off, which removes the charge from every node.
1382
+ */
1383
+ constructor(functions, maxNestingDepth, counted) {
1384
+ this.functions = functions;
1385
+ this.maxNestingDepth = maxNestingDepth;
1386
+ this.counted = counted;
1387
+ }
1388
+ /** In a counted tree, charges the budget for the node before running it; otherwise `run` as it is. */
1389
+ charged(depth, run) {
1390
+ if (!this.counted) return run;
1391
+ return (context, resolvers, budget) => budget.checkNode(depth) ?? run(context, resolvers, budget);
1392
+ }
1393
+ /** A node left to the interpreter. The interpreter charges the budget for it and its descendants itself, so this is not wrapped in `charged`. */
1394
+ interpretedPredicate(node, depth) {
1395
+ this.interpreted = true;
1396
+ const { functions } = this;
1397
+ return (context, resolvers, budget) => runSync(evaluatePredicateInternal(node, context, resolvers, void 0, functions, NO_TREE_KEYS, 0, budget, depth));
1398
+ }
1399
+ interpretedValue(node, depth) {
1400
+ this.interpreted = true;
1401
+ const { functions } = this;
1402
+ return (context, resolvers, budget) => runSync(evaluateValueInternal(node, context, resolvers, void 0, functions, NO_TREE_KEYS, 0, budget, depth));
1403
+ }
1404
+ predicate(node, depth) {
1405
+ if (depth >= this.maxNestingDepth) return this.interpretedPredicate(node, depth);
1406
+ this.nodesCompiled += 1;
1407
+ const child = (operand) => this.predicate(operand, depth + 1);
1408
+ const value = (operand) => this.value(operand, depth + 1, false);
1409
+ switch (node.kind) {
1410
+ case "not": {
1411
+ const operand = child(node.operand);
1412
+ return this.charged(depth, (context, resolvers, budget) => {
1413
+ const result = operand(context, resolvers, budget);
1414
+ return result.status === "indeterminate" ? result : definite(!result.value);
1415
+ });
1416
+ }
1417
+ case "and": {
1418
+ const left = child(node.left);
1419
+ const right = child(node.right);
1420
+ return this.charged(depth, (context, resolvers, budget) => {
1421
+ return combineAnd(left(context, resolvers, budget), right(context, resolvers, budget));
1422
+ });
1423
+ }
1424
+ case "or": {
1425
+ const left = child(node.left);
1426
+ const right = child(node.right);
1427
+ return this.charged(depth, (context, resolvers, budget) => {
1428
+ return combineOr(left(context, resolvers, budget), right(context, resolvers, budget));
1429
+ });
1430
+ }
1431
+ case "allOf": {
1432
+ const operands = node.operands.map(child);
1433
+ return this.charged(depth, (context, resolvers, budget) => {
1434
+ let combined = definite(true);
1435
+ for (const operand of operands) combined = combineAnd(combined, operand(context, resolvers, budget));
1436
+ return combined;
1437
+ });
1438
+ }
1439
+ case "anyOf": {
1440
+ const operands = node.operands.map(child);
1441
+ return this.charged(depth, (context, resolvers, budget) => {
1442
+ let combined = definite(false);
1443
+ for (const operand of operands) combined = combineOr(combined, operand(context, resolvers, budget));
1444
+ return combined;
1445
+ });
1446
+ }
1447
+ case "compare": {
1448
+ const left = value(node.left);
1449
+ const right = value(node.right);
1450
+ const { op } = node;
1451
+ return this.charged(depth, (context, resolvers, budget) => {
1452
+ const leftResult = left(context, resolvers, budget);
1453
+ const rightResult = right(context, resolvers, budget);
1454
+ if (leftResult.status === "indeterminate") return leftResult;
1455
+ if (rightResult.status === "indeterminate") return rightResult;
1456
+ return compareValues(op, leftResult.value, rightResult.value);
1457
+ });
1458
+ }
1459
+ case "textCompare": {
1460
+ const left = value(node.left);
1461
+ const right = value(node.right);
1462
+ const { op } = node;
1463
+ return this.charged(depth, (context, resolvers, budget) => {
1464
+ const leftResult = left(context, resolvers, budget);
1465
+ const rightResult = right(context, resolvers, budget);
1466
+ if (leftResult.status === "indeterminate") return leftResult;
1467
+ if (rightResult.status === "indeterminate") return rightResult;
1468
+ return compareText(op, leftResult.value, rightResult.value);
1469
+ });
1470
+ }
1471
+ case "memberOf": {
1472
+ const operand = value(node.operand);
1473
+ const candidates = node.candidates.map(value);
1474
+ const matched = node.op === "in";
1475
+ return this.charged(depth, (context, resolvers, budget) => {
1476
+ const operandResult = operand(context, resolvers, budget);
1477
+ if (operandResult.status === "indeterminate") return operandResult;
1478
+ const outcomes = candidates.map((candidate) => {
1479
+ const candidateResult = candidate(context, resolvers, budget);
1480
+ if (candidateResult.status === "indeterminate") return candidateResult;
1481
+ return computeMembershipMatch(operandResult.value, candidateResult.value);
1482
+ });
1483
+ for (const outcome of outcomes) if (outcome.status === "definite" && outcome.value) return definite(matched);
1484
+ const reason = firstIndeterminate(...outcomes);
1485
+ if (reason !== void 0) return {
1486
+ status: "indeterminate",
1487
+ reason
1488
+ };
1489
+ return definite(!matched);
1490
+ });
1491
+ }
1492
+ case "exists": {
1493
+ const operand = value(node.operand);
1494
+ return this.charged(depth, (context, resolvers, budget) => {
1495
+ const result = operand(context, resolvers, budget);
1496
+ if (result.status === "indeterminate") {
1497
+ if (result.reason.code === "not-yet-known") return result;
1498
+ if (result.reason.code === "not-found") return definite(false);
1499
+ }
1500
+ return definite(true);
1501
+ });
1502
+ }
1503
+ case "some":
1504
+ case "every":
1505
+ case "treeReference": return this.interpretedPredicate(node, depth);
1506
+ default: return this.interpretedPredicate(node, depth);
1507
+ }
1508
+ }
1509
+ /**
1510
+ * Compiles an expression node. `fresh` says whether its value will be handed to code outside this package (a registered function or a resolver): a literal is then built anew on each call, as the interpreter builds it, so no mutation by that code can reach a later call; otherwise it is built once and shared, since only this package's own operators read it.
1511
+ */
1512
+ value(node, depth, fresh) {
1513
+ if (depth >= this.maxNestingDepth) return this.interpretedValue(node, depth);
1514
+ this.nodesCompiled += 1;
1515
+ const child = (operand) => this.value(operand, depth + 1, false);
1516
+ const handedOver = (operand) => this.value(operand, depth + 1, true);
1517
+ switch (node.kind) {
1518
+ case "reference": {
1519
+ const { key, unit } = node;
1520
+ const keyText = JSON.stringify(key);
1521
+ const notFound = `no value found for reference key ${keyText}`;
1522
+ const notYetKnown = `the value for reference key ${keyText} is not yet known`;
1523
+ return this.charged(depth, (context, resolvers) => {
1524
+ const resolution = settleSync(resolvers.resolveValue(key, context));
1525
+ if (!resolution.found) return absenceEvaluation(resolution, notFound, notYetKnown);
1526
+ const unitError = checkReferenceUnit(unit, resolution.value);
1527
+ if (unitError !== void 0) return unitError;
1528
+ return definite(resolution.value);
1529
+ });
1530
+ }
1531
+ case "accumulator": return this.charged(depth, () => indeterminate("wrong-type", ACCUMULATOR_OUTSIDE_FOLD));
1532
+ case "call": {
1533
+ const args = node.args.map(handedOver);
1534
+ const { fn } = node;
1535
+ const { functions } = this;
1536
+ return this.charged(depth, (context, resolvers, budget) => {
1537
+ const results = args.map((arg) => arg(context, resolvers, budget));
1538
+ const values = [];
1539
+ for (const result of results) {
1540
+ if (result.status === "indeterminate") return result;
1541
+ values.push(result.value);
1542
+ }
1543
+ return invokeRegisteredFunction(functions, fn, values);
1544
+ });
1545
+ }
1546
+ case "numberLiteral":
1547
+ case "textLiteral":
1548
+ case "booleanLiteral":
1549
+ case "instantLiteral":
1550
+ case "durationLiteral":
1551
+ case "complexLiteral": {
1552
+ if (fresh) return this.charged(depth, () => definite(literalValue(node)));
1553
+ const shared = definite(literalValue(node));
1554
+ return this.charged(depth, () => shared);
1555
+ }
1556
+ case "arithmetic": {
1557
+ const left = child(node.left);
1558
+ const right = child(node.right);
1559
+ const { op } = node;
1560
+ return this.charged(depth, (context, resolvers, budget) => {
1561
+ const leftResult = left(context, resolvers, budget);
1562
+ const rightResult = right(context, resolvers, budget);
1563
+ if (leftResult.status === "indeterminate") return leftResult;
1564
+ if (rightResult.status === "indeterminate") return rightResult;
1565
+ return applyArithmetic(op, leftResult.value, rightResult.value);
1566
+ });
1567
+ }
1568
+ case "negate": {
1569
+ const operand = child(node.operand);
1570
+ return this.charged(depth, (context, resolvers, budget) => {
1571
+ const result = operand(context, resolvers, budget);
1572
+ if (result.status === "indeterminate") return result;
1573
+ return applyNegate(result.value);
1574
+ });
1575
+ }
1576
+ case "lookup": {
1577
+ const keys = node.keys.map(handedOver);
1578
+ const { table } = node;
1579
+ const tableText = JSON.stringify(table);
1580
+ const notFound = `no match found in lookup table ${tableText}`;
1581
+ const notYetKnown = `the match in lookup table ${tableText} is not yet known`;
1582
+ return this.charged(depth, (context, resolvers, budget) => {
1583
+ const results = keys.map((key) => key(context, resolvers, budget));
1584
+ const keyValues = [];
1585
+ for (const result of results) {
1586
+ if (result.status === "indeterminate") return result;
1587
+ keyValues.push(result.value);
1588
+ }
1589
+ const resolution = settleSync(resolvers.resolveLookup(table, keyValues, context));
1590
+ if (!resolution.found) return absenceEvaluation(resolution, notFound, notYetKnown);
1591
+ return definite(resolution.value);
1592
+ });
1593
+ }
1594
+ case "conditional": {
1595
+ const fallback = child(node.fallback);
1596
+ const cases = node.cases.map(({ when, then }) => ({
1597
+ when: this.predicate(when, depth + 1),
1598
+ then: child(then)
1599
+ }));
1600
+ if ((node.hitPolicy ?? "first") === "first") return this.charged(depth, (context, resolvers, budget) => {
1601
+ for (const { when, then } of cases) {
1602
+ const whenResult = when(context, resolvers, budget);
1603
+ if (whenResult.status === "indeterminate") return whenResult;
1604
+ if (whenResult.value) return then(context, resolvers, budget);
1605
+ }
1606
+ return fallback(context, resolvers, budget);
1607
+ });
1608
+ return this.charged(depth, (context, resolvers, budget) => {
1609
+ const whenResults = cases.map(({ when }) => when(context, resolvers, budget));
1610
+ let matches = 0;
1611
+ let matched;
1612
+ cases.forEach(({ then }, index) => {
1613
+ const whenResult = whenResults[index];
1614
+ if (whenResult?.status === "definite" && whenResult.value) {
1615
+ matches += 1;
1616
+ matched = then;
1617
+ }
1618
+ });
1619
+ if (matches >= 2) return indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
1620
+ const reason = firstIndeterminate(...whenResults);
1621
+ if (reason !== void 0) return {
1622
+ status: "indeterminate",
1623
+ reason
1624
+ };
1625
+ return (matched ?? fallback)(context, resolvers, budget);
1626
+ });
1627
+ }
1628
+ case "delegate": {
1629
+ const { system, payload } = node;
1630
+ const notFound = `delegate handler for external system '${system}' reported no value`;
1631
+ const notYetKnown = `the value from the delegate handler for external system '${system}' is not yet known`;
1632
+ const noHandler = `no delegate handler registered for external system '${system}'`;
1633
+ return this.charged(depth, (context, resolvers) => {
1634
+ if (resolvers.resolveDelegate === void 0) return indeterminate("wrong-type", noHandler);
1635
+ const resolution = settleSync(resolvers.resolveDelegate(system, payload, context));
1636
+ if (!resolution.found) return absenceEvaluation(resolution, notFound, notYetKnown);
1637
+ return definite(resolution.value);
1638
+ });
1639
+ }
1640
+ case "fold":
1641
+ case "treeReference": return this.interpretedValue(node, depth);
1642
+ default: return this.interpretedValue(node, depth);
1643
+ }
1644
+ }
1645
+ };
1646
+ /**
1647
+ * Compiles `node` to a function that evaluates it over the resolvers of each call, with the same `Evaluation` as the synchronous interpreter: status, value, and the reason an indeterminate result carries, including which of several candidate reasons it is. The tree is walked once here, so each call does no per-node dispatch, builds no generator or suspension objects, and precomputes everything that depends only on the tree (the messages of absence, the literal values).
1648
+ *
1649
+ * Compiled natively: `not`, `and`, `or`, `allOf`, `anyOf`, `compare`, `textCompare`, `memberOf` and `exists`, and the expression kinds `reference`, `accumulator`, every literal, `arithmetic`, `negate`, `call`, `lookup`, `conditional` (both hit policies) and `delegate`. Left to the interpreter, as a subtree evaluated by `evaluatePredicateInternal` or `evaluateValueInternal` with the same budget: `some`, `every`, `fold` and `treeReference`, since each re-evaluates a subtree per item or per resolved tree. A tree containing any of them, or more nodes than `maxNodes`, charges the budget at every node exactly as the interpreter does, so a limit is met at the same node; any other tree cannot exhaust either limit and skips the charge.
1650
+ *
1651
+ * Operands are evaluated in the interpreter's synchronous order, and every operand is evaluated even when an earlier one has settled the result, so the resolvers are called in the same sequence as `evaluatePredicate` calls them. A resolver that returns a promise makes the call throw, as it does there.
1652
+ *
1653
+ * Precondition: `node` is a well-formed `PredicateNode` and is not mutated after this call, since what the tree fixes is read here once. Errors: none at compile time; a call throws exactly when the interpreter would (a resolver or registered function that throws, a promise from a resolver).
1654
+ */
1655
+ function compilePredicateTree(node, functions, maxNodes, maxNestingDepth) {
1656
+ const uncounted = new NodeCompiler(functions, maxNestingDepth, false);
1657
+ const uncountedRun = uncounted.predicate(node, 0);
1658
+ if (!uncounted.interpreted && uncounted.nodesCompiled <= maxNodes) return (context, resolvers) => uncountedRun(context, resolvers, UNLIMITED_BUDGET);
1659
+ const countedRun = new NodeCompiler(functions, maxNestingDepth, true).predicate(node, 0);
1660
+ return (context, resolvers) => countedRun(context, resolvers, createEvaluationBudget(maxNodes, maxNestingDepth));
1661
+ }
1662
+ //#endregion
1345
1663
  //#region src/functions.ts
1346
1664
  const emptyFunctionRegistry = {};
1347
1665
  //#endregion
@@ -1361,7 +1679,8 @@ function createEvaluator({ functions = emptyFunctionRegistry, maxNodes = DEFAULT
1361
1679
  function createSyncEvaluator({ functions = emptyFunctionRegistry, maxNodes = DEFAULT_MAX_EVALUATION_NODES, maxNestingDepth = 500 }) {
1362
1680
  return {
1363
1681
  evaluatePredicate: (node, context, resolvers) => runSync(evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)),
1364
- evaluateValue: (node, context, resolvers) => runSync(evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0))
1682
+ evaluateValue: (node, context, resolvers) => runSync(evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)),
1683
+ compilePredicate: (node) => compilePredicateTree(node, functions, maxNodes, maxNestingDepth)
1365
1684
  };
1366
1685
  }
1367
1686
  const { evaluatePredicate, evaluateValue } = createEvaluator({});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "trilean",
3
3
  "description": "Three-valued predicate and expression evaluation trees, stored as JSON and evaluated against injected resolvers, for domain logic — business rules, eligibility checks, formulas, search filters, and more — that needs to be data instead of code.",
4
- "version": "1.12.0",
4
+ "version": "1.13.1",
5
5
  "bin": {
6
6
  "trilean": "./dist-cli/trilean.mjs"
7
7
  },
@@ -9,7 +9,7 @@
9
9
  "url": "https://github.com/ExaDev/trilean/issues"
10
10
  },
11
11
  "dependencies": {
12
- "trilean-regex": "1.0.16",
12
+ "trilean-regex": "1.0.17",
13
13
  "zod": "^4.6.5"
14
14
  },
15
15
  "devDependencies": {
@@ -1 +1 @@
1
- {"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@1.12.0/schemas/trilean.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/PredicateNode"},{"$ref":"#/$defs/ExpressionNode"}]}
1
+ {"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@1.13.1/schemas/trilean.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/PredicateNode"},{"$ref":"#/$defs/ExpressionNode"}]}