trilean 1.13.12 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +1 -1
  2. package/dist/evaluator-operations.js +24 -4
  3. package/dist-cli/trilean.mjs +25 -5
  4. package/package.json +10 -20
  5. package/schemas/trilean.schema.json +1 -1
  6. package/dist/builtin-functions.cjs +0 -242
  7. package/dist/builtin-functions.d.cts +0 -13
  8. package/dist/complex-division.cjs +0 -47
  9. package/dist/complex-division.d.cts +0 -23
  10. package/dist/complex.cjs +0 -35
  11. package/dist/complex.d.cts +0 -23
  12. package/dist/computed-value.cjs +0 -80
  13. package/dist/computed-value.d.cts +0 -48
  14. package/dist/derived-aggregates.cjs +0 -73
  15. package/dist/derived-aggregates.d.cts +0 -9
  16. package/dist/derived-connectives.cjs +0 -39
  17. package/dist/derived-connectives.d.cts +0 -14
  18. package/dist/derived-patterns.cjs +0 -93
  19. package/dist/derived-patterns.d.cts +0 -4
  20. package/dist/derived-values.cjs +0 -23
  21. package/dist/derived-values.d.cts +0 -7
  22. package/dist/dist-ed78Tuwe.js +0 -1612
  23. package/dist/dist-ySX7cb5d.cjs +0 -1612
  24. package/dist/duration-order.cjs +0 -83
  25. package/dist/duration-order.d.cts +0 -21
  26. package/dist/evaluate-document.cjs +0 -92
  27. package/dist/evaluate-document.d.cts +0 -42
  28. package/dist/evaluation.cjs +0 -47
  29. package/dist/evaluation.d.cts +0 -29
  30. package/dist/evaluator-budget.cjs +0 -37
  31. package/dist/evaluator-budget.d.cts +0 -22
  32. package/dist/evaluator-collection.cjs +0 -33
  33. package/dist/evaluator-collection.d.cts +0 -21
  34. package/dist/evaluator-compiled.cjs +0 -310
  35. package/dist/evaluator-compiled.d.cts +0 -18
  36. package/dist/evaluator-effect.cjs +0 -57
  37. package/dist/evaluator-effect.d.cts +0 -40
  38. package/dist/evaluator-factory.cjs +0 -31
  39. package/dist/evaluator-factory.d.cts +0 -34
  40. package/dist/evaluator-literals.cjs +0 -42
  41. package/dist/evaluator-literals.d.cts +0 -8
  42. package/dist/evaluator-operations.cjs +0 -440
  43. package/dist/evaluator-operations.d.cts +0 -27
  44. package/dist/evaluator-test-helpers.cjs +0 -15030
  45. package/dist/evaluator-test-helpers.d.cts +0 -10
  46. package/dist/evaluator-test-helpers.d.ts +0 -10
  47. package/dist/evaluator-test-helpers.js +0 -14902
  48. package/dist/evaluator.cjs +0 -228
  49. package/dist/evaluator.d.cts +0 -12
  50. package/dist/functions.cjs +0 -4
  51. package/dist/functions.d.cts +0 -12
  52. package/dist/index.cjs +0 -97
  53. package/dist/index.d.cts +0 -18
  54. package/dist/input-resolvers.cjs +0 -109
  55. package/dist/input-resolvers.d.cts +0 -22
  56. package/dist/integer-power.cjs +0 -19
  57. package/dist/integer-power.d.cts +0 -11
  58. package/dist/json-value.cjs +0 -12
  59. package/dist/json-value.d.cts +0 -8
  60. package/dist/plain-record.cjs +0 -7
  61. package/dist/plain-record.d.cts +0 -2
  62. package/dist/resolvers.cjs +0 -0
  63. package/dist/resolvers.d.cts +0 -54
  64. package/dist/tree.cjs +0 -332
  65. package/dist/tree.d.cts +0 -446
@@ -1,83 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- // src/duration-order.ts
3
- /** How many milliseconds one of each duration unit is. Every unit is a whole multiple of every finer one, which is what lets a value be divided down into a coarser unit by an exact integer. */
4
- const millisecondsPerDurationUnit = {
5
- ms: 1,
6
- s: 1e3,
7
- min: 6e4,
8
- h: 36e5,
9
- d: 864e5
10
- };
11
- const ONE = 1n;
12
- const FRACTION_BITS = 52n;
13
- const FRACTION_MASK = (ONE << FRACTION_BITS) - ONE;
14
- const IMPLICIT_LEADING_BIT = ONE << FRACTION_BITS;
15
- const EXPONENT_FIELD_MASK = 2047n;
16
- const EXPONENT_BIAS_WITH_FRACTION = 1075;
17
- const SUBNORMAL_EXPONENT = -1074;
18
- const scratchValue = /* @__PURE__ */ new Float64Array(1);
19
- const scratchBits = new BigUint64Array(scratchValue.buffer);
20
- /** A finite double as `significand * 2 ** exponent` with an integer significand, exactly, read from its bit pattern. Zero has a zero significand. */
21
- function exactParts(magnitude) {
22
- scratchValue[0] = magnitude;
23
- const bits = scratchBits[0];
24
- if (bits === void 0) throw new Error("a one-element array always has an element zero");
25
- const exponentField = Number(bits >> FRACTION_BITS & EXPONENT_FIELD_MASK);
26
- const fraction = bits & FRACTION_MASK;
27
- if (exponentField === 0) return {
28
- significand: fraction,
29
- exponent: SUBNORMAL_EXPONENT
30
- };
31
- return {
32
- significand: fraction | IMPLICIT_LEADING_BIT,
33
- exponent: exponentField - EXPONENT_BIAS_WITH_FRACTION
34
- };
35
- }
36
- function orderOf(left, right) {
37
- if (left < right) return -1;
38
- return left > right ? 1 : 0;
39
- }
40
- /** The exact order of `left * leftSize` and `right * rightSize` for finite doubles and positive integer sizes, by comparing the products as integers once both are written over a common power of two. */
41
- function exactOrder(left, right) {
42
- const leftSign = Math.sign(left.value);
43
- const rightSign = Math.sign(right.value);
44
- if (leftSign !== rightSign) return leftSign < rightSign ? -1 : 1;
45
- if (leftSign === 0) return 0;
46
- const leftParts = exactParts(Math.abs(left.value));
47
- const rightParts = exactParts(Math.abs(right.value));
48
- let leftProduct = leftParts.significand * BigInt(left.size);
49
- let rightProduct = rightParts.significand * BigInt(right.size);
50
- const shift = leftParts.exponent - rightParts.exponent;
51
- if (shift > 0) leftProduct <<= BigInt(shift);
52
- else rightProduct <<= BigInt(-shift);
53
- return leftSign < 0 ? orderOf(rightProduct, leftProduct) : orderOf(leftProduct, rightProduct);
54
- }
55
- /**
56
- * The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
57
- *
58
- * A value that is not finite is handled first, as numbers are: a NaN is unordered against everything (so every comparison with it is false, and `neq` true), and an infinity is equal to the same infinity and greater or less than anything finite whatever the units, since a unit only scales by a positive amount. The bit-pattern comparison below reads a finite double's exact value and has no meaning for these.
59
- *
60
- * Two finite durations are ordered exactly, with no overflow and no underflow. Both are divided into the coarser of the two units. A division by an exact integer is correctly rounded and rounding is monotone, so it can collapse a difference into equality but never reverse an order: when the two rounded values differ their order is the true order, and that settles almost every comparison without leaving floating point. Dividing can lose the difference, though: two close values round to the same double, and a subnormal rounds to zero. Only when the rounded values are equal is the answer settled exactly, from the doubles' binary expansions, by comparing each value times its unit's size in milliseconds as integers.
61
- *
62
- * Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
63
- */
64
- function compareDurations(left, right) {
65
- if (Number.isNaN(left.value) || Number.isNaN(right.value)) return void 0;
66
- if (!Number.isFinite(left.value) || !Number.isFinite(right.value)) return orderOf(left.value, right.value);
67
- const leftSize = millisecondsPerDurationUnit[left.unit];
68
- const rightSize = millisecondsPerDurationUnit[right.unit];
69
- const sharedSize = Math.max(leftSize, rightSize);
70
- const leftInShared = left.value / (sharedSize / leftSize);
71
- const rightInShared = right.value / (sharedSize / rightSize);
72
- if (leftInShared < rightInShared) return -1;
73
- if (leftInShared > rightInShared) return 1;
74
- return exactOrder({
75
- value: left.value,
76
- size: leftSize
77
- }, {
78
- value: right.value,
79
- size: rightSize
80
- });
81
- }
82
- exports.compareDurations = compareDurations;
83
- exports.millisecondsPerDurationUnit = millisecondsPerDurationUnit;
@@ -1,21 +0,0 @@
1
- import { DurationUnit } from "./computed-value.cjs";
2
- /** How many milliseconds one of each duration unit is. Every unit is a whole multiple of every finer one, which is what lets a value be divided down into a coarser unit by an exact integer. */
3
- export declare const millisecondsPerDurationUnit: Record<DurationUnit, number>;
4
- type Ordering = -1 | 0 | 1;
5
- /**
6
- * The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
7
- *
8
- * A value that is not finite is handled first, as numbers are: a NaN is unordered against everything (so every comparison with it is false, and `neq` true), and an infinity is equal to the same infinity and greater or less than anything finite whatever the units, since a unit only scales by a positive amount. The bit-pattern comparison below reads a finite double's exact value and has no meaning for these.
9
- *
10
- * Two finite durations are ordered exactly, with no overflow and no underflow. Both are divided into the coarser of the two units. A division by an exact integer is correctly rounded and rounding is monotone, so it can collapse a difference into equality but never reverse an order: when the two rounded values differ their order is the true order, and that settles almost every comparison without leaving floating point. Dividing can lose the difference, though: two close values round to the same double, and a subnormal rounds to zero. Only when the rounded values are equal is the answer settled exactly, from the doubles' binary expansions, by comparing each value times its unit's size in milliseconds as integers.
11
- *
12
- * Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
13
- */
14
- export declare function compareDurations(left: Readonly<{
15
- value: number;
16
- unit: DurationUnit;
17
- }>, right: Readonly<{
18
- value: number;
19
- unit: DurationUnit;
20
- }>): Ordering | undefined;
21
- export {};
@@ -1,92 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_computed_value = require("./computed-value.cjs");
3
- const require_evaluator_factory = require("./evaluator-factory.cjs");
4
- const require_builtin_functions = require("./builtin-functions.cjs");
5
- const require_input_resolvers = require("./input-resolvers.cjs");
6
- const require_plain_record = require("./plain-record.cjs");
7
- const require_tree = require("./tree.cjs");
8
- // src/evaluate-document.ts
9
- const predicateKinds = new Set(require_tree.PredicateNodeSchema.options.map((option) => option.shape.kind.value));
10
- /** What a definite expression result that `ComputedValueSchema` refuses is reported as: the only way a result fails it is a non-finite number, which JSON would write as `null`. The evaluator's arithmetic and the built-in functions already keep one from forming, so this is the last check before a value leaves the document boundary, and it fails loudly rather than print a different value from the one computed. */
11
- const NOT_REPRESENTABLE = "(result): the value is not a finite number";
12
- const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; set `as` to \"predicate\" or \"expression\"";
13
- const defaultEvaluator = require_evaluator_factory.createSyncEvaluator({ functions: require_builtin_functions.builtinFunctions });
14
- /** Turns zod's issues into `path: message` lines. A failed union wraps one list of issues per branch, each path relative to the union; the branch the input got furthest into (the deepest path) is the one it was meant to match, so only that branch's issues are reported, under the union's own path. */
15
- function describeIssues(issues, parentPath = []) {
16
- return issues.flatMap((issue) => {
17
- const path = [...parentPath, ...issue.path];
18
- if (issue.code === "invalid_union" && issue.errors.length > 0) return describeIssues(issue.errors.reduce((best, branch) => maxPathLength(branch) > maxPathLength(best) ? branch : best), path);
19
- return [`${path.length === 0 ? "(root)" : path.join(".")}: ${issue.message}`];
20
- });
21
- }
22
- function maxPathLength(issues) {
23
- return Math.max(0, ...issues.map((issue) => issue.path.length));
24
- }
25
- function resolveTreeKind(tree, requested) {
26
- if (requested !== void 0) return requested;
27
- const kind = require_plain_record.isPlainRecord(tree) ? tree.kind : void 0;
28
- if (kind === "treeReference") return "ambiguous";
29
- return typeof kind === "string" && predicateKinds.has(kind) ? "predicate" : "expression";
30
- }
31
- /**
32
- * Validates a tree and its named inputs and evaluates it with the built-in function registry (`builtinFunctions`), the evaluation the `trilean evaluate` command performs. The tree kind is read from the root node's `kind` unless `as` names it. There are three outcomes:
33
- *
34
- * - `evaluated`: an `Evaluation`, definite or indeterminate.
35
- * - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
36
- * - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
37
- *
38
- * The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
39
- *
40
- * Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
41
- */
42
- function evaluateDocument({ tree, inputs, as, maxNodes }) {
43
- const evaluator = maxNodes === void 0 ? defaultEvaluator : require_evaluator_factory.createSyncEvaluator({
44
- functions: require_builtin_functions.builtinFunctions,
45
- maxNodes
46
- });
47
- const parsedInputs = require_input_resolvers.parseInputs(inputs ?? {});
48
- if (!parsedInputs.ok) return {
49
- outcome: "rejected",
50
- reason: "invalid",
51
- issues: parsedInputs.issues
52
- };
53
- const resolvers = require_input_resolvers.createInputResolvers(parsedInputs.inputs, parsedInputs.collections);
54
- const treeKind = resolveTreeKind(tree, as);
55
- if (treeKind === "ambiguous") return {
56
- outcome: "rejected",
57
- reason: "ambiguous-tree-kind",
58
- issues: [AMBIGUOUS_TREE_KIND]
59
- };
60
- if (treeKind === "predicate") {
61
- const parsed = require_tree.PredicateNodeSchema.safeParse(tree);
62
- if (!parsed.success) return {
63
- outcome: "rejected",
64
- reason: "invalid",
65
- issues: describeIssues(parsed.error.issues)
66
- };
67
- const node = parsed.data;
68
- return {
69
- outcome: "evaluated",
70
- treeKind,
71
- evaluation: evaluator.evaluatePredicate(node, void 0, resolvers)
72
- };
73
- }
74
- const parsed = require_tree.ExpressionNodeSchema.safeParse(tree);
75
- if (!parsed.success) return {
76
- outcome: "rejected",
77
- reason: "invalid",
78
- issues: describeIssues(parsed.error.issues)
79
- };
80
- const node = parsed.data;
81
- const evaluation = evaluator.evaluateValue(node, void 0, resolvers);
82
- if (evaluation.status === "definite" && !require_computed_value.ComputedValueSchema.safeParse(evaluation.value).success) return {
83
- outcome: "unrepresentable",
84
- issues: [NOT_REPRESENTABLE]
85
- };
86
- return {
87
- outcome: "evaluated",
88
- treeKind,
89
- evaluation
90
- };
91
- }
92
- exports.evaluateDocument = evaluateDocument;
@@ -1,42 +0,0 @@
1
- import { ComputedValue } from "./computed-value.cjs";
2
- import { Evaluation } from "./evaluation.cjs";
3
- export type TreeKind = "predicate" | "expression";
4
- export interface EvaluateDocumentOptions {
5
- /** The tree as parsed from JSON, not yet validated. */
6
- tree: unknown;
7
- /** Named values and lists of items as parsed from JSON (see `parseInputs`); absent means none. */
8
- inputs?: unknown;
9
- /** Which tree `tree` is. Needed only when its root is a `treeReference`, the one node kind valid in both. */
10
- as?: TreeKind;
11
- /** The most nodes one evaluation may visit before it ends as an indeterminate result (see `createSyncEvaluator`); absent means the evaluator's default. A fold visits its combine expression once per item, so a long list needs a larger budget. The caller supplies a positive integer. */
12
- maxNodes?: number;
13
- }
14
- export type DocumentEvaluation = {
15
- outcome: "evaluated";
16
- treeKind: "predicate";
17
- evaluation: Evaluation<boolean>;
18
- } | {
19
- outcome: "evaluated";
20
- treeKind: "expression";
21
- evaluation: Evaluation<ComputedValue>;
22
- } | {
23
- outcome: "rejected";
24
- /** `ambiguous-tree-kind` is a root `treeReference` evaluated without `as`; every other rejection is `invalid`, a tree or an input that fails validation. */
25
- reason: "invalid" | "ambiguous-tree-kind";
26
- issues: readonly string[];
27
- } | {
28
- outcome: "unrepresentable";
29
- issues: readonly string[];
30
- };
31
- /**
32
- * Validates a tree and its named inputs and evaluates it with the built-in function registry (`builtinFunctions`), the evaluation the `trilean evaluate` command performs. The tree kind is read from the root node's `kind` unless `as` names it. There are three outcomes:
33
- *
34
- * - `evaluated`: an `Evaluation`, definite or indeterminate.
35
- * - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
36
- * - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
37
- *
38
- * The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
39
- *
40
- * Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
41
- */
42
- export declare function evaluateDocument({ tree, inputs, as, maxNodes }: EvaluateDocumentOptions): DocumentEvaluation;
@@ -1,47 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let zod = require("zod");
3
- // src/evaluation.ts
4
- const IndeterminateReasonSchema = zod.z.object({
5
- /** Which of the four reason categories applies. `not-yet-known` is the only one that is not a property of the data: it says a resolver has not been supplied the value yet, so a later evaluation may settle it either way. */
6
- code: zod.z.enum([
7
- "not-found",
8
- "not-yet-known",
9
- "wrong-type",
10
- "domain-error"
11
- ]),
12
- /** A human-readable explanation, for logging and debugging. */
13
- message: zod.z.string()
14
- });
15
- function definite(value) {
16
- return {
17
- status: "definite",
18
- value
19
- };
20
- }
21
- function indeterminate(code, message) {
22
- return {
23
- status: "indeterminate",
24
- reason: {
25
- code,
26
- message
27
- }
28
- };
29
- }
30
- /**
31
- * Implements the tie-break rule from "The evaluation model": when several sub-evaluations could each independently be indeterminate for a different reason, take the first indeterminate reason encountered in the node's own declared operand order, except that a `not-yet-known` reason outranks every other. Entries that are `undefined` (an operand not yet evaluated, or not applicable to this node kind) are skipped rather than treated as indeterminate.
32
- *
33
- * The exception exists because this function is only called where a later outcome can still absorb an indeterminate one (`and`, `or`, `memberOf`, a `unique` conditional). Reporting `not-found` for such a node while another operand is still `not-yet-known` would be wrong: that operand might settle as a definite absorbing value, and the node would then be definite where `exists` had already reported its absence. Preferring `not-yet-known` keeps every non-`not-yet-known` reason a statement that no completion of the unknown values can overturn.
34
- */
35
- function firstIndeterminate(...results) {
36
- let first;
37
- for (const result of results) {
38
- if (result?.status !== "indeterminate") continue;
39
- if (result.reason.code === "not-yet-known") return result.reason;
40
- first ??= result.reason;
41
- }
42
- return first;
43
- }
44
- exports.IndeterminateReasonSchema = IndeterminateReasonSchema;
45
- exports.definite = definite;
46
- exports.firstIndeterminate = firstIndeterminate;
47
- exports.indeterminate = indeterminate;
@@ -1,29 +0,0 @@
1
- import { z } from "zod";
2
- /**
3
- * Every evaluation -- of a predicate node or an expression node -- produces exactly one of two outcomes: a definite result, or an indeterminate result carrying a reason. Never a bare boolean/number, and never a thrown exception for a data-quality problem.
4
- */
5
- export type Evaluation<T> = {
6
- status: "definite";
7
- value: T;
8
- } | {
9
- status: "indeterminate";
10
- reason: IndeterminateReason;
11
- };
12
- export declare const IndeterminateReasonSchema: z.ZodObject<{
13
- code: z.ZodEnum<{
14
- "not-found": "not-found";
15
- "not-yet-known": "not-yet-known";
16
- "wrong-type": "wrong-type";
17
- "domain-error": "domain-error";
18
- }>;
19
- message: z.ZodString;
20
- }, z.core.$strip>;
21
- export type IndeterminateReason = z.infer<typeof IndeterminateReasonSchema>;
22
- export declare function definite<T>(value: T): Evaluation<T>;
23
- export declare function indeterminate(code: IndeterminateReason["code"], message: string): Evaluation<never>;
24
- /**
25
- * Implements the tie-break rule from "The evaluation model": when several sub-evaluations could each independently be indeterminate for a different reason, take the first indeterminate reason encountered in the node's own declared operand order, except that a `not-yet-known` reason outranks every other. Entries that are `undefined` (an operand not yet evaluated, or not applicable to this node kind) are skipped rather than treated as indeterminate.
26
- *
27
- * The exception exists because this function is only called where a later outcome can still absorb an indeterminate one (`and`, `or`, `memberOf`, a `unique` conditional). Reporting `not-found` for such a node while another operand is still `not-yet-known` would be wrong: that operand might settle as a definite absorbing value, and the node would then be definite where `exists` had already reported its absence. Preferring `not-yet-known` keeps every non-`not-yet-known` reason a statement that no completion of the unknown values can overturn.
28
- */
29
- export declare function firstIndeterminate(...results: readonly (Evaluation<unknown> | undefined)[]): IndeterminateReason | undefined;
@@ -1,37 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluation = require("./evaluation.cjs");
3
- // src/evaluator-budget.ts
4
- /** The reason objects that report an exhausted resource limit (node budget, nesting depth, treeReference chain depth). Every such reason has the code `domain-error`, so the code alone cannot tell a limit from any other domain error; membership here is what `exists` reads to let a limit propagate instead of counting as "the value resolved". Identity is preserved by every node that forwards an operand's reason, so a reason keeps its membership as it propagates. */
5
- const exhaustedReasons = /* @__PURE__ */ new WeakSet();
6
- /** The indeterminate result for an exhausted resource limit: code `domain-error` with the limit's own message, recorded so `isResourceExhaustion` recognises it. */
7
- function resourceExhausted(message) {
8
- const result = require_evaluation.indeterminate("domain-error", message);
9
- if (result.status === "indeterminate") exhaustedReasons.add(result.reason);
10
- return result;
11
- }
12
- /** Whether `reason` reports an exhausted resource limit, as opposed to any other indeterminacy. */
13
- function isResourceExhaustion(reason) {
14
- return exhaustedReasons.has(reason);
15
- }
16
- /** 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 in evaluator.ts (`visitedTreeKeys`), which catches an actual repeat immediately and more precisely. */
17
- const MAX_TREE_REFERENCE_DEPTH = 100;
18
- /** 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. */
19
- const DEFAULT_MAX_EVALUATION_NODES = 1e4;
20
- /** 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. */
21
- const DEFAULT_MAX_NESTING_DEPTH = 500;
22
- /** 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. */
23
- function createEvaluationBudget(maxNodes, maxNestingDepth) {
24
- /** 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. */
25
- let nodesVisited = 0;
26
- return { checkNode(nestingDepth) {
27
- nodesVisited += 1;
28
- if (nodesVisited > maxNodes) return resourceExhausted(`evaluation exceeded the maximum of ${maxNodes.toString()} nodes visited in a single call (resource exhausted)`);
29
- if (nestingDepth >= maxNestingDepth) return resourceExhausted(`evaluation nesting depth exceeds the maximum of ${maxNestingDepth.toString()} (resource exhausted)`);
30
- } };
31
- }
32
- exports.DEFAULT_MAX_EVALUATION_NODES = DEFAULT_MAX_EVALUATION_NODES;
33
- exports.DEFAULT_MAX_NESTING_DEPTH = DEFAULT_MAX_NESTING_DEPTH;
34
- exports.MAX_TREE_REFERENCE_DEPTH = MAX_TREE_REFERENCE_DEPTH;
35
- exports.createEvaluationBudget = createEvaluationBudget;
36
- exports.isResourceExhaustion = isResourceExhaustion;
37
- exports.resourceExhausted = resourceExhausted;
@@ -1,22 +0,0 @@
1
- import { Evaluation, IndeterminateReason } from "./evaluation.cjs";
2
- /** The indeterminate result for an exhausted resource limit: code `domain-error` with the limit's own message, recorded so `isResourceExhaustion` recognises it. */
3
- export declare function resourceExhausted(message: string): Evaluation<never>;
4
- /** Whether `reason` reports an exhausted resource limit, as opposed to any other indeterminacy. */
5
- export declare function isResourceExhaustion(reason: Readonly<IndeterminateReason>): boolean;
6
- /** 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 in evaluator.ts (`visitedTreeKeys`), which catches an actual repeat immediately and more precisely. */
7
- export declare const MAX_TREE_REFERENCE_DEPTH = 100;
8
- /** 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. */
9
- export declare const DEFAULT_MAX_EVALUATION_NODES = 10000;
10
- /** 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. */
11
- export declare const DEFAULT_MAX_NESTING_DEPTH = 500;
12
- /**
13
- * A single `evaluatePredicate`/`evaluateValue` call's resource limits, independent of and layered underneath `MAX_TREE_REFERENCE_DEPTH`'s own cross-tree chain guard above: that guard only advances at an actual `treeReference` resolution and says nothing about a plain, self-contained tree built from ordinary `and`/`or`/`fold`/`conditional`/quantifier nesting, with no `treeReference` node anywhere in it. This closes that gap for a consumer evaluating a tree it did not author and cannot fully trust before evaluation (e.g. a tree embedded in a signed but otherwise attacker-controlled payload).
14
- *
15
- * Exposed as a single `checkNode` method rather than a raw mutable counter, following the same all-callback shape `Resolvers` and `FunctionRegistry` use in evaluator.ts: every recursive call site threads this object through as `Readonly<EvaluationBudget>`, and that wrapper genuinely prevents tampering because the running node count lives in `createEvaluationBudget`'s own closure, never as an assignable property on the object itself.
16
- */
17
- export interface EvaluationBudget {
18
- /** Charges one node visit and checks both caps, returning the `Evaluation` to return immediately if either is now exceeded, or `undefined` if evaluation of this node may proceed. Called as the very first action inside `evaluatePredicateInternal`/`evaluateValueInternal`, before any of that node's own work or further recursion, so an exceeded budget is discovered before it can be spent on additional descent. */
19
- checkNode: (nestingDepth: number) => Evaluation<never> | undefined;
20
- }
21
- /** 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. */
22
- export declare function createEvaluationBudget(maxNodes: number, maxNestingDepth: number): EvaluationBudget;
@@ -1,33 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluator_effect = require("./evaluator-effect.cjs");
3
- // src/evaluator-collection.ts
4
- /**
5
- * Collection resolution shared by the quantifiers (`some`/`every`) and by `fold` in evaluator.ts: resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` (via the injected `evaluatePredicate`, see `EvaluatePredicate`'s own doc comment) 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.
6
- */
7
- function* resolveParticipatingItems(evaluatePredicate, collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
8
- const candidates = yield* require_evaluator_effect.wait(resolvers.resolveCollection(collection, context));
9
- return yield* require_evaluator_effect.all(candidates.map(function* (item) {
10
- if (filter === void 0) return {
11
- item,
12
- filterOutcome: "include"
13
- };
14
- const filterResult = yield* evaluatePredicate(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
15
- if (filterResult.status === "indeterminate") return {
16
- item,
17
- filterOutcome: filterResult
18
- };
19
- return {
20
- item,
21
- filterOutcome: filterResult.value ? "include" : "exclude"
22
- };
23
- }));
24
- }
25
- /** 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. */
26
- function firstFilterIndeterminate(participating) {
27
- for (const { filterOutcome } of participating) {
28
- if (filterOutcome === "include" || filterOutcome === "exclude") continue;
29
- if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
30
- }
31
- }
32
- exports.firstFilterIndeterminate = firstFilterIndeterminate;
33
- exports.resolveParticipatingItems = resolveParticipatingItems;
@@ -1,21 +0,0 @@
1
- import { ComputedValue } from "./computed-value.cjs";
2
- import { Evaluation, IndeterminateReason } from "./evaluation.cjs";
3
- import { EvaluationBudget } from "./evaluator-budget.cjs";
4
- import { FunctionRegistry } from "./functions.cjs";
5
- import { JsonValue } from "./json-value.cjs";
6
- import { Task } from "./evaluator-effect.cjs";
7
- import { EvaluationContext, EvaluatorResolvers } from "./resolvers.cjs";
8
- import { PredicateNode } from "./tree.cjs";
9
- /** `resolveParticipatingItems`'s own view of `evaluatePredicateInternal` -- the exact signature that function has in evaluator.ts, injected here rather than imported directly so this module has no dependency back on evaluator.ts. Evaluating a `filter` genuinely does need the full recursive predicate evaluator (a filter can itself be arbitrarily nested), but taking it as a parameter rather than an import means this collection-resolution logic and evaluator.ts's mutually-recursive `evaluatePredicateInternal`/`evaluateValueInternal` pair never import each other, so there is no circular-import hazard between the two files. */
10
- export type EvaluatePredicate = (node: PredicateNode, context: EvaluationContext, resolvers: Readonly<EvaluatorResolvers>, accumulator: ComputedValue | undefined, functions: Readonly<FunctionRegistry>, visitedTreeKeys: ReadonlySet<string>, treeReferenceDepth: number, budget: Readonly<EvaluationBudget>, nestingDepth: number) => Task<Evaluation<boolean>>;
11
- /** A collection candidate paired with its own pre-filter outcome: `"include"`/`"exclude"` when `filter` resolved definitely, or the filter's own indeterminate `Evaluation` when it did not (there is no third, definite-but-neither branch -- see `resolveParticipatingItems` below). */
12
- export interface ResolvedCollectionItem {
13
- readonly item: unknown;
14
- readonly filterOutcome: "include" | "exclude" | Evaluation<never>;
15
- }
16
- /**
17
- * Collection resolution shared by the quantifiers (`some`/`every`) and by `fold` in evaluator.ts: resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` (via the injected `evaluatePredicate`, see `EvaluatePredicate`'s own doc comment) 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.
18
- */
19
- export declare function resolveParticipatingItems(evaluatePredicate: EvaluatePredicate, collection: JsonValue, filter: PredicateNode | undefined, context: EvaluationContext, resolvers: Readonly<EvaluatorResolvers>, functions: Readonly<FunctionRegistry>, visitedTreeKeys: ReadonlySet<string>, treeReferenceDepth: number, budget: Readonly<EvaluationBudget>, nestingDepth: number): Task<ResolvedCollectionItem[]>;
20
- /** 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. */
21
- export declare function firstFilterIndeterminate(participating: readonly ResolvedCollectionItem[]): IndeterminateReason | undefined;