trilean 1.5.1 → 1.6.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.
Files changed (50) hide show
  1. package/dist/complex.d.cts +1 -1
  2. package/dist/complex.d.ts +1 -1
  3. package/dist/computed-value-CbRF0Izc.d.cts +51 -0
  4. package/dist/computed-value-CbRF0Izc.d.ts +51 -0
  5. package/dist/computed-value.cjs +1 -1
  6. package/dist/computed-value.d.cts +1 -50
  7. package/dist/computed-value.d.ts +1 -50
  8. package/dist/computed-value.js +1 -1
  9. package/dist/evaluator-budget.cjs +24 -0
  10. package/dist/evaluator-budget.d.cts +21 -0
  11. package/dist/evaluator-budget.d.ts +21 -0
  12. package/dist/evaluator-budget.js +20 -0
  13. package/dist/evaluator-collection.cjs +33 -0
  14. package/dist/evaluator-collection.d.cts +23 -0
  15. package/dist/evaluator-collection.d.ts +23 -0
  16. package/dist/evaluator-collection.js +31 -0
  17. package/dist/evaluator-factory.cjs +19 -0
  18. package/dist/evaluator-factory.d.cts +22 -0
  19. package/dist/evaluator-factory.d.ts +22 -0
  20. package/dist/evaluator-factory.js +16 -0
  21. package/dist/evaluator-indeterminacy-helpers.cjs +180 -0
  22. package/dist/evaluator-indeterminacy-helpers.d.cts +57 -0
  23. package/dist/evaluator-indeterminacy-helpers.d.ts +57 -0
  24. package/dist/evaluator-indeterminacy-helpers.js +158 -0
  25. package/dist/evaluator-operations.cjs +385 -0
  26. package/dist/evaluator-operations.d.cts +27 -0
  27. package/dist/evaluator-operations.d.ts +27 -0
  28. package/dist/evaluator-operations.js +376 -0
  29. package/dist/evaluator-test-helpers.cjs +40 -0
  30. package/dist/evaluator-test-helpers.d.cts +13 -0
  31. package/dist/evaluator-test-helpers.d.ts +13 -0
  32. package/dist/evaluator-test-helpers.js +35 -0
  33. package/dist/evaluator.cjs +55 -454
  34. package/dist/evaluator.d.cts +6 -10
  35. package/dist/evaluator.d.ts +6 -10
  36. package/dist/evaluator.js +44 -442
  37. package/dist/functions.d.cts +2 -2
  38. package/dist/functions.d.ts +2 -2
  39. package/dist/index.cjs +5 -5
  40. package/dist/index.d.cts +2 -2
  41. package/dist/index.d.ts +2 -2
  42. package/dist/index.js +2 -2
  43. package/dist/magic-string.es-BWtG0AyA.js +1017 -0
  44. package/dist/magic-string.es-BvKy4sJx.cjs +1017 -0
  45. package/dist/resolvers.d.cts +1 -1
  46. package/dist/resolvers.d.ts +1 -1
  47. package/dist/test.DNmyFkvJ-Dasq3mQO.cjs +13578 -0
  48. package/dist/test.DNmyFkvJ-SCEEf0VK.js +13573 -0
  49. package/package.json +2 -2
  50. package/schemas/trilean.schema.json +1 -1
@@ -1,436 +1,52 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_complex = require("./complex.cjs");
3
- const require_computed_value = require("./computed-value.cjs");
4
3
  const require_evaluation = require("./evaluation.cjs");
5
- const require_functions = require("./functions.cjs");
4
+ require("./evaluator-budget.cjs");
5
+ const require_evaluator_collection = require("./evaluator-collection.cjs");
6
+ const require_evaluator_operations = require("./evaluator-operations.cjs");
6
7
  const require_tree = require("./tree.cjs");
7
- let trilean_regex = require("trilean-regex");
8
8
  //#region src/evaluator.ts
9
9
  /**
10
- * `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.
10
+ * `evaluatePredicateInternal` and `evaluateValueInternal` below 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. `resolveParticipatingItems` (in `evaluator-collection.ts`) would share that same hazard if it imported `evaluatePredicateInternal` directly, since it calls back into it to evaluate each candidate's filter -- so it instead takes the evaluator as an injected `EvaluatePredicate` parameter (see that type's own doc comment), which is what lets it live in its own file with no circular dependency on this one. The pure, non-recursive value-combination logic (`combineAnd`/`compareValues`/`applyArithmetic` and their siblings) carries no such constraint either and lives in `evaluator-operations.ts`; the resource-limit infrastructure (`EvaluationBudget` and its constants), likewise self-contained, lives in `evaluator-budget.ts`.
11
11
  */
12
- /** The three-valued AND table: `false` is absorbing regardless of the other operand's indeterminacy; otherwise both-definite folds to a boolean AND; otherwise indeterminate, with the tie-break rule (declared operand order, left before right) applied via `firstIndeterminate`. */
13
- function combineAnd(left, right) {
14
- if (left.status === "definite" && !left.value) return require_evaluation.definite(false);
15
- if (right.status === "definite" && !right.value) return require_evaluation.definite(false);
16
- const reason = require_evaluation.firstIndeterminate(left, right);
17
- if (reason !== void 0) return {
18
- status: "indeterminate",
19
- reason
20
- };
21
- return require_evaluation.definite(true);
22
- }
23
- /** The three-valued OR table: mirror image of `combineAnd`, with `true` absorbing. */
24
- function combineOr(left, right) {
25
- if (left.status === "definite" && left.value) return require_evaluation.definite(true);
26
- if (right.status === "definite" && right.value) return require_evaluation.definite(true);
27
- const reason = require_evaluation.firstIndeterminate(left, right);
28
- if (reason !== void 0) return {
29
- status: "indeterminate",
30
- reason
31
- };
32
- return require_evaluation.definite(false);
33
- }
34
- function applyComparisonOperator(op, left, right) {
35
- switch (op) {
36
- case "gt": return left > right;
37
- case "gte": return left >= right;
38
- case "lt": return left < right;
39
- case "lte": return left <= right;
40
- case "eq": return left === right;
41
- case "neq": return left !== right;
42
- default: throw new Error("unreachable comparison operator");
43
- }
44
- }
45
- const millisecondsPerDurationUnit = {
46
- ms: 1,
47
- s: 1e3,
48
- min: 6e4,
49
- h: 36e5,
50
- d: 864e5
51
- };
52
- /** Normalises a `duration`'s magnitude to milliseconds, the common base unit for combining or comparing two `duration`s (or an `instant` and a `duration`) of potentially different `DurationUnit`s -- shared by `compareValues`'s own `duration` branch below and by the temporal arithmetic further down. */
53
- function toMilliseconds(value, unit) {
54
- return value * millisecondsPerDurationUnit[unit];
55
- }
56
- /** `Date.parse` reports an unparseable timestamp as `NaN`, and every downstream use of that `NaN` then fails silently rather than loudly: every comparison against it is `false` (so `neq` between two unparseable instants would come back definitely `true`), a subtraction yields a `NaN`-magnitude duration, and `new Date(NaN).toISOString()` throws a `RangeError` outright -- a thrown exception for a data-quality problem, which this design never does (see `Evaluation<T>`'s own doc comment in evaluation.ts). An `instant` whose string will not parse is a value the operation cannot use, so every caller below reports it as `wrong-type`, exactly like any other unusable operand. */
57
- function toEpochMilliseconds(value) {
58
- const epochMilliseconds = Date.parse(value);
59
- return Number.isNaN(epochMilliseconds) ? void 0 : epochMilliseconds;
60
- }
61
- function unparseableInstant(value) {
62
- return require_evaluation.indeterminate("wrong-type", `'${value}' is not a parseable ISO-8601 timestamp`);
63
- }
64
- /** The representable timestamp range is finite, so a valid instant shifted by a large enough duration lands outside it, where `new Date(...).toISOString()` throws a `RangeError`. Checking the shifted date against the platform's own notion of a valid time value keeps that inside the three-outcome model as a `domain-error` -- an operation pushed outside its valid domain, the same category as division by zero -- and avoids hardcoding the range bound. */
65
- function instantFromEpochMilliseconds(epochMilliseconds) {
66
- const shifted = new Date(epochMilliseconds);
67
- if (Number.isNaN(shifted.getTime())) return require_evaluation.indeterminate("domain-error", "the resulting instant falls outside the representable timestamp range");
68
- return require_evaluation.definite({
69
- kind: "instant",
70
- value: shifted.toISOString()
71
- });
72
- }
73
- /** `compare`'s two operands: valid kinds are `number` (matching units required), `instant` (ordered by parsed epoch millisecond), or `duration` (ordered by magnitude normalised to milliseconds) -- `text` is never valid here (see `textCompare`), and a kind mismatch between the two operands is `wrong-type`. Narrowing `right` against a literal `left.kind` case (rather than asserting it) is what lets both sides stay properly typed with no `as`. */
74
- function compareValues(op, left, right) {
75
- switch (left.kind) {
76
- case "number":
77
- if (right.kind !== "number") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'number' value with a '${right.kind}' value`);
78
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare numbers with incompatible units");
79
- return require_evaluation.definite(applyComparisonOperator(op, left.value, right.value));
80
- case "text": return require_evaluation.indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
81
- case "boolean":
82
- if (right.kind !== "boolean") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
83
- if (op !== "eq" && op !== "neq") return require_evaluation.indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
84
- return require_evaluation.definite(op === "eq" ? left.value === right.value : left.value !== right.value);
85
- case "instant": {
86
- if (right.kind !== "instant") return require_evaluation.indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
87
- const leftEpoch = toEpochMilliseconds(left.value);
88
- if (leftEpoch === void 0) return unparseableInstant(left.value);
89
- const rightEpoch = toEpochMilliseconds(right.value);
90
- if (rightEpoch === void 0) return unparseableInstant(right.value);
91
- return require_evaluation.definite(applyComparisonOperator(op, leftEpoch, rightEpoch));
92
- }
93
- case "duration":
94
- if (right.kind !== "duration") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
95
- return require_evaluation.definite(applyComparisonOperator(op, toMilliseconds(left.value, left.unit), toMilliseconds(right.value, right.unit)));
96
- case "complex":
97
- if (op !== "eq" && op !== "neq") return require_evaluation.indeterminate("wrong-type", `ordering operator '${op}' is not defined for complex values; the complex plane has no total order`);
98
- if (right.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
99
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare complex values with incompatible units");
100
- return require_evaluation.definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
101
- default: throw new Error("unreachable computed-value kind");
102
- }
103
- }
104
- /** `textCompare`'s two operands must both resolve to the `text` computed-value kind -- any other kind, on either operand, is `wrong-type` (see the `textCompare` section of README.md). `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right`'s text as an ECMAScript regular expression tested against `left`'s text; `portableMatches`/`portableNotMatches` interpret it as a pattern in `trilean-regex`'s own restricted grammar instead, matched by that package's finite-automaton reference matcher rather than the host's native `RegExp` engine -- see the `textCompare` section of README.md for when to reach for the portable pair instead of the plain one. An invalid pattern is `wrong-type` rather than a thrown exception either way -- every data-quality problem stays inside the `Evaluation` result, per `Evaluation<T>`'s own doc comment in evaluation.ts. */
105
- function compareText(op, left, right) {
106
- if (left.kind !== "text") return require_evaluation.indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
107
- if (right.kind !== "text") return require_evaluation.indeterminate("wrong-type", `'textCompare' requires 'text' operands; the right operand is '${right.kind}'`);
108
- switch (op) {
109
- case "equals": return require_evaluation.definite(left.value === right.value);
110
- case "notEquals": return require_evaluation.definite(left.value !== right.value);
111
- case "matches":
112
- case "notMatches": {
113
- let pattern;
114
- try {
115
- pattern = new RegExp(right.value);
116
- } catch {
117
- return require_evaluation.indeterminate("wrong-type", `'${right.value}' is not a valid regular expression pattern`);
118
- }
119
- const isMatch = pattern.test(left.value);
120
- return require_evaluation.definite(op === "matches" ? isMatch : !isMatch);
121
- }
122
- case "portableMatches":
123
- case "portableNotMatches": {
124
- let compiled;
125
- try {
126
- compiled = (0, trilean_regex.compilePattern)(right.value);
127
- } catch (error) {
128
- const reason = error instanceof trilean_regex.RegexParseError ? error.message : String(error);
129
- return require_evaluation.indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
130
- }
131
- const isMatch = compiled.test(left.value);
132
- return require_evaluation.definite(op === "portableMatches" ? isMatch : !isMatch);
133
- }
134
- default: throw new Error("unreachable text comparison operator");
135
- }
136
- }
137
- /** `memberOf`'s own value-equality test between two computed values -- kind-agnostic across `number`/`text`/`instant`/`duration` (see the `memberOf` section of README.md, and its "Derived aggregates" note that this equality is kind-agnostic across every computed-value kind), unlike `compare`'s own `eq`, which rejects a `text` operand outright and directs callers to `textCompare` instead. A kind mismatch, or a `number` pair with an incompatible unit, is `wrong-type` -- never simply "not equal". Narrowing `candidate` against a literal `operand.kind` case (rather than asserting it) is the same technique `compareValues` uses above. */
138
- function computeMembershipMatch(operand, candidate) {
139
- switch (operand.kind) {
140
- case "number":
141
- if (candidate.kind !== "number") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'number' value with a '${candidate.kind}' value for membership`);
142
- if (!require_computed_value.unitsEqual(operand.unit, candidate.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare numbers with incompatible units for membership");
143
- return require_evaluation.definite(operand.value === candidate.value);
144
- case "text":
145
- if (candidate.kind !== "text") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
146
- return require_evaluation.definite(operand.value === candidate.value);
147
- case "boolean":
148
- if (candidate.kind !== "boolean") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
149
- return require_evaluation.definite(operand.value === candidate.value);
150
- case "instant": {
151
- if (candidate.kind !== "instant") return require_evaluation.indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
152
- const operandEpoch = toEpochMilliseconds(operand.value);
153
- if (operandEpoch === void 0) return unparseableInstant(operand.value);
154
- const candidateEpoch = toEpochMilliseconds(candidate.value);
155
- if (candidateEpoch === void 0) return unparseableInstant(candidate.value);
156
- return require_evaluation.definite(operandEpoch === candidateEpoch);
157
- }
158
- case "duration":
159
- if (candidate.kind !== "duration") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
160
- return require_evaluation.definite(toMilliseconds(operand.value, operand.unit) === toMilliseconds(candidate.value, candidate.unit));
161
- case "complex":
162
- if (candidate.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
163
- if (!require_computed_value.unitsEqual(operand.unit, candidate.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
164
- return require_evaluation.definite(operand.re === candidate.re && operand.im === candidate.im);
165
- default: throw new Error("unreachable computed-value kind");
166
- }
167
- }
168
- /** `power`/`modulo` have no defined unit-combination rule in this design (unlike `add`/`subtract`'s "identical units" requirement or `multiply`/`divide`'s dimensional-exponent combination) -- scoping them to dimensionless operands avoids inventing an unspecified unit-scaling semantics for a fractional or runtime-determined exponent. */
169
- function isDimensionless(unit) {
170
- return require_computed_value.unitsEqual(unit, void 0);
171
- }
172
- /** `negate` is never sugar for "zero minus the value" (see the `arithmetic`/`negate` section of README.md) -- a `duration`'s magnitude is negated directly, in its own original unit, with no subtraction or millisecond normalisation involved. */
173
- function applyNegate(operand) {
174
- switch (operand.kind) {
175
- case "number": return require_evaluation.definite({
176
- kind: "number",
177
- value: -operand.value,
178
- unit: operand.unit
179
- });
180
- case "duration": return require_evaluation.definite({
181
- kind: "duration",
182
- value: -operand.value,
183
- unit: operand.unit
184
- });
185
- case "complex": return require_evaluation.definite({
186
- kind: "complex",
187
- re: -operand.re,
188
- im: -operand.im,
189
- unit: operand.unit
190
- });
191
- case "text":
192
- case "instant":
193
- case "boolean": return require_evaluation.indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
194
- default: throw new Error("unreachable computed-value kind");
195
- }
196
- }
197
- function applyArithmeticOnNumbers(op, left, right) {
198
- switch (op) {
199
- case "add":
200
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot add numbers with incompatible units");
201
- return require_evaluation.definite({
202
- kind: "number",
203
- value: left.value + right.value,
204
- unit: left.unit
205
- });
206
- case "subtract":
207
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot subtract numbers with incompatible units");
208
- return require_evaluation.definite({
209
- kind: "number",
210
- value: left.value - right.value,
211
- unit: left.unit
212
- });
213
- case "multiply": return require_evaluation.definite({
214
- kind: "number",
215
- value: left.value * right.value,
216
- unit: require_computed_value.combineUnitsForMultiply(left.unit, right.unit)
217
- });
218
- case "divide":
219
- if (right.value === 0) return require_evaluation.indeterminate("domain-error", "division by zero");
220
- return require_evaluation.definite({
221
- kind: "number",
222
- value: left.value / right.value,
223
- unit: require_computed_value.combineUnitsForDivide(left.unit, right.unit)
224
- });
225
- case "power":
226
- if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return require_evaluation.indeterminate("wrong-type", "'power' requires dimensionless operands");
227
- if (left.value < 0 && !Number.isInteger(right.value)) return require_evaluation.indeterminate("domain-error", "a negative base raised to a non-integer power is not a real number");
228
- if (left.value === 0 && right.value < 0) return require_evaluation.indeterminate("domain-error", "zero raised to a negative power is a division by zero");
229
- return require_evaluation.definite({
230
- kind: "number",
231
- value: left.value ** right.value
232
- });
233
- case "modulo":
234
- if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return require_evaluation.indeterminate("wrong-type", "'modulo' requires dimensionless operands");
235
- if (right.value === 0) return require_evaluation.indeterminate("domain-error", "modulo by zero");
236
- return require_evaluation.definite({
237
- kind: "number",
238
- value: left.value % right.value
239
- });
240
- default: throw new Error("unreachable arithmetic operator");
241
- }
242
- }
243
- /** The only same-kind, non-`number` arithmetic this design defines: two `duration`s combine by normalising both to milliseconds first (see `toMilliseconds`), reporting the result in milliseconds -- `multiply`/`divide`/`power`/`modulo` have no representable result unit for a `duration` squared or a dimensionless ratio, so they are `wrong-type` rather than invented. */
244
- function applyArithmeticOnDurations(op, left, right) {
245
- switch (op) {
246
- case "add": return require_evaluation.definite({
247
- kind: "duration",
248
- value: toMilliseconds(left.value, left.unit) + toMilliseconds(right.value, right.unit),
249
- unit: "ms"
250
- });
251
- case "subtract": return require_evaluation.definite({
252
- kind: "duration",
253
- value: toMilliseconds(left.value, left.unit) - toMilliseconds(right.value, right.unit),
254
- unit: "ms"
255
- });
256
- case "multiply":
257
- case "divide":
258
- case "power":
259
- case "modulo": return require_evaluation.indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between two 'duration' values`);
260
- default: throw new Error("unreachable arithmetic operator");
261
- }
262
- }
263
- /** Every real number is a complex number with a zero imaginary part, so promoting one is exact and total -- unlike the temporal cross-kind combinations above, which each had to be enumerated because no such embedding exists between an `instant` and a `duration`. This is what lets a tree mix real and complex terms freely instead of forcing every real literal to be written as a complex one. */
264
- function toComplexValue(value) {
265
- if (value.kind === "complex") return value;
266
- return {
267
- kind: "complex",
268
- re: value.value,
269
- im: 0,
270
- unit: value.unit
271
- };
272
- }
273
- /** The complex product, as its own component-level helper rather than only a branch of the operator switch below, because `power`'s repeated multiplication needs exactly this and must not re-derive it. */
274
- function multiplyComplexValues(left, right) {
275
- return {
276
- kind: "complex",
277
- re: left.re * right.re - left.im * right.im,
278
- im: left.re * right.im + left.im * right.re,
279
- unit: require_computed_value.combineUnitsForMultiply(left.unit, right.unit)
280
- };
281
- }
282
- /** Complex arithmetic, over the one canonical rectangular representation the `complex` kind stores (see the "Complex values" section of README.md). `add`/`subtract` are component-wise and carry the same identical-units requirement real numbers already have. `power` is deliberately excluded from this operator set rather than handled and rejected here: its exponent must stay an un-promoted real number, so the dispatcher routes it to `applyComplexPower` first, and excluding it from the type is what makes the compiler enforce that routing instead of leaving a dead branch behind. */
283
- function applyArithmeticOnComplex(op, left, right) {
284
- switch (op) {
285
- case "add":
286
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot add complex values with incompatible units");
287
- return require_evaluation.definite({
288
- kind: "complex",
289
- re: left.re + right.re,
290
- im: left.im + right.im,
291
- unit: left.unit
292
- });
293
- case "subtract":
294
- if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
295
- return require_evaluation.definite({
296
- kind: "complex",
297
- re: left.re - right.re,
298
- im: left.im - right.im,
299
- unit: left.unit
300
- });
301
- case "multiply": return require_evaluation.definite(multiplyComplexValues(left, right));
302
- case "divide": {
303
- const divisorSquaredMagnitude = right.re * right.re + right.im * right.im;
304
- if (divisorSquaredMagnitude === 0) return require_evaluation.indeterminate("domain-error", "division by zero");
305
- return require_evaluation.definite({
306
- kind: "complex",
307
- re: (left.re * right.re + left.im * right.im) / divisorSquaredMagnitude,
308
- im: (left.im * right.re - left.re * right.im) / divisorSquaredMagnitude,
309
- unit: require_computed_value.combineUnitsForDivide(left.unit, right.unit)
310
- });
311
- }
312
- case "modulo": return require_evaluation.indeterminate("domain-error", "'modulo' is undefined for complex values");
313
- default: throw new Error("unreachable arithmetic operator");
314
- }
315
- }
316
- /** `power` with a complex operand on either side, defined for exactly one case: a real integer exponent, evaluated as the repeated multiplication that integer exponentiation *is* (see the "Complex values" section of README.md for why an arbitrary complex exponent stays out of scope). */
317
- function applyComplexPower(base, exponent) {
318
- if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return require_evaluation.indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
319
- if (!isDimensionless(base.unit) || !isDimensionless(exponent.unit)) return require_evaluation.indeterminate("wrong-type", "'power' requires dimensionless operands");
320
- const complexUnit = {
321
- kind: "complex",
322
- re: 1,
323
- im: 0,
324
- unit: {}
325
- };
326
- const complexBase = toComplexValue(base);
327
- let repeatedProduct = complexUnit;
328
- for (let applied = 0; applied < Math.abs(exponent.value); applied += 1) repeatedProduct = multiplyComplexValues(repeatedProduct, complexBase);
329
- if (exponent.value >= 0) return require_evaluation.definite(repeatedProduct);
330
- return applyArithmeticOnComplex("divide", complexUnit, repeatedProduct);
331
- }
332
- /**
333
- * Dispatches `arithmetic` by operand kind. The three cross-kind temporal combinations this design defines (`instant - instant`, `instant + duration`, `duration + instant`) are checked explicitly first, in that order, against the exact operator each requires; any other combination touching an `instant` is `wrong-type` (see "Temporal values" in README.md -- e.g. adding two instants, or subtracting a `duration` from an `instant`, are deliberately *not* defined). Same-kind `duration`/`duration` combinations are delegated to `applyArithmeticOnDurations`; a `duration` paired with anything other than an `instant` or another `duration` is `wrong-type`. Everything remaining requires two `number` operands.
334
- */
335
- function applyArithmetic(op, left, right) {
336
- if (left.kind === "instant" && right.kind === "instant" && op === "subtract") {
337
- const leftEpoch = toEpochMilliseconds(left.value);
338
- if (leftEpoch === void 0) return unparseableInstant(left.value);
339
- const rightEpoch = toEpochMilliseconds(right.value);
340
- if (rightEpoch === void 0) return unparseableInstant(right.value);
341
- return require_evaluation.definite({
342
- kind: "duration",
343
- value: leftEpoch - rightEpoch,
344
- unit: "ms"
345
- });
346
- }
347
- if (left.kind === "instant" && right.kind === "duration" && op === "add") {
348
- const leftEpoch = toEpochMilliseconds(left.value);
349
- if (leftEpoch === void 0) return unparseableInstant(left.value);
350
- return instantFromEpochMilliseconds(leftEpoch + toMilliseconds(right.value, right.unit));
351
- }
352
- if (left.kind === "duration" && right.kind === "instant" && op === "add") {
353
- const rightEpoch = toEpochMilliseconds(right.value);
354
- if (rightEpoch === void 0) return unparseableInstant(right.value);
355
- return instantFromEpochMilliseconds(rightEpoch + toMilliseconds(left.value, left.unit));
356
- }
357
- if (left.kind === "instant" || right.kind === "instant") return require_evaluation.indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
358
- if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
359
- if (left.kind === "duration" || right.kind === "duration") return require_evaluation.indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
360
- if (left.kind !== "number" && left.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
361
- if (right.kind !== "number" && right.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
362
- if (left.kind === "complex" || right.kind === "complex") {
363
- if (op === "power") return applyComplexPower(left, right);
364
- return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
365
- }
366
- return applyArithmeticOnNumbers(op, left, right);
367
- }
368
- /** 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. */
369
- const MAX_TREE_REFERENCE_DEPTH = 100;
370
- /**
371
- * 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.
372
- */
373
- async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
374
- const candidates = await resolvers.resolveCollection(collection, context);
375
- return Promise.all(candidates.map(async (item) => {
376
- if (filter === void 0) return {
377
- item,
378
- filterOutcome: "include"
379
- };
380
- const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
381
- if (filterResult.status === "indeterminate") return {
382
- item,
383
- filterOutcome: filterResult
384
- };
385
- return {
386
- item,
387
- filterOutcome: filterResult.value ? "include" : "exclude"
388
- };
389
- }));
390
- }
391
- /** The first participating item (in declared collection order) whose `filter` evaluation was itself indeterminate, or `undefined` if every participating item's filter resolved definitely -- a filter-excluded item's own `"exclude"` outcome never counts here. Used only by `fold`, which -- unlike `some`/`every`'s OR/AND absorption -- has no absorbing value at all: any participating item's indeterminate filter makes the whole fold indeterminate outright, with no other item's outcome able to override it. */
392
- function firstFilterIndeterminate(participating) {
393
- for (const { filterOutcome } of participating) {
394
- if (filterOutcome === "include" || filterOutcome === "exclude") continue;
395
- if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
396
- }
397
- }
398
- async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
12
+ async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
13
+ const budgetExceeded = budget.checkNode(nestingDepth);
14
+ if (budgetExceeded !== void 0) return budgetExceeded;
399
15
  switch (node.kind) {
400
16
  case "not": {
401
- const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
17
+ const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
402
18
  if (operand.status === "indeterminate") return operand;
403
19
  return require_evaluation.definite(!operand.value);
404
20
  }
405
21
  case "and": {
406
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
407
- return combineAnd(left, right);
22
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
23
+ return require_evaluator_operations.combineAnd(left, right);
408
24
  }
409
25
  case "or": {
410
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
411
- return combineOr(left, right);
26
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
27
+ return require_evaluator_operations.combineOr(left, right);
412
28
  }
413
- 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));
414
- 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));
29
+ case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(require_evaluator_operations.combineAnd, require_evaluation.definite(true));
30
+ case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(require_evaluator_operations.combineOr, require_evaluation.definite(false));
415
31
  case "compare": {
416
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
32
+ const [left, right] = await Promise.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)]);
417
33
  if (left.status === "indeterminate") return left;
418
34
  if (right.status === "indeterminate") return right;
419
- return compareValues(node.op, left.value, right.value);
35
+ return require_evaluator_operations.compareValues(node.op, left.value, right.value);
420
36
  }
421
37
  case "textCompare": {
422
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
38
+ const [left, right] = await Promise.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)]);
423
39
  if (left.status === "indeterminate") return left;
424
40
  if (right.status === "indeterminate") return right;
425
- return compareText(node.op, left.value, right.value);
41
+ return require_evaluator_operations.compareText(node.op, left.value, right.value);
426
42
  }
427
43
  case "memberOf": {
428
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
44
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
429
45
  if (operandResult.status === "indeterminate") return operandResult;
430
46
  const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
431
- const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
47
+ const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
432
48
  if (candidateResult.status === "indeterminate") return candidateResult;
433
- return computeMembershipMatch(operandResult.value, candidateResult.value);
49
+ return require_evaluator_operations.computeMembershipMatch(operandResult.value, candidateResult.value);
434
50
  }));
435
51
  for (const outcome of candidateOutcomes) if (outcome.status === "definite" && outcome.value) return require_evaluation.definite(node.op === "in");
436
52
  const reason = require_evaluation.firstIndeterminate(...candidateOutcomes);
@@ -441,19 +57,19 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
441
57
  return require_evaluation.definite(node.op === "notIn");
442
58
  }
443
59
  case "exists": {
444
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
60
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
445
61
  if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return require_evaluation.definite(false);
446
62
  return require_evaluation.definite(true);
447
63
  }
448
64
  case "some":
449
65
  case "every": {
450
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
66
+ const participating = await require_evaluator_collection.resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
451
67
  const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
452
68
  if (filterOutcome === "exclude") return void 0;
453
69
  if (filterOutcome !== "include") return filterOutcome;
454
- return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
70
+ return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
455
71
  }))).filter((vote) => vote !== void 0);
456
- const combine = node.kind === "some" ? combineOr : combineAnd;
72
+ const combine = node.kind === "some" ? require_evaluator_operations.combineOr : require_evaluator_operations.combineAnd;
457
73
  const identity = node.kind === "some" ? require_evaluation.definite(false) : require_evaluation.definite(true);
458
74
  return votes.reduce(combine, identity);
459
75
  }
@@ -461,42 +77,38 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
461
77
  if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
462
78
  const keyString = JSON.stringify(node.key);
463
79
  if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
464
- if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
80
+ if (treeReferenceDepth >= 100) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
465
81
  const resolution = await resolvers.resolveTree(node.key, context);
466
82
  if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
467
83
  const parsed = require_tree.PredicateNodeSchema.safeParse(resolution.node);
468
84
  if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
469
- return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
85
+ return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
470
86
  }
471
87
  default: throw new Error("unreachable predicate node kind");
472
88
  }
473
89
  }
474
- async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
90
+ async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
91
+ const budgetExceeded = budget.checkNode(nestingDepth);
92
+ if (budgetExceeded !== void 0) return budgetExceeded;
475
93
  switch (node.kind) {
476
94
  case "reference": {
477
95
  const resolution = await resolvers.resolveValue(node.key, context);
478
96
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
479
- if (node.unit !== void 0) {
480
- if (resolution.value.kind !== "number" && resolution.value.kind !== "complex") return require_evaluation.indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
481
- if (!require_computed_value.unitsEqual(node.unit, resolution.value.unit)) return require_evaluation.indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
482
- }
97
+ const unitError = require_evaluator_operations.checkReferenceUnit(node.unit, resolution.value);
98
+ if (unitError !== void 0) return unitError;
483
99
  return require_evaluation.definite(resolution.value);
484
100
  }
485
101
  case "accumulator":
486
102
  if (accumulator === void 0) return require_evaluation.indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
487
103
  return require_evaluation.definite(accumulator);
488
104
  case "call": {
489
- const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
105
+ const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
490
106
  const args = [];
491
107
  for (const result of argResults) {
492
108
  if (result.status === "indeterminate") return result;
493
109
  args.push(result.value);
494
110
  }
495
- const fn = Object.hasOwn(functions, node.fn) ? functions[node.fn] : void 0;
496
- if (fn === void 0) return require_evaluation.indeterminate("wrong-type", `no function registered under the name '${node.fn}'`);
497
- const outcome = fn(args);
498
- if ("domainError" in outcome) return require_evaluation.indeterminate("domain-error", outcome.domainError);
499
- return require_evaluation.definite(outcome);
111
+ return require_evaluator_operations.invokeRegisteredFunction(functions, node.fn, args);
500
112
  }
501
113
  case "numberLiteral": return require_evaluation.definite({
502
114
  kind: "number",
@@ -529,18 +141,18 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
529
141
  });
530
142
  return require_evaluation.definite(require_complex.complexFromPolar(node.magnitude, node.phase, node.unit));
531
143
  case "arithmetic": {
532
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
144
+ const [left, right] = await Promise.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)]);
533
145
  if (left.status === "indeterminate") return left;
534
146
  if (right.status === "indeterminate") return right;
535
- return applyArithmetic(node.op, left.value, right.value);
147
+ return require_evaluator_operations.applyArithmetic(node.op, left.value, right.value);
536
148
  }
537
149
  case "negate": {
538
- const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
150
+ const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
539
151
  if (operand.status === "indeterminate") return operand;
540
- return applyNegate(operand.value);
152
+ return require_evaluator_operations.applyNegate(operand.value);
541
153
  }
542
154
  case "lookup": {
543
- const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
155
+ const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
544
156
  const keyValues = [];
545
157
  for (const result of keyResults) {
546
158
  if (result.status === "indeterminate") return result;
@@ -553,15 +165,15 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
553
165
  case "conditional": {
554
166
  if ((node.hitPolicy ?? "first") === "first") {
555
167
  for (const { when, then } of node.cases) {
556
- const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
168
+ const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
557
169
  if (whenResult.status === "indeterminate") return whenResult;
558
- if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
170
+ if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
559
171
  }
560
- return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
172
+ return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
561
173
  }
562
174
  const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
563
175
  then,
564
- whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
176
+ whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)
565
177
  })));
566
178
  const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
567
179
  if (matches.length >= 2) return require_evaluation.indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
@@ -571,23 +183,23 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
571
183
  reason
572
184
  };
573
185
  const [match] = matches;
574
- if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
575
- return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
186
+ if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
187
+ return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
576
188
  }
577
189
  case "fold": {
578
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
579
- const filterIndeterminateReason = firstFilterIndeterminate(participating);
190
+ const participating = await require_evaluator_collection.resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
191
+ const filterIndeterminateReason = require_evaluator_collection.firstFilterIndeterminate(participating);
580
192
  if (filterIndeterminateReason !== void 0) return {
581
193
  status: "indeterminate",
582
194
  reason: filterIndeterminateReason
583
195
  };
584
196
  const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
585
197
  if (node.combiner.mode === "reduce") {
586
- const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
198
+ const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
587
199
  if (initialResult.status === "indeterminate") return initialResult;
588
200
  let runningAccumulator = initialResult.value;
589
201
  for (const item of includedItems) {
590
- const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
202
+ const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
591
203
  if (stepResult.status === "indeterminate") return stepResult;
592
204
  runningAccumulator = stepResult.value;
593
205
  }
@@ -597,13 +209,13 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
597
209
  const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
598
210
  let runningExtremum;
599
211
  for (const item of includedItems) {
600
- const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
212
+ const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
601
213
  if (itemResult.status === "indeterminate") return itemResult;
602
214
  if (runningExtremum === void 0) {
603
215
  runningExtremum = itemResult.value;
604
216
  continue;
605
217
  }
606
- const comparison = compareValues(dominatesOp, itemResult.value, runningExtremum);
218
+ const comparison = require_evaluator_operations.compareValues(dominatesOp, itemResult.value, runningExtremum);
607
219
  if (comparison.status === "indeterminate") return comparison;
608
220
  if (comparison.value) runningExtremum = itemResult.value;
609
221
  }
@@ -620,27 +232,16 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
620
232
  if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
621
233
  const keyString = JSON.stringify(node.key);
622
234
  if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
623
- if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
235
+ if (treeReferenceDepth >= 100) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
624
236
  const resolution = await resolvers.resolveTree(node.key, context);
625
237
  if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
626
238
  const parsed = require_tree.ExpressionNodeSchema.safeParse(resolution.node);
627
239
  if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
628
- return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
240
+ return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
629
241
  }
630
242
  default: throw new Error("unreachable expression node kind");
631
243
  }
632
244
  }
633
- /**
634
- * Builds a bound `{ evaluatePredicate, evaluateValue }` pair over a caller-supplied function registry for `call` nodes -- the registry is bound once, at construction time, unlike `resolvers`, which are supplied fresh to every call. The bare module-level `evaluatePredicate`/`evaluateValue` exports below are `createEvaluator({})`'s output.
635
- */
636
- function createEvaluator({ functions = require_functions.emptyFunctionRegistry }) {
637
- return {
638
- evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
639
- evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
640
- };
641
- }
642
- const { evaluatePredicate, evaluateValue } = createEvaluator({});
643
245
  //#endregion
644
- exports.createEvaluator = createEvaluator;
645
- exports.evaluatePredicate = evaluatePredicate;
646
- exports.evaluateValue = evaluateValue;
246
+ exports.evaluatePredicateInternal = evaluatePredicateInternal;
247
+ exports.evaluateValueInternal = evaluateValueInternal;