trilean 1.0.12 → 1.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
@@ -188,7 +188,7 @@ These hold across every part of the design below, and any implementation change
188
188
 
189
189
  - **No assumptions about consumer data.** The only places this package touches real data are three named resolver contracts (see [Resolvers](#resolvers)). The schema stores *what to pass* to a resolver, never any resolver logic itself, and never interprets the meaning of an opaque key, table identifier, or collection reference.
190
190
  - **Three outcomes, never two.** Every evaluation produces a definite result or an indeterminate result carrying a reason — never a bare `boolean`/`number`, and never a thrown exception for a data-quality problem. See [The evaluation model](#the-evaluation-model).
191
- - **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives) and [Derived aggregates](#derived-aggregates).
191
+ - **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates), and [Derived values](#derived-values).
192
192
  - **One schema, mechanically derived artefacts.** A single canonical type definition produces the runtime validator and the portable wire-format schema; they cannot drift apart because there is only one source. See [Schema strategy](#schema-strategy).
193
193
  - **Generic examples only.** Every example in this document uses invented, placeholder field names (`temperature`, `orderTotal`, `isActive`, `x`, `y`, `amount`, `items`) with no resemblance to any particular company, product, or industry's real data model.
194
194
 
@@ -353,7 +353,8 @@ type PredicateNode =
353
353
  | { kind: "memberOf"; op: MembershipOperator; operand: ExpressionNode; candidates: ExpressionNode[] }
354
354
  | { kind: "exists"; operand: ExpressionNode }
355
355
  | { kind: "some"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
356
- | { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode };
356
+ | { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
357
+ | { kind: "treeReference"; key: JsonValue };
357
358
  ```
358
359
 
359
360
  ### `not`, `and`, `or`
@@ -409,6 +410,8 @@ type FoldCombiner =
409
410
  | { mode: "min"; item: ExpressionNode }
410
411
  | { mode: "reduce"; initial: ExpressionNode; combine: ExpressionNode };
411
412
 
413
+ type HitPolicy = "first" | "unique";
414
+
412
415
  type ExpressionNode =
413
416
  | { kind: "numberLiteral"; value: number; unit?: Unit }
414
417
  | { kind: "textLiteral"; value: string }
@@ -419,10 +422,11 @@ type ExpressionNode =
419
422
  | { kind: "negate"; operand: ExpressionNode }
420
423
  | { kind: "call"; fn: string; args: ExpressionNode[] }
421
424
  | { kind: "lookup"; table: JsonValue; keys: ExpressionNode[] }
422
- | { kind: "conditional"; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
425
+ | { kind: "conditional"; hitPolicy?: HitPolicy; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
423
426
  | { kind: "fold"; collection: JsonValue; filter?: PredicateNode; combiner: FoldCombiner }
424
427
  | { kind: "accumulator" }
425
- | { kind: "delegate"; system: string; payload: JsonValue };
428
+ | { kind: "delegate"; system: string; payload: JsonValue }
429
+ | { kind: "treeReference"; key: JsonValue };
426
430
  ```
427
431
 
428
432
  A `textLiteral` kind is included even though it is not separately enumerated as its own top-level construct, because `textCompare`'s symmetry requirement (either side may be an arbitrary computed value, per the section above) is meaningless without a way to write a constant string or pattern — matching a field against the fixed text `"active"`, or against a fixed regular expression, needs a text constant on one side. This is a structural consequence of the symmetry already required for text matching, not an added feature.
@@ -465,7 +469,16 @@ Resolves a single value from a named external table-like source, keyed by one or
465
469
 
466
470
  ### `conditional`
467
471
 
468
- A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`. Evaluates to the `then` of the first case whose `when` predicate is definitely `true`; if no case matches, evaluates to `fallback`. If evaluating a `when` predicate produces an indeterminate outcome **before any earlier case has matched**, the whole `conditional` node's own result is that same indeterminate outcome (reason preserved) — evaluation does not skip past an unknown guard to try the next one, because doing so could silently pick a later branch that only looks correct because an earlier one couldn't actually be checked.
472
+ A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`. An optional `hitPolicy` field (`"first"` or `"unique"`) decides how cases are read; absent is treated as `"first"` — the exact, unchanged behaviour of every tree serialised before this field existed, not a masked-bug fallback.
473
+
474
+ **`hitPolicy: "first"`** (the default). Evaluates to the `then` of the first case whose `when` predicate is definitely `true`; if no case matches, evaluates to `fallback`. If evaluating a `when` predicate produces an indeterminate outcome **before any earlier case has matched**, the whole `conditional` node's own result is that same indeterminate outcome (reason preserved) — evaluation does not skip past an unknown guard to try the next one, because doing so could silently pick a later branch that only looks correct because an earlier one couldn't actually be checked.
475
+
476
+ **`hitPolicy: "unique"`** asserts that at most one case is expected to match, and treats two or more matches as a data error rather than silently taking the first. Every case's `when` is evaluated concurrently (there is no "earlier case" to short-circuit on), then resolved in this order:
477
+
478
+ 1. **Two or more cases are definitely `true`** — `domain-error` ("more than one case matched under the 'unique' hit policy"), regardless of any other case's own indeterminacy. This mirrors `memberOf`/`some`/`every`'s existing absorption: a confirmed outcome (here, "there is a genuine ambiguity") cannot be undone by an unrelated case's data problem.
479
+ 2. Otherwise, **any case's `when` is indeterminate** — the whole node is indeterminate with that reason (first such candidate, in declared case order, per [The evaluation model](#the-evaluation-model)'s tie-break rule). This is deliberately **not** absorbed by a single already-confirmed match, unlike step 1 above and unlike `memberOf`/`some`/`every`'s own absorption: an unresolved case might still turn out to be a second match, so "exactly one match so far" cannot be trusted as final until every other case is known to not also match.
480
+ 3. Otherwise, **exactly one case is definitely `true`** — evaluate and return that case's `then`. No other case's `then` is ever evaluated.
481
+ 4. Otherwise (zero matches, and nothing indeterminate) — evaluate and return `fallback`, exactly as `"first"` already does.
469
482
 
470
483
  ### `fold`
471
484
 
@@ -538,10 +551,58 @@ const average = (collection: JsonValue, item: ExpressionNode, filter?: Predicate
538
551
 
539
552
  `average` is `sum` divided by `count` over the same `collection`/`filter`, with no `probe` — `sum`'s own `item` already forces every participating item's projected value to resolve, so `average`'s numerator is already indeterminate under exactly the condition a `count` probe exists to detect, with nothing left to duplicate. Nothing new to verify for the empty-collection case either: division's own already-established rule (zero divisor is `domain-error`) is *why* `average` over an empty collection is `domain-error`, since `count` over an empty collection is `0` and `sum(...)/0` already means exactly that.
540
553
 
554
+ ### Derived values
555
+
556
+ `coalesce` is never its own evaluated node kind — it is a builder function that assembles an ordinary `conditional`, the same treatment [Derived connectives](#derived-connectives) and [Derived aggregates](#derived-aggregates) already give `xor`/`nand`/`nor`/`implies`/`iff`/`none`/`sum`/`count`/`average`: correctness is inherited from the mechanism it's built from, rather than needing its own independent implementation that could silently drift from it.
557
+
558
+ ```ts
559
+ const coalesce = (
560
+ first: ExpressionNode,
561
+ second: ExpressionNode,
562
+ ...rest: ExpressionNode[]
563
+ ): ExpressionNode =>
564
+ [first, second, ...rest].reduceRight(
565
+ (fallback, candidate): ExpressionNode => ({
566
+ kind: "conditional",
567
+ cases: [{ when: { kind: "exists", operand: candidate }, then: candidate }],
568
+ fallback,
569
+ }),
570
+ );
571
+ ```
572
+
573
+ Built right-to-left over the full candidate list via `reduceRight`, needing no seed value: `first`/`second` are required arguments (rather than accepting a single `ExpressionNode[]`), which guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
574
+
575
+ **Worked correctness check.** `coalesce`'s only interesting behaviour — whether a given candidate is skipped past or propagated — reduces entirely to what its single `exists` probe reports, per [`exists`](#exists)'s and [`conditional`](#conditional)'s own already-established rules:
576
+
577
+ | A candidate's own evaluation | `exists(candidate)` | The `conditional` case | `coalesce` evaluates to |
578
+ |---|---|---|---|
579
+ | A definite value | definite `true` | matches | The candidate's value (re-evaluated as `then`, same result) |
580
+ | Indeterminate, `not-found` | definite `false` | does not match | The next candidate (the enclosing `fallback`), evaluated fresh |
581
+ | Indeterminate, `wrong-type` | definite `true` | matches | The candidate's own `wrong-type` result (re-evaluated as `then`) |
582
+ | Indeterminate, `domain-error` | definite `true` | matches | The candidate's own `domain-error` result (re-evaluated as `then`) |
583
+
584
+ Falling through to the next candidate therefore happens only on `exists`'s own `false` — a genuinely absent value (`not-found`) — never on a candidate that resolved to something merely unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line, and `coalesce` inherits it unmodified rather than re-deciding it. This is the one behaviour a naive reimplementation is likely to get backwards (treating *any* indeterminate candidate as "try the next one"), so it is worth stating explicitly rather than leaving it to be inferred from the composition alone.
585
+
586
+ A real implementation may memoise a candidate's single evaluation rather than running its resolver twice — once for the `exists` probe, once again for `then` — exactly the same performance caveat [Derived aggregates](#derived-aggregates)'s `presenceOf` already documents for its own `memberOf` probe; resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.
587
+
541
588
  ### `delegate`
542
589
 
543
590
  An explicitly-named external system plus an arbitrary, unevaluated JSON payload, standing in for the whole node without this package attempting to evaluate it itself — see [Out of scope](#out-of-scope). Evaluating a `delegate` node is not part of this package's own evaluation semantics. The reference evaluator accepts an optional delegate handler per external system name; if none is registered for the named `system`, evaluating the node is indeterminate (`wrong-type`, "no delegate handler registered for external system '<name>'"). Consumers who want a `delegate` node to actually resolve are expected either to register a handler, or to pre-process the tree — walk it, find delegation nodes, invoke the named external system out of band, and substitute the result as a literal — before the tree ever reaches this package's evaluator.
544
591
 
592
+ ### `treeReference`
593
+
594
+ A reference to a whole other tree, identified by an opaque `key` (see [Resolvers](#resolvers)) — the only node kind valid from *both* a `PredicateNode` and an `ExpressionNode` position: the exact same schema is appended as the last member of each of the two discriminated unions above, not two separately-declared copies that happen to look alike. Unlike [`delegate`](#delegate), which hands the whole node off to an *external* system this package never evaluates, `treeReference` resolves to *another tree of this same schema* and evaluates it with this same evaluator — a sub-rule reference, not an escape hatch.
595
+
596
+ `resolveTree` is optional on `Resolvers`, for the same reason `resolveDelegate` is: a well-defined indeterminate result on absence, not a masked bug, and an additive, non-breaking interface change for every consumer implemented before this node kind existed. If no `resolveTree` is registered, evaluating a `treeReference` node is `wrong-type` ("no tree resolver registered for treeReference nodes"). If the resolver reports no match, the result is `not-found`.
597
+
598
+ A resolved tree is never merely trusted — it is re-validated with a fresh `PredicateNodeSchema`/`ExpressionNodeSchema` parse (`PredicateNodeSchema` from a predicate-position reference, `ExpressionNodeSchema` from an expression-position one) before evaluation proceeds, exactly the same discipline the top-level tree itself is subject to when it first arrives at this package. A resolver fetching "a named rule from storage" is very often surfacing the same non-developer-authored JSON the top-level tree already is, with no static guarantee it still matches the schema; a failed parse is `wrong-type`.
599
+
600
+ `context` and the enclosing fold's `accumulator` both pass through a `treeReference` unchanged — the referenced tree shares the caller's evaluation scope, like a subroutine call, not a nested evaluation with its own fresh context. There is deliberately no mechanism to override the context at a `treeReference` boundary; a consumer wanting that already has [`delegate`](#delegate).
601
+
602
+ **Cycle and depth protection.** A tree that references itself, directly or through a longer chain, is guarded by two independent, layered checks rather than one: a cycle detector tracks every `key` (by its `JSON.stringify`'d form) already on the current reference chain, and reports `domain-error` ("circular treeReference detected") the moment a repeat is seen; a fixed depth cap separately reports `domain-error` ("...exceeds the maximum depth") on a long *acyclic* chain the cycle detector alone would never catch. Neither check is a substitute for the other.
603
+
604
+ **A known, accepted design consequence.** `resolveTree` has no built-in way to know whether a given `key` is being resolved from a predicate-position or an expression-position reference — the same is already true of `reference.key` and `lookup.table`, neither of which carries a type discriminator either. A consumer needing to disambiguate structures their own key accordingly (e.g. `{ kind: "predicate", id: "..." }` as the `JsonValue` itself) rather than this schema growing a bespoke field for it.
605
+
545
606
  ## Collections
546
607
 
547
608
  Both `fold` and the two quantifier leaves (`some`/`every`, and transitively `none`) need "a collection of items" resolved from something the schema itself treats as opaque data. The schema's job is only to carry an opaque reference to what collection is meant, plus a sub-node (an `ExpressionNode` for `fold`, a `PredicateNode` for the quantifiers) to be evaluated once per resolved item, using that single item as its evaluation context, plus an optional per-item pre-filter — see [Pre-filtering which items participate](#pre-filtering-which-items-participate).
@@ -564,13 +625,17 @@ An item whose `filter` is itself indeterminate is never silently included or exc
564
625
 
565
626
  ## Resolvers
566
627
 
567
- Three independent points of extension, each supplied separately by the embedding consumer, each treated by the schema as pure data to hand over — never as resolver logic living inside the schema itself:
628
+ Three core, required points of extension, plus two further independent optional ones, each supplied separately by the embedding consumer, each treated by the schema as pure data to hand over — never as resolver logic living inside the schema itself:
568
629
 
569
630
  ```ts
570
631
  type Resolution =
571
632
  | { found: true; value: ComputedValue }
572
633
  | { found: false };
573
634
 
635
+ type TreeResolution =
636
+ | { found: true; node: JsonValue }
637
+ | { found: false };
638
+
574
639
  interface Resolvers {
575
640
  /** Resolver 1 — a single opaque key to a single value (IV.reference). */
576
641
  resolveValue(key: JsonValue, context: EvaluationContext): Promise<Resolution>;
@@ -583,10 +648,15 @@ interface Resolvers {
583
648
 
584
649
  /** Optional, separate from the three core contracts — see the `delegate` node kind. */
585
650
  resolveDelegate?(system: string, payload: JsonValue, context: EvaluationContext): Promise<Resolution>;
651
+
652
+ /** Optional, separate from the three core contracts — see the `treeReference` node kind. */
653
+ resolveTree?(key: JsonValue, context: EvaluationContext): Promise<TreeResolution>;
586
654
  }
587
655
  ```
588
656
 
589
- `resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three needs to know anything about the other two; a consumer implementing all three (and, optionally, the delegate handler) is free to have them share underlying data-access logic, but the schema and evaluator never require or assume that they do.
657
+ `resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three core resolvers needs to know anything about the other two, or about either optional one; a consumer implementing all five is free to have them share underlying data-access logic, but the schema and evaluator never require or assume that they do.
658
+
659
+ `resolveTree` returns a `TreeResolution`, deliberately shaped like `Resolution` but distinct from it: `node` carries opaque JSON — the referenced tree, re-validated by the evaluator rather than trusted (see [`treeReference`](#treereference)) — where `Resolution`'s `value` carries an already-typed `ComputedValue`. It is otherwise the same "found" envelope for the same reason: a `treeReference`'s absence needs to be distinguishable from any tree the resolver might otherwise legitimately return, exactly as a `reference`'s absence needs to be distinguishable from any value. `resolveDelegate` and `resolveTree` solve different problems and are never a substitute for one another: `resolveDelegate` hands a payload to an *external* system this package never evaluates; `resolveTree` hands back *more of this same schema*, for this same evaluator to keep evaluating.
590
660
 
591
661
  ## Evaluator entry points
592
662
 
@@ -654,10 +724,11 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
654
724
  | `negate` | operand not found | operand not `number`/`duration` | never directly |
655
725
  | `call` | any argument not found | unregistered function name, or an argument of the wrong kind for that function | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
656
726
  | `lookup` | any key not found, or resolver reports no match | a key expression resolves to the wrong kind for that table | never directly |
657
- | `conditional` | an unmatched guard's own evaluation is `not-found`, before any earlier guard matched | as `not-found`; also the chosen branch's own result if it is `wrong-type` | as `not-found`; also the chosen branch's own result if it is `domain-error` |
727
+ | `conditional` | `"first"`: an unmatched guard's own evaluation is `not-found`, before any earlier guard matched.<br>`"unique"`: any case's `when` is `not-found`, unless 2+ cases already definitely matched (see `domain-error`, which then takes priority).<br>Both: also the chosen branch's (`then`/`fallback`) own result if it is `not-found`. | Same pattern as `not-found`, substituting `wrong-type` throughout (guard evaluation and chosen branch alike). | `"unique"` only: 2+ cases are definitely `true` — see [`conditional`](#conditional)'s absorption order.<br>Both: same pattern as `not-found`, substituting `domain-error` (guard evaluation and chosen branch alike). |
658
728
  | `fold` | any participating item's `filter`, `item`, or `combine` evaluation is `not-found`; or a `reduce`'s `initial` is `not-found` | any participating item's `filter`, `item`, or `combine` evaluation is `wrong-type`; or a `reduce`'s `initial` is `wrong-type` | empty (post-filter) collection with `max`/`min` (no first item to seed from); or any participating item's `item`/`combine` evaluation is `domain-error`; or a `reduce`'s `initial` is `domain-error` |
659
729
  | `accumulator` | never | used outside a reduce fold's `combine` expression | never |
660
730
  | `delegate` | never (no resolution attempted without a handler) | no handler registered for the named `system` | never |
731
+ | `treeReference` | resolver reports no match | no `resolveTree` registered; or the resolved node fails schema validation | a circular reference is detected; or the reference chain exceeds the maximum depth |
661
732
 
662
733
  ## Worked example
663
734
 
@@ -748,3 +819,40 @@ This package is a representation-plus-evaluator for conditions and formulas over
748
819
  - **Batch unresolvable-reference reporting.** This design deliberately has no node kind for asking "which of these references, across a whole batch, are unresolvable" as a single evaluation — only the [`exists`](#exists) leaf's one-at-a-time true/false/false-on-absence check. A tool that wants to report a *list* of every missing reference (for an authoring UI validating a tree before it's saved, say) is expected to build that on top of `exists` — walk the references of interest and evaluate an `exists` leaf over each — at the authoring/tooling layer, rather than this package growing a bespoke aggregate-diagnostic node kind for it. This is a deliberate boundary, not an oversight: it keeps the evaluation tree itself limited to producing one `Evaluation` per node, and leaves "collect many such results and report on them together" to whatever sits above the evaluator, exactly like symbolic algebra and complex-number arithmetic above are left to whatever sits beside it.
749
820
 
750
821
  This package does not name or depend on any specific external tool for either of the two delegation cases above — it only defines the shape of the hand-off (an opaque payload plus a named destination system).
822
+
823
+ ## Prior art
824
+
825
+ Twenty-three existing tools — JSON rule engines, expression languages, query-filter conventions, and three-valued-logic precedents — researched against seven properties trilean combines: a genuinely portable representation, injected async data access, a real three-outcome logic, vendor-agnostic scope, mixing logic and arithmetic in one tree, no code-execution surface for an untrusted author, and a formally published schema. None of the twenty-three combine all seven. Each verdict below was checked against the tool's own documentation, specification, or a security advisory, not assumed from category.
826
+
827
+ The closest structural relative is [GoRules' Zen Engine](https://gorules.io) (`@gorules/zen-engine`), whose JDM format is a genuinely portable JSON decision graph with a real injected extension point — but its outcome model is value-level nulls, not a propagating three-valued logic, and its "Function" node type runs real JavaScript rather than staying within a bounded grammar. The closest semantic relative is [DMN](https://www.omg.org/spec/DMN)'s FEEL expression language, which implements the identical absorbing-AND/OR three-valued truth tables trilean does — but FEEL's canonical form is XML, not JSON.
828
+
829
+ Worth knowing: a Rust crate on crates.io is also named [`trilean`](https://crates.io/crates/trilean) and also implements Kleene's three-valued logic — a genuine name collision, different ecosystem, no npm conflict, unrelated project.
830
+
831
+ The security research here surfaced findings worth knowing independent of the comparison: [JSONata](https://jsonata.org) has had multiple prototype-pollution CVEs reaching `Function`/`child_process`; [jexl](https://github.com/TomFrost/Jexl) has a documented, unfixed path to `Function.prototype` via `__proto__`; [expr-eval](https://github.com/silentmatt/expr-eval) has a prototype-pollution CVE (CVE-2026-12866); and MongoDB's `$where`/`$function` and JsonLogic's `method` operator are documented, acknowledged arbitrary-code escape hatches. [CEL](https://cel.dev), [filtrex](https://github.com/cshaa/filtrex), and [Rego](https://www.openpolicyagent.org/docs/policy-language) are the standouts, each explicitly designed and marketed as safe for untrusted input.
832
+
833
+ | Tool | Category | Portable data | Async access | Missing ≠ false | Vendor-agnostic | Mixes logic & math | No code-exec risk | Published schema |
834
+ |---|---|---|---|---|---|---|---|---|
835
+ | [trilean](https://www.npmjs.com/package/trilean) | — | 🟢<br>JSON, Zod-validated, RFC 8785 canonical | 🟢<br>three typed resolver contracts | 🟢<br>definite/indeterminate, typed reason | 🟢<br>no assumptions about consumer data | 🟢<br>compare/textCompare/memberOf take formulas | 🟢<br>call's fn is a registry key, never code | 🟢<br>one Zod schema generates both |
836
+ | [JsonLogic](https://www.npmjs.com/package/json-logic-js) | Rule engine | 🟢 | 🔴<br>direct path lookup | 🔴<br>counts as false | 🟢 | 🟢<br>any operand can be another rule | 🟡<br>`method` op is an acknowledged escape hatch | 🔴<br>a JSON Schema request was never resolved |
837
+ | [json-rules-engine](https://www.npmjs.com/package/json-rules-engine) | Rule engine | 🟢 | 🟢<br>async fact handlers | 🔴<br>undocumented | 🟢 | 🔴<br>docs call inline formulas "a design smell" | 🟢<br>operators are name-based registry lookups | 🔴<br>a proposed schema was never merged |
838
+ | [json-rules-engine-simplified](https://www.npmjs.com/package/json-rules-engine-simplified) | Rule engine | 🟢 | 🔴<br>direct path lookup | 🔴<br>falls through to false | 🟢 | 🔴<br>no arithmetic/formula node exists | 🟢<br>no `eval()`, by the project's own claim | 🔴<br>README prose only |
839
+ | [Zen Engine](https://www.npmjs.com/package/@gorules/zen-engine) / [JDM](https://docs.gorules.io/developers/jdm/standard) | Rule engine | 🟢 | 🟢<br>injected custom-node callback | 🟡<br>null-coalescing only | 🟢 | 🟢<br>ZEN expressions nest arithmetic in comparisons | 🟡<br>Function nodes run real JS, sandboxed | 🟡<br>docs claim one, none found published |
840
+ | [nools](https://www.npmjs.com/package/nools) | Rule engine | 🔴<br>JS/DSL | 🔴 | 🔴 | 🟢 | 🟢<br>DSL nests arithmetic in comparisons | 🔴<br>the `then` block is literal JS | 🔴<br>DSL documented only in prose |
841
+ | [rools](https://www.npmjs.com/package/rools) | Rule engine | 🔴<br>rules are JS | 🔴 | 🔴 | 🟢 | 🟢<br>but only because it's unrestricted JS | 🔴<br>"rules are specified in pure JavaScript" | 🔴<br>plain JS, prose docs only |
842
+ | [node-rules](https://www.npmjs.com/package/node-rules) | Rule engine | 🔴<br>conditions are JS | 🔴 | 🔴 | 🟢 | 🟢<br>but only because it's unrestricted JS | 🔴<br>a condition is explicitly "a function" | 🔴<br>prose docs only |
843
+ | [JSONata](https://www.npmjs.com/package/jsonata) | Expression lang. | 🟡<br>undocumented shape | 🟢 | — | 🟢 | 🟢<br>arithmetic on both sides of any comparison | 🔴<br>multiple prototype-pollution CVEs to RCE | 🔴<br>hand-written parser, a grammar request was declined |
844
+ | [CEL](https://cel.dev) | Expression lang. | 🟢<br>as Protobuf, not JSON | 🔴<br>sync by design | — | 🟢 | 🟢<br>arithmetic feeds directly into comparison | 🟢<br>explicitly designed safe for untrusted code | 🟢<br>versioned .proto files, wire-compatible forever |
845
+ | [jexl](https://www.npmjs.com/package/jexl) | Expression lang. | 🔴<br>private, unexposed | 🟢<br>closest match | — | 🟢 | 🟢<br>arithmetic and logical ops nest freely | 🔴<br>documented unfixed `__proto__` access issue | 🔴<br>grammar lives in a JS source file |
846
+ | [filtrex](https://www.npmjs.com/package/filtrex) | Expression lang. | 🔴<br>AST retained | 🔴<br>sandboxed sync closure | — | 🟢 | 🟢<br>documented example nests a product in a condition | 🟢<br>markets itself explicitly as safe for end-users | 🔴<br>a real grammar file exists but ships unpublished |
847
+ | [expr-eval](https://www.npmjs.com/package/expr-eval) | Expression lang. | 🔴<br>(jsep-based siblings do) | 🔴 | — | 🟢 | 🟢<br>and/or plus comparisons alongside arithmetic | 🔴<br>CVE-2026-12866, prototype pollution to RCE | 🔴<br>prose README only |
848
+ | [mathjs](https://www.npmjs.com/package/mathjs) | Expression lang. | 🔴<br>round-trip unreliable | 🔴<br>sync `evaluate()` | — | 🟢 | 🟢<br>arithmetic binds tighter than and/or, by design | 🟡<br>`eval` removed, but real sandbox-escape CVEs existed | 🔴<br>documented only in prose |
849
+ | [MongoDB query operators](https://www.mongodb.com/docs/manual/reference/operator/query/) | Query/filter DSL | 🟢 | — | — | 🔴<br>MQL only | 🟡<br>only behind the `$expr` escape hatch | 🟡<br>`$where`/`$function` run arbitrary server-side JS | 🟡<br>an official grammar exists but is archived since 2021 |
850
+ | [Prisma `where`](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting) | Query/filter DSL | 🔴<br>never transmitted | — | — | 🔴<br>per-schema generated | 🔴<br>computed fields aren't usable for filtering at all | 🟢<br>a fixed, enumerated operator set only | 🔴<br>generated internal TypeScript types only |
851
+ | [OData `$filter`](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html) | Query/filter DSL | 🟢<br>as a query string | — | — | 🟢<br>OASIS standard | 🟢<br>arithmetic operators combine directly with comparisons | 🟢<br>fixed operator set, no code-reference mechanism | 🟢<br>a normative, versioned ABNF grammar document |
852
+ | [JSON:API `filter`](https://jsonapi.org/format/#fetching-filtering) | Query/filter DSL | 🔴<br>reservation only | — | — | 🟡<br>no grammar defined | — | — | — |
853
+ | [GraphQL (Hasura-style)](https://hasura.io/docs/2.0/queries/postgres/filters/boolean-operators/) | Query/filter DSL | 🟢 | — | — | 🟡<br>de facto convention | 🟡<br>operand can be a column, never a computed formula | 🟢<br>fixed comparison-operator vocabulary | 🟡<br>real schema, but generated per deployment |
854
+ | [SQL `NULL` / `UNKNOWN`](https://www.postgresql.org/docs/current/functions-comparison.html) | 3VL precedent | 🔴<br>language semantic | — | 🟢<br>same absorbing tables | 🟢 | 🟢<br>WHERE-clause operands are arbitrary expressions | — | — |
855
+ | [DMN's FEEL](https://www.omg.org/spec/DMN) | 3VL precedent | 🟢<br>as XML, not JSON | — | 🟢<br>absorbing | 🟢<br>OMG standard | 🟢<br>full FEEL mixes arithmetic and and/or freely | 🟡<br>a boxed function can invoke external Java/PMML by name | 🟡<br>DMN XML has an XSD, FEEL itself is prose BNF |
856
+ | [OPA / Rego](https://www.openpolicyagent.org/docs/policy-language) | 3VL precedent | 🟢<br>, as source text | — | 🟡<br>absence, not a value | 🟢 | 🟢<br>comparisons take arithmetic sub-expressions | 🟢<br>explicitly not Turing-complete, by design | 🔴<br>grammar is prose EBNF, no standalone file |
857
+ | [AWS IAM policy language](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_grammar.html) | 3VL precedent | 🟢 | — | 🟡<br>default, not propagating | 🔴<br>AWS-specific | 🔴<br>every condition value is a literal string | 🟢<br>bounded grammar, fixed operator set | 🔴<br>only a prose BNF-like description |
858
+ | [`trinary`](https://pypi.org/project/trinary/), [`tvl`](https://github.com/archanpatkar/tvl), [`3vl`](https://www.npmjs.com/package/3vl), Go [`ternary`](https://github.com/mithrandie/ternary) | 3VL precedent | 🔴<br>in-memory only | — | 🟢<br>Kleene K3 | 🟢 | — | — | — |
@@ -0,0 +1,24 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/derived-values.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ const coalesce = (first, second, ...rest) => [
9
+ first,
10
+ second,
11
+ ...rest
12
+ ].reduceRight((fallback, candidate) => ({
13
+ kind: "conditional",
14
+ cases: [{
15
+ when: {
16
+ kind: "exists",
17
+ operand: candidate
18
+ },
19
+ then: candidate
20
+ }],
21
+ fallback
22
+ }));
23
+ //#endregion
24
+ exports.coalesce = coalesce;
@@ -0,0 +1,10 @@
1
+ import { ExpressionNode } from "./tree.cjs";
2
+ //#region src/derived-values.d.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ declare const coalesce: (first: ExpressionNode, second: ExpressionNode, ...rest: readonly ExpressionNode[]) => ExpressionNode;
9
+ //#endregion
10
+ export { coalesce };
@@ -0,0 +1,10 @@
1
+ import { ExpressionNode } from "./tree.js";
2
+ //#region src/derived-values.d.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ declare const coalesce: (first: ExpressionNode, second: ExpressionNode, ...rest: readonly ExpressionNode[]) => ExpressionNode;
9
+ //#endregion
10
+ export { coalesce };
@@ -0,0 +1,23 @@
1
+ //#region src/derived-values.ts
2
+ /**
3
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
4
+ *
5
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
6
+ */
7
+ const coalesce = (first, second, ...rest) => [
8
+ first,
9
+ second,
10
+ ...rest
11
+ ].reduceRight((fallback, candidate) => ({
12
+ kind: "conditional",
13
+ cases: [{
14
+ when: {
15
+ kind: "exists",
16
+ operand: candidate
17
+ },
18
+ then: candidate
19
+ }],
20
+ fallback
21
+ }));
22
+ //#endregion
23
+ export { coalesce };
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_computed_value = require("./computed-value.cjs");
3
3
  const require_evaluation = require("./evaluation.cjs");
4
4
  const require_functions = require("./functions.cjs");
5
+ const require_tree = require("./tree.cjs");
5
6
  //#region src/evaluator.ts
6
7
  /**
7
8
  * `evaluatePredicateInternal` and `evaluateValueInternal` are co-located in this one file, rather than split across `predicate-evaluator.ts`/`value-evaluator.ts`, because they are mutually recursive: a predicate leaf (`compare`, `textCompare`, `memberOf`, `exists`) holds `ExpressionNode` operands, and an expression node (`conditional`'s `when`, a fold's `filter`) holds `PredicateNode` operands. Splitting them across modules would make each half import the other, and whichever module finished loading second would see the other's export as `undefined` at its own module-evaluation time -- a genuine circular-import TDZ hazard, not merely a style preference.
@@ -254,17 +255,19 @@ function applyArithmetic(op, left, right) {
254
255
  if (right.kind !== "number") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
255
256
  return applyArithmeticOnNumbers(op, left, right);
256
257
  }
258
+ /** A defense-in-depth guard against a long acyclic `treeReference` chain exhausting the call stack -- distinct from, and layered on top of, the cycle detector below (`visitedTreeKeys`), which catches an actual repeat immediately and more precisely. */
259
+ const MAX_TREE_REFERENCE_DEPTH = 100;
257
260
  /**
258
261
  * Collection resolution shared by the quantifiers (`some`/`every`, below) and by `fold` (a later phase): resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` with that candidate as its own evaluation context and the accumulator reset to `undefined` -- see the README's "Evaluation context" and "Pre-filtering which items participate" sections. Deliberately stops short of deciding how an indeterminate filter combines with the rest of the surrounding node: `some`/`every` fold a filter-indeterminate item in as its own vote via the surrounding OR/AND absorption, while `fold` has no absorbing value at all and goes indeterminate outright on the same condition -- the two callers need genuinely different combination logic over these same per-item outcomes, so this helper only produces the outcomes and leaves combining them to the caller.
259
262
  */
260
- async function resolveParticipatingItems(collection, filter, context, resolvers, functions) {
263
+ async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
261
264
  const candidates = await resolvers.resolveCollection(collection, context);
262
265
  return Promise.all(candidates.map(async (item) => {
263
266
  if (filter === void 0) return {
264
267
  item,
265
268
  filterOutcome: "include"
266
269
  };
267
- const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions);
270
+ const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
268
271
  if (filterResult.status === "indeterminate") return {
269
272
  item,
270
273
  filterOutcome: filterResult
@@ -282,40 +285,40 @@ function firstFilterIndeterminate(participating) {
282
285
  if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
283
286
  }
284
287
  }
285
- async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions) {
288
+ async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
286
289
  switch (node.kind) {
287
290
  case "not": {
288
- const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions);
291
+ const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
289
292
  if (operand.status === "indeterminate") return operand;
290
293
  return require_evaluation.definite(!operand.value);
291
294
  }
292
295
  case "and": {
293
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
296
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
294
297
  return combineAnd(left, right);
295
298
  }
296
299
  case "or": {
297
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
300
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
298
301
  return combineOr(left, right);
299
302
  }
300
- case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineAnd, require_evaluation.definite(true));
301
- case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineOr, require_evaluation.definite(false));
303
+ case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineAnd, require_evaluation.definite(true));
304
+ case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineOr, require_evaluation.definite(false));
302
305
  case "compare": {
303
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
306
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
304
307
  if (left.status === "indeterminate") return left;
305
308
  if (right.status === "indeterminate") return right;
306
309
  return compareValues(node.op, left.value, right.value);
307
310
  }
308
311
  case "textCompare": {
309
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
312
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
310
313
  if (left.status === "indeterminate") return left;
311
314
  if (right.status === "indeterminate") return right;
312
315
  return compareText(node.op, left.value, right.value);
313
316
  }
314
317
  case "memberOf": {
315
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
318
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
316
319
  if (operandResult.status === "indeterminate") return operandResult;
317
320
  const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
318
- const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions);
321
+ const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
319
322
  if (candidateResult.status === "indeterminate") return candidateResult;
320
323
  return computeMembershipMatch(operandResult.value, candidateResult.value);
321
324
  }));
@@ -328,26 +331,37 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
328
331
  return require_evaluation.definite(node.op === "notIn");
329
332
  }
330
333
  case "exists": {
331
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
334
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
332
335
  if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return require_evaluation.definite(false);
333
336
  return require_evaluation.definite(true);
334
337
  }
335
338
  case "some":
336
339
  case "every": {
337
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
340
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
338
341
  const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
339
342
  if (filterOutcome === "exclude") return void 0;
340
343
  if (filterOutcome !== "include") return filterOutcome;
341
- return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions);
344
+ return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
342
345
  }))).filter((vote) => vote !== void 0);
343
346
  const combine = node.kind === "some" ? combineOr : combineAnd;
344
347
  const identity = node.kind === "some" ? require_evaluation.definite(false) : require_evaluation.definite(true);
345
348
  return votes.reduce(combine, identity);
346
349
  }
350
+ case "treeReference": {
351
+ if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
352
+ const keyString = JSON.stringify(node.key);
353
+ if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
354
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
355
+ const resolution = await resolvers.resolveTree(node.key, context);
356
+ if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
357
+ const parsed = require_tree.PredicateNodeSchema.safeParse(resolution.node);
358
+ if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
359
+ return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
360
+ }
347
361
  default: throw new Error("unreachable predicate node kind");
348
362
  }
349
363
  }
350
- async function evaluateValueInternal(node, context, resolvers, accumulator, functions) {
364
+ async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
351
365
  switch (node.kind) {
352
366
  case "reference": {
353
367
  const resolution = await resolvers.resolveValue(node.key, context);
@@ -362,7 +376,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
362
376
  if (accumulator === void 0) return require_evaluation.indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
363
377
  return require_evaluation.definite(accumulator);
364
378
  case "call": {
365
- const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions)));
379
+ const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
366
380
  const args = [];
367
381
  for (const result of argResults) {
368
382
  if (result.status === "indeterminate") return result;
@@ -393,18 +407,18 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
393
407
  unit: node.unit
394
408
  });
395
409
  case "arithmetic": {
396
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
410
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
397
411
  if (left.status === "indeterminate") return left;
398
412
  if (right.status === "indeterminate") return right;
399
413
  return applyArithmetic(node.op, left.value, right.value);
400
414
  }
401
415
  case "negate": {
402
- const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
416
+ const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
403
417
  if (operand.status === "indeterminate") return operand;
404
418
  return applyNegate(operand.value);
405
419
  }
406
420
  case "lookup": {
407
- const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions)));
421
+ const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
408
422
  const keyValues = [];
409
423
  for (const result of keyResults) {
410
424
  if (result.status === "indeterminate") return result;
@@ -414,15 +428,32 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
414
428
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `no match found in lookup table ${JSON.stringify(node.table)}`);
415
429
  return require_evaluation.definite(resolution.value);
416
430
  }
417
- case "conditional":
418
- for (const { when, then } of node.cases) {
419
- const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions);
420
- if (whenResult.status === "indeterminate") return whenResult;
421
- if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions);
431
+ case "conditional": {
432
+ if ((node.hitPolicy ?? "first") === "first") {
433
+ for (const { when, then } of node.cases) {
434
+ const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
435
+ if (whenResult.status === "indeterminate") return whenResult;
436
+ if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
437
+ }
438
+ return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
422
439
  }
423
- return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions);
440
+ const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
441
+ then,
442
+ whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
443
+ })));
444
+ const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
445
+ if (matches.length >= 2) return require_evaluation.indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
446
+ const reason = require_evaluation.firstIndeterminate(...evaluatedCases.map(({ whenResult }) => whenResult));
447
+ if (reason !== void 0) return {
448
+ status: "indeterminate",
449
+ reason
450
+ };
451
+ const [match] = matches;
452
+ if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
453
+ return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
454
+ }
424
455
  case "fold": {
425
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
456
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
426
457
  const filterIndeterminateReason = firstFilterIndeterminate(participating);
427
458
  if (filterIndeterminateReason !== void 0) return {
428
459
  status: "indeterminate",
@@ -430,11 +461,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
430
461
  };
431
462
  const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
432
463
  if (node.combiner.mode === "reduce") {
433
- const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions);
464
+ const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
434
465
  if (initialResult.status === "indeterminate") return initialResult;
435
466
  let runningAccumulator = initialResult.value;
436
467
  for (const item of includedItems) {
437
- const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions);
468
+ const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
438
469
  if (stepResult.status === "indeterminate") return stepResult;
439
470
  runningAccumulator = stepResult.value;
440
471
  }
@@ -444,7 +475,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
444
475
  const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
445
476
  let runningExtremum;
446
477
  for (const item of includedItems) {
447
- const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions);
478
+ const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
448
479
  if (itemResult.status === "indeterminate") return itemResult;
449
480
  if (runningExtremum === void 0) {
450
481
  runningExtremum = itemResult.value;
@@ -463,6 +494,17 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
463
494
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `delegate handler for external system '${node.system}' reported no value`);
464
495
  return require_evaluation.definite(resolution.value);
465
496
  }
497
+ case "treeReference": {
498
+ if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
499
+ const keyString = JSON.stringify(node.key);
500
+ if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
501
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
502
+ const resolution = await resolvers.resolveTree(node.key, context);
503
+ if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
504
+ const parsed = require_tree.ExpressionNodeSchema.safeParse(resolution.node);
505
+ if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
506
+ return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
507
+ }
466
508
  default: throw new Error("unreachable expression node kind");
467
509
  }
468
510
  }
@@ -471,8 +513,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
471
513
  */
472
514
  function createEvaluator({ functions = require_functions.emptyFunctionRegistry }) {
473
515
  return {
474
- evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions),
475
- evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions)
516
+ evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
517
+ evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
476
518
  };
477
519
  }
478
520
  const { evaluatePredicate, evaluateValue } = createEvaluator({});