trilean 1.7.12 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -14
- package/dist/builtin-functions.cjs +146 -0
- package/dist/builtin-functions.d.cts +13 -0
- package/dist/builtin-functions.d.ts +13 -0
- package/dist/builtin-functions.js +145 -0
- package/dist/complex-division.cjs +48 -0
- package/dist/complex-division.d.cts +25 -0
- package/dist/complex-division.d.ts +25 -0
- package/dist/complex-division.js +47 -0
- package/dist/complex.cjs +4 -2
- package/dist/complex.d.cts +4 -2
- package/dist/complex.d.ts +4 -2
- package/dist/complex.js +4 -2
- package/dist/duration-order.cjs +84 -0
- package/dist/duration-order.d.cts +22 -0
- package/dist/duration-order.d.ts +22 -0
- package/dist/duration-order.js +82 -0
- package/dist/evaluate-document.cjs +93 -0
- package/dist/evaluate-document.d.cts +44 -0
- package/dist/evaluate-document.d.ts +44 -0
- package/dist/evaluate-document.js +92 -0
- package/dist/evaluator-collection.d.cts +1 -1
- package/dist/evaluator-collection.d.ts +1 -1
- package/dist/evaluator-factory.d.cts +1 -1
- package/dist/evaluator-factory.d.ts +1 -1
- package/dist/evaluator-indeterminacy-helpers.d.cts +1 -1
- package/dist/evaluator-indeterminacy-helpers.d.ts +1 -1
- package/dist/evaluator-operations.cjs +75 -24
- package/dist/evaluator-operations.d.cts +3 -3
- package/dist/evaluator-operations.d.ts +3 -3
- package/dist/evaluator-operations.js +74 -23
- package/dist/evaluator.d.cts +1 -1
- package/dist/evaluator.d.ts +1 -1
- package/dist/functions.d.cts +8 -4
- package/dist/functions.d.ts +8 -4
- package/dist/index.cjs +8 -1
- package/dist/index.d.cts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -2
- package/dist/input-resolvers.cjs +110 -0
- package/dist/input-resolvers.d.cts +24 -0
- package/dist/input-resolvers.d.ts +24 -0
- package/dist/input-resolvers.js +108 -0
- package/dist/integer-power.cjs +20 -0
- package/dist/integer-power.d.cts +13 -0
- package/dist/integer-power.d.ts +13 -0
- package/dist/integer-power.js +19 -0
- package/dist/plain-record.cjs +8 -0
- package/dist/plain-record.d.cts +4 -0
- package/dist/plain-record.d.ts +4 -0
- package/dist/plain-record.js +7 -0
- package/dist-cli/trilean.mjs +1848 -0
- package/package.json +5 -1
- package/schemas/trilean.schema.json +1 -1
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//#region src/complex-division.ts
|
|
2
|
+
/**
|
|
3
|
+
* `value * 2 ** exponent`, applied in two halves because `2 ** exponent` is infinite beyond 1023 and a quotient can need a shift of about twice that. A power of two multiplies a double exactly while the result stays normal, so when the result can be non-zero and finite (a shift between about -1077 and 1024 for a scaled quotient of order one) each half is at most about 540 in magnitude, the first multiplication is exact, and the second rounds only where the result is subnormal. Outside that range the result overflows or is below the smallest subnormal: a non-zero value gives an infinity or zero, which is correct, and a zero value with a shift of 2047 or more gives NaN (zero times an infinite half), which the caller's finite check treats as it does an infinity.
|
|
4
|
+
*/
|
|
5
|
+
function scaleByPowerOfTwo(value, exponent) {
|
|
6
|
+
const firstHalf = Math.trunc(exponent / 2);
|
|
7
|
+
return value * 2 ** firstHalf * 2 ** (exponent - firstHalf);
|
|
8
|
+
}
|
|
9
|
+
/** The exponent of the power of two that brings a magnitude to between a quarter and a half, which this file calls about a quarter. `Math.log2` is rounded, so for a magnitude just under a power of two it can return that power itself and the result lands just under a quarter instead. The magnitude must be non-zero. */
|
|
10
|
+
function scaleToAboutAQuarter(larger) {
|
|
11
|
+
return -Math.floor(Math.log2(larger)) - 2;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The components of `dividend / divisor` for a non-zero divisor.
|
|
15
|
+
*
|
|
16
|
+
* The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
|
|
17
|
+
*
|
|
18
|
+
* Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
|
|
19
|
+
*
|
|
20
|
+
* The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
|
|
21
|
+
*
|
|
22
|
+
* Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
|
|
23
|
+
*
|
|
24
|
+
* A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
|
|
25
|
+
*/
|
|
26
|
+
function divideComplexComponents(dividend, divisor) {
|
|
27
|
+
const largerDividend = Math.max(Math.abs(dividend.re), Math.abs(dividend.im));
|
|
28
|
+
if (largerDividend === 0) return {
|
|
29
|
+
re: 0,
|
|
30
|
+
im: 0
|
|
31
|
+
};
|
|
32
|
+
const largerDivisor = Math.max(Math.abs(divisor.re), Math.abs(divisor.im));
|
|
33
|
+
const dividendScale = scaleToAboutAQuarter(largerDividend);
|
|
34
|
+
const divisorScale = scaleToAboutAQuarter(largerDivisor);
|
|
35
|
+
const a = scaleByPowerOfTwo(dividend.re, dividendScale);
|
|
36
|
+
const b = scaleByPowerOfTwo(dividend.im, dividendScale);
|
|
37
|
+
const c = scaleByPowerOfTwo(divisor.re, divisorScale);
|
|
38
|
+
const d = scaleByPowerOfTwo(divisor.im, divisorScale);
|
|
39
|
+
const denominator = c * c + d * d;
|
|
40
|
+
const shift = divisorScale - dividendScale;
|
|
41
|
+
return {
|
|
42
|
+
re: scaleByPowerOfTwo((a * c + b * d) / denominator, shift),
|
|
43
|
+
im: scaleByPowerOfTwo((b * c - a * d) / denominator, shift)
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { divideComplexComponents };
|
package/dist/complex.cjs
CHANGED
|
@@ -22,10 +22,12 @@ const complexMagnitude = (value) => ({
|
|
|
22
22
|
value: Math.hypot(value.re, value.im),
|
|
23
23
|
unit: value.unit
|
|
24
24
|
});
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
27
|
+
*/
|
|
26
28
|
const complexPhase = (value) => ({
|
|
27
29
|
kind: "number",
|
|
28
|
-
value: Math.atan2(value.im, value.re)
|
|
30
|
+
value: Math.atan2(value.im + 0, value.re + 0)
|
|
29
31
|
});
|
|
30
32
|
//#endregion
|
|
31
33
|
exports.complexFromPolar = complexFromPolar;
|
package/dist/complex.d.cts
CHANGED
|
@@ -4,7 +4,7 @@ import { ComplexLiteralNode } from "./tree.cjs";
|
|
|
4
4
|
/**
|
|
5
5
|
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
6
|
*
|
|
7
|
-
* Phase is in radians throughout, measured from the positive real axis,
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, in the range [-pi, pi] that `complexPhase` below states, which differs from `Math.atan2`'s only for a zero imaginary part of either sign.
|
|
8
8
|
*/
|
|
9
9
|
type ComplexValue = Extract<ComputedValue, {
|
|
10
10
|
kind: "complex";
|
|
@@ -17,6 +17,8 @@ export declare const complexFromPolar: (magnitude: number, phase: number, unit?:
|
|
|
17
17
|
export declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
18
|
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
19
|
export declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
22
|
+
*/
|
|
21
23
|
export declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
24
|
//#endregion
|
package/dist/complex.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { ComplexLiteralNode } from "./tree.js";
|
|
|
4
4
|
/**
|
|
5
5
|
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
6
|
*
|
|
7
|
-
* Phase is in radians throughout, measured from the positive real axis,
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, in the range [-pi, pi] that `complexPhase` below states, which differs from `Math.atan2`'s only for a zero imaginary part of either sign.
|
|
8
8
|
*/
|
|
9
9
|
type ComplexValue = Extract<ComputedValue, {
|
|
10
10
|
kind: "complex";
|
|
@@ -17,6 +17,8 @@ export declare const complexFromPolar: (magnitude: number, phase: number, unit?:
|
|
|
17
17
|
export declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
18
|
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
19
|
export declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
22
|
+
*/
|
|
21
23
|
export declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
24
|
//#endregion
|
package/dist/complex.js
CHANGED
|
@@ -21,10 +21,12 @@ const complexMagnitude = (value) => ({
|
|
|
21
21
|
value: Math.hypot(value.re, value.im),
|
|
22
22
|
unit: value.unit
|
|
23
23
|
});
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
26
|
+
*/
|
|
25
27
|
const complexPhase = (value) => ({
|
|
26
28
|
kind: "number",
|
|
27
|
-
value: Math.atan2(value.im, value.re)
|
|
29
|
+
value: Math.atan2(value.im + 0, value.re + 0)
|
|
28
30
|
});
|
|
29
31
|
//#endregion
|
|
30
32
|
export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region 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
|
+
//#endregion
|
|
83
|
+
exports.compareDurations = compareDurations;
|
|
84
|
+
exports.millisecondsPerDurationUnit = millisecondsPerDurationUnit;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { r as DurationUnit } from "./computed-value-CbRF0Izc.cjs";
|
|
2
|
+
//#region src/duration-order.d.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
|
+
export declare const millisecondsPerDurationUnit: Record<DurationUnit, number>;
|
|
5
|
+
type Ordering = -1 | 0 | 1;
|
|
6
|
+
/**
|
|
7
|
+
* The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
|
|
8
|
+
*
|
|
9
|
+
* 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.
|
|
10
|
+
*
|
|
11
|
+
* 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.
|
|
12
|
+
*
|
|
13
|
+
* Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
|
|
14
|
+
*/
|
|
15
|
+
export declare function compareDurations(left: Readonly<{
|
|
16
|
+
value: number;
|
|
17
|
+
unit: DurationUnit;
|
|
18
|
+
}>, right: Readonly<{
|
|
19
|
+
value: number;
|
|
20
|
+
unit: DurationUnit;
|
|
21
|
+
}>): Ordering | undefined;
|
|
22
|
+
//#endregion
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { r as DurationUnit } from "./computed-value-CbRF0Izc.js";
|
|
2
|
+
//#region src/duration-order.d.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
|
+
export declare const millisecondsPerDurationUnit: Record<DurationUnit, number>;
|
|
5
|
+
type Ordering = -1 | 0 | 1;
|
|
6
|
+
/**
|
|
7
|
+
* The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
|
|
8
|
+
*
|
|
9
|
+
* 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.
|
|
10
|
+
*
|
|
11
|
+
* 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.
|
|
12
|
+
*
|
|
13
|
+
* Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
|
|
14
|
+
*/
|
|
15
|
+
export declare function compareDurations(left: Readonly<{
|
|
16
|
+
value: number;
|
|
17
|
+
unit: DurationUnit;
|
|
18
|
+
}>, right: Readonly<{
|
|
19
|
+
value: number;
|
|
20
|
+
unit: DurationUnit;
|
|
21
|
+
}>): Ordering | undefined;
|
|
22
|
+
//#endregion
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//#region src/duration-order.ts
|
|
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
|
+
const millisecondsPerDurationUnit = {
|
|
4
|
+
ms: 1,
|
|
5
|
+
s: 1e3,
|
|
6
|
+
min: 6e4,
|
|
7
|
+
h: 36e5,
|
|
8
|
+
d: 864e5
|
|
9
|
+
};
|
|
10
|
+
const ONE = 1n;
|
|
11
|
+
const FRACTION_BITS = 52n;
|
|
12
|
+
const FRACTION_MASK = (ONE << FRACTION_BITS) - ONE;
|
|
13
|
+
const IMPLICIT_LEADING_BIT = ONE << FRACTION_BITS;
|
|
14
|
+
const EXPONENT_FIELD_MASK = 2047n;
|
|
15
|
+
const EXPONENT_BIAS_WITH_FRACTION = 1075;
|
|
16
|
+
const SUBNORMAL_EXPONENT = -1074;
|
|
17
|
+
const scratchValue = /* @__PURE__ */ new Float64Array(1);
|
|
18
|
+
const scratchBits = new BigUint64Array(scratchValue.buffer);
|
|
19
|
+
/** A finite double as `significand * 2 ** exponent` with an integer significand, exactly, read from its bit pattern. Zero has a zero significand. */
|
|
20
|
+
function exactParts(magnitude) {
|
|
21
|
+
scratchValue[0] = magnitude;
|
|
22
|
+
const bits = scratchBits[0];
|
|
23
|
+
if (bits === void 0) throw new Error("a one-element array always has an element zero");
|
|
24
|
+
const exponentField = Number(bits >> FRACTION_BITS & EXPONENT_FIELD_MASK);
|
|
25
|
+
const fraction = bits & FRACTION_MASK;
|
|
26
|
+
if (exponentField === 0) return {
|
|
27
|
+
significand: fraction,
|
|
28
|
+
exponent: SUBNORMAL_EXPONENT
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
significand: fraction | IMPLICIT_LEADING_BIT,
|
|
32
|
+
exponent: exponentField - EXPONENT_BIAS_WITH_FRACTION
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function orderOf(left, right) {
|
|
36
|
+
if (left < right) return -1;
|
|
37
|
+
return left > right ? 1 : 0;
|
|
38
|
+
}
|
|
39
|
+
/** 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. */
|
|
40
|
+
function exactOrder(left, right) {
|
|
41
|
+
const leftSign = Math.sign(left.value);
|
|
42
|
+
const rightSign = Math.sign(right.value);
|
|
43
|
+
if (leftSign !== rightSign) return leftSign < rightSign ? -1 : 1;
|
|
44
|
+
if (leftSign === 0) return 0;
|
|
45
|
+
const leftParts = exactParts(Math.abs(left.value));
|
|
46
|
+
const rightParts = exactParts(Math.abs(right.value));
|
|
47
|
+
let leftProduct = leftParts.significand * BigInt(left.size);
|
|
48
|
+
let rightProduct = rightParts.significand * BigInt(right.size);
|
|
49
|
+
const shift = leftParts.exponent - rightParts.exponent;
|
|
50
|
+
if (shift > 0) leftProduct <<= BigInt(shift);
|
|
51
|
+
else rightProduct <<= BigInt(-shift);
|
|
52
|
+
return leftSign < 0 ? orderOf(rightProduct, leftProduct) : orderOf(leftProduct, rightProduct);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
|
|
56
|
+
*
|
|
57
|
+
* 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.
|
|
58
|
+
*
|
|
59
|
+
* 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.
|
|
60
|
+
*
|
|
61
|
+
* Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
|
|
62
|
+
*/
|
|
63
|
+
function compareDurations(left, right) {
|
|
64
|
+
if (Number.isNaN(left.value) || Number.isNaN(right.value)) return void 0;
|
|
65
|
+
if (!Number.isFinite(left.value) || !Number.isFinite(right.value)) return orderOf(left.value, right.value);
|
|
66
|
+
const leftSize = millisecondsPerDurationUnit[left.unit];
|
|
67
|
+
const rightSize = millisecondsPerDurationUnit[right.unit];
|
|
68
|
+
const sharedSize = Math.max(leftSize, rightSize);
|
|
69
|
+
const leftInShared = left.value / (sharedSize / leftSize);
|
|
70
|
+
const rightInShared = right.value / (sharedSize / rightSize);
|
|
71
|
+
if (leftInShared < rightInShared) return -1;
|
|
72
|
+
if (leftInShared > rightInShared) return 1;
|
|
73
|
+
return exactOrder({
|
|
74
|
+
value: left.value,
|
|
75
|
+
size: leftSize
|
|
76
|
+
}, {
|
|
77
|
+
value: right.value,
|
|
78
|
+
size: rightSize
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
export { compareDurations, millisecondsPerDurationUnit };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_computed_value = require("./computed-value.cjs");
|
|
3
|
+
const require_builtin_functions = require("./builtin-functions.cjs");
|
|
4
|
+
const require_tree = require("./tree.cjs");
|
|
5
|
+
const require_evaluator_factory = require("./evaluator-factory.cjs");
|
|
6
|
+
const require_plain_record = require("./plain-record.cjs");
|
|
7
|
+
const require_input_resolvers = require("./input-resolvers.cjs");
|
|
8
|
+
//#region 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
|
+
//#endregion
|
|
93
|
+
exports.evaluateDocument = evaluateDocument;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
|
+
import { Evaluation } from "./evaluation.cjs";
|
|
3
|
+
//#region src/evaluate-document.d.ts
|
|
4
|
+
export type TreeKind = "predicate" | "expression";
|
|
5
|
+
export interface EvaluateDocumentOptions {
|
|
6
|
+
/** The tree as parsed from JSON, not yet validated. */
|
|
7
|
+
tree: unknown;
|
|
8
|
+
/** Named values and lists of items as parsed from JSON (see `parseInputs`); absent means none. */
|
|
9
|
+
inputs?: unknown;
|
|
10
|
+
/** Which tree `tree` is. Needed only when its root is a `treeReference`, the one node kind valid in both. */
|
|
11
|
+
as?: TreeKind;
|
|
12
|
+
/** 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. */
|
|
13
|
+
maxNodes?: number;
|
|
14
|
+
}
|
|
15
|
+
export type DocumentEvaluation = {
|
|
16
|
+
outcome: "evaluated";
|
|
17
|
+
treeKind: "predicate";
|
|
18
|
+
evaluation: Evaluation<boolean>;
|
|
19
|
+
} | {
|
|
20
|
+
outcome: "evaluated";
|
|
21
|
+
treeKind: "expression";
|
|
22
|
+
evaluation: Evaluation<ComputedValue>;
|
|
23
|
+
} | {
|
|
24
|
+
outcome: "rejected";
|
|
25
|
+
/** `ambiguous-tree-kind` is a root `treeReference` evaluated without `as`; every other rejection is `invalid`, a tree or an input that fails validation. */
|
|
26
|
+
reason: "invalid" | "ambiguous-tree-kind";
|
|
27
|
+
issues: readonly string[];
|
|
28
|
+
} | {
|
|
29
|
+
outcome: "unrepresentable";
|
|
30
|
+
issues: readonly string[];
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* 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:
|
|
34
|
+
*
|
|
35
|
+
* - `evaluated`: an `Evaluation`, definite or indeterminate.
|
|
36
|
+
* - `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.
|
|
37
|
+
* - `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.
|
|
38
|
+
*
|
|
39
|
+
* 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.
|
|
40
|
+
*
|
|
41
|
+
* 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.
|
|
42
|
+
*/
|
|
43
|
+
export declare function evaluateDocument({ tree, inputs, as, maxNodes }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
44
|
+
//#endregion
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { t as ComputedValue } from "./computed-value-CbRF0Izc.js";
|
|
2
|
+
import { Evaluation } from "./evaluation.js";
|
|
3
|
+
//#region src/evaluate-document.d.ts
|
|
4
|
+
export type TreeKind = "predicate" | "expression";
|
|
5
|
+
export interface EvaluateDocumentOptions {
|
|
6
|
+
/** The tree as parsed from JSON, not yet validated. */
|
|
7
|
+
tree: unknown;
|
|
8
|
+
/** Named values and lists of items as parsed from JSON (see `parseInputs`); absent means none. */
|
|
9
|
+
inputs?: unknown;
|
|
10
|
+
/** Which tree `tree` is. Needed only when its root is a `treeReference`, the one node kind valid in both. */
|
|
11
|
+
as?: TreeKind;
|
|
12
|
+
/** 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. */
|
|
13
|
+
maxNodes?: number;
|
|
14
|
+
}
|
|
15
|
+
export type DocumentEvaluation = {
|
|
16
|
+
outcome: "evaluated";
|
|
17
|
+
treeKind: "predicate";
|
|
18
|
+
evaluation: Evaluation<boolean>;
|
|
19
|
+
} | {
|
|
20
|
+
outcome: "evaluated";
|
|
21
|
+
treeKind: "expression";
|
|
22
|
+
evaluation: Evaluation<ComputedValue>;
|
|
23
|
+
} | {
|
|
24
|
+
outcome: "rejected";
|
|
25
|
+
/** `ambiguous-tree-kind` is a root `treeReference` evaluated without `as`; every other rejection is `invalid`, a tree or an input that fails validation. */
|
|
26
|
+
reason: "invalid" | "ambiguous-tree-kind";
|
|
27
|
+
issues: readonly string[];
|
|
28
|
+
} | {
|
|
29
|
+
outcome: "unrepresentable";
|
|
30
|
+
issues: readonly string[];
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* 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:
|
|
34
|
+
*
|
|
35
|
+
* - `evaluated`: an `Evaluation`, definite or indeterminate.
|
|
36
|
+
* - `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.
|
|
37
|
+
* - `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.
|
|
38
|
+
*
|
|
39
|
+
* 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.
|
|
40
|
+
*
|
|
41
|
+
* 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.
|
|
42
|
+
*/
|
|
43
|
+
export declare function evaluateDocument({ tree, inputs, as, maxNodes }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
44
|
+
//#endregion
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { ComputedValueSchema } from "./computed-value.js";
|
|
2
|
+
import { builtinFunctions } from "./builtin-functions.js";
|
|
3
|
+
import { ExpressionNodeSchema, PredicateNodeSchema } from "./tree.js";
|
|
4
|
+
import { createSyncEvaluator } from "./evaluator-factory.js";
|
|
5
|
+
import { isPlainRecord } from "./plain-record.js";
|
|
6
|
+
import { createInputResolvers, parseInputs } from "./input-resolvers.js";
|
|
7
|
+
//#region src/evaluate-document.ts
|
|
8
|
+
const predicateKinds = new Set(PredicateNodeSchema.options.map((option) => option.shape.kind.value));
|
|
9
|
+
/** 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. */
|
|
10
|
+
const NOT_REPRESENTABLE = "(result): the value is not a finite number";
|
|
11
|
+
const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; set `as` to \"predicate\" or \"expression\"";
|
|
12
|
+
const defaultEvaluator = createSyncEvaluator({ functions: builtinFunctions });
|
|
13
|
+
/** 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. */
|
|
14
|
+
function describeIssues(issues, parentPath = []) {
|
|
15
|
+
return issues.flatMap((issue) => {
|
|
16
|
+
const path = [...parentPath, ...issue.path];
|
|
17
|
+
if (issue.code === "invalid_union" && issue.errors.length > 0) return describeIssues(issue.errors.reduce((best, branch) => maxPathLength(branch) > maxPathLength(best) ? branch : best), path);
|
|
18
|
+
return [`${path.length === 0 ? "(root)" : path.join(".")}: ${issue.message}`];
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function maxPathLength(issues) {
|
|
22
|
+
return Math.max(0, ...issues.map((issue) => issue.path.length));
|
|
23
|
+
}
|
|
24
|
+
function resolveTreeKind(tree, requested) {
|
|
25
|
+
if (requested !== void 0) return requested;
|
|
26
|
+
const kind = isPlainRecord(tree) ? tree.kind : void 0;
|
|
27
|
+
if (kind === "treeReference") return "ambiguous";
|
|
28
|
+
return typeof kind === "string" && predicateKinds.has(kind) ? "predicate" : "expression";
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* 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:
|
|
32
|
+
*
|
|
33
|
+
* - `evaluated`: an `Evaluation`, definite or indeterminate.
|
|
34
|
+
* - `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.
|
|
35
|
+
* - `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.
|
|
36
|
+
*
|
|
37
|
+
* 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.
|
|
38
|
+
*
|
|
39
|
+
* 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.
|
|
40
|
+
*/
|
|
41
|
+
function evaluateDocument({ tree, inputs, as, maxNodes }) {
|
|
42
|
+
const evaluator = maxNodes === void 0 ? defaultEvaluator : createSyncEvaluator({
|
|
43
|
+
functions: builtinFunctions,
|
|
44
|
+
maxNodes
|
|
45
|
+
});
|
|
46
|
+
const parsedInputs = parseInputs(inputs ?? {});
|
|
47
|
+
if (!parsedInputs.ok) return {
|
|
48
|
+
outcome: "rejected",
|
|
49
|
+
reason: "invalid",
|
|
50
|
+
issues: parsedInputs.issues
|
|
51
|
+
};
|
|
52
|
+
const resolvers = createInputResolvers(parsedInputs.inputs, parsedInputs.collections);
|
|
53
|
+
const treeKind = resolveTreeKind(tree, as);
|
|
54
|
+
if (treeKind === "ambiguous") return {
|
|
55
|
+
outcome: "rejected",
|
|
56
|
+
reason: "ambiguous-tree-kind",
|
|
57
|
+
issues: [AMBIGUOUS_TREE_KIND]
|
|
58
|
+
};
|
|
59
|
+
if (treeKind === "predicate") {
|
|
60
|
+
const parsed = PredicateNodeSchema.safeParse(tree);
|
|
61
|
+
if (!parsed.success) return {
|
|
62
|
+
outcome: "rejected",
|
|
63
|
+
reason: "invalid",
|
|
64
|
+
issues: describeIssues(parsed.error.issues)
|
|
65
|
+
};
|
|
66
|
+
const node = parsed.data;
|
|
67
|
+
return {
|
|
68
|
+
outcome: "evaluated",
|
|
69
|
+
treeKind,
|
|
70
|
+
evaluation: evaluator.evaluatePredicate(node, void 0, resolvers)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const parsed = ExpressionNodeSchema.safeParse(tree);
|
|
74
|
+
if (!parsed.success) return {
|
|
75
|
+
outcome: "rejected",
|
|
76
|
+
reason: "invalid",
|
|
77
|
+
issues: describeIssues(parsed.error.issues)
|
|
78
|
+
};
|
|
79
|
+
const node = parsed.data;
|
|
80
|
+
const evaluation = evaluator.evaluateValue(node, void 0, resolvers);
|
|
81
|
+
if (evaluation.status === "definite" && !ComputedValueSchema.safeParse(evaluation.value).success) return {
|
|
82
|
+
outcome: "unrepresentable",
|
|
83
|
+
issues: [NOT_REPRESENTABLE]
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
outcome: "evaluated",
|
|
87
|
+
treeKind,
|
|
88
|
+
evaluation
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
export { evaluateDocument };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
|
+
import { FunctionRegistry } from "./functions.cjs";
|
|
2
3
|
import { t as JsonValue } from "./json-value-B1Hjjjri.cjs";
|
|
3
4
|
import { PredicateNode } from "./tree.cjs";
|
|
4
5
|
import { Evaluation, IndeterminateReason } from "./evaluation.cjs";
|
|
5
6
|
import { EvaluationBudget } from "./evaluator-budget.cjs";
|
|
6
|
-
import { FunctionRegistry } from "./functions.cjs";
|
|
7
7
|
import { Task } from "./evaluator-effect.cjs";
|
|
8
8
|
import { EvaluationContext, EvaluatorResolvers } from "./resolvers.cjs";
|
|
9
9
|
//#region src/evaluator-collection.d.ts
|