trilean 1.6.0 → 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.
- 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 +2 -2
- package/schemas/trilean.schema.json +1 -1
package/dist/evaluator.d.ts
CHANGED
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import { ComputedValue } from "./computed-value.js";
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.js";
|
|
2
2
|
import { ExpressionNode, PredicateNode } from "./tree.js";
|
|
3
3
|
import { Evaluation } from "./evaluation.js";
|
|
4
|
+
import { EvaluationBudget } from "./evaluator-budget.js";
|
|
4
5
|
import { FunctionRegistry } from "./functions.js";
|
|
5
6
|
import { EvaluationContext, Resolvers } from "./resolvers.js";
|
|
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 };
|
package/dist/evaluator.js
CHANGED
|
@@ -1,413 +1,13 @@
|
|
|
1
1
|
import { complexFromPolar } from "./complex.js";
|
|
2
|
-
import { combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
|
|
3
2
|
import { definite, firstIndeterminate, indeterminate } from "./evaluation.js";
|
|
4
|
-
import
|
|
3
|
+
import "./evaluator-budget.js";
|
|
4
|
+
import { firstFilterIndeterminate, resolveParticipatingItems } from "./evaluator-collection.js";
|
|
5
|
+
import { applyArithmetic, applyNegate, checkReferenceUnit, combineAnd, combineOr, compareText, compareValues, computeMembershipMatch, invokeRegisteredFunction } from "./evaluator-operations.js";
|
|
5
6
|
import { ExpressionNodeSchema, PredicateNodeSchema } from "./tree.js";
|
|
6
|
-
import { RegexParseError, compilePattern } from "trilean-regex";
|
|
7
7
|
//#region src/evaluator.ts
|
|
8
8
|
/**
|
|
9
|
-
* `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.
|
|
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`.
|
|
10
10
|
*/
|
|
11
|
-
/** 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`. */
|
|
12
|
-
function combineAnd(left, right) {
|
|
13
|
-
if (left.status === "definite" && !left.value) return definite(false);
|
|
14
|
-
if (right.status === "definite" && !right.value) return definite(false);
|
|
15
|
-
const reason = firstIndeterminate(left, right);
|
|
16
|
-
if (reason !== void 0) return {
|
|
17
|
-
status: "indeterminate",
|
|
18
|
-
reason
|
|
19
|
-
};
|
|
20
|
-
return definite(true);
|
|
21
|
-
}
|
|
22
|
-
/** The three-valued OR table: mirror image of `combineAnd`, with `true` absorbing. */
|
|
23
|
-
function combineOr(left, right) {
|
|
24
|
-
if (left.status === "definite" && left.value) return definite(true);
|
|
25
|
-
if (right.status === "definite" && right.value) return definite(true);
|
|
26
|
-
const reason = firstIndeterminate(left, right);
|
|
27
|
-
if (reason !== void 0) return {
|
|
28
|
-
status: "indeterminate",
|
|
29
|
-
reason
|
|
30
|
-
};
|
|
31
|
-
return definite(false);
|
|
32
|
-
}
|
|
33
|
-
function applyComparisonOperator(op, left, right) {
|
|
34
|
-
switch (op) {
|
|
35
|
-
case "gt": return left > right;
|
|
36
|
-
case "gte": return left >= right;
|
|
37
|
-
case "lt": return left < right;
|
|
38
|
-
case "lte": return left <= right;
|
|
39
|
-
case "eq": return left === right;
|
|
40
|
-
case "neq": return left !== right;
|
|
41
|
-
default: throw new Error("unreachable comparison operator");
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
const millisecondsPerDurationUnit = {
|
|
45
|
-
ms: 1,
|
|
46
|
-
s: 1e3,
|
|
47
|
-
min: 6e4,
|
|
48
|
-
h: 36e5,
|
|
49
|
-
d: 864e5
|
|
50
|
-
};
|
|
51
|
-
/** 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. */
|
|
52
|
-
function toMilliseconds(value, unit) {
|
|
53
|
-
return value * millisecondsPerDurationUnit[unit];
|
|
54
|
-
}
|
|
55
|
-
/** `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. */
|
|
56
|
-
function toEpochMilliseconds(value) {
|
|
57
|
-
const epochMilliseconds = Date.parse(value);
|
|
58
|
-
return Number.isNaN(epochMilliseconds) ? void 0 : epochMilliseconds;
|
|
59
|
-
}
|
|
60
|
-
function unparseableInstant(value) {
|
|
61
|
-
return indeterminate("wrong-type", `'${value}' is not a parseable ISO-8601 timestamp`);
|
|
62
|
-
}
|
|
63
|
-
/** 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. */
|
|
64
|
-
function instantFromEpochMilliseconds(epochMilliseconds) {
|
|
65
|
-
const shifted = new Date(epochMilliseconds);
|
|
66
|
-
if (Number.isNaN(shifted.getTime())) return indeterminate("domain-error", "the resulting instant falls outside the representable timestamp range");
|
|
67
|
-
return definite({
|
|
68
|
-
kind: "instant",
|
|
69
|
-
value: shifted.toISOString()
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
/** `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`. */
|
|
73
|
-
function compareValues(op, left, right) {
|
|
74
|
-
switch (left.kind) {
|
|
75
|
-
case "number":
|
|
76
|
-
if (right.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${right.kind}' value`);
|
|
77
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units");
|
|
78
|
-
return definite(applyComparisonOperator(op, left.value, right.value));
|
|
79
|
-
case "text": return indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
|
|
80
|
-
case "boolean":
|
|
81
|
-
if (right.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
|
|
82
|
-
if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
|
|
83
|
-
return definite(op === "eq" ? left.value === right.value : left.value !== right.value);
|
|
84
|
-
case "instant": {
|
|
85
|
-
if (right.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
|
|
86
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
87
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
88
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
89
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
90
|
-
return definite(applyComparisonOperator(op, leftEpoch, rightEpoch));
|
|
91
|
-
}
|
|
92
|
-
case "duration":
|
|
93
|
-
if (right.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
|
|
94
|
-
return definite(applyComparisonOperator(op, toMilliseconds(left.value, left.unit), toMilliseconds(right.value, right.unit)));
|
|
95
|
-
case "complex":
|
|
96
|
-
if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `ordering operator '${op}' is not defined for complex values; the complex plane has no total order`);
|
|
97
|
-
if (right.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
|
|
98
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units");
|
|
99
|
-
return definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
|
|
100
|
-
default: throw new Error("unreachable computed-value kind");
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/** `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. */
|
|
104
|
-
function compareText(op, left, right) {
|
|
105
|
-
if (left.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
|
|
106
|
-
if (right.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the right operand is '${right.kind}'`);
|
|
107
|
-
switch (op) {
|
|
108
|
-
case "equals": return definite(left.value === right.value);
|
|
109
|
-
case "notEquals": return definite(left.value !== right.value);
|
|
110
|
-
case "matches":
|
|
111
|
-
case "notMatches": {
|
|
112
|
-
let pattern;
|
|
113
|
-
try {
|
|
114
|
-
pattern = new RegExp(right.value);
|
|
115
|
-
} catch {
|
|
116
|
-
return indeterminate("wrong-type", `'${right.value}' is not a valid regular expression pattern`);
|
|
117
|
-
}
|
|
118
|
-
const isMatch = pattern.test(left.value);
|
|
119
|
-
return definite(op === "matches" ? isMatch : !isMatch);
|
|
120
|
-
}
|
|
121
|
-
case "portableMatches":
|
|
122
|
-
case "portableNotMatches": {
|
|
123
|
-
let compiled;
|
|
124
|
-
try {
|
|
125
|
-
compiled = compilePattern(right.value);
|
|
126
|
-
} catch (error) {
|
|
127
|
-
const reason = error instanceof RegexParseError ? error.message : String(error);
|
|
128
|
-
return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
|
|
129
|
-
}
|
|
130
|
-
const isMatch = compiled.test(left.value);
|
|
131
|
-
return definite(op === "portableMatches" ? isMatch : !isMatch);
|
|
132
|
-
}
|
|
133
|
-
default: throw new Error("unreachable text comparison operator");
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
/** `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. */
|
|
137
|
-
function computeMembershipMatch(operand, candidate) {
|
|
138
|
-
switch (operand.kind) {
|
|
139
|
-
case "number":
|
|
140
|
-
if (candidate.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${candidate.kind}' value for membership`);
|
|
141
|
-
if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units for membership");
|
|
142
|
-
return definite(operand.value === candidate.value);
|
|
143
|
-
case "text":
|
|
144
|
-
if (candidate.kind !== "text") return indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
|
|
145
|
-
return definite(operand.value === candidate.value);
|
|
146
|
-
case "boolean":
|
|
147
|
-
if (candidate.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
|
|
148
|
-
return definite(operand.value === candidate.value);
|
|
149
|
-
case "instant": {
|
|
150
|
-
if (candidate.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
|
|
151
|
-
const operandEpoch = toEpochMilliseconds(operand.value);
|
|
152
|
-
if (operandEpoch === void 0) return unparseableInstant(operand.value);
|
|
153
|
-
const candidateEpoch = toEpochMilliseconds(candidate.value);
|
|
154
|
-
if (candidateEpoch === void 0) return unparseableInstant(candidate.value);
|
|
155
|
-
return definite(operandEpoch === candidateEpoch);
|
|
156
|
-
}
|
|
157
|
-
case "duration":
|
|
158
|
-
if (candidate.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
|
|
159
|
-
return definite(toMilliseconds(operand.value, operand.unit) === toMilliseconds(candidate.value, candidate.unit));
|
|
160
|
-
case "complex":
|
|
161
|
-
if (candidate.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
|
|
162
|
-
if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
|
|
163
|
-
return definite(operand.re === candidate.re && operand.im === candidate.im);
|
|
164
|
-
default: throw new Error("unreachable computed-value kind");
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
/** `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. */
|
|
168
|
-
function isDimensionless(unit) {
|
|
169
|
-
return unitsEqual(unit, void 0);
|
|
170
|
-
}
|
|
171
|
-
/** `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. */
|
|
172
|
-
function applyNegate(operand) {
|
|
173
|
-
switch (operand.kind) {
|
|
174
|
-
case "number": return definite({
|
|
175
|
-
kind: "number",
|
|
176
|
-
value: -operand.value,
|
|
177
|
-
unit: operand.unit
|
|
178
|
-
});
|
|
179
|
-
case "duration": return definite({
|
|
180
|
-
kind: "duration",
|
|
181
|
-
value: -operand.value,
|
|
182
|
-
unit: operand.unit
|
|
183
|
-
});
|
|
184
|
-
case "complex": return definite({
|
|
185
|
-
kind: "complex",
|
|
186
|
-
re: -operand.re,
|
|
187
|
-
im: -operand.im,
|
|
188
|
-
unit: operand.unit
|
|
189
|
-
});
|
|
190
|
-
case "text":
|
|
191
|
-
case "instant":
|
|
192
|
-
case "boolean": return indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
|
|
193
|
-
default: throw new Error("unreachable computed-value kind");
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
function applyArithmeticOnNumbers(op, left, right) {
|
|
197
|
-
switch (op) {
|
|
198
|
-
case "add":
|
|
199
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add numbers with incompatible units");
|
|
200
|
-
return definite({
|
|
201
|
-
kind: "number",
|
|
202
|
-
value: left.value + right.value,
|
|
203
|
-
unit: left.unit
|
|
204
|
-
});
|
|
205
|
-
case "subtract":
|
|
206
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract numbers with incompatible units");
|
|
207
|
-
return definite({
|
|
208
|
-
kind: "number",
|
|
209
|
-
value: left.value - right.value,
|
|
210
|
-
unit: left.unit
|
|
211
|
-
});
|
|
212
|
-
case "multiply": return definite({
|
|
213
|
-
kind: "number",
|
|
214
|
-
value: left.value * right.value,
|
|
215
|
-
unit: combineUnitsForMultiply(left.unit, right.unit)
|
|
216
|
-
});
|
|
217
|
-
case "divide":
|
|
218
|
-
if (right.value === 0) return indeterminate("domain-error", "division by zero");
|
|
219
|
-
return definite({
|
|
220
|
-
kind: "number",
|
|
221
|
-
value: left.value / right.value,
|
|
222
|
-
unit: combineUnitsForDivide(left.unit, right.unit)
|
|
223
|
-
});
|
|
224
|
-
case "power":
|
|
225
|
-
if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
|
|
226
|
-
if (left.value < 0 && !Number.isInteger(right.value)) return indeterminate("domain-error", "a negative base raised to a non-integer power is not a real number");
|
|
227
|
-
if (left.value === 0 && right.value < 0) return indeterminate("domain-error", "zero raised to a negative power is a division by zero");
|
|
228
|
-
return definite({
|
|
229
|
-
kind: "number",
|
|
230
|
-
value: left.value ** right.value
|
|
231
|
-
});
|
|
232
|
-
case "modulo":
|
|
233
|
-
if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return indeterminate("wrong-type", "'modulo' requires dimensionless operands");
|
|
234
|
-
if (right.value === 0) return indeterminate("domain-error", "modulo by zero");
|
|
235
|
-
return definite({
|
|
236
|
-
kind: "number",
|
|
237
|
-
value: left.value % right.value
|
|
238
|
-
});
|
|
239
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
/** 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. */
|
|
243
|
-
function applyArithmeticOnDurations(op, left, right) {
|
|
244
|
-
switch (op) {
|
|
245
|
-
case "add": return definite({
|
|
246
|
-
kind: "duration",
|
|
247
|
-
value: toMilliseconds(left.value, left.unit) + toMilliseconds(right.value, right.unit),
|
|
248
|
-
unit: "ms"
|
|
249
|
-
});
|
|
250
|
-
case "subtract": return definite({
|
|
251
|
-
kind: "duration",
|
|
252
|
-
value: toMilliseconds(left.value, left.unit) - toMilliseconds(right.value, right.unit),
|
|
253
|
-
unit: "ms"
|
|
254
|
-
});
|
|
255
|
-
case "multiply":
|
|
256
|
-
case "divide":
|
|
257
|
-
case "power":
|
|
258
|
-
case "modulo": return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between two 'duration' values`);
|
|
259
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
/** 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. */
|
|
263
|
-
function toComplexValue(value) {
|
|
264
|
-
if (value.kind === "complex") return value;
|
|
265
|
-
return {
|
|
266
|
-
kind: "complex",
|
|
267
|
-
re: value.value,
|
|
268
|
-
im: 0,
|
|
269
|
-
unit: value.unit
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
/** 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. */
|
|
273
|
-
function multiplyComplexValues(left, right) {
|
|
274
|
-
return {
|
|
275
|
-
kind: "complex",
|
|
276
|
-
re: left.re * right.re - left.im * right.im,
|
|
277
|
-
im: left.re * right.im + left.im * right.re,
|
|
278
|
-
unit: combineUnitsForMultiply(left.unit, right.unit)
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
/** 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. */
|
|
282
|
-
function applyArithmeticOnComplex(op, left, right) {
|
|
283
|
-
switch (op) {
|
|
284
|
-
case "add":
|
|
285
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add complex values with incompatible units");
|
|
286
|
-
return definite({
|
|
287
|
-
kind: "complex",
|
|
288
|
-
re: left.re + right.re,
|
|
289
|
-
im: left.im + right.im,
|
|
290
|
-
unit: left.unit
|
|
291
|
-
});
|
|
292
|
-
case "subtract":
|
|
293
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
|
|
294
|
-
return definite({
|
|
295
|
-
kind: "complex",
|
|
296
|
-
re: left.re - right.re,
|
|
297
|
-
im: left.im - right.im,
|
|
298
|
-
unit: left.unit
|
|
299
|
-
});
|
|
300
|
-
case "multiply": return definite(multiplyComplexValues(left, right));
|
|
301
|
-
case "divide": {
|
|
302
|
-
const divisorSquaredMagnitude = right.re * right.re + right.im * right.im;
|
|
303
|
-
if (divisorSquaredMagnitude === 0) return indeterminate("domain-error", "division by zero");
|
|
304
|
-
return definite({
|
|
305
|
-
kind: "complex",
|
|
306
|
-
re: (left.re * right.re + left.im * right.im) / divisorSquaredMagnitude,
|
|
307
|
-
im: (left.im * right.re - left.re * right.im) / divisorSquaredMagnitude,
|
|
308
|
-
unit: combineUnitsForDivide(left.unit, right.unit)
|
|
309
|
-
});
|
|
310
|
-
}
|
|
311
|
-
case "modulo": return indeterminate("domain-error", "'modulo' is undefined for complex values");
|
|
312
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
/** `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). */
|
|
316
|
-
function applyComplexPower(base, exponent) {
|
|
317
|
-
if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
|
|
318
|
-
if (!isDimensionless(base.unit) || !isDimensionless(exponent.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
|
|
319
|
-
const complexUnit = {
|
|
320
|
-
kind: "complex",
|
|
321
|
-
re: 1,
|
|
322
|
-
im: 0,
|
|
323
|
-
unit: {}
|
|
324
|
-
};
|
|
325
|
-
const complexBase = toComplexValue(base);
|
|
326
|
-
let repeatedProduct = complexUnit;
|
|
327
|
-
for (let applied = 0; applied < Math.abs(exponent.value); applied += 1) repeatedProduct = multiplyComplexValues(repeatedProduct, complexBase);
|
|
328
|
-
if (exponent.value >= 0) return definite(repeatedProduct);
|
|
329
|
-
return applyArithmeticOnComplex("divide", complexUnit, repeatedProduct);
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* 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.
|
|
333
|
-
*/
|
|
334
|
-
function applyArithmetic(op, left, right) {
|
|
335
|
-
if (left.kind === "instant" && right.kind === "instant" && op === "subtract") {
|
|
336
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
337
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
338
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
339
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
340
|
-
return definite({
|
|
341
|
-
kind: "duration",
|
|
342
|
-
value: leftEpoch - rightEpoch,
|
|
343
|
-
unit: "ms"
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
if (left.kind === "instant" && right.kind === "duration" && op === "add") {
|
|
347
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
348
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
349
|
-
return instantFromEpochMilliseconds(leftEpoch + toMilliseconds(right.value, right.unit));
|
|
350
|
-
}
|
|
351
|
-
if (left.kind === "duration" && right.kind === "instant" && op === "add") {
|
|
352
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
353
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
354
|
-
return instantFromEpochMilliseconds(rightEpoch + toMilliseconds(left.value, left.unit));
|
|
355
|
-
}
|
|
356
|
-
if (left.kind === "instant" || right.kind === "instant") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
|
|
357
|
-
if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
|
|
358
|
-
if (left.kind === "duration" || right.kind === "duration") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
|
|
359
|
-
if (left.kind !== "number" && left.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
|
|
360
|
-
if (right.kind !== "number" && right.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
|
|
361
|
-
if (left.kind === "complex" || right.kind === "complex") {
|
|
362
|
-
if (op === "power") return applyComplexPower(left, right);
|
|
363
|
-
return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
|
|
364
|
-
}
|
|
365
|
-
return applyArithmeticOnNumbers(op, left, right);
|
|
366
|
-
}
|
|
367
|
-
/** 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. */
|
|
368
|
-
const MAX_TREE_REFERENCE_DEPTH = 100;
|
|
369
|
-
/** 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. */
|
|
370
|
-
const DEFAULT_MAX_EVALUATION_NODES = 1e4;
|
|
371
|
-
/** 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. */
|
|
372
|
-
const DEFAULT_MAX_NESTING_DEPTH = 500;
|
|
373
|
-
/** 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. */
|
|
374
|
-
function createEvaluationBudget(maxNodes, maxNestingDepth) {
|
|
375
|
-
/** 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. */
|
|
376
|
-
let nodesVisited = 0;
|
|
377
|
-
return { checkNode(nestingDepth) {
|
|
378
|
-
nodesVisited += 1;
|
|
379
|
-
if (nodesVisited > maxNodes) return indeterminate("domain-error", `evaluation exceeded the maximum of ${maxNodes.toString()} nodes visited in a single call (resource exhausted)`);
|
|
380
|
-
if (nestingDepth >= maxNestingDepth) return indeterminate("domain-error", `evaluation nesting depth exceeds the maximum of ${maxNestingDepth.toString()} (resource exhausted)`);
|
|
381
|
-
} };
|
|
382
|
-
}
|
|
383
|
-
/**
|
|
384
|
-
* 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.
|
|
385
|
-
*/
|
|
386
|
-
async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
387
|
-
const candidates = await resolvers.resolveCollection(collection, context);
|
|
388
|
-
return Promise.all(candidates.map(async (item) => {
|
|
389
|
-
if (filter === void 0) return {
|
|
390
|
-
item,
|
|
391
|
-
filterOutcome: "include"
|
|
392
|
-
};
|
|
393
|
-
const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
394
|
-
if (filterResult.status === "indeterminate") return {
|
|
395
|
-
item,
|
|
396
|
-
filterOutcome: filterResult
|
|
397
|
-
};
|
|
398
|
-
return {
|
|
399
|
-
item,
|
|
400
|
-
filterOutcome: filterResult.value ? "include" : "exclude"
|
|
401
|
-
};
|
|
402
|
-
}));
|
|
403
|
-
}
|
|
404
|
-
/** 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. */
|
|
405
|
-
function firstFilterIndeterminate(participating) {
|
|
406
|
-
for (const { filterOutcome } of participating) {
|
|
407
|
-
if (filterOutcome === "include" || filterOutcome === "exclude") continue;
|
|
408
|
-
if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
11
|
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
412
12
|
const budgetExceeded = budget.checkNode(nestingDepth);
|
|
413
13
|
if (budgetExceeded !== void 0) return budgetExceeded;
|
|
@@ -462,7 +62,7 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
462
62
|
}
|
|
463
63
|
case "some":
|
|
464
64
|
case "every": {
|
|
465
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
65
|
+
const participating = await resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
466
66
|
const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
|
|
467
67
|
if (filterOutcome === "exclude") return void 0;
|
|
468
68
|
if (filterOutcome !== "include") return filterOutcome;
|
|
@@ -476,7 +76,7 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
476
76
|
if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
477
77
|
const keyString = JSON.stringify(node.key);
|
|
478
78
|
if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
|
|
479
|
-
if (treeReferenceDepth >=
|
|
79
|
+
if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
480
80
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
481
81
|
if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
482
82
|
const parsed = PredicateNodeSchema.safeParse(resolution.node);
|
|
@@ -493,10 +93,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
493
93
|
case "reference": {
|
|
494
94
|
const resolution = await resolvers.resolveValue(node.key, context);
|
|
495
95
|
if (!resolution.found) return indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
if (!unitsEqual(node.unit, resolution.value.unit)) return indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
|
|
499
|
-
}
|
|
96
|
+
const unitError = checkReferenceUnit(node.unit, resolution.value);
|
|
97
|
+
if (unitError !== void 0) return unitError;
|
|
500
98
|
return definite(resolution.value);
|
|
501
99
|
}
|
|
502
100
|
case "accumulator":
|
|
@@ -509,11 +107,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
509
107
|
if (result.status === "indeterminate") return result;
|
|
510
108
|
args.push(result.value);
|
|
511
109
|
}
|
|
512
|
-
|
|
513
|
-
if (fn === void 0) return indeterminate("wrong-type", `no function registered under the name '${node.fn}'`);
|
|
514
|
-
const outcome = fn(args);
|
|
515
|
-
if ("domainError" in outcome) return indeterminate("domain-error", outcome.domainError);
|
|
516
|
-
return definite(outcome);
|
|
110
|
+
return invokeRegisteredFunction(functions, node.fn, args);
|
|
517
111
|
}
|
|
518
112
|
case "numberLiteral": return definite({
|
|
519
113
|
kind: "number",
|
|
@@ -592,7 +186,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
592
186
|
return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
593
187
|
}
|
|
594
188
|
case "fold": {
|
|
595
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
189
|
+
const participating = await resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
596
190
|
const filterIndeterminateReason = firstFilterIndeterminate(participating);
|
|
597
191
|
if (filterIndeterminateReason !== void 0) return {
|
|
598
192
|
status: "indeterminate",
|
|
@@ -637,7 +231,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
637
231
|
if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
638
232
|
const keyString = JSON.stringify(node.key);
|
|
639
233
|
if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
|
|
640
|
-
if (treeReferenceDepth >=
|
|
234
|
+
if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
641
235
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
642
236
|
if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
643
237
|
const parsed = ExpressionNodeSchema.safeParse(resolution.node);
|
|
@@ -647,15 +241,5 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
647
241
|
default: throw new Error("unreachable expression node kind");
|
|
648
242
|
}
|
|
649
243
|
}
|
|
650
|
-
/**
|
|
651
|
-
* 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.
|
|
652
|
-
*/
|
|
653
|
-
function createEvaluator({ functions = emptyFunctionRegistry, maxNodes = DEFAULT_MAX_EVALUATION_NODES, maxNestingDepth = DEFAULT_MAX_NESTING_DEPTH }) {
|
|
654
|
-
return {
|
|
655
|
-
evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0),
|
|
656
|
-
evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
|
-
const { evaluatePredicate, evaluateValue } = createEvaluator({});
|
|
660
244
|
//#endregion
|
|
661
|
-
export {
|
|
245
|
+
export { evaluatePredicateInternal, evaluateValueInternal };
|
package/dist/functions.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ComputedValue } from "./computed-value.cjs";
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
2
|
//#region src/functions.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* Named functions available to a `call` expression node, supplied once at evaluator construction time (see `createEvaluator` in evaluator.ts) rather than per evaluation call. A function reports a domain violation (e.g. `squareRoot` given a negative number) by returning a `domainError` rather than throwing -- this keeps `call` inside the same three-outcome model as every other node kind.
|
|
4
|
+
* Named functions available to a `call` expression node, supplied once at evaluator construction time (see `createEvaluator` in evaluator-factory.ts) rather than per evaluation call. A function reports a domain violation (e.g. `squareRoot` given a negative number) by returning a `domainError` rather than throwing -- this keeps `call` inside the same three-outcome model as every other node kind.
|
|
5
5
|
*/
|
|
6
6
|
type FunctionRegistry = Record<string, (args: readonly ComputedValue[]) => ComputedValue | {
|
|
7
7
|
domainError: string;
|
package/dist/functions.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ComputedValue } from "./computed-value.js";
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.js";
|
|
2
2
|
//#region src/functions.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* Named functions available to a `call` expression node, supplied once at evaluator construction time (see `createEvaluator` in evaluator.ts) rather than per evaluation call. A function reports a domain violation (e.g. `squareRoot` given a negative number) by returning a `domainError` rather than throwing -- this keeps `call` inside the same three-outcome model as every other node kind.
|
|
4
|
+
* Named functions available to a `call` expression node, supplied once at evaluator construction time (see `createEvaluator` in evaluator-factory.ts) rather than per evaluation call. A function reports a domain violation (e.g. `squareRoot` given a negative number) by returning a `domainError` rather than throwing -- this keeps `call` inside the same three-outcome model as every other node kind.
|
|
5
5
|
*/
|
|
6
6
|
type FunctionRegistry = Record<string, (args: readonly ComputedValue[]) => ComputedValue | {
|
|
7
7
|
domainError: string;
|
package/dist/index.cjs
CHANGED
|
@@ -6,10 +6,10 @@ const require_derived_connectives = require("./derived-connectives.cjs");
|
|
|
6
6
|
const require_derived_patterns = require("./derived-patterns.cjs");
|
|
7
7
|
const require_derived_values = require("./derived-values.cjs");
|
|
8
8
|
const require_evaluation = require("./evaluation.cjs");
|
|
9
|
-
const require_functions = require("./functions.cjs");
|
|
10
9
|
const require_json_value = require("./json-value.cjs");
|
|
11
10
|
const require_tree = require("./tree.cjs");
|
|
12
|
-
const
|
|
11
|
+
const require_functions = require("./functions.cjs");
|
|
12
|
+
const require_evaluator_factory = require("./evaluator-factory.cjs");
|
|
13
13
|
exports.AccumulatorNodeSchema = require_tree.AccumulatorNodeSchema;
|
|
14
14
|
exports.AllOfNodeSchema = require_tree.AllOfNodeSchema;
|
|
15
15
|
exports.AndNodeSchema = require_tree.AndNodeSchema;
|
|
@@ -63,11 +63,11 @@ exports.complexLiteralFromPolar = require_complex.complexLiteralFromPolar;
|
|
|
63
63
|
exports.complexMagnitude = require_complex.complexMagnitude;
|
|
64
64
|
exports.complexPhase = require_complex.complexPhase;
|
|
65
65
|
exports.count = require_derived_aggregates.count;
|
|
66
|
-
exports.createEvaluator =
|
|
66
|
+
exports.createEvaluator = require_evaluator_factory.createEvaluator;
|
|
67
67
|
exports.definite = require_evaluation.definite;
|
|
68
68
|
exports.emptyFunctionRegistry = require_functions.emptyFunctionRegistry;
|
|
69
|
-
exports.evaluatePredicate =
|
|
70
|
-
exports.evaluateValue =
|
|
69
|
+
exports.evaluatePredicate = require_evaluator_factory.evaluatePredicate;
|
|
70
|
+
exports.evaluateValue = require_evaluator_factory.evaluateValue;
|
|
71
71
|
exports.firstIndeterminate = require_evaluation.firstIndeterminate;
|
|
72
72
|
exports.hierarchicalGlobPattern = require_derived_patterns.hierarchicalGlobPattern;
|
|
73
73
|
exports.iff = require_derived_connectives.iff;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as Unit, c as combineUnitsForMultiply, i as DurationUnitSchema, l as unitsEqual, n as ComputedValueSchema, o as UnitSchema, r as DurationUnit, s as combineUnitsForDivide, t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
2
|
import { n as JsonValueSchema, t as JsonValue } from "./json-value-B1Hjjjri.cjs";
|
|
3
3
|
import { AccumulatorNode, AccumulatorNodeSchema, AllOfNode, AllOfNodeSchema, AndNode, AndNodeSchema, AnyOfNode, AnyOfNodeSchema, ArithmeticNode, ArithmeticNodeSchema, ArithmeticOperator, ArithmeticOperatorSchema, BooleanLiteralNode, BooleanLiteralNodeSchema, CallNode, CallNodeSchema, CompareNode, CompareNodeSchema, ComparisonOperator, ComparisonOperatorSchema, ComplexLiteralNode, ComplexLiteralNodeSchema, ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, ConditionalCase, ConditionalCaseSchema, ConditionalNode, ConditionalNodeSchema, DelegateNode, DelegateNodeSchema, DurationLiteralNode, DurationLiteralNodeSchema, EveryNode, EveryNodeSchema, ExistsNode, ExistsNodeSchema, ExpressionNode, ExpressionNodeSchema, FoldCombiner, FoldCombinerSchema, FoldNode, FoldNodeSchema, HitPolicy, HitPolicySchema, InstantLiteralNode, InstantLiteralNodeSchema, LookupNode, LookupNodeSchema, MemberOfNode, MemberOfNodeSchema, MembershipOperator, MembershipOperatorSchema, NegateNode, NegateNodeSchema, NotNode, NotNodeSchema, NumberLiteralNode, NumberLiteralNodeSchema, OrNode, OrNodeSchema, PredicateNode, PredicateNodeSchema, ReferenceNode, ReferenceNodeSchema, SomeNode, SomeNodeSchema, TextCompareNode, TextCompareNodeSchema, TextComparisonOperator, TextComparisonOperatorSchema, TextLiteralNode, TextLiteralNodeSchema, TreeReferenceNode, TreeReferenceNodeSchema } from "./tree.cjs";
|
|
4
4
|
import { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase } from "./complex.cjs";
|
|
@@ -9,5 +9,5 @@ import { coalesce } from "./derived-values.cjs";
|
|
|
9
9
|
import { Evaluation, IndeterminateReason, IndeterminateReasonSchema, definite, firstIndeterminate, indeterminate } from "./evaluation.cjs";
|
|
10
10
|
import { FunctionRegistry, emptyFunctionRegistry } from "./functions.cjs";
|
|
11
11
|
import { EvaluationContext, Resolution, Resolvers, TreeResolution } from "./resolvers.cjs";
|
|
12
|
-
import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator.cjs";
|
|
12
|
+
import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator-factory.cjs";
|
|
13
13
|
export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type Evaluation, type EvaluationContext, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, hierarchicalGlobPattern, iff, implies, indeterminate, nand, none, nor, not, or, prefixPattern, presenceOf, sum, unitsEqual, wildcardPattern, xor };
|