trilean 1.6.0 → 1.6.2
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/dist/complex.d.cts +1 -1
- package/dist/complex.d.ts +1 -1
- package/dist/computed-value-CbRF0Izc.d.cts +51 -0
- package/dist/computed-value-CbRF0Izc.d.ts +51 -0
- package/dist/computed-value.cjs +1 -1
- package/dist/computed-value.d.cts +1 -50
- package/dist/computed-value.d.ts +1 -50
- package/dist/computed-value.js +1 -1
- package/dist/evaluator-budget.cjs +24 -0
- package/dist/evaluator-budget.d.cts +21 -0
- package/dist/evaluator-budget.d.ts +21 -0
- package/dist/evaluator-budget.js +20 -0
- package/dist/evaluator-collection.cjs +33 -0
- package/dist/evaluator-collection.d.cts +23 -0
- package/dist/evaluator-collection.d.ts +23 -0
- package/dist/evaluator-collection.js +31 -0
- package/dist/evaluator-factory.cjs +19 -0
- package/dist/evaluator-factory.d.cts +22 -0
- package/dist/evaluator-factory.d.ts +22 -0
- package/dist/evaluator-factory.js +16 -0
- package/dist/evaluator-indeterminacy-helpers.cjs +180 -0
- package/dist/evaluator-indeterminacy-helpers.d.cts +57 -0
- package/dist/evaluator-indeterminacy-helpers.d.ts +57 -0
- package/dist/evaluator-indeterminacy-helpers.js +158 -0
- package/dist/evaluator-operations.cjs +385 -0
- package/dist/evaluator-operations.d.cts +27 -0
- package/dist/evaluator-operations.d.ts +27 -0
- package/dist/evaluator-operations.js +376 -0
- package/dist/evaluator-test-helpers.cjs +40 -0
- package/dist/evaluator-test-helpers.d.cts +13 -0
- package/dist/evaluator-test-helpers.d.ts +13 -0
- package/dist/evaluator-test-helpers.js +35 -0
- package/dist/evaluator.cjs +25 -442
- package/dist/evaluator.d.cts +6 -14
- package/dist/evaluator.d.ts +6 -14
- package/dist/evaluator.js +12 -428
- package/dist/functions.d.cts +2 -2
- package/dist/functions.d.ts +2 -2
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/magic-string.es-BWtG0AyA.js +1017 -0
- package/dist/magic-string.es-BvKy4sJx.cjs +1017 -0
- package/dist/resolvers.d.cts +1 -1
- package/dist/resolvers.d.ts +1 -1
- package/dist/test.DNmyFkvJ-Dasq3mQO.cjs +13578 -0
- package/dist/test.DNmyFkvJ-SCEEf0VK.js +13573 -0
- package/package.json +3 -3
- package/schemas/trilean.schema.json +1 -1
package/dist/evaluator.cjs
CHANGED
|
@@ -1,414 +1,14 @@
|
|
|
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
|
-
|
|
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
|
-
/** Default cap on the total number of predicate/expression nodes a single `evaluatePredicate`/`evaluateValue` call may visit -- see `createEvaluator`'s `maxNodes` option, threaded through to `createEvaluationBudget` below. Chosen generously above any realistic hand-authored business-rule, eligibility, or formula tree (see README.md's own consumer use cases), while still bounding an untrusted, adversarially-authored tree's total evaluation cost to a fixed, small amount of work regardless of how it is shaped. */
|
|
371
|
-
const DEFAULT_MAX_EVALUATION_NODES = 1e4;
|
|
372
|
-
/** Default cap on ordinary recursive-descent nesting depth -- see `createEvaluator`'s `maxNestingDepth` option, threaded through to `createEvaluationBudget` below. Set comfortably below the depth at which this evaluator's own recursive descent has been observed to exhaust the host call stack (a chain of plain `not` nodes wrapped around a single leaf, evaluated directly against this file under Node.js, failed consistently somewhere in the low thousands of nesting levels, with some run-to-run variance from whatever else already occupied the stack), while remaining far deeper than any legitimate hand-authored tree is ever likely to nest. Kept well clear of that measured failure point because the exact threshold varies by host runtime (a Cloudflare Workers isolate's own stack is smaller than Node's) and by how much of the stack the rest of the call chain has already used. */
|
|
373
|
-
const DEFAULT_MAX_NESTING_DEPTH = 500;
|
|
374
|
-
/** Constructs a fresh `EvaluationBudget` for one top-level `evaluatePredicate`/`evaluateValue` call -- see `createEvaluator`'s `maxNodes`/`maxNestingDepth` options, which supply `maxNodes`/`maxNestingDepth` here. A fresh closure per call is what keeps `nodesVisited` from leaking between unrelated evaluations. */
|
|
375
|
-
function createEvaluationBudget(maxNodes, maxNestingDepth) {
|
|
376
|
-
/** Total predicate/expression nodes visited so far across the whole call -- shared by every branch of an `and`/`or`/`allOf`/`anyOf`/fold/quantifier through the closure below, so it accumulates across the whole traversal rather than resetting per branch. */
|
|
377
|
-
let nodesVisited = 0;
|
|
378
|
-
return { checkNode(nestingDepth) {
|
|
379
|
-
nodesVisited += 1;
|
|
380
|
-
if (nodesVisited > maxNodes) return require_evaluation.indeterminate("domain-error", `evaluation exceeded the maximum of ${maxNodes.toString()} nodes visited in a single call (resource exhausted)`);
|
|
381
|
-
if (nestingDepth >= maxNestingDepth) return require_evaluation.indeterminate("domain-error", `evaluation nesting depth exceeds the maximum of ${maxNestingDepth.toString()} (resource exhausted)`);
|
|
382
|
-
} };
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* 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.
|
|
386
|
-
*/
|
|
387
|
-
async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
388
|
-
const candidates = await resolvers.resolveCollection(collection, context);
|
|
389
|
-
return Promise.all(candidates.map(async (item) => {
|
|
390
|
-
if (filter === void 0) return {
|
|
391
|
-
item,
|
|
392
|
-
filterOutcome: "include"
|
|
393
|
-
};
|
|
394
|
-
const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
395
|
-
if (filterResult.status === "indeterminate") return {
|
|
396
|
-
item,
|
|
397
|
-
filterOutcome: filterResult
|
|
398
|
-
};
|
|
399
|
-
return {
|
|
400
|
-
item,
|
|
401
|
-
filterOutcome: filterResult.value ? "include" : "exclude"
|
|
402
|
-
};
|
|
403
|
-
}));
|
|
404
|
-
}
|
|
405
|
-
/** 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. */
|
|
406
|
-
function firstFilterIndeterminate(participating) {
|
|
407
|
-
for (const { filterOutcome } of participating) {
|
|
408
|
-
if (filterOutcome === "include" || filterOutcome === "exclude") continue;
|
|
409
|
-
if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
12
|
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
413
13
|
const budgetExceeded = budget.checkNode(nestingDepth);
|
|
414
14
|
if (budgetExceeded !== void 0) return budgetExceeded;
|
|
@@ -420,25 +20,25 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
420
20
|
}
|
|
421
21
|
case "and": {
|
|
422
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)]);
|
|
423
|
-
return combineAnd(left, right);
|
|
23
|
+
return require_evaluator_operations.combineAnd(left, right);
|
|
424
24
|
}
|
|
425
25
|
case "or": {
|
|
426
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)]);
|
|
427
|
-
return combineOr(left, right);
|
|
27
|
+
return require_evaluator_operations.combineOr(left, right);
|
|
428
28
|
}
|
|
429
|
-
case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(combineAnd, require_evaluation.definite(true));
|
|
430
|
-
case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).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));
|
|
431
31
|
case "compare": {
|
|
432
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)]);
|
|
433
33
|
if (left.status === "indeterminate") return left;
|
|
434
34
|
if (right.status === "indeterminate") return right;
|
|
435
|
-
return compareValues(node.op, left.value, right.value);
|
|
35
|
+
return require_evaluator_operations.compareValues(node.op, left.value, right.value);
|
|
436
36
|
}
|
|
437
37
|
case "textCompare": {
|
|
438
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)]);
|
|
439
39
|
if (left.status === "indeterminate") return left;
|
|
440
40
|
if (right.status === "indeterminate") return right;
|
|
441
|
-
return compareText(node.op, left.value, right.value);
|
|
41
|
+
return require_evaluator_operations.compareText(node.op, left.value, right.value);
|
|
442
42
|
}
|
|
443
43
|
case "memberOf": {
|
|
444
44
|
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
@@ -446,7 +46,7 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
446
46
|
const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
|
|
447
47
|
const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
448
48
|
if (candidateResult.status === "indeterminate") return candidateResult;
|
|
449
|
-
return computeMembershipMatch(operandResult.value, candidateResult.value);
|
|
49
|
+
return require_evaluator_operations.computeMembershipMatch(operandResult.value, candidateResult.value);
|
|
450
50
|
}));
|
|
451
51
|
for (const outcome of candidateOutcomes) if (outcome.status === "definite" && outcome.value) return require_evaluation.definite(node.op === "in");
|
|
452
52
|
const reason = require_evaluation.firstIndeterminate(...candidateOutcomes);
|
|
@@ -463,13 +63,13 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
463
63
|
}
|
|
464
64
|
case "some":
|
|
465
65
|
case "every": {
|
|
466
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
66
|
+
const participating = await require_evaluator_collection.resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
467
67
|
const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
|
|
468
68
|
if (filterOutcome === "exclude") return void 0;
|
|
469
69
|
if (filterOutcome !== "include") return filterOutcome;
|
|
470
70
|
return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
471
71
|
}))).filter((vote) => vote !== void 0);
|
|
472
|
-
const combine = node.kind === "some" ? combineOr : combineAnd;
|
|
72
|
+
const combine = node.kind === "some" ? require_evaluator_operations.combineOr : require_evaluator_operations.combineAnd;
|
|
473
73
|
const identity = node.kind === "some" ? require_evaluation.definite(false) : require_evaluation.definite(true);
|
|
474
74
|
return votes.reduce(combine, identity);
|
|
475
75
|
}
|
|
@@ -477,7 +77,7 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
477
77
|
if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
478
78
|
const keyString = JSON.stringify(node.key);
|
|
479
79
|
if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
|
|
480
|
-
if (treeReferenceDepth >=
|
|
80
|
+
if (treeReferenceDepth >= 100) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
481
81
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
482
82
|
if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
483
83
|
const parsed = require_tree.PredicateNodeSchema.safeParse(resolution.node);
|
|
@@ -494,10 +94,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
494
94
|
case "reference": {
|
|
495
95
|
const resolution = await resolvers.resolveValue(node.key, context);
|
|
496
96
|
if (!resolution.found) return require_evaluation.indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
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");
|
|
500
|
-
}
|
|
97
|
+
const unitError = require_evaluator_operations.checkReferenceUnit(node.unit, resolution.value);
|
|
98
|
+
if (unitError !== void 0) return unitError;
|
|
501
99
|
return require_evaluation.definite(resolution.value);
|
|
502
100
|
}
|
|
503
101
|
case "accumulator":
|
|
@@ -510,11 +108,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
510
108
|
if (result.status === "indeterminate") return result;
|
|
511
109
|
args.push(result.value);
|
|
512
110
|
}
|
|
513
|
-
|
|
514
|
-
if (fn === void 0) return require_evaluation.indeterminate("wrong-type", `no function registered under the name '${node.fn}'`);
|
|
515
|
-
const outcome = fn(args);
|
|
516
|
-
if ("domainError" in outcome) return require_evaluation.indeterminate("domain-error", outcome.domainError);
|
|
517
|
-
return require_evaluation.definite(outcome);
|
|
111
|
+
return require_evaluator_operations.invokeRegisteredFunction(functions, node.fn, args);
|
|
518
112
|
}
|
|
519
113
|
case "numberLiteral": return require_evaluation.definite({
|
|
520
114
|
kind: "number",
|
|
@@ -550,12 +144,12 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
550
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)]);
|
|
551
145
|
if (left.status === "indeterminate") return left;
|
|
552
146
|
if (right.status === "indeterminate") return right;
|
|
553
|
-
return applyArithmetic(node.op, left.value, right.value);
|
|
147
|
+
return require_evaluator_operations.applyArithmetic(node.op, left.value, right.value);
|
|
554
148
|
}
|
|
555
149
|
case "negate": {
|
|
556
150
|
const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
557
151
|
if (operand.status === "indeterminate") return operand;
|
|
558
|
-
return applyNegate(operand.value);
|
|
152
|
+
return require_evaluator_operations.applyNegate(operand.value);
|
|
559
153
|
}
|
|
560
154
|
case "lookup": {
|
|
561
155
|
const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
|
|
@@ -593,8 +187,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
593
187
|
return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
594
188
|
}
|
|
595
189
|
case "fold": {
|
|
596
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
597
|
-
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);
|
|
598
192
|
if (filterIndeterminateReason !== void 0) return {
|
|
599
193
|
status: "indeterminate",
|
|
600
194
|
reason: filterIndeterminateReason
|
|
@@ -621,7 +215,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
621
215
|
runningExtremum = itemResult.value;
|
|
622
216
|
continue;
|
|
623
217
|
}
|
|
624
|
-
const comparison = compareValues(dominatesOp, itemResult.value, runningExtremum);
|
|
218
|
+
const comparison = require_evaluator_operations.compareValues(dominatesOp, itemResult.value, runningExtremum);
|
|
625
219
|
if (comparison.status === "indeterminate") return comparison;
|
|
626
220
|
if (comparison.value) runningExtremum = itemResult.value;
|
|
627
221
|
}
|
|
@@ -638,7 +232,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
638
232
|
if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
639
233
|
const keyString = JSON.stringify(node.key);
|
|
640
234
|
if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
|
|
641
|
-
if (treeReferenceDepth >=
|
|
235
|
+
if (treeReferenceDepth >= 100) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
642
236
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
643
237
|
if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
644
238
|
const parsed = require_tree.ExpressionNodeSchema.safeParse(resolution.node);
|
|
@@ -648,17 +242,6 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
648
242
|
default: throw new Error("unreachable expression node kind");
|
|
649
243
|
}
|
|
650
244
|
}
|
|
651
|
-
/**
|
|
652
|
-
* 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. `maxNodes` and `maxNestingDepth` configure that same pair's own `EvaluationBudget` (see its doc comment above), created fresh for every top-level `evaluatePredicate`/`evaluateValue` invocation so budgets never leak between unrelated calls. The bare module-level `evaluatePredicate`/`evaluateValue` exports below are `createEvaluator({})`'s output, so both caps default to `DEFAULT_MAX_EVALUATION_NODES`/`DEFAULT_MAX_NESTING_DEPTH` for every caller that does not explicitly configure them.
|
|
653
|
-
*/
|
|
654
|
-
function createEvaluator({ functions = require_functions.emptyFunctionRegistry, maxNodes = DEFAULT_MAX_EVALUATION_NODES, maxNestingDepth = DEFAULT_MAX_NESTING_DEPTH }) {
|
|
655
|
-
return {
|
|
656
|
-
evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0),
|
|
657
|
-
evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
const { evaluatePredicate, evaluateValue } = createEvaluator({});
|
|
661
245
|
//#endregion
|
|
662
|
-
exports.
|
|
663
|
-
exports.
|
|
664
|
-
exports.evaluateValue = evaluateValue;
|
|
246
|
+
exports.evaluatePredicateInternal = evaluatePredicateInternal;
|
|
247
|
+
exports.evaluateValueInternal = evaluateValueInternal;
|
package/dist/evaluator.d.cts
CHANGED
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import { ComputedValue } from "./computed-value.cjs";
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
2
|
import { ExpressionNode, PredicateNode } from "./tree.cjs";
|
|
3
3
|
import { Evaluation } from "./evaluation.cjs";
|
|
4
|
+
import { EvaluationBudget } from "./evaluator-budget.cjs";
|
|
4
5
|
import { FunctionRegistry } from "./functions.cjs";
|
|
5
6
|
import { EvaluationContext, Resolvers } from "./resolvers.cjs";
|
|
6
7
|
//#region src/evaluator.d.ts
|
|
7
8
|
/**
|
|
8
|
-
*
|
|
9
|
+
* `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`.
|
|
9
10
|
*/
|
|
10
|
-
declare function
|
|
11
|
-
|
|
12
|
-
/** Caps the total number of predicate/expression nodes a single `evaluatePredicate`/`evaluateValue` call may visit -- see `createEvaluationBudget`. Defaults to `DEFAULT_MAX_EVALUATION_NODES`. */
|
|
13
|
-
maxNodes?: number;
|
|
14
|
-
/** Caps ordinary recursive-descent nesting depth, independent of `MAX_TREE_REFERENCE_DEPTH`'s own `treeReference` chain-depth cap -- see `createEvaluationBudget`. Defaults to `DEFAULT_MAX_NESTING_DEPTH`. */
|
|
15
|
-
maxNestingDepth?: number;
|
|
16
|
-
}): {
|
|
17
|
-
evaluatePredicate: (node: PredicateNode, context: EvaluationContext, resolvers: Readonly<Resolvers>) => Promise<Evaluation<boolean>>;
|
|
18
|
-
evaluateValue: (node: ExpressionNode, context: EvaluationContext, resolvers: Readonly<Resolvers>) => Promise<Evaluation<ComputedValue>>;
|
|
19
|
-
};
|
|
20
|
-
declare const evaluatePredicate: (node: PredicateNode, context: EvaluationContext, resolvers: Readonly<Resolvers>) => Promise<Evaluation<boolean>>, evaluateValue: (node: ExpressionNode, context: EvaluationContext, resolvers: Readonly<Resolvers>) => Promise<Evaluation<ComputedValue>>;
|
|
11
|
+
declare function evaluatePredicateInternal(node: PredicateNode, context: EvaluationContext, resolvers: Readonly<Resolvers>, accumulator: ComputedValue | undefined, functions: Readonly<FunctionRegistry>, visitedTreeKeys: ReadonlySet<string>, treeReferenceDepth: number, budget: Readonly<EvaluationBudget>, nestingDepth: number): Promise<Evaluation<boolean>>;
|
|
12
|
+
declare function evaluateValueInternal(node: ExpressionNode, context: EvaluationContext, resolvers: Readonly<Resolvers>, accumulator: ComputedValue | undefined, functions: Readonly<FunctionRegistry>, visitedTreeKeys: ReadonlySet<string>, treeReferenceDepth: number, budget: Readonly<EvaluationBudget>, nestingDepth: number): Promise<Evaluation<ComputedValue>>;
|
|
21
13
|
//#endregion
|
|
22
|
-
export {
|
|
14
|
+
export { evaluatePredicateInternal, evaluateValueInternal };
|