solve-engine 2.31.0 → 2.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{chunk-V7LXOTCU.js → chunk-6LA7HC46.js} +3 -3
  2. package/dist/{chunk-V7LXOTCU.js.map → chunk-6LA7HC46.js.map} +1 -1
  3. package/dist/{chunk-2PGGPFF3.js → chunk-AF6NDOIE.js} +2 -2
  4. package/dist/{chunk-2PGGPFF3.js.map → chunk-AF6NDOIE.js.map} +1 -1
  5. package/dist/{chunk-5EL4WXLF.cjs → chunk-BSGZ3OEL.cjs} +3 -3
  6. package/dist/{chunk-5EL4WXLF.cjs.map → chunk-BSGZ3OEL.cjs.map} +1 -1
  7. package/dist/chunk-BWTVJD5L.js +2 -0
  8. package/dist/chunk-BWTVJD5L.js.map +1 -0
  9. package/dist/{chunk-D4UHCZAW.js → chunk-KBRSNJMQ.js} +3 -3
  10. package/dist/{chunk-D4UHCZAW.js.map → chunk-KBRSNJMQ.js.map} +1 -1
  11. package/dist/{chunk-RAFOQ4T5.cjs → chunk-LCYQQFUH.cjs} +2 -2
  12. package/dist/{chunk-RAFOQ4T5.cjs.map → chunk-LCYQQFUH.cjs.map} +1 -1
  13. package/dist/{chunk-JPT6L7BG.cjs → chunk-MDTIL3UT.cjs} +4 -4
  14. package/dist/{chunk-JPT6L7BG.cjs.map → chunk-MDTIL3UT.cjs.map} +1 -1
  15. package/dist/{chunk-W7NN77PH.cjs → chunk-MZQ3ED6J.cjs} +3 -3
  16. package/dist/{chunk-W7NN77PH.cjs.map → chunk-MZQ3ED6J.cjs.map} +1 -1
  17. package/dist/{chunk-YN5H54GM.js → chunk-OE2DBN4K.js} +2 -2
  18. package/dist/{chunk-YN5H54GM.js.map → chunk-OE2DBN4K.js.map} +1 -1
  19. package/dist/chunk-PHWIO4P3.cjs +2 -0
  20. package/dist/chunk-PHWIO4P3.cjs.map +1 -0
  21. package/dist/{chunk-VYB44JLS.js → chunk-SNYFNARL.js} +3 -3
  22. package/dist/{chunk-VYB44JLS.js.map → chunk-SNYFNARL.js.map} +1 -1
  23. package/dist/{chunk-64OGL465.js → chunk-TP5EQCGH.js} +2 -2
  24. package/dist/{chunk-64OGL465.js.map → chunk-TP5EQCGH.js.map} +1 -1
  25. package/dist/{chunk-GWV273KZ.cjs → chunk-UNKZ5XRC.cjs} +2 -2
  26. package/dist/{chunk-GWV273KZ.cjs.map → chunk-UNKZ5XRC.cjs.map} +1 -1
  27. package/dist/{chunk-UHS4HMOQ.cjs → chunk-VYQNPCM5.cjs} +2 -2
  28. package/dist/{chunk-UHS4HMOQ.cjs.map → chunk-VYQNPCM5.cjs.map} +1 -1
  29. package/dist/constants.cjs +1 -1
  30. package/dist/constants.js +1 -1
  31. package/dist/engine.cjs +1 -1
  32. package/dist/engine.js +1 -1
  33. package/dist/engine.worker.cjs +1 -1
  34. package/dist/engine.worker.js +1 -1
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/language.cjs +1 -1
  38. package/dist/language.js +1 -1
  39. package/dist/packages.cjs +1 -1
  40. package/dist/packages.js +1 -1
  41. package/dist/testing.cjs +2 -2
  42. package/dist/testing.js +1 -1
  43. package/dist/uom.cjs +1 -1
  44. package/dist/uom.js +1 -1
  45. package/dist/vm.cjs +1 -1
  46. package/dist/vm.js +1 -1
  47. package/dist/worker.cjs +2 -2
  48. package/dist/worker.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-4CNYGIND.js +0 -2
  51. package/dist/chunk-4CNYGIND.js.map +0 -1
  52. package/dist/chunk-ZKFCKAIX.cjs +0 -2
  53. package/dist/chunk-ZKFCKAIX.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkEZKR44MA_cjs=require('./chunk-EZKR44MA.cjs');var y=new Map(Object.entries(chunkEZKR44MA_cjs.a)),I=new Map(Object.entries(chunkEZKR44MA_cjs.b));function c(n){return y.get(n)}function b(n,e,t){let r=y.get(e);if(r===void 0)throw new RangeError(`${e} is not a valid unit`);let i=y.get(t);if(i===void 0)throw new RangeError(`${t} is not a valid unit`);return w(n,e,t,r,i)}function w(n,e,t,r,i){let s=r,o=i;if(s[0]!==o[0])throw new RangeError(`Cannot convert between different measures: ${e} and ${t}`);let u=s[1],a=o[1],l=I.get(e),g=I.get(t);return l!==void 0?g!==void 0?(n+l)*(u/a)-g:(n+l)*(u/a):g!==void 0?n*(u/a)-g:n*(u/a)}function O(n,e){let t=y.get(e);if(t===void 0)throw new RangeError(`${e} is not a valid unit`);let r=chunkEZKR44MA_cjs.c[t[0]],i=r[0][0],s=i,o=b(n,e,i),u=o<0?-o:o;for(let a=0;a<r.length;a++){let l=r[a];if(u>=l[1])s=l[0];else break}return {quantity:b(n,e,s),unit:s}}var h=new Set(["workday","workdays"]),S=7/5;function m(n){return typeof n=="string"&&h.has(n)}function P(n){return n}function f(n){if(m(n))return f("day");let e=chunkEZKR44MA_cjs.f[n];if(e)return e.measure;let t=c(n);if(t!==void 0)return chunkEZKR44MA_cjs.e[t[0]]}function Y(n,e){if(n===e)return true;if(m(n)||m(e)){let o=f(n),u=f(e);return !!o&&o===u}let t=c(n),r=c(e);if(t!==void 0&&r!==void 0)return t[0]===r[0];let i=chunkEZKR44MA_cjs.f[n],s=chunkEZKR44MA_cjs.f[e];return i!==void 0&&s!==void 0?i.measure===s.measure:U(n,e)||U(e,n)}function U(n,e){let t=chunkEZKR44MA_cjs.f[n];if(t===void 0)return false;let r=c(e);return r===void 0?false:chunkEZKR44MA_cjs.e[r[0]]===t.measure}function p(n,e,t){if(e===t)return n;let r=c(e),i=c(t);if(r!==void 0&&i!==void 0)return w(n,e,t,r,i);if(m(e)&&m(t))return n;if(m(e)){let u=n*S;return t==="day"?u:p(u,"day",t)}if(m(t))return (e==="day"?n:p(n,e,"day"))/S;let s=chunkEZKR44MA_cjs.f[e],o=chunkEZKR44MA_cjs.f[t];if(s!==void 0&&o!==void 0){if(s.measure!==o.measure)throw new RangeError(`Cannot convert between different measures: ${e} and ${t}`);return n*(s.toBase/o.toBase)}return s!==void 0&&U(e,t)?b(n*s.toBase,A(t),t):o!==void 0&&U(t,e)?b(n,e,A(e))/o.toBase:b(n,e,t)}function A(n){let e=c(n);if(e===void 0)return n;for(let t of Object.keys(chunkEZKR44MA_cjs.a)){let r=chunkEZKR44MA_cjs.a[t];if(r[0]===e[0]&&r[1]===1)return t}return n}function j(n){let e=n,t=c(e);if(t===void 0)return [];let r=chunkEZKR44MA_cjs.d[t[0]];return r?r.filter(i=>i!==e):[]}function W(n){return m(n)||chunkEZKR44MA_cjs.f[n]?true:c(n)!==void 0}function Q(n,e){let t=e;try{let r=O(n,t);return {value:r.quantity,unit:r.unit}}catch{return {value:n,unit:t}}}var D={mpg:{numerator:"km",denominator:"l",factor:1.609344/3.785411784},kmpl:{numerator:"km",denominator:"l",factor:1},l100km:{numerator:"l",denominator:"km",factor:.01}};function M(n,e){let t=D[e];if(t!==void 0)return {value:n*t.factor,numerator:t.numerator,denominator:t.denominator};let r=e.indexOf("/");if(r>=0)return {value:n,numerator:e.slice(0,r),denominator:e.slice(r+1)};let i=chunkEZKR44MA_cjs.f[e];return i!==void 0&&i.measure==="speed"?{value:n*i.toBase,numerator:"m",denominator:"s"}:i!==void 0&&i.measure==="dataRate"?{value:n*i.toBase,numerator:"b",denominator:"s"}:null}function q(n){if(n===void 0)return false;let e=M(1,n);if(e===null||f(e.denominator)!=="time")return false;let t=f(e.numerator);return t==="length"||t==="data"}function X(n,e,t,r){let i=M(t,r);if(i===null||f(i.denominator)!=="time"||f(e)!==f(i.numerator))return null;let o=p(n,e,i.numerator)/i.value;return p(o,i.denominator,"s")}function R(n,e){if(n===e)return 1;if(n===""||e==="")return null;let t=f(n),r=f(e);return t===void 0||r===void 0||t!==r?null:p(1,n,e)}function z(n,e,t){let r=M(n,e);if(r===null)return null;let i,s,o,u=D[t],a=t.indexOf("/");if(u!==void 0)i=u.numerator,s=u.denominator,o=u.factor;else if(a>=0)i=t.slice(0,a),s=t.slice(a+1),o=1;else {let x=chunkEZKR44MA_cjs.f[t];if(x===void 0||x.measure!=="speed")return null;i="m",s="s",o=x.toBase;}let l=R(r.numerator,i),g=R(r.denominator,s);if(l!==null&&g!==null)return r.value*l/g/o;let N=R(r.denominator,i),_=R(r.numerator,s);return N!==null&&_!==null&&r.value!==0?N/_/r.value/o:null}exports.a=m;exports.b=P;exports.c=f;exports.d=Y;exports.e=p;exports.f=j;exports.g=W;exports.h=Q;exports.i=q;exports.j=X;exports.k=z;//# sourceMappingURL=chunk-PHWIO4P3.cjs.map
2
+ //# sourceMappingURL=chunk-PHWIO4P3.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uom/UnitConversion.ts","../src/uom/UomConverter.ts"],"names":["UNIT_LOOKUP","UNIT_TABLE","DIFFERENCE_LOOKUP","UNIT_DIFFERENCES","lookupUnit","unit","convertRaw","quantity","from","to","parsedFrom","parsedTo","convertResolved","fromEntry","toEntry","fromRatio","toRatio","fromDifference","toDifference","convertToBestMetric","best","BEST_UNITS_METRIC","smallestUnit","bestUnit","baseQuantity","absQuantity","i","bestEntry","WORKDAY_UNIT_NAMES","WORKDAY_TO_DAY_FACTOR","isWorkdayUnit","resolveUnit","getMeasure","extended","EXTENDED_UNITS","entry","MEASURE_KIND_NAMES","canConvert","fromMeasure","toMeasure","fromExtended","toExtended","bridgesToBaseMeasure","extendedUnit","baseUnit","base","convertUnit","value","days","fExt","tExt","baseUnitFor","symbol","candidate","getConvertiblePossibilities","resolved","symbols","MEASURE_SYMBOLS","s","isConvertibleUnit","getBestUnit","u","result","FUEL_RATE_UNITS","expandUnitToRate","fuel","slash","ext","isPhysicalTimeRate","rate","numeratorMeasure","quantityAtRateSeconds","quantityUnit","rateValue","rateUnit","timeInDenominator","rateAxisFactor","convertRate","source","targetNumerator","targetDenominator","targetScale","fuelTarget","numeratorFactor","denominatorFactor","crossNumerator","crossDenominator"],"mappings":"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","file":"chunk-PHWIO4P3.cjs","sourcesContent":["/**\n * The unit conversion algorithm, ported from the `convert` npm package v7.0.2\n * alongside its tables (see `generated/UnitTable.generated.ts` and\n * THIRD-PARTY-NOTICES.md).\n *\n * Transliterated expression for expression rather than rewritten. Floating\n * point is not associative, so `(q + d) * (a / b) - d2` and any algebraically\n * equal rearrangement disagree in the last bits. Those bits are observable:\n * `0.5 l` best-converts to `500.00000000000006 mL` today, and the test suite\n * pins several conversions to ten decimal places.\n *\n * This module is deliberately unaware of the engine's own additions. Workdays,\n * extended units, currency and the caches all live in `UomConverter.ts`, which\n * layers them on top of these three functions.\n */\n\nimport {\n UNIT_TABLE,\n UNIT_DIFFERENCES,\n BEST_UNITS_METRIC,\n type UnitEntry,\n} from \"./generated/UnitTable.generated\";\n\n/**\n * The generated tables re-keyed into Maps once at module load.\n *\n * Not a micro-optimization. A 1456-key object literal lands in V8's dictionary\n * mode, and guarding a read on it against inherited names (`constructor`,\n * `toString`) costs about 123ns per call with either `hasOwnProperty.call` or\n * `Object.hasOwn`, measured. `Map.get` is about 6ns and needs no guard at all,\n * because a Map has no prototype chain to fall through to. That is a 20x\n * difference on the single hottest operation in the unit system: `convertRaw`\n * performs two of these per call, and `LanguageService` sweeps all 1456 keys\n * to build completions.\n */\nconst UNIT_LOOKUP: ReadonlyMap<string, UnitEntry> = new Map(Object.entries(UNIT_TABLE));\n\n/**\n * Temperature offsets, as a Map for the same reason.\n *\n * Also removes a latent hazard: the upstream code tests membership with `in`,\n * and `\"toString\" in UNIT_DIFFERENCES` is true, so an inherited name reaching\n * that branch would add a function to a number.\n */\nconst DIFFERENCE_LOOKUP: ReadonlyMap<string, number> = new Map(Object.entries(UNIT_DIFFERENCES));\n\n/**\n * Looks up a unit spelling.\n *\n * @returns its `[kind, ratio]` entry, or `undefined` if the spelling is not a\n * unit. Case-sensitive: no normalization or aliasing happens anywhere in this\n * module.\n *\n * The one deliberate deviation from upstream. `convert` tests membership with\n * `in` and reads the property directly, so inherited names like \"constructor\"\n * and \"toString\" reach its measure comparison and fail there with \"Cannot\n * convert between different measures\" instead of \"is not a valid unit\". Both\n * throw a RangeError and both report no measure, so nothing downstream can\n * tell the difference, and naming the real problem is the better message.\n */\nexport function lookupUnit(unit: string): UnitEntry | undefined {\n return UNIT_LOOKUP.get(unit);\n}\n\n/**\n * Converts `quantity` from one unit to another.\n *\n * THROWS a `RangeError` for an unknown unit or a pair in different measures.\n * Callers depend on that: `VM.ts`'s `extractDurationMs()` calls this with an\n * arbitrary unit inside a bare try/catch and treats the throw as \"not a\n * duration, contribute zero\". Returning NaN or the input unchanged instead\n * would turn `<date> + 5 kg` into an Invalid Date rather than a no-op.\n */\nexport function convertRaw(quantity: number, from: string, to: string): number {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const parsedTo = UNIT_LOOKUP.get(to);\n if (parsedTo === undefined) {\n throw new RangeError(`${to} is not a valid unit`);\n }\n\n return convertResolved(quantity, from, to, parsedFrom, parsedTo);\n}\n\n/**\n * The conversion arithmetic, for callers that have already looked both units\n * up and want to skip doing it twice.\n *\n * Split out for `UomConverter.convertUnit()`, which has to check whether\n * either side is a workday or an extended unit before it can dispatch, and\n * would otherwise resolve each unit once to decide and again to convert. The\n * entries MUST be the ones this module returned for these exact spellings.\n */\nexport function convertResolved(\n quantity: number,\n from: string,\n to: string,\n fromEntry: UnitEntry,\n toEntry: UnitEntry\n): number {\n const parsedFrom = fromEntry;\n const parsedTo = toEntry;\n\n if (parsedFrom[0] !== parsedTo[0]) {\n // DELIBERATE DEVIATION from the ported original, which silently reinterpreted\n // \"m\" as minutes whenever the other side was a time unit. That is a guess,\n // and this project's stated position is that refusing to guess is the safer\n // default for a tool doing arithmetic on someone's real numbers (see\n // docs/architecture/design-decisions.md). The guess was not harmless: it\n // reached `<date> + <duration>` through VM.ts's extractDurationMs(), where\n // `today + 5 m` silently added five MINUTES for someone who wrote metres.\n //\n // Minutes are spelled \"min\", \"minute\" or \"minutes\", all of which the table\n // has always accepted.\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n\n const fromRatio = parsedFrom[1];\n const toRatio = parsedTo[1];\n\n // Only six units in the whole table carry an offset, so the common path is\n // both misses. Reading the Map once per side and reusing the value beats\n // testing membership and then reading it again.\n const fromDifference = DIFFERENCE_LOOKUP.get(from);\n const toDifference = DIFFERENCE_LOOKUP.get(to);\n\n // Scales that do not share an origin (temperature) need the offset applied\n // around the ratio. Do not refactor the four branches into one expression:\n // the grouping is what makes the result bit-identical to the original.\n if (fromDifference !== undefined) {\n if (toDifference !== undefined) {\n return (quantity + fromDifference) * (fromRatio / toRatio) - toDifference;\n }\n return (quantity + fromDifference) * (fromRatio / toRatio);\n }\n\n if (toDifference !== undefined) {\n return quantity * (fromRatio / toRatio) - toDifference;\n }\n\n return quantity * (fromRatio / toRatio);\n}\n\n/**\n * Picks the most readable metric unit for a magnitude and converts to it.\n *\n * Only the metric lists are ported; nothing has ever requested the imperial\n * ones. Note the final conversion goes from the ORIGINAL unit to the chosen\n * one directly rather than via the smallest unit, which is what keeps the\n * result exact.\n */\nexport function convertToBestMetric(\n quantity: number,\n from: string\n): { quantity: number; unit: string } {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const best = BEST_UNITS_METRIC[parsedFrom[0]];\n const smallestUnit = best[0][0];\n let bestUnit = smallestUnit;\n\n const baseQuantity = convertRaw(quantity, from, smallestUnit);\n const absQuantity = baseQuantity < 0 ? -baseQuantity : baseQuantity;\n\n // Thresholds are expressed in the smallest unit and ascend, so the last one\n // the magnitude reaches wins. Breaking early rather than scanning the whole\n // list matters for zero and for negatives, which stay on the smallest unit.\n for (let i = 0; i < best.length; i++) {\n const bestEntry = best[i];\n if (absQuantity >= bestEntry[1]) {\n bestUnit = bestEntry[0];\n } else {\n break;\n }\n }\n\n return { quantity: convertRaw(quantity, from, bestUnit), unit: bestUnit };\n}\n","/**\n * UoM Converter, built on the in-house unit tables in `UnitConversion.ts` and\n * `generated/UnitTable.generated.ts` (ported from the `convert` npm package\n * v7.0.2 so the engine ships with no runtime dependencies).\n *\n * Units are strictly case-sensitive and are looked up without aliasing. No unit\n * remapping, what you type is what you get.\n * e.g. 'C' = Celsius, 'c' = cup; 'MB' = megabytes, 'mb' = millibits.\n *\n * This file owns everything the base tables do not: the workday shim, the\n * extended (custom-measure) units, and the two caches.\n */\n\nimport { lookupUnit, convertRaw, convertResolved, convertToBestMetric } from \"@solve-js/uom/UnitConversion\";\nimport { MEASURE_KIND_NAMES, MEASURE_SYMBOLS, UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\nimport { EXTENDED_UNITS } from \"@solve-js/uom/ExtendedUnits\";\n\n// ── \"workday\", a synthetic unit with no entry in the base table ───────────\n//\n// A business day (Mon-Fri) backing the datetime package's `<date> + N\n// workdays` arithmetic and `$X/workday` Rate literals\n// (packages/datetime/). NOT a real physical unit, a business day has no\n// fixed duration, since it depends on which calendar dates are weekends\n// so the ported base table has no concept of it and can't be\n// taught one without monkey-patching its internal unit table.\n//\n// For RATE-MATH purposes only (e.g. \"$500/workday x 4 weeks\" needs a\n// workday count to multiply by), a workday is treated as a FIXED 7/5 of a\n// calendar day: 5 workdays span exactly 7 calendar days in a whole week,\n// so this ratio is exact for whole-week spans and a reasonable linear\n// approximation otherwise. This is deliberately NOT the same\n// calendar-aware, weekend-skipping logic real \"<date> + N workdays\" date\n// arithmetic needs (see vm/VM.ts's addBusinessDays()), that can't be\n// reduced to a fixed ratio, since the exact skip pattern depends on which\n// day of the week the calculation actually starts from.\n//\n// Handled here as a thin pre/post layer in front of the normal\n// base-table path (rather than inside the tables themselves) so every\n// caller of getMeasure()/convertUnit()/canConvert() automatically gets\n// workday support for free.\nconst WORKDAY_UNIT_NAMES = new Set([\"workday\", \"workdays\"]);\nconst WORKDAY_TO_DAY_FACTOR = 7 / 5; // 1 workday == 1.4 calendar days\n\n/** Whether `unit` is the synthetic \"workday\" unit (see module note above). */\nexport function isWorkdayUnit(unit: string | undefined): unit is string {\n return typeof unit === \"string\" && WORKDAY_UNIT_NAMES.has(unit);\n}\n\n/**\n * Validate `unit` against the known unit table.\n *\n * @returns `unit` unchanged in all cases. This does NOT normalize casing\n * or aliasing (units are strictly case-sensitive, see the module note\n * above). A unit the table doesn't recognize is still\n * returned as-is (not thrown), so callers must not assume a returned\n * string is actually convertible, check with {@link isConvertibleUnit}\n * or {@link canConvert} first if that matters.\n *\n * Kept as an identity function purely for API compatibility. It used to guard\n * a validity cache, which existed because validating a unit meant a\n * throw/catch round trip through the old dependency. Validation is now a Map\n * lookup, so the cache cost more than it saved: worse, it was capped at 1000\n * entries against a 1456-unit table, so any sweep over the full vocabulary\n * (which is exactly what LanguageService does to build completions) evicted\n * on almost every call. That one change took the full-table sweep from 7.7ms\n * to under 20us.\n */\nexport function resolveUnit(unit: string): string {\n return unit;\n}\n\n// MEASURE_KIND_NAMES now comes from the generated table (it is derived data,\n// so the generator emits it rather than it being retyped here). The reason it\n// is a module-level constant has not changed: getMeasure() runs at least twice\n// per conversion, and this used to be reallocated on every call.\n\n/**\n * Get the measure/dimension kind for `unit` (e.g. `\"length\"`, `\"mass\"`,\n * `\"temperature\"`), used to check whether two units are even in the same\n * dimension before attempting a conversion.\n *\n * @returns `undefined` if `unit` isn't recognized, rather than throwing.\n */\nexport function getMeasure(unit: string): string | undefined {\n // Workday is a Time-measure unit by convention (see isWorkdayUnit's doc\n // comment) and is not in the base table, so resolve its measure via \"day\"\n // instead of attempting the real lookup below.\n if (isWorkdayUnit(unit)) return getMeasure(\"day\");\n\n // Extended (custom) categories the base table has no measure kind for,\n // see ExtendedUnits.ts.\n const extended = EXTENDED_UNITS[unit];\n if (extended) return extended.measure;\n\n const entry = lookupUnit(unit);\n if (entry === undefined) return undefined;\n\n return MEASURE_KIND_NAMES[entry[0]];\n}\n\n/**\n * Check whether `from` can be converted to `to`. Same unit, or same\n * measure kind (length, mass, ...) and the underlying tables accept the pair.\n * Never throws; returns `false` on any failure.\n */\nexport function canConvert(from: string, to: string): boolean {\n if (from === to) return true;\n if (isWorkdayUnit(from) || isWorkdayUnit(to)) {\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n return !!fromMeasure && fromMeasure === toMeasure;\n }\n // One table read per side, comparing numeric kind ids. The old shape called\n // getMeasure() on each side (two more reads) purely to compare the resulting\n // STRINGS, then did a throwaway conversion to confirm what the kind check had\n // already established.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return fromEntry[0] === toEntry[0];\n }\n\n // Extended (custom) categories aren't in the base table at all, so they are\n // compared on their own measure names instead.\n const fromExtended = EXTENDED_UNITS[from];\n const toExtended = EXTENDED_UNITS[to];\n if (fromExtended !== undefined && toExtended !== undefined) {\n return fromExtended.measure === toExtended.measure;\n }\n\n // Mixed: one side is in the base table and the other is extended. That used\n // to be refused outright, on the grounds that the two measure spaces are\n // disjoint. They are not, once an extended unit names a measure the base\n // table also has: `furlong` is a length and so is `m`, and the ratio between\n // them is exactly what both tables already record.\n return bridgesToBaseMeasure(from, to) || bridgesToBaseMeasure(to, from);\n}\n\n/**\n * Whether `extendedUnit` extends a measure the base table also knows, so a\n * value in it can reach `baseUnit`.\n *\n * The bridge works because both tables express a unit as a ratio to the same\n * physical base: the generated table's length ratios are metres and its mass\n * ratios are grams, and an extended unit declaring `measure: \"length\"` states\n * its `toBase` in the same metres. Composing the two ratios is then ordinary\n * arithmetic rather than a second conversion system.\n *\n * A measure the base table has no concept of, such as pace, still fails here,\n * which is the behaviour this replaced and the reason the check is by measure\n * name rather than by presence in the extended table.\n */\nfunction bridgesToBaseMeasure(extendedUnit: string, baseUnit: string): boolean {\n const extended = EXTENDED_UNITS[extendedUnit];\n if (extended === undefined) return false;\n\n const base = lookupUnit(resolveUnit(baseUnit));\n if (base === undefined) return false;\n\n return MEASURE_KIND_NAMES[base[0]] === extended.measure;\n}\n\n/**\n * Convert `value` from unit `from` to unit `to`.\n *\n * Does not validate that the conversion is possible, callers should check\n * with {@link canConvert} first if `from`/`to` aren't already known-good.\n *\n * THROWS a RangeError for an unknown unit or a cross-measure pair. `VM.ts`'s\n * `extractDurationMs()` depends on that, see {@link convertRaw}.\n *\n * This used to memoize a per-pair conversion factor in an LFU cache. The cache\n * is gone: computing the factor is now two Map reads, while the cache cost a\n * template-string key allocation on every call plus the LFU's own frequency\n * bookkeeping, so it was slower than the work it avoided. Removing it is\n * bit-exact, not merely close: the cache stored `convertRaw(1, f, t)`, which is\n * exactly `fromRatio / toRatio`, and then multiplied, which is the identical\n * expression `convertRaw(value, f, t)` evaluates. It also deleted the special\n * case that existed only to keep offset-based temperature pairs out of a\n * factor cache.\n */\nexport function convertUnit(value: number, from: string, to: string): number {\n if (from === to) return value;\n\n // Fast path first: two ordinary units, which is nearly every call. Resolving\n // both here and handing the entries to convertResolved() avoids looking them\n // up again inside convertRaw(). Neither workdays nor extended units appear in\n // the base table, so they always fall through to the branches below and this\n // ordering cannot steal a case from them. UnitVocabulary.spec.ts pins that\n // the two vocabularies stay disjoint.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return convertResolved(value, from, to, fromEntry, toEntry);\n }\n\n // Workday <-> any other Time-measure unit: pivot through \"day\" using the\n // fixed 7/5 ratio (see isWorkdayUnit's doc comment above).\n if (isWorkdayUnit(from) && isWorkdayUnit(to)) return value; // \"workday\" <-> \"workdays\" alias\n if (isWorkdayUnit(from)) {\n const days = value * WORKDAY_TO_DAY_FACTOR;\n return to === \"day\" ? days : convertUnit(days, \"day\", to);\n }\n if (isWorkdayUnit(to)) {\n const days = from === \"day\" ? value : convertUnit(value, from, \"day\");\n return days / WORKDAY_TO_DAY_FACTOR;\n }\n\n // Extended (custom) categories the base table has no measure kind for\n // (see ExtendedUnits.ts), compute the ratio directly from each unit's\n // factor-to-base value instead of calling convertRaw(), which would throw\n // on an unrecognized unit string. Every extended category is a pure linear\n // ratio scale (no Temperature-style offset), so the ratio itself is safe.\n //\n // The measures still have to match, and this is the one place that used to\n // forget it. `mpg` is distance over volume and `l100km` is volume over\n // distance, so they are different measures and `canConvert` says false, but\n // both are extended units, so this branch happily multiplied their ratios\n // and answered 1,488 for 35 mpg. A number with no meaning is worse than a\n // refusal: a first version of the travel package's trip arithmetic was built\n // on that one and had a 300-mile drive burning seven thousand litres.\n // Reciprocal pairs like those two are what `convertRate` is for.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\n if (fExt.measure !== tExt.measure) {\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n return value * (fExt.toBase / tExt.toBase);\n }\n\n // One side extended, the other in the base table, sharing a measure. Convert\n // through the measure's base unit, which both tables state their ratios\n // against: an extended length declares its `toBase` in metres, and the\n // generated table's length ratios are metres too.\n if (fExt !== undefined && bridgesToBaseMeasure(from, to)) {\n return convertRaw(value * fExt.toBase, baseUnitFor(to), to);\n }\n if (tExt !== undefined && bridgesToBaseMeasure(to, from)) {\n return convertRaw(value, from, baseUnitFor(from)) / tExt.toBase;\n }\n\n // Offsets, cross-measure rejection and the unknown-unit throw all live in\n // convertRaw. Nothing is layered on top here any more.\n return convertRaw(value, from, to);\n}\n\n/**\n * The unit a measure states its ratios against, found from any unit in it.\n *\n * Read out of the table rather than hard-coded, so it cannot drift from the\n * ratios it has to agree with: the base is whichever unit of that measure has\n * a ratio of exactly one.\n */\nfunction baseUnitFor(unit: string): string {\n const entry = lookupUnit(resolveUnit(unit));\n if (entry === undefined) return unit;\n\n for (const symbol of Object.keys(UNIT_TABLE)) {\n const candidate = UNIT_TABLE[symbol];\n if (candidate[0] === entry[0] && candidate[1] === 1) return symbol;\n }\n return unit;\n}\n\n/**\n * List every unit symbol in the same measure/dimension as `unit` (wiki:\n * Units-Of-Measurement, \"Conversion Possibilities\", `sourceUnit to ?`\n * e.g. `cm to ?\"` → every Length unit). Excludes `unit` itself.\n *\n * Reads MEASURE_SYMBOLS, which is a curated symbols-only vocabulary and\n * deliberately NOT the keys of the unit table filtered by kind. The two\n * differ: Volume's symbols include `c` and `pt` but not `cup`/`cups`, and\n * Time's include `wk` and `mo` but not `week`/`month`. Deriving this list\n * from the unit table instead would roughly quadruple every answer.\n *\n * @returns `[]` if `unit` isn't recognized, rather than throwing.\n */\nexport function getConvertiblePossibilities(unit: string): string[] {\n const resolved = resolveUnit(unit);\n const entry = lookupUnit(resolved);\n if (entry === undefined) return [];\n const symbols = MEASURE_SYMBOLS[entry[0]];\n if (!symbols) return [];\n return symbols.filter((s) => s !== resolved);\n}\n\n/** Check whether `unit` is a unit the conversion tables recognize. Never throws. */\nexport function isConvertibleUnit(unit: string): boolean {\n if (isWorkdayUnit(unit)) return true;\n if (EXTENDED_UNITS[unit]) return true;\n return lookupUnit(resolveUnit(unit)) !== undefined;\n}\n\n/**\n * Convert `value` (in `unit`) to whichever unit of the same measure gives\n * the most human-readable magnitude, e.g. 1500 metres becomes 1.5 km. Falls\n * back to returning `value`/`unit` unchanged if `unit` isn't recognized,\n * which is what every extended unit and workday does.\n *\n * Note the chosen unit is drawn from the best-unit lists, which are not\n * restricted to spellings the lexer accepts: 0.5 l reports \"mL\".\n */\nexport function getBestUnit(value: number, unit: string): { value: number; unit: string } {\n const u = resolveUnit(unit);\n try {\n const result = convertToBestMetric(value, u);\n return { value: result.quantity, unit: result.unit };\n } catch {\n return { value, unit: u };\n }\n}\n\n// ── Rate and derived-unit conversion ───────────────────────────────────────\n//\n// A rate value carries a compound unit spelled \"numerator/denominator\" (e.g.\n// \"km/h\", \"m/s\"), see vm/Value.ts's rateValue(). Plain convertUnit() cannot\n// touch one, because neither half is the whole unit and getMeasure(\"km/h\") is\n// undefined. This section converts a rate to another rate, and bridges a rate\n// to the single-token speed spellings (mph, kph, mps, ...) that ExtendedUnits.ts\n// already carries, so \"100 km/h in mph\" and \"60 mph in km/h\" resolve instead of\n// reporting incompatible units.\n\n/** A rate reduced to a numerator unit over a denominator unit. */\ninterface RateForm {\n /** Magnitude, scaled so `value numerator/denominator` is the physical quantity. */\n value: number;\n /** Numerator unit spelling, or `\"\"` for a countless rate such as `30/week`. */\n numerator: string;\n /** Denominator unit spelling. */\n denominator: string;\n}\n\n/**\n * Express `value unit` as a numerator/denominator rate, or `null` when `unit`\n * is neither a compound rate spelling nor a single-token speed alias.\n *\n * A speed alias (mph, kph, ...) is one unit standing for a length/time rate, so\n * it expands to the base pair `m`/`s` with its value scaled by the alias's\n * metres-per-second factor. That collapses both inputs to one shape, so a\n * single routine handles rate/rate and rate/alias without a second code path.\n */\n/**\n * The single-token fuel-economy units, each as the `numerator/denominator` rate\n * it stands for and the factor that turns one of it into that rate's base. `mpg`\n * is `km/l` scaled, `l/100km` is `l/km` scaled by a hundredth (issue #190).\n */\nconst FUEL_RATE_UNITS: Record<string, { numerator: string; denominator: string; factor: number }> = {\n mpg: { numerator: \"km\", denominator: \"l\", factor: 1.609344 / 3.785411784 },\n kmpl: { numerator: \"km\", denominator: \"l\", factor: 1 },\n l100km: { numerator: \"l\", denominator: \"km\", factor: 0.01 },\n};\n\nfunction expandUnitToRate(value: number, unit: string): RateForm | null {\n const fuel = FUEL_RATE_UNITS[unit];\n if (fuel !== undefined) {\n return { value: value * fuel.factor, numerator: fuel.numerator, denominator: fuel.denominator };\n }\n const slash = unit.indexOf(\"/\");\n if (slash >= 0) {\n return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };\n }\n const ext = EXTENDED_UNITS[unit];\n if (ext !== undefined && ext.measure === \"speed\") {\n // 1 alias == ext.toBase m/s, so `value alias` is `value * toBase` m/s.\n return { value: value * ext.toBase, numerator: \"m\", denominator: \"s\" };\n }\n if (ext !== undefined && ext.measure === \"dataRate\") {\n // 1 alias == ext.toBase bits/s, so `value alias` is `value * toBase` b/s.\n return { value: value * ext.toBase, numerator: \"b\", denominator: \"s\" };\n }\n return null;\n}\n\n/**\n * Whether `unit` is a *physical* rate over time, one whose numerator is a length\n * or a data size, so `<quantity> at <unit>` means dividing that quantity by the\n * rate to get a duration: `250 miles at 60 mph`, `4 GB at 50 Mbps`.\n *\n * Deliberately NOT true for a price rate like `$/hour`: those are handled by the\n * existing at-rate builtin, which multiplies or divides against the currency,\n * and must keep their own answer (`$500 at $20/hour` is `25 hours`, formatted\n * that way). The numerator-measure check is what tells the two apart.\n */\nexport function isPhysicalTimeRate(unit: string | undefined): boolean {\n if (unit === undefined) return false;\n const rate = expandUnitToRate(1, unit);\n if (rate === null || getMeasure(rate.denominator) !== \"time\") return false;\n const numeratorMeasure = getMeasure(rate.numerator);\n return numeratorMeasure === \"length\" || numeratorMeasure === \"data\";\n}\n\n/**\n * `<quantity> at <rate>` where `rate` is a {@link isPhysicalTimeRate}, in\n * seconds. The quantity's measure must match the rate's numerator (a distance at\n * a speed, a data size at a bandwidth); otherwise the pair does not line up and\n * this returns null for the caller to report.\n */\nexport function quantityAtRateSeconds(\n quantity: number,\n quantityUnit: string,\n rateValue: number,\n rateUnit: string,\n): number | null {\n const rate = expandUnitToRate(rateValue, rateUnit);\n if (rate === null || getMeasure(rate.denominator) !== \"time\") return null;\n if (getMeasure(quantityUnit) !== getMeasure(rate.numerator)) return null;\n const quantityInNumerator = convertUnit(quantity, quantityUnit, rate.numerator);\n const timeInDenominator = quantityInNumerator / rate.value;\n return convertUnit(timeInDenominator, rate.denominator, \"s\");\n}\n\n/**\n * The factor that turns one `from` into `to` along a single rate axis, or\n * `null` when the two cannot line up.\n *\n * Same spelling needs no conversion. A countless axis (`\"\"`) only lines up with\n * another countless one, never with a real unit. Otherwise both sides must name\n * the same measure, which is what keeps a length numerator from pairing with a\n * mass one.\n */\nfunction rateAxisFactor(from: string, to: string): number | null {\n if (from === to) return 1;\n if (from === \"\" || to === \"\") return null;\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n if (fromMeasure === undefined || toMeasure === undefined || fromMeasure !== toMeasure) {\n return null;\n }\n return convertUnit(1, from, to);\n}\n\n/**\n * Convert `value` from a rate/speed unit `from` to a rate/speed unit `to`,\n * returning the converted magnitude, or `null` when the pair is not\n * rate-convertible (so the caller falls back to its own incompatible-units\n * handling).\n *\n * Handles rate to rate (`10 m/s in km/h`), rate to speed alias\n * (`100 km/h in mph`) and speed alias to rate (`60 mph in km/h`). Plain\n * same-measure pairs (`kph in mph`, `km in miles`) never reach here, they are\n * resolved by {@link convertUnit} first.\n *\n * The rule is the ordinary one for a quotient of quantities: convert the\n * numerator and the denominator each on their own, so `A/B -> C/D` scales by\n * `(A->C) / (B->D)`.\n */\nexport function convertRate(value: number, from: string, to: string): number | null {\n const source = expandUnitToRate(value, from);\n if (source === null) return null;\n\n // The target is either a rate spelling or a single-token speed alias. An\n // alias expands to the base m/s pair, and `targetScale` is what the base-form\n // magnitude is divided by to read out in the alias itself.\n let targetNumerator: string;\n let targetDenominator: string;\n let targetScale: number;\n const fuelTarget = FUEL_RATE_UNITS[to];\n const slash = to.indexOf(\"/\");\n if (fuelTarget !== undefined) {\n // The base-pair magnitude divided by the fuel unit's own factor reads out in\n // that unit (so a l/km magnitude becomes a l/100km figure).\n targetNumerator = fuelTarget.numerator;\n targetDenominator = fuelTarget.denominator;\n targetScale = fuelTarget.factor;\n } else if (slash >= 0) {\n targetNumerator = to.slice(0, slash);\n targetDenominator = to.slice(slash + 1);\n targetScale = 1;\n } else {\n const ext = EXTENDED_UNITS[to];\n if (ext === undefined || ext.measure !== \"speed\") return null;\n targetNumerator = \"m\";\n targetDenominator = \"s\";\n targetScale = ext.toBase;\n }\n\n const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);\n const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);\n if (numeratorFactor !== null && denominatorFactor !== null) {\n return (source.value * numeratorFactor) / denominatorFactor / targetScale;\n }\n\n // A reciprocal pairing: distance-per-volume against volume-per-distance, the\n // fuel-economy case (miles per gallon to litres per kilometre). The two rates\n // measure the same thing upside down, so the source's numerator lines up with\n // the target's denominator and its denominator with the target's numerator,\n // and the magnitude is inverted. `40 miles/gallon` becomes `0.0588 l/km`:\n // one over forty, scaled gallon-to-litre over mile-to-kilometre. See issue\n // #190; this is why fuel economy needs its own route and is not a rescale of\n // each axis like `mph` to `km/h`.\n const crossNumerator = rateAxisFactor(source.denominator, targetNumerator);\n const crossDenominator = rateAxisFactor(source.numerator, targetDenominator);\n if (crossNumerator !== null && crossDenominator !== null && source.value !== 0) {\n return (crossNumerator / crossDenominator / source.value) / targetScale;\n }\n\n return null;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import {b as b$3,a as a$5}from'./chunk-CB3EXUM2.js';import {a as a$3}from'./chunk-IJHL3LMH.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d as d$1,a as a$2,b,c as c$5}from'./chunk-2PGGPFF3.js';import {a as a$4,b as b$4,c as c$8}from'./chunk-JP4JMQOG.js';import {c as c$a,a as a$a}from'./chunk-IQVSCL2R.js';import {h as h$1,t,p,o,n as n$1,l,i,m,k,b as b$9,q,s as s$1,g,r as r$1,j as j$1}from'./chunk-FXB5GCBT.js';import {d as d$2}from'./chunk-VLX7ZVK4.js';import {c as c$3,d as d$3,b as b$8}from'./chunk-B2NL65FI.js';import {b as b$7}from'./chunk-76F3LCIL.js';import {c as c$6,a as a$7,b as b$b}from'./chunk-TCZSPH4A.js';import {K as K$1,x,F as F$1,H,I,i as i$1}from'./chunk-YN5H54GM.js';import {_,da}from'./chunk-KH4QXKLT.js';import {b as b$5}from'./chunk-NQFCXLEF.js';import {P,n,O,t as t$1,l as l$1,L,u,N,M,s,r,m as m$1,g as g$1}from'./chunk-X5K72MBV.js';import {a as a$1,c as c$2,b as b$1}from'./chunk-64OGL465.js';import {c as c$1,b as b$2}from'./chunk-CDE2ZUGG.js';import {b as b$6,c as c$7}from'./chunk-JPFCXLJV.js';import {c as c$4,a as a$8}from'./chunk-LP3JYC3A.js';import {a,c as c$9}from'./chunk-FAO6DQ74.js';import {a as a$9}from'./chunk-LHLW7JLS.js';import {c,d,b as b$a}from'./chunk-RELMEWY6.js';function jt(r,e,t,n,i){let s=t[e],o=n[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let l of Object.keys(o))c.has(l)&&i.push({kind:r,severity:"warning",detail:`Both "${t.name}" and "${n.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,n.name]});}function Wt(r,e){let t=[];if(jt("prefixParseletTokenType","prefixParselets",r,e,t),jt("infixParseletTokenType","infixParselets",r,e,t),r.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=r.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[r.name,e.name]});}if(r.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(r.asConverters).some(c=>c.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[r.name,e.name]});}if(r.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(r.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[r.name,e.name]});}if(r.normalizerRules&&e.normalizerRules){let s=new Set(r.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[r.name,e.name]});}let n=r.lexerVocabulary,i=e.lexerVocabulary;if(n?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let c=n.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[r.name,e.name]});}if(n?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=n.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[r.name,e.name]});}if(r.asyncResolvers&&e.asyncResolvers){let s=new Set(r.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${r.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[r.name,e.name]});}if(r.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let c=r.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[r.name,e.name]});}return t}function Jr(r,e){let t=[];for(let n of e)n===r||n.name===r.name||t.push(...Wt(n,r));return {compatible:!t.some(n=>n.severity==="error"),conflicts:t}}var ve=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,n=(s,o)=>{let c=s.get(o);c&&c!==e&&c.name!==e.name&&t.add(c);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))n(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))n(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))n(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))n(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))n(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)n(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))n(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))n(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)n(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))n(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Wt(s,e));return i}add(e){let t=(n,i)=>{n.has(i)||n.set(i,e);};if(e.prefixParselets)for(let n of Object.keys(e.prefixParselets))t(this.prefixOwners,n);if(e.infixParselets)for(let n of Object.keys(e.infixParselets))t(this.infixOwners,n);if(e.phrases)for(let n of Object.keys(e.phrases))t(this.phraseOwners,n);if(e.asConverters)for(let n of Object.keys(e.asConverters))t(this.converterOwners,n.toLowerCase());if(e.pluginFunctions)for(let n of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,n);if(e.normalizerRules)for(let n of e.normalizerRules)t(this.ruleOwners,n.name);if(e.lexerVocabulary?.keywords)for(let n of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,n);if(e.lexerVocabulary?.operators)for(let n of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,n);if(e.asyncResolvers)for(let n of e.asyncResolvers)t(this.resolverOwners,n.namespace);if(e.tokenCategories)for(let n of Object.keys(e.tokenCategories))t(this.categoryOwners,n);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Cr=/(\d+)\.(\d+)\.(\d+)/,Tr=/^\d+$/;function Ht(r){let e=Cr.exec(r.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Nr(r,e){return r[0]-e[0]||r[1]-e[1]||r[2]-e[2]}function De(r){let e=r.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let n=0;n<e.length;n++){if(!Tr.test(e[n]))return null;t[n]=Number(e[n]);}return [t[0],t[1],t[2]]}function wr([r,e,t]){let n=r>0?[r+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[r,e,t]},{op:"<",v:n}]}function Rr([r,e,t]){return [{op:">=",v:[r,e,t]},{op:"<",v:[r,e+1,0]}]}function Ar(r){if(r===""||r==="*"||r==="x"||r==="X")return [];if(r[0]==="^"){let i=De(r.slice(1));return i&&wr(i)}if(r[0]==="~"){let i=De(r.slice(1));return i&&Rr(i)}let e=/^(>=|<=|>|<|=)/.exec(r),t=e?e[1]:"=",n=De(e?r.slice(e[1].length):r);return n&&[{op:t,v:n}]}function Kt(r){let e=[];for(let t of r.split("||")){let n=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of n){let o=Ar(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Gt(r){return Kt(r.trim())!==null}function Pr(r,e){let t=Nr(r,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function qt(r,e){let t=Kt(e.trim());return t===null?false:t.some(n=>n.every(i=>Pr(r,i)))}function Or(r,e=a$1){if(!r.engineVersion)return {compatible:true};if(!Gt(r.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:r.engineVersion,engineVersion:e};let t=Ht(e);return t===null||!qt(t,r.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:r.engineVersion,engineVersion:e}:{compatible:true}}function Qt(r,e=a$1){let t=Or(r,e);if(!t.compatible)throw t.reason==="invalid-range"?c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${r.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${r.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:r.name,declaredRange:t.declaredRange}}):c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${r.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${r.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:r.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function $(r){return Number.isFinite(r)?r:Number.isNaN(r)?"NaN":r>0?"Infinity":"-Infinity"}function F(r){if(typeof r=="number")return r;if(r==="NaN")return NaN;if(r==="Infinity")return 1/0;if(r==="-Infinity")return -1/0;throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(r)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(r)})}var V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Yt(r){return {coef:r.coef.toString(),scale:r.scale}}function Xt(r){return {coef:BigInt(r.coef),scale:r.scale}}function Lr(r){return {n:r.n.toString(),d:r.d.toString()}}function Ir(r){return {n:BigInt(r.n),d:BigInt(r.d)}}function Jt(r){return g$1[r]??String(r)}function Ve(r,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Jt(r)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Jt(r)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:r,location:e}})}function Me(r,e){switch(r.type){case 0:{let t={t:0,v:$(r.value)};return r.exact!==void 0&&(t.exact=Yt(r.exact)),r.rational!==void 0&&(t.rational=Lr(r.rational)),t}case 1:{let t=r.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:r.unit}:{t:1,v:$(t),base:r.unit}}case 2:return {t:2,v:r.value.toString()};case 3:return {t:3,v:r.value};case 4:{let t={t:4,v:$(r.value)};return r.grain!==void 0&&(t.g=r.grain),r.zone!==void 0&&(t.z=r.zone),t}case 5:return {t:5,v:$(r.value)};case 6:{let t={t:6,v:$(r.value),unit:r.unit??""};return r.exact!==void 0&&(t.exact=Yt(r.exact)),t}case 7:{let t=r.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let n=t.data.map(i=>Dr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:n}}case 8:{let t=r.value;return {t:8,min:$(t.min),max:$(t.max)}}case 10:return {t:10,v:r.value};case 13:return {t:13,code:r.value,message:r.unit??""};default:return Ve(r.type,e)}}function Dr(r,e){return typeof r=="boolean"?r:typeof r=="number"?$(r):Ve(9,`${e} (symbolic matrix cell)`)}function Be(r){switch(r.t){case 0:{let e=new m$1(0,F(r.v));return r.exact!==void 0&&(e.exact=Xt(r.exact)),r.rational!==void 0&&(e.rational=Ir(r.rational)),e}case 1:{let e=r.big?BigInt(r.v):F(r.v);return new m$1(1,e,r.base)}case 2:return new m$1(2,BigInt(r.v));case 3:return new m$1(3,r.v);case 4:{let e=new m$1(4,F(r.v));return r.g!==void 0&&(e.grain=r.g),r.z!==void 0&&(e.zone=r.z),e}case 5:return new m$1(5,F(r.v));case 6:{let e=new m$1(6,F(r.v),r.unit);return r.exact!==void 0&&(e.exact=Xt(r.exact)),e}case 7:{let e=r.data.map(n=>typeof n=="boolean"?n:F(n)),t={rows:r.rows,cols:r.cols,data:e,hasSymbolic:false};return new m$1(7,t)}case 8:return new m$1(8,{min:F(r.min),max:F(r.max)});case 10:return new m$1(10,r.v);case 13:return new m$1(13,r.code,r.message);default:throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(r.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(r.t)})}}function ue(r){let e={opcodes:Array.from(r.opcodes),numbers:Array.from(r.numbers,$),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=Array.from(r.constants.entries())),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(Ue)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(r){let e={opcodes:Uint8Array.from(r.opcodes),numbers:Float64Array.from(r.numbers,F),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=new Map(r.constants)),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(_e)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function Ue(r){return {name:r.name,params:r.params.slice(),program:ue(r.program)}}function _e(r){return {name:r.name,params:r.params.slice(),program:pe(r.program)}}function rr(r){if(typeof r!="object"||r===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:r===null?"null":typeof r});let e=r;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Br(r);}var Zt=32;function Vr(r){return r===null?"null":Array.isArray(r)?`an array of ${r.length}`:typeof r=="object"?"an object":`${typeof r} ${JSON.stringify(r)}`.slice(0,80)}function h(r,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${r}: expected ${e}.`,expected:e,found:Vr(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:r}})}function j(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function z(r){return typeof r=="number"||r==="NaN"||r==="Infinity"||r==="-Infinity"}function ce(r){return typeof r=="string"&&/^-?\d+$/.test(r)}function be(r,e){(!Array.isArray(r)||!r.every(t=>typeof t=="string"))&&h(e,"an array of strings",r);}function er(r,e){(!j(r)||!ce(r.coef)||typeof r.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",r);}function Mr(r,e){(!j(r)||!ce(r.n)||!ce(r.d))&&h(e,"a rational as { n: digits, d: digits }",r);}function tr(r,e){switch(j(r)||h(e,"a serialised value object",r),r.t){case 0:z(r.v)||h(`${e}.v`,"a number",r.v),r.exact!==void 0&&er(r.exact,`${e}.exact`),r.rational!==void 0&&Mr(r.rational,`${e}.rational`);return;case 1:(r.big?!ce(r.v):!z(r.v))&&h(`${e}.v`,r.big?"an integer string":"a number",r.v),r.base!==void 0&&typeof r.base!="string"&&h(`${e}.base`,"a base name",r.base);return;case 2:ce(r.v)||h(`${e}.v`,"an integer string",r.v);return;case 3:typeof r.v!="string"&&h(`${e}.v`,"a string",r.v);return;case 4:z(r.v)||h(`${e}.v`,"a number",r.v),r.g!==void 0&&r.g!=="date"&&r.g!=="datetime"&&r.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',r.g),r.z!==void 0&&typeof r.z!="string"&&h(`${e}.z`,"a zone reference",r.z);return;case 5:z(r.v)||h(`${e}.v`,"a number",r.v);return;case 6:z(r.v)||h(`${e}.v`,"a number",r.v),typeof r.unit!="string"&&h(`${e}.unit`,"a unit name",r.unit),r.exact!==void 0&&er(r.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:n,data:i}=r;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(n)||n<0)&&h(`${e}.cols`,"a non-negative integer",n),(!Array.isArray(i)||i.length!==t*n)&&h(`${e}.data`,`an array of ${t} \xD7 ${n} cells`,i),i.every(s=>typeof s=="boolean"||z(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!z(r.min)||!z(r.max))&&h(e,"a range with numeric min and max",r);return;case 10:typeof r.v!="boolean"&&h(`${e}.v`,"a boolean",r.v);return;case 13:(typeof r.code!="string"||typeof r.message!="string")&&h(e,"an error with a string code and message",r);return;default:return}}function Ee(r,e,t){if(t>Zt&&h(e,`function bodies nested at most ${Zt} deep`,"deeper nesting"),j(r)||h(e,"a serialised program object",r),(!Array.isArray(r.opcodes)||!r.opcodes.every(n=>Number.isInteger(n)&&n>=0&&n<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",r.opcodes),(!Array.isArray(r.numbers)||!r.numbers.every(z))&&h(`${e}.numbers`,"an array of numbers",r.numbers),be(r.strings,`${e}.strings`),typeof r.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",r.hasAsync),r.constants!==void 0){let n=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(r.constants)||!r.constants.every(n))&&h(`${e}.constants`,"an array of [number, number] pairs",r.constants);}r.userFunctionBodies!==void 0&&(Array.isArray(r.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",r.userFunctionBodies),r.userFunctionBodies.forEach((n,i)=>nr(n,`${e}.userFunctionBodies[${i}]`,t+1))),r.anonymousBodies!==void 0&&(Array.isArray(r.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",r.anonymousBodies),r.anonymousBodies.forEach((n,i)=>{let s=`${e}.anonymousBodies[${i}]`;j(n)||h(s,"a body object",n),be(n.params,`${s}.params`),Ee(n.program,`${s}.program`,t+1);}));}function nr(r,e,t){j(r)||h(e,"a function object",r),typeof r.name!="string"&&h(`${e}.name`,"a function name",r.name),be(r.params,`${e}.params`),Ee(r.program,`${e}.program`,t);}function Br(r){r.locale!==void 0&&typeof r.locale!="string"&&h("locale","a locale code",r.locale),j(r.variables)||h("variables","an object of values by name",r.variables);for(let[e,t]of Object.entries(r.variables))tr(t,`variables.${e}`);Array.isArray(r.userFunctions)||h("userFunctions","an array of functions",r.userFunctions),r.userFunctions.forEach((e,t)=>nr(e,`userFunctions[${t}]`,1)),Array.isArray(r.lineCache)||h("lineCache","an array of cached lines",r.lineCache),r.lineCache.forEach((e,t)=>{let n=`lineCache[${t}]`;j(e)||h(n,"a cached line",e),Number.isInteger(e.line)||h(`${n}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${n}.expression`,"the line's expression text",e.expression),tr(e.result,`${n}.result`),Ee(e.bytecode,`${n}.bytecode`,1),be(e.reads,`${n}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${n}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(r.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",r.bytecodeCache),r.bytecodeCache.forEach((e,t)=>{let n=`bytecodeCache[${t}]`;(!j(e)||typeof e.expression!="string")&&h(n,"an { expression, program } pair",e),Ee(e.program,`${n}.program`,1);});}var ir=null;function cn(r){ir=r;}function Fe(){return ir}var sr=3e4,or=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=Fe();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let n=[];for(let l of e){let a=t.get(l);if(!a||a.bytecode.opcodes.length===0)continue;let u=a.bytecode.opcodes,p=a.bytecode.numbers,f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),m=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);n.push({lineNumber:l,opcodesBuffer:f,numbersBuffer:m,opcodesLength:u.length,numbersLength:p.length,strings:[...a.bytecode.strings]});}if(n.length===0)return Promise.resolve([]);let i=[];for(let l of n)l.opcodesBuffer.byteLength>0&&i.push(l.opcodesBuffer),l.numbersBuffer.byteLength>0&&i.push(l.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),c=this.workers[o];return new Promise(l=>{let a=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${sr/1e3} seconds; the worker was replaced`);},sr);this.pendingBatches.set(s,{id:s,lineNumbers:n.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(a),l(u);}}),c.postMessage({type:"EXECUTE_BATCH",id:s,items:n},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++)this.spawnWorker(e);}spawnWorker(e){let t=Fe();if(t===null)return;let n=t();n.onmessage=i=>{this.handleWorkerMessage(i.data);},n.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=n;}failWorker(e,t,n){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Ur(s.lineNumbers,t,n)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Ur(r,e,t){return r.map(n=>({lineNumber:n,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function ar(r$1){switch(r$1.valueType){case 0:return n(r$1.value);case 1:return r(r$1.value);case 2:return s(BigInt(r$1.value));case 3:return t$1(String(r$1.value));case 4:return M(r$1.value);case 5:return N(r$1.value);case 6:return u(r$1.value,r$1.unit??"");case 7:return n(r$1.value);case 10:return L(r$1.value!==0);case 12:return O(r$1.queryKey??"");case 13:return P(r$1.errorCode??"WORKER_EXECUTION_ERROR",r$1.unit??"Unknown worker error");default:return n(r$1.value)}}var Se=class Se{constructor(e,t,n,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=n,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let n=d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${n.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let a of e){let u=`${a.packageId}:${a.queryKey}`;t.set(u,a);}let n=[],i=[];for(let a of t.values())a.isError?n.push(a):i.push(a);for(let a of n)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let s=new Set,o=[],c=[...i,...n];for(let a of c){if(a.signal.aborted)continue;o.push(a.queryKey);let u=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>or){let a=new Map;for(let u of l)a.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,a,o).catch(u=>{let p=d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,n=new Map,i=new Map;for(let c of e)t.set(c,0),n.set(c,[]);for(let c of e){let l=this.dag.getWrites(c);for(let a of l)i.set(a,c);}for(let c of e){let l=this.dag.getDependencies(c);for(let a of l){let u=i.get(a);u!==void 0&&u!==c&&(n.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,l]of t)l===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,l)=>c-l);let o=[];for(;s.length>0;){let c=s.shift();o.push(c);for(let l of n.get(c)??[]){let a=(t.get(l)??1)-1;t.set(l,a),a===0&&s.push(l);}}if(o.length<e.length){let c=e.filter(l=>!o.includes(l)).sort((l,a)=>l-a);o.push(...c);}return o}async reExecuteViaWorkerPool(e,t,n){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,n,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let c of s){let l=t.get(c.lineNumber);if(!l||c.isPending)continue;let a=ar(c);l.result=a,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,a),o.push(c.lineNumber);}this.cleared||(o.length>0||n.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:n});}reExecuteMainThread(e,t,n){let i=[];for(let s of e){let o=n?n.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.vm.getStack().length;try{let l=d$1(o.bytecode,this.vm,void 0,void 0,{lineIndex:s,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>c;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let a=P(l.error.code,l.error.message);o.result=a,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,a),i.push(s);}}catch(l){for(;this.vm.getStack().length>c;)this.vm.pop();let a=d(l),u=P(a.code,a.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var ke=Se;function ze(r,e){if(r.length>e.maxExpressionLength){let t=c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${r.length})`,{expressionLength:r.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function $e(r,e){let t=0,n=0,i=0;for(let o of r)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(n++,i=Math.max(i,n)),(o.value===")"||o.type==="RPAREN")&&n--;let s=r.length+t*5+i*10;if(s>e.maxComplexity){let o=c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function de(r){return r.type==="IDENT"||r.type==="UNIT"}function _r(r){return r.type==="NUMBER"||r.type==="TO"||r.type==="IN"||r.type==="RPAREN"}function lr(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n].type==="LPAREN")t++;else if(r[n].type==="RPAREN"&&(t--,t===0))return n;return null}function Fr(r){let e=new Set;for(let t=0;t<r.length;t++){if(!de(r[t])||t>0&&r[t-1].type==="COLON"||r[t+1]?.type!=="LPAREN")continue;let n=lr(r,t+1);if(n!==null&&r[n+1]?.type==="EQUALS")for(let i=t+2;i<n;i++)de(r[i])&&e.add(r[i].value);}return e}function Ce(r){let e=[],t=[],n=Fr(r);for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="GLOBAL"){if(i+2<r.length&&r[i+1].type==="COLON"&&de(r[i+2])){let o=K$1(r[i+2].value);e.push(o),i+3<r.length&&r[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&r[i-1].type==="GLOBAL")continue;if(i+1<r.length&&de(r[i+1])){let o=r[i+1].value;e.push(o),i+2<r.length&&r[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&r[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&_r(r[i-1])||n.has(s.value))continue;if(r[i+1]?.type==="LPAREN"){let c=lr(r,i+1);if(c!==null&&r[c+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=r[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Cn(r){return c$1.classifyLine(r).skip}function Tn(r,e){return c$1.findInlineSolves(r).map(n=>({start:n.start,end:n.end,expression:n.expression,lineNumber:e,columnNumber:n.columnNumber}))}var K=class{constructor(e,t,n,i){this.result=e;this.bytecode=t;this.readVariables=n;this.writeVariable=i;}},Te=class r{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(r.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let n of t.values())return n}set(e,t,n){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=r.exprKey(n);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(r.exprKey(t))??false}remove(e,t){let n=this.byLine.get(e);n&&n.delete(r.exprKey(t))&&(this.count--,n.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,n]of this.byLine)for(let[i,s]of n)e(r.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,n]of this.byLine)for(let[i,s]of n)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,n]of this.byLine)for(let i of n.keys())e.push(r.displayKey(t,i));return e}};function je(r,e){let t=e.fields(r),n=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${n}-${i}`}function zr(r,e){if(r instanceof Date)return je(r.getTime(),e);if(typeof r=="number")return Number.isFinite(r)?je(r,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(r.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function cr(r,e){if(r===void 0)return;if(typeof r=="function")return n=>r(new Date(n));let t=new Set;for(let n of r){let i=zr(n,e);i!==null&&t.add(i);}return n=>t.has(je(n,e))}function $r(r,e){if(!r||r.type!==e.type||r.value!==e.value)return true;let t=r.unit,n=e.unit;return t!==n}var Ne=class r{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=r.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let n=setInterval(()=>{this.tick(t);},e.intervalMs);n.unref?.(),this.entries.set(t,{...e,timer:n,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let n=await t.refetch(),i=this.entries.get(e);if(!i)return;n&&$r(i.lastValue,n)&&(i.lastValue=n,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let n=this.entries.get(e);n&&(n.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,n){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),c=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,a=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:a,...n};return {result:o,alloc:p}}static generateReport(e,t){let n=[];n.push(t?`## ${t}`:"## Pipeline Allocation Report"),n.push(""),n.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),n.push("");let i=this.aggregate(e);if(i.length===0)return n.push("_No telemetry data._"),n.join(`
1
+ import {b as b$3,a as a$5}from'./chunk-CB3EXUM2.js';import {a as a$3}from'./chunk-IJHL3LMH.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d as d$1,a as a$2,b,c as c$5}from'./chunk-AF6NDOIE.js';import {a as a$4,b as b$4,c as c$8}from'./chunk-JP4JMQOG.js';import {c as c$a,a as a$a}from'./chunk-IQVSCL2R.js';import {h as h$1,t,p,o,n as n$1,l,i,m,k,b as b$9,q,s as s$1,g,r as r$1,j as j$1}from'./chunk-FXB5GCBT.js';import {d as d$2}from'./chunk-VLX7ZVK4.js';import {c as c$3,d as d$3,b as b$8}from'./chunk-B2NL65FI.js';import {b as b$7}from'./chunk-76F3LCIL.js';import {c as c$6,a as a$7,b as b$b}from'./chunk-TCZSPH4A.js';import {K as K$1,x,F as F$1,H,I,i as i$1}from'./chunk-OE2DBN4K.js';import {_,da}from'./chunk-KH4QXKLT.js';import {b as b$5}from'./chunk-NQFCXLEF.js';import {P,n,O,t as t$1,l as l$1,L,u,N,M,s,r,m as m$1,g as g$1}from'./chunk-X5K72MBV.js';import {a as a$1,c as c$2,b as b$1}from'./chunk-TP5EQCGH.js';import {c as c$1,b as b$2}from'./chunk-CDE2ZUGG.js';import {b as b$6,c as c$7}from'./chunk-JPFCXLJV.js';import {c as c$4,a as a$8}from'./chunk-LP3JYC3A.js';import {a,c as c$9}from'./chunk-FAO6DQ74.js';import {a as a$9}from'./chunk-LHLW7JLS.js';import {c,d,b as b$a}from'./chunk-RELMEWY6.js';function jt(r,e,t,n,i){let s=t[e],o=n[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let l of Object.keys(o))c.has(l)&&i.push({kind:r,severity:"warning",detail:`Both "${t.name}" and "${n.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,n.name]});}function Wt(r,e){let t=[];if(jt("prefixParseletTokenType","prefixParselets",r,e,t),jt("infixParseletTokenType","infixParselets",r,e,t),r.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=r.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[r.name,e.name]});}if(r.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(r.asConverters).some(c=>c.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[r.name,e.name]});}if(r.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(r.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[r.name,e.name]});}if(r.normalizerRules&&e.normalizerRules){let s=new Set(r.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[r.name,e.name]});}let n=r.lexerVocabulary,i=e.lexerVocabulary;if(n?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let c=n.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[r.name,e.name]});}if(n?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=n.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[r.name,e.name]});}if(r.asyncResolvers&&e.asyncResolvers){let s=new Set(r.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${r.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[r.name,e.name]});}if(r.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let c=r.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[r.name,e.name]});}return t}function Jr(r,e){let t=[];for(let n of e)n===r||n.name===r.name||t.push(...Wt(n,r));return {compatible:!t.some(n=>n.severity==="error"),conflicts:t}}var ve=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,n=(s,o)=>{let c=s.get(o);c&&c!==e&&c.name!==e.name&&t.add(c);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))n(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))n(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))n(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))n(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))n(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)n(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))n(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))n(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)n(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))n(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Wt(s,e));return i}add(e){let t=(n,i)=>{n.has(i)||n.set(i,e);};if(e.prefixParselets)for(let n of Object.keys(e.prefixParselets))t(this.prefixOwners,n);if(e.infixParselets)for(let n of Object.keys(e.infixParselets))t(this.infixOwners,n);if(e.phrases)for(let n of Object.keys(e.phrases))t(this.phraseOwners,n);if(e.asConverters)for(let n of Object.keys(e.asConverters))t(this.converterOwners,n.toLowerCase());if(e.pluginFunctions)for(let n of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,n);if(e.normalizerRules)for(let n of e.normalizerRules)t(this.ruleOwners,n.name);if(e.lexerVocabulary?.keywords)for(let n of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,n);if(e.lexerVocabulary?.operators)for(let n of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,n);if(e.asyncResolvers)for(let n of e.asyncResolvers)t(this.resolverOwners,n.namespace);if(e.tokenCategories)for(let n of Object.keys(e.tokenCategories))t(this.categoryOwners,n);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Cr=/(\d+)\.(\d+)\.(\d+)/,Tr=/^\d+$/;function Ht(r){let e=Cr.exec(r.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Nr(r,e){return r[0]-e[0]||r[1]-e[1]||r[2]-e[2]}function De(r){let e=r.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let n=0;n<e.length;n++){if(!Tr.test(e[n]))return null;t[n]=Number(e[n]);}return [t[0],t[1],t[2]]}function wr([r,e,t]){let n=r>0?[r+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[r,e,t]},{op:"<",v:n}]}function Rr([r,e,t]){return [{op:">=",v:[r,e,t]},{op:"<",v:[r,e+1,0]}]}function Ar(r){if(r===""||r==="*"||r==="x"||r==="X")return [];if(r[0]==="^"){let i=De(r.slice(1));return i&&wr(i)}if(r[0]==="~"){let i=De(r.slice(1));return i&&Rr(i)}let e=/^(>=|<=|>|<|=)/.exec(r),t=e?e[1]:"=",n=De(e?r.slice(e[1].length):r);return n&&[{op:t,v:n}]}function Kt(r){let e=[];for(let t of r.split("||")){let n=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of n){let o=Ar(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Gt(r){return Kt(r.trim())!==null}function Pr(r,e){let t=Nr(r,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function qt(r,e){let t=Kt(e.trim());return t===null?false:t.some(n=>n.every(i=>Pr(r,i)))}function Or(r,e=a$1){if(!r.engineVersion)return {compatible:true};if(!Gt(r.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:r.engineVersion,engineVersion:e};let t=Ht(e);return t===null||!qt(t,r.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:r.engineVersion,engineVersion:e}:{compatible:true}}function Qt(r,e=a$1){let t=Or(r,e);if(!t.compatible)throw t.reason==="invalid-range"?c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${r.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${r.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:r.name,declaredRange:t.declaredRange}}):c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${r.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${r.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:r.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function $(r){return Number.isFinite(r)?r:Number.isNaN(r)?"NaN":r>0?"Infinity":"-Infinity"}function F(r){if(typeof r=="number")return r;if(r==="NaN")return NaN;if(r==="Infinity")return 1/0;if(r==="-Infinity")return -1/0;throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(r)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(r)})}var V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Yt(r){return {coef:r.coef.toString(),scale:r.scale}}function Xt(r){return {coef:BigInt(r.coef),scale:r.scale}}function Lr(r){return {n:r.n.toString(),d:r.d.toString()}}function Ir(r){return {n:BigInt(r.n),d:BigInt(r.d)}}function Jt(r){return g$1[r]??String(r)}function Ve(r,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Jt(r)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Jt(r)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:r,location:e}})}function Me(r,e){switch(r.type){case 0:{let t={t:0,v:$(r.value)};return r.exact!==void 0&&(t.exact=Yt(r.exact)),r.rational!==void 0&&(t.rational=Lr(r.rational)),t}case 1:{let t=r.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:r.unit}:{t:1,v:$(t),base:r.unit}}case 2:return {t:2,v:r.value.toString()};case 3:return {t:3,v:r.value};case 4:{let t={t:4,v:$(r.value)};return r.grain!==void 0&&(t.g=r.grain),r.zone!==void 0&&(t.z=r.zone),t}case 5:return {t:5,v:$(r.value)};case 6:{let t={t:6,v:$(r.value),unit:r.unit??""};return r.exact!==void 0&&(t.exact=Yt(r.exact)),t}case 7:{let t=r.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let n=t.data.map(i=>Dr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:n}}case 8:{let t=r.value;return {t:8,min:$(t.min),max:$(t.max)}}case 10:return {t:10,v:r.value};case 13:return {t:13,code:r.value,message:r.unit??""};default:return Ve(r.type,e)}}function Dr(r,e){return typeof r=="boolean"?r:typeof r=="number"?$(r):Ve(9,`${e} (symbolic matrix cell)`)}function Be(r){switch(r.t){case 0:{let e=new m$1(0,F(r.v));return r.exact!==void 0&&(e.exact=Xt(r.exact)),r.rational!==void 0&&(e.rational=Ir(r.rational)),e}case 1:{let e=r.big?BigInt(r.v):F(r.v);return new m$1(1,e,r.base)}case 2:return new m$1(2,BigInt(r.v));case 3:return new m$1(3,r.v);case 4:{let e=new m$1(4,F(r.v));return r.g!==void 0&&(e.grain=r.g),r.z!==void 0&&(e.zone=r.z),e}case 5:return new m$1(5,F(r.v));case 6:{let e=new m$1(6,F(r.v),r.unit);return r.exact!==void 0&&(e.exact=Xt(r.exact)),e}case 7:{let e=r.data.map(n=>typeof n=="boolean"?n:F(n)),t={rows:r.rows,cols:r.cols,data:e,hasSymbolic:false};return new m$1(7,t)}case 8:return new m$1(8,{min:F(r.min),max:F(r.max)});case 10:return new m$1(10,r.v);case 13:return new m$1(13,r.code,r.message);default:throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(r.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(r.t)})}}function ue(r){let e={opcodes:Array.from(r.opcodes),numbers:Array.from(r.numbers,$),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=Array.from(r.constants.entries())),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(Ue)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(r){let e={opcodes:Uint8Array.from(r.opcodes),numbers:Float64Array.from(r.numbers,F),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=new Map(r.constants)),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(_e)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function Ue(r){return {name:r.name,params:r.params.slice(),program:ue(r.program)}}function _e(r){return {name:r.name,params:r.params.slice(),program:pe(r.program)}}function rr(r){if(typeof r!="object"||r===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:r===null?"null":typeof r});let e=r;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Br(r);}var Zt=32;function Vr(r){return r===null?"null":Array.isArray(r)?`an array of ${r.length}`:typeof r=="object"?"an object":`${typeof r} ${JSON.stringify(r)}`.slice(0,80)}function h(r,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${r}: expected ${e}.`,expected:e,found:Vr(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:r}})}function j(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function z(r){return typeof r=="number"||r==="NaN"||r==="Infinity"||r==="-Infinity"}function ce(r){return typeof r=="string"&&/^-?\d+$/.test(r)}function be(r,e){(!Array.isArray(r)||!r.every(t=>typeof t=="string"))&&h(e,"an array of strings",r);}function er(r,e){(!j(r)||!ce(r.coef)||typeof r.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",r);}function Mr(r,e){(!j(r)||!ce(r.n)||!ce(r.d))&&h(e,"a rational as { n: digits, d: digits }",r);}function tr(r,e){switch(j(r)||h(e,"a serialised value object",r),r.t){case 0:z(r.v)||h(`${e}.v`,"a number",r.v),r.exact!==void 0&&er(r.exact,`${e}.exact`),r.rational!==void 0&&Mr(r.rational,`${e}.rational`);return;case 1:(r.big?!ce(r.v):!z(r.v))&&h(`${e}.v`,r.big?"an integer string":"a number",r.v),r.base!==void 0&&typeof r.base!="string"&&h(`${e}.base`,"a base name",r.base);return;case 2:ce(r.v)||h(`${e}.v`,"an integer string",r.v);return;case 3:typeof r.v!="string"&&h(`${e}.v`,"a string",r.v);return;case 4:z(r.v)||h(`${e}.v`,"a number",r.v),r.g!==void 0&&r.g!=="date"&&r.g!=="datetime"&&r.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',r.g),r.z!==void 0&&typeof r.z!="string"&&h(`${e}.z`,"a zone reference",r.z);return;case 5:z(r.v)||h(`${e}.v`,"a number",r.v);return;case 6:z(r.v)||h(`${e}.v`,"a number",r.v),typeof r.unit!="string"&&h(`${e}.unit`,"a unit name",r.unit),r.exact!==void 0&&er(r.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:n,data:i}=r;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(n)||n<0)&&h(`${e}.cols`,"a non-negative integer",n),(!Array.isArray(i)||i.length!==t*n)&&h(`${e}.data`,`an array of ${t} \xD7 ${n} cells`,i),i.every(s=>typeof s=="boolean"||z(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!z(r.min)||!z(r.max))&&h(e,"a range with numeric min and max",r);return;case 10:typeof r.v!="boolean"&&h(`${e}.v`,"a boolean",r.v);return;case 13:(typeof r.code!="string"||typeof r.message!="string")&&h(e,"an error with a string code and message",r);return;default:return}}function Ee(r,e,t){if(t>Zt&&h(e,`function bodies nested at most ${Zt} deep`,"deeper nesting"),j(r)||h(e,"a serialised program object",r),(!Array.isArray(r.opcodes)||!r.opcodes.every(n=>Number.isInteger(n)&&n>=0&&n<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",r.opcodes),(!Array.isArray(r.numbers)||!r.numbers.every(z))&&h(`${e}.numbers`,"an array of numbers",r.numbers),be(r.strings,`${e}.strings`),typeof r.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",r.hasAsync),r.constants!==void 0){let n=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(r.constants)||!r.constants.every(n))&&h(`${e}.constants`,"an array of [number, number] pairs",r.constants);}r.userFunctionBodies!==void 0&&(Array.isArray(r.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",r.userFunctionBodies),r.userFunctionBodies.forEach((n,i)=>nr(n,`${e}.userFunctionBodies[${i}]`,t+1))),r.anonymousBodies!==void 0&&(Array.isArray(r.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",r.anonymousBodies),r.anonymousBodies.forEach((n,i)=>{let s=`${e}.anonymousBodies[${i}]`;j(n)||h(s,"a body object",n),be(n.params,`${s}.params`),Ee(n.program,`${s}.program`,t+1);}));}function nr(r,e,t){j(r)||h(e,"a function object",r),typeof r.name!="string"&&h(`${e}.name`,"a function name",r.name),be(r.params,`${e}.params`),Ee(r.program,`${e}.program`,t);}function Br(r){r.locale!==void 0&&typeof r.locale!="string"&&h("locale","a locale code",r.locale),j(r.variables)||h("variables","an object of values by name",r.variables);for(let[e,t]of Object.entries(r.variables))tr(t,`variables.${e}`);Array.isArray(r.userFunctions)||h("userFunctions","an array of functions",r.userFunctions),r.userFunctions.forEach((e,t)=>nr(e,`userFunctions[${t}]`,1)),Array.isArray(r.lineCache)||h("lineCache","an array of cached lines",r.lineCache),r.lineCache.forEach((e,t)=>{let n=`lineCache[${t}]`;j(e)||h(n,"a cached line",e),Number.isInteger(e.line)||h(`${n}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${n}.expression`,"the line's expression text",e.expression),tr(e.result,`${n}.result`),Ee(e.bytecode,`${n}.bytecode`,1),be(e.reads,`${n}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${n}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(r.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",r.bytecodeCache),r.bytecodeCache.forEach((e,t)=>{let n=`bytecodeCache[${t}]`;(!j(e)||typeof e.expression!="string")&&h(n,"an { expression, program } pair",e),Ee(e.program,`${n}.program`,1);});}var ir=null;function cn(r){ir=r;}function Fe(){return ir}var sr=3e4,or=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=Fe();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let n=[];for(let l of e){let a=t.get(l);if(!a||a.bytecode.opcodes.length===0)continue;let u=a.bytecode.opcodes,p=a.bytecode.numbers,f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),m=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);n.push({lineNumber:l,opcodesBuffer:f,numbersBuffer:m,opcodesLength:u.length,numbersLength:p.length,strings:[...a.bytecode.strings]});}if(n.length===0)return Promise.resolve([]);let i=[];for(let l of n)l.opcodesBuffer.byteLength>0&&i.push(l.opcodesBuffer),l.numbersBuffer.byteLength>0&&i.push(l.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),c=this.workers[o];return new Promise(l=>{let a=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${sr/1e3} seconds; the worker was replaced`);},sr);this.pendingBatches.set(s,{id:s,lineNumbers:n.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(a),l(u);}}),c.postMessage({type:"EXECUTE_BATCH",id:s,items:n},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++)this.spawnWorker(e);}spawnWorker(e){let t=Fe();if(t===null)return;let n=t();n.onmessage=i=>{this.handleWorkerMessage(i.data);},n.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=n;}failWorker(e,t,n){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Ur(s.lineNumbers,t,n)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Ur(r,e,t){return r.map(n=>({lineNumber:n,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function ar(r$1){switch(r$1.valueType){case 0:return n(r$1.value);case 1:return r(r$1.value);case 2:return s(BigInt(r$1.value));case 3:return t$1(String(r$1.value));case 4:return M(r$1.value);case 5:return N(r$1.value);case 6:return u(r$1.value,r$1.unit??"");case 7:return n(r$1.value);case 10:return L(r$1.value!==0);case 12:return O(r$1.queryKey??"");case 13:return P(r$1.errorCode??"WORKER_EXECUTION_ERROR",r$1.unit??"Unknown worker error");default:return n(r$1.value)}}var Se=class Se{constructor(e,t,n,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=n,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let n=d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${n.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let a of e){let u=`${a.packageId}:${a.queryKey}`;t.set(u,a);}let n=[],i=[];for(let a of t.values())a.isError?n.push(a):i.push(a);for(let a of n)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let s=new Set,o=[],c=[...i,...n];for(let a of c){if(a.signal.aborted)continue;o.push(a.queryKey);let u=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>or){let a=new Map;for(let u of l)a.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,a,o).catch(u=>{let p=d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,n=new Map,i=new Map;for(let c of e)t.set(c,0),n.set(c,[]);for(let c of e){let l=this.dag.getWrites(c);for(let a of l)i.set(a,c);}for(let c of e){let l=this.dag.getDependencies(c);for(let a of l){let u=i.get(a);u!==void 0&&u!==c&&(n.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,l]of t)l===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,l)=>c-l);let o=[];for(;s.length>0;){let c=s.shift();o.push(c);for(let l of n.get(c)??[]){let a=(t.get(l)??1)-1;t.set(l,a),a===0&&s.push(l);}}if(o.length<e.length){let c=e.filter(l=>!o.includes(l)).sort((l,a)=>l-a);o.push(...c);}return o}async reExecuteViaWorkerPool(e,t,n){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,n,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let c of s){let l=t.get(c.lineNumber);if(!l||c.isPending)continue;let a=ar(c);l.result=a,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,a),o.push(c.lineNumber);}this.cleared||(o.length>0||n.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:n});}reExecuteMainThread(e,t,n){let i=[];for(let s of e){let o=n?n.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.vm.getStack().length;try{let l=d$1(o.bytecode,this.vm,void 0,void 0,{lineIndex:s,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>c;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let a=P(l.error.code,l.error.message);o.result=a,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,a),i.push(s);}}catch(l){for(;this.vm.getStack().length>c;)this.vm.pop();let a=d(l),u=P(a.code,a.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var ke=Se;function ze(r,e){if(r.length>e.maxExpressionLength){let t=c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${r.length})`,{expressionLength:r.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function $e(r,e){let t=0,n=0,i=0;for(let o of r)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(n++,i=Math.max(i,n)),(o.value===")"||o.type==="RPAREN")&&n--;let s=r.length+t*5+i*10;if(s>e.maxComplexity){let o=c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function de(r){return r.type==="IDENT"||r.type==="UNIT"}function _r(r){return r.type==="NUMBER"||r.type==="TO"||r.type==="IN"||r.type==="RPAREN"}function lr(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n].type==="LPAREN")t++;else if(r[n].type==="RPAREN"&&(t--,t===0))return n;return null}function Fr(r){let e=new Set;for(let t=0;t<r.length;t++){if(!de(r[t])||t>0&&r[t-1].type==="COLON"||r[t+1]?.type!=="LPAREN")continue;let n=lr(r,t+1);if(n!==null&&r[n+1]?.type==="EQUALS")for(let i=t+2;i<n;i++)de(r[i])&&e.add(r[i].value);}return e}function Ce(r){let e=[],t=[],n=Fr(r);for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="GLOBAL"){if(i+2<r.length&&r[i+1].type==="COLON"&&de(r[i+2])){let o=K$1(r[i+2].value);e.push(o),i+3<r.length&&r[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&r[i-1].type==="GLOBAL")continue;if(i+1<r.length&&de(r[i+1])){let o=r[i+1].value;e.push(o),i+2<r.length&&r[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&r[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&_r(r[i-1])||n.has(s.value))continue;if(r[i+1]?.type==="LPAREN"){let c=lr(r,i+1);if(c!==null&&r[c+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=r[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Cn(r){return c$1.classifyLine(r).skip}function Tn(r,e){return c$1.findInlineSolves(r).map(n=>({start:n.start,end:n.end,expression:n.expression,lineNumber:e,columnNumber:n.columnNumber}))}var K=class{constructor(e,t,n,i){this.result=e;this.bytecode=t;this.readVariables=n;this.writeVariable=i;}},Te=class r{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(r.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let n of t.values())return n}set(e,t,n){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=r.exprKey(n);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(r.exprKey(t))??false}remove(e,t){let n=this.byLine.get(e);n&&n.delete(r.exprKey(t))&&(this.count--,n.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,n]of this.byLine)for(let[i,s]of n)e(r.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,n]of this.byLine)for(let[i,s]of n)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,n]of this.byLine)for(let i of n.keys())e.push(r.displayKey(t,i));return e}};function je(r,e){let t=e.fields(r),n=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${n}-${i}`}function zr(r,e){if(r instanceof Date)return je(r.getTime(),e);if(typeof r=="number")return Number.isFinite(r)?je(r,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(r.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function cr(r,e){if(r===void 0)return;if(typeof r=="function")return n=>r(new Date(n));let t=new Set;for(let n of r){let i=zr(n,e);i!==null&&t.add(i);}return n=>t.has(je(n,e))}function $r(r,e){if(!r||r.type!==e.type||r.value!==e.value)return true;let t=r.unit,n=e.unit;return t!==n}var Ne=class r{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=r.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let n=setInterval(()=>{this.tick(t);},e.intervalMs);n.unref?.(),this.entries.set(t,{...e,timer:n,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let n=await t.refetch(),i=this.entries.get(e);if(!i)return;n&&$r(i.lastValue,n)&&(i.lastValue=n,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let n=this.entries.get(e);n&&(n.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,n){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),c=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,a=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:a,...n};return {result:o,alloc:p}}static generateReport(e,t){let n=[];n.push(t?`## ${t}`:"## Pipeline Allocation Report"),n.push(""),n.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),n.push("");let i=this.aggregate(e);if(i.length===0)return n.push("_No telemetry data._"),n.join(`
2
2
  `);n.push("### Per-Stage Breakdown"),n.push(""),n.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),n.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)n.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,a)=>l+a.totalAllocBytes,0),o=e.reduce((l,a)=>l+a.totalWallTimeNs,0),c=e.filter(l=>l.fastPath).length;return n.push(""),n.push("### Totals"),n.push(""),n.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),n.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),n.push(`- **Fast-path runs:** ${c}/${e.length} (${(c/e.length*100).toFixed(0)}%)`),n.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),n.join(`
3
3
  `)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let n=[];for(let[i,s]of t){let o=s.map(a=>a.wallTimeNs).sort((a,u)=>a-u),c=s.map(a=>a.allocBytes),l=s.length;n.push({stage:i,count:l,meanAllocBytes:c.reduce((a,u)=>a+u,0)/l,meanWallTimeNs:o.reduce((a,u)=>a+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:We(o,50),p95WallTimeNs:We(o,95),p99WallTimeNs:We(o,99)});}return n.sort((i,s)=>i.stage.localeCompare(s.stage)),n}static createTelemetry(e,t,n=false){let i=t.reduce((o,c)=>o+c.allocBytes,0),s=t.reduce((o,c)=>o+c.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:n}}};U.enabled=false;function We(r,e){if(r.length===0)return 0;if(r.length===1)return r[0];let t=e/100*(r.length-1),n=Math.floor(t),i=Math.ceil(t);if(n===i)return r[n];let s=t-n;return r[n]*(1-s)+r[i]*s}function ur(r){let e=r[r.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...r.slice(0,-1),t].join(" ")}var we=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,n){let i=ur(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:n}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let n=t;n>=1;n--){let i=this.byKey.get(ur(e.slice(0,n)));if(i!==void 0)return {definition:i,wordCount:n}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function pr(r,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,n){if(r.isEmpty)return null;let i=t[n];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=r.maxWordCount;for(let d=n+1;d<t.length&&s.length<o&&t[d].type==="IDENT";d++)s.push(t[d].value);if(s.length===0)return null;let c=r.match(s);if(c===null||t[n+1+c.wordCount]?.type==="EQUALS")return null;let{ratioText:a,baseUnit:u}=c.definition,p=new a$8("STAR",c$9("STAR"),"*","*",i.offset,0,i.line,i.col),f=new a$8("NUMBER",c$9("NUMBER"),a,a,i.offset,0,i.line,i.col),m=new a$8("UNIT",c$9("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+c.wordCount,replacement:[i,p,f,m],ruleName:"uom:user-unit"}}}}var dr="engine:call-fusion";function fr(r,e=80){return {name:dr,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,n){let i=t[n];if(!i||i.type!=="IDENT"||t[n+1]?.type!=="LPAREN"||t[n-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=r.get(s);return o===void 0?null:{consumed:1,replacement:[new a$8(o,c$9(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:dr}}}}var jr={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function gr(r){return r===void 0||r.type!=="IDENT"&&r.type!=="UNIT"?0:jr[(r.text??r.value??"").toLowerCase()]??0}var fe=/^\d+$/;function Re(r){return r.length===4}function te(r,e,t,n,i,s){let o="datetime:month-name-date",c=q(r,e,t,n,o,i);return c!==null?c:s==="arithmetic"||e<1||e>12||r<1||r>31?null:s$1(g.DATE_NOT_A_CALENDAR_DAY,`"${r$1(n)}" is not a real date: ${j$1(r,e,t)}.`,n,`${o}:unreadable`)}function hr(r){return r.fields(r.now()).year}function mr(r=64,e=()=>b$5,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:r,startTokenTypes:["NUMBER","IDENT","UNIT"],match(n,i){let s=e(),o=t(),c=n[i];if(c?.type==="NUMBER"&&fe.test(c.text??"")){let m=gr(n[i+1]);if(m===0)return null;let d=Number(c.text);if(d<1||d>31)return null;let T=n[i+2];return T?.type==="NUMBER"&&fe.test(T.text??"")&&Re(T.text??"")?te(d,m,Number(T.text),n.slice(i,i+3),s,o):te(d,m,hr(s),n.slice(i,i+2),s,o)}let l=gr(c);if(l===0)return null;let a=n[i+1];if(a?.type!=="NUMBER"||!fe.test(a.text??""))return null;if(Re(a.text??""))return te(1,l,Number(a.text),n.slice(i,i+2),s,o);let u=Number(a.text),p=n[i+2],f=n[i+3];return p?.type==="COMMA"&&f?.type==="NUMBER"&&fe.test(f.text??"")&&Re(f.text??"")?te(u,l,Number(f.text),n.slice(i,i+4),s,o):p?.type==="NUMBER"&&fe.test(p.text??"")&&Re(p.text??"")?te(u,l,Number(p.text),n.slice(i,i+3),s,o):te(u,l,hr(s),n.slice(i,i+2),s,o)}}}var Wr=30,Hr=40,Kr=50,Gr=24;function qr(r){switch(r){case a.PLUS:case a.MINUS:return Wr;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return Hr;case a.CARET:return Kr;case a.PCT_ON:case a.PCT_OFF:return Gr;default:return 0}}function Qr(r){switch(r){case a.PLUS:return "plus";case a.MINUS:return "minus";case a.STAR:return "times";case a.SLASH:return "divided by";case a.MOD:return "mod";case a.CARET:return "to the power of";case a.OF:return "of";case a.PCT_ON:return "plus";case a.PCT_OFF:return "less";default:return r.toLowerCase()}}function yr(r){return r.sourceEnd??r.offset+r.value.length}var Yr=new Set([a.NUMBER,a.BIGINT,a.IDENT,a.UNIT,a.PERCENT,a.PI,a.E,a.TRUE,a.FALSE,a.DOLLAR,a.POUND,a.EURO,a.YEN,a.RUBLE,a.WON,a.CURRENCY_SYMBOL]);function Xr(r){return !Yr.has(r)}var He=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let n=this.peek();if(!n)break;let i=qr(n.type);if(i===0||i<=e)break;this.next();let s=n.type===a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:n.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===a.LPAREN)return this.parseGroup();let t=e.offset,n=false;for(;this.peek()&&(this.peek().type===a.PLUS||this.peek().type===a.MINUS);)this.next(),n=true;if(n&&this.peek()&&this.peek().type===a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!Xr(this.peek().type);)i=yr(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),n=this.peek();if(!n||n.type!==a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:yr(n)}}},Ke=class{constructor(e,t,n){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$9(n).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=Qr(e.op);return e.op===a.PCT_ON||e.op===a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let n=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,n),n}render(e){let t=c$a(e,a$a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function Ge(r){let{expression:e,tokens:t,evaluate:n,locale:i,readings:s=[]}=r,o=a=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:a})),c=()=>{let a=n(e);return {expression:e,steps:o(a),result:a}},l;try{l=new He(t).parseAll();}catch{return c()}try{let{steps:a,result:u}=new Ke(e,n,i).build(l);return {expression:e,steps:[...o(u),...a],result:u}}catch{return c()}}var Y=class Y{constructor(e={}){this.dag=new a$2;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new b;this.resolverRegistry=new a$3;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new ve;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new we;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t$1="en",diagnostics:n=false,config:i,packages:s,calendar:o}=e;this.localeCode=t$1,this.config=c$2(b$1,i??{}),this.dateReading=h$1(this.config.date),this.lexer=new b$2(t$1),this.registry=new b$3,this.context=x({networkEnabled:this.config.network.enabled,calendar:o}),n?(this.diagnosticPipeline=new a$4,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$4,this.normalizer=new c$3;for(let[l,a]of Object.entries(c$4))this.normalizer.addPhrase(l,a);this.normalizer.register(d$3(50,l=>this.normalizer.canStartPhrase(l))),this.normalizer.register(pr(this.userUnits)),this.normalizer.register(fr(this.callFusions));let c=s??[];for(let l of c)try{this.registerPackage(l);}catch(a){let u=d(a);console.error(`[ExpressionEngine] Failed to register package "${l.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let l=()=>this.context.calendar;this.normalizer.register(t(()=>this.dateReading.order,l,()=>this.config.date.onAmbiguous)),this.normalizer.register(mr(void 0,l,()=>this.config.date.onAmbiguous));}this.parser=new a$5(this.registry,this.config.validation.maxNestingDepth,t$1,this.pluginFunctionIndexByName,this.context.calendar),this.vm=c$5(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,cr(this.config.date.holidays,this.context.calendar)),this.queryClient=c$6(),this.batcher=new ke(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Ne(this.dag,(l,a)=>this.batcher.add({queryKey:a,packageId:l,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new d$2(this.pluginFunctionIndexByName);for(let t of Y.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let n=[];for(let o of this.lexer)o.type!=="COMMENT"&&n.push(o);let i=this.normalizer.normalize(n);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),d$1(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,n=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:n?s=>{let o=n[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,c,l)=>this.evaluateLineWithBinding(s,o,c,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:t?s=>t.getLineAt(s)?.text:n?s=>n[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,n,i){let s=this.documentModel;if(!s)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=Y.GOAL_SEEK_MAX_NESTING_DEPTH)return P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let c=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,n]]),a=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=d$1(c,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>a;)this.vm.pop();}}catch(l){return P("GOAL_SEEK_TARGET_ERROR",d(l).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,n){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,n);}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let n=this.failedParses.keys().next().value;n!==void 0&&this.failedParses.delete(n);}this.failedParses.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Qt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let n={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=F$1(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),n.pluginFunctionIndices.push(o),n.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),n.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),n.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase(),c=this.callFusionOwners.get(o);c?c.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),n.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$6(i,s),n.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))H(i,s),n.asConverterNames.push(i);this.packageContributions.set(e.name,n),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let n of t.pluginFunctionIndices)delete this.context.pluginFunctions[n],delete this.context.pluginFunctionOwners[n];for(let n of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(n);for(let n of t.resolverNamespaces)this.resolverRegistry.unregister(n);for(let n of t.tokenCategories)c$7(n);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let n of t.asConverterNames)I(n);for(let n of t.normalizerRuleNames)this.normalizer.unregister(n);for(let n of t.callFusionNames){let i=(this.callFusionOwners.get(n)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(n),this.callFusions.delete(n)):(this.callFusionOwners.set(n,i),this.callFusions.set(n,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s of n){let o$1=s.type===p;if(!o$1&&s.type!==o)continue;let c=s.offset,l=s.sourceEnd??s.offset+s.text.length;i.push(this.describeDateLiteral(e.slice(c,l),c,l,s,o$1));}return i}describeDateLiteral(e,t,n,i$1,s){let o=n$1(e);if(o!==null){let a=l(o,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=i(o.groups[0],o.groups[1],o.groups[2],o.separator)==="iso",p=this.dateReading.order==="auto"?o.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,f=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return a.kind==="date"?m({text:e,start:t,end:n,iso:k(a.day,a.month,a.year),...f,contested:a.alternative!==void 0,shortYear:a.shortYear,alternative:a.alternative},o.separator):m({text:e,start:t,end:n,iso:null,...f,contested:false,shortYear:false,problem:a.kind==="refuse"?a.code:void 0},o.separator,a.kind==="refuse"?a.message:void 0)}if(s){let a=i$1.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i$1.value}" is not a date this engine can read.`};return m({text:e,start:t,end:n,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:a.code},"slash",a.message)}let c=this.context.calendar.fields(Number(i$1.value)),l$1=/^\d{4}-/.test(e)?"iso":"spelled";return m({text:e,start:t,end:n,iso:k(c.day,c.month0+1,c.year),order:l$1==="iso"?"ISO":"spelled",orderSource:l$1,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,n,i,s,o){this.lineCache.set(e,new K(t,n,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,n,i,s,o,c,l){let a=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),a$6.localControllerCreated("executeAndStore"),this.keystrokeSignal&&a$6.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},a$7(this.queryClient);let f=d$1(e,this.vm,c,l,this.makeLineContext(t));for(;this.vm.getStack().length>a;)this.vm.pop();if(f.type==="pending"){this.resolveAsync(f),this.dag.registerLineDataSourceDependency(t,f.packageId||o,[f.queryKey]);let m=O(f.queryKey);return this.storeLineResult(t,m,e,i,s,n),m}if(f.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),f.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,f.value,e,i,s,n),f.value}executeRaw(e,t=-1){let n=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),a$6.localControllerCreated("executeRaw"),this.keystrokeSignal&&a$6.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},a$7(this.queryClient);let o=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>n;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:n,packageId:i,signal:s}=e,o=i||"_engine";try{if(await n,s.aborted){a$6.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(c){if(s.aborted){a$6.staleDataDiscarded(t,"signal aborted after error");return}let l=c instanceof Error?c:new Error(String(c));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let n=this.config.performance.maxDocumentLines;if(b$7(e,n)>n)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${n.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:n});this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let a of l.inlineSolves)a.error&&o.errors.push(`Line ${l.lineNumber}: ${a.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),n=this.lexer.scanDocument(t);return this.processScanResults(n)}processScanResults(e){let t=[],n=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,c=s.lineNumber,l=s.startOffset,a=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(d=>({start:d.start,end:d.end,expression:d.expression,lineNumber:c,columnNumber:d.columnNumber})),f=p.length>0,m={lineNumber:c,text:o,startPosition:l,endPosition:a,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(s.error)m.error=s.error.message;else if(!u){let d=o.trim().startsWith(":");if(f&&!d)for(let T of p)try{T.result=this.evaluateLine(c,T.expression);}catch(b){let R=b instanceof Error?b.message:String(b);T.error=R;}else {let T=s.classification.contentOffset,R=(T===void 0?o:o.slice(T-l)).trim();if(R)try{let L=this.evaluateLineWithPreTokenized(c,R,s.tokens);m.expression=R,m.result=L[0];}catch(L){let G=L instanceof Error?L.message:String(L);m.error=G;}}}t.push(m);}}finally{this.batchScanResults=n,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,n){let i=[],s=false;for(let o of n)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,n,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?n:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let c$1=true;for(let l=0;l<o;l++){let a=t[l].type;if(a!=="NUMBER"&&a!=="COLON"){c$1=false;break}}if(c$1){let l=t.slice(0,o+2).map(a=>a.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),n,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$2(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let n=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(n.type==="error")throw n.error;if(n.type==="pending")throw c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return n.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let n=0;n<e.length;n++)if(n%2===0){if(e[n].type!=="IDENT"&&e[n].type!=="UNIT")return null;t.push(e[n].value);}else if(e[n].type!=="STAR")return null;return t}solveEquation(e,t=-1){let n=[];for(let c of e.factorNames){let l=this.vm.getVar(c);if(l===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(l.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);n.push(l);}let i=n[0].value;for(let c=1;c<n.length;c++){let l=_(i,n[c].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let n=[];for(;t<e.length&&e[t].type==="IDENT";)n.push(e[t].value),t++;if(n.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(n,i.value,s.value),this.clearCompiledCache(),t$1(`${n.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let n$1=e[0],i=e[1],s=n$1.type==="IDENT"||n$1.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let c$1=e.slice(2);if(c$1.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${n$1.value} ${i.value}" needs an expression on the right, e.g. "${n$1.value} ${i.value} 10".`);let l=n$1.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,n(0));let a=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$8("IDENT",l,[n$1]),b$8(a.type,a.text,[i]),b$8("LPAREN","(",[i]),...c$1,b$8("RPAREN",")",[i])],p=d$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let a=e.slice(0,-1);if(a.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(a.length===1&&(a[0].type==="IDENT"||a[0].type==="UNIT")){let u=a[0].value,p=this.vm.getEquation(u),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t)}return this.simplifySymbolically(a,t)}if(b$9(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(a=>a.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let a=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],a),a}let c$1=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(c$1,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(c$1,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),t$1(`${c$1} stored as an equation \u2014 solve with "${c$1} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let n=e.slice(0,t),i=e.slice(t+1);if(i.some(c=>c.type==="EQUALS"))return null;let s=this.equationUnknowns(n,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(n),this.compileAdHoc(i)),t$1(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let n=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||n.includes(i.value)||n.push(i.value));return n}solveScalarEquation(e,t=-1){let n=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return i$1(n,i,e.variable)}lexToTokens(e,t,n=true){let i=[],s=false;if(n&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,n,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return {kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),l;if(c)l=c.normalizedTokens;else {let b=ze(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let R=t.filter(G=>G.type!=="COMMENT");if(R.length===0)return {kind:"empty"};l=this.normalizer.normalize(R,i);let L=$e(l,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:l}}let a,u=null;try{if(a=this.tryDefineUserUnit(l),a===null){let b=this.tryCompoundAssignment(l,s);b!==null&&(a=b,u=Ce(l));}a===null&&(a=this.trySymbolicGrammar(l,s));}catch(b){let{reads:R,writes:L}=Ce(l);return {kind:"error",stage:"parse",error:d(b),reads:R,writes:L,normalizedTokens:l}}if(a!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:a,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:l};let{reads:p,writes:f}=Ce(l);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:o,cached:true};let m=this.builderPool[this.builderPoolIndex++%this.builderPool.length];m.reset();let d$1,T=null;try{let b=U.track("parser",()=>(this.parseExpression(m,l,n),m.build()));d$1=b.result,T=b.alloc;}catch(b){let R=d(b);return this.rememberFailedParse(e,{error:R,normalizedTokens:l,reads:p,writes:f}),{kind:"error",stage:"parse",error:R,reads:p,writes:f,normalizedTokens:l}}return this.cacheBytecode(e,d$1,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:d$1,cached:false,parserAlloc:T}}preflightAsync(e,t,n,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let a=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",a,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(n,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(n,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,n$1,i){let s=this.prepareExpression(t,n$1,i,void 0,e);if(s.kind==="empty"){let p=n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:c,writes:l,program:a}=s,u=this.preflightAsync(o,a,e,t,c,l);return u.kind==="pending"?u.value:this.executeAndStore(a,e,t,c,l,"_engine")}evaluateLine(e,t){let n=this.evaluateLineWithDebug(e,t);if(n.error)throw n.engineError?n.engineError:c.execution("EVALUATION_ERROR",n.error,{lineNumber:e});return l$1(n.value)}evaluateLineWithDebug(e,t,n="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,n),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,n)}addDiagnosticStage(e,t,n,i,s,o,c,l,a){e.push({stage:t,label:n,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:l,output:a});}evaluateExpressionWithDiagnostic(e,t,n$1="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c$1=U.isEnabled(),l=[],a=[],u=0,p=ze(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$8.PipelineStart,elapsedNs:0,expression:e,inputType:n$1}),this.addDiagnosticStage(a,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:n$1}),this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let f=s?y=>{i.fireTokenEmitted({type:c$8.TokenEmitted,elapsedNs:0,expression:e,token:{type:y.type,value:y.value,offset:y.offset||0,line:y.line||t,col:y.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,f)),d$1=m.result.tokens,T=m.result.hasParens,b=m.result.compiled;if(c$1&&m.alloc&&l.push(m.alloc),s){let y={};for(let O of d$1)y[O.type]=(y[O.type]||0)+1;this.addDiagnosticStage(a,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d$1.length,tokenTypes:y,hasParens:T,locale:this.localeCode,tokens:[...d$1]});let A=[];for(let O=0;O<d$1.length;O++){let se=d$1[O];if(se.type==="INLINE_SOLVE_START"){let M=-1;for(let W=O+1;W<d$1.length;W++)if(d$1[W].type==="BACKTICK_OPEN"){M=W;break}if(M>O){let kr=d$1.slice(O+1,M).map(Sr=>Sr.value).join("");A.push({startTokenIndex:O,endTokenIndex:M,expression:kr,columnNumber:se.col||1}),O=M;}}}this.addDiagnosticStage(a,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&d$1.length===0){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let R=0,L=[],G=new Map,br=s?y=>{R++,L.push(y),G.set(y.rule,(G.get(y.rule)||0)+1),i.fireTokenFused({type:c$8.TokenFused,elapsedNs:0,expression:e,ruleName:y.rule,sourceTokenCount:y.sourceTokens.length,fusedTokenType:y.fusedToken.type,fusedTokenValue:y.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$8.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d$1.length});let D=this.bytecodeCache.get(e);s&&!D&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d$1,T,br,t);b&&v.kind==="ready"&&(d$1=v.normalizedTokens),c$1&&v.kind==="ready"&&v.parserAlloc&&l.push(v.parserAlloc),s&&!D&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d$1:v.normalizedTokens??d$1;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$8.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:R}),this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...G.entries()].map(([y,A])=>({rule:y,count:A})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:d$1.length,fusions:[],rulesApplied:[],tokens:[...d$1],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d$1)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d$1.length,totalOpcodes:0}),v.kind==="empty"){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let re=$e(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:re.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:re.errorMessage}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:re.errorMessage,engineError:re.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:re.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:0});let y={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,y,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:y,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],ne=v.writes??[];if(s&&(this.addDiagnosticStage(a,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:ne,isAssignment:ne.length>0}),this.addDiagnosticStage(a,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!D,cacheSize:this.bytecodeCache.size,cacheKey:e}),D?i.fireCacheHit({type:c$8.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$8.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0}),{value:n(0),tokens:k,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(a,"parser","Parser","\u{1F333}","parser",8,u,!!D,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(a,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!D,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!D}),i.fireBytecodeBuilt({type:c$8.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!D}));let Er=x.hasAsync||this.resolverRegistry.size>0,ie=this.preflightAsync(k,x,t,e,ge,ne);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:ie.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Er?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,ie.value,k,x,null):void 0};let xr=s&&this.config.diagnostic.vmTraceEnabled===true,N;try{let y=U.track("vm",()=>this.executeAndStore(x,t,e,ge,ne,"_engine",xr?i:void 0,e),{cacheHit:!!D});N=y.result,c$1&&y.alloc&&l.push(y.alloc);}catch(y){let A=d(y);return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:n(0),tokens:k,program:x,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let he=N.type===12;if(s){let y=he?"pending":String(N.value??""),A=he?"Pending":N.unit?"Uom":"Number";this.addDiagnosticStage(a,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:y,isPending:he});}if(he)return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:N,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,N,k,x,null):void 0};if(c$1&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!D)),s&&(this.addDiagnosticStage(a,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:ne,dataSourcesRegistered:[]}),this.addDiagnosticStage(a,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(a,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(N.value),formattedValue:String(N.value),valueType:N.type===0?"Number":"Value",unit:N.unit}),i.fireVmHalt({type:c$8.VmHalt,elapsedNs:0,expression:e,result:N?{type:N.type,value:N.value,unit:N.unit}:void 0}),this.addDiagnosticStage(a,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length,cacheHit:!!D}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),O=A;if(A){let se=A.parselets.slice(o),M={};for(let W of se)M[W.parseletCategory]=(M[W.parseletCategory]??0)+1;O={...A,parselets:se,summary:{...A.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:N,tokens:k,program:x,debug:O,diagnostic:this.buildDiagnosticResult(a,N,k,x,null)}}return {value:N,tokens:k,program:x}}buildDiagnosticResult(e,t,n,i,s){return {stages:e,value:t,tokens:n,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let n=this.lineCache.get(e,t);if(!n)return;let i=this.bytecodeCache.get(t);if(!i)return;if(n.bytecode.hasAsync||this.resolverRegistry.size>0){let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let a=c.signal,u=this.resolverRegistry.preflightAll([],n.bytecode,"_engine",a,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return n.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let n=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return n.length===0?[]:this.normalizer.normalize(n)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?a$6.keystrokeSignalSet(e.aborted):a$6.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,c]of this.bytecodeCache)e.push({expression:o,opcodesLength:c.opcodes.length,numbersLength:c.numbers.length,stringsLength:c.strings.length,hasAsync:c.hasAsync});let t=[];for(let o of this.lineCache.keys()){let c=o.indexOf(":"),l=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,a=c>0?o.slice(c+1):void 0,u=a!==void 0?this.lineCache.get(l,a):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let c=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:c}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(n);return Ge({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:n$1}=this.lexToTokens(e),i=this.prepareExpression(e,t,n$1,void 0,-1);if(i.kind==="empty")return n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:n}=t,i=this.prepareExpression(e,t.tokens,n),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$a(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:n}=this.lexToTokens(e);return this.prepareExpression(e,t,n).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return n(0);let n$1=this.executeRaw(e,t);if(n$1.type==="pending")return this.resolveAsync(n$1),O(n$1.queryKey);if(n$1.type==="error")throw n$1.error;return n$1.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let n=this.evaluateLine(-1,e);return n.isFault()?NaN:n.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$b()===this.queryClient&&a$7(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let a of Object.keys(e.dataSourceDeps)){let u=Number(a);Number.isNaN(u)||t.add(u);}let n=this.lineCache.snapshotEntries(),i=new Map;for(let{line:a,entry:u}of n){let p=t.has(a)||u.bytecode.hasAsync;p&&t.add(a);let f=u.writeVariable;if(f){let m=i.get(f);(!m||a>=m.line)&&i.set(f,{line:a,async:p});}}let s={};for(let[a,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(a)?.async)try{s[a]=Me(u,`variable "${a}"`);}catch(p){if(p instanceof b$a&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Ue),c=[];for(let{line:a,expression:u,entry:p}of n){if(t.has(a)||p.result.type===12)continue;let f;try{f=Me(p.result,`line ${a}`);}catch(m){if(m instanceof b$a&&m.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}c.push({line:a,expression:u,result:f,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([a,u])=>({expression:a,program:ue(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:l}}static fromJSON(e,t={}){rr(e);let n=t.locale??e.locale??"en",i=new Y({locale:n,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,n]of Object.entries(e.variables))this.vm.setVar(t,Be(n));for(let t of e.userFunctions){let n=_e(t);this.vm.defineUserFunction(n.name,n.params,n.program);}for(let t of e.lineCache){let n=new K(Be(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,n,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:n}of e.bytecodeCache)this.bytecodeCache.set(t,pe(n));}evaluateIncremental(e,t){let n$1=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,n(t));let i=new Map;for(let s of n$1){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.executeRaw(o.bytecode,s);if(c.type==="pending"){this.resolveAsync(c);continue}if(c.type==="error"){let a=P(c.error.code,c.error.message);i.set(s,a),o.result=a;continue}let l=c.value;i.set(s,l),o.result=l;}return i}};Y.GOAL_SEEK_MAX_NESTING_DEPTH=1,Y.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var vr=Y;export{Jr as a,Or as b,Qt as c,ee as d,Q as e,V as f,cn as g,Fe as h,ke as i,ze as j,$e as k,Ce as l,Cn as m,Tn as n,vr as o};//# sourceMappingURL=chunk-VYB44JLS.js.map
5
- //# sourceMappingURL=chunk-VYB44JLS.js.map
4
+ `),n=this.lexer.scanDocument(t);return this.processScanResults(n)}processScanResults(e){let t=[],n=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,c=s.lineNumber,l=s.startOffset,a=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(d=>({start:d.start,end:d.end,expression:d.expression,lineNumber:c,columnNumber:d.columnNumber})),f=p.length>0,m={lineNumber:c,text:o,startPosition:l,endPosition:a,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(s.error)m.error=s.error.message;else if(!u){let d=o.trim().startsWith(":");if(f&&!d)for(let T of p)try{T.result=this.evaluateLine(c,T.expression);}catch(b){let R=b instanceof Error?b.message:String(b);T.error=R;}else {let T=s.classification.contentOffset,R=(T===void 0?o:o.slice(T-l)).trim();if(R)try{let L=this.evaluateLineWithPreTokenized(c,R,s.tokens);m.expression=R,m.result=L[0];}catch(L){let G=L instanceof Error?L.message:String(L);m.error=G;}}}t.push(m);}}finally{this.batchScanResults=n,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,n){let i=[],s=false;for(let o of n)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,n,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?n:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let c$1=true;for(let l=0;l<o;l++){let a=t[l].type;if(a!=="NUMBER"&&a!=="COLON"){c$1=false;break}}if(c$1){let l=t.slice(0,o+2).map(a=>a.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),n,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$2(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let n=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(n.type==="error")throw n.error;if(n.type==="pending")throw c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return n.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let n=0;n<e.length;n++)if(n%2===0){if(e[n].type!=="IDENT"&&e[n].type!=="UNIT")return null;t.push(e[n].value);}else if(e[n].type!=="STAR")return null;return t}solveEquation(e,t=-1){let n=[];for(let c of e.factorNames){let l=this.vm.getVar(c);if(l===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(l.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);n.push(l);}let i=n[0].value;for(let c=1;c<n.length;c++){let l=_(i,n[c].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let n=[];for(;t<e.length&&e[t].type==="IDENT";)n.push(e[t].value),t++;if(n.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(n,i.value,s.value),this.clearCompiledCache(),t$1(`${n.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let n$1=e[0],i=e[1],s=n$1.type==="IDENT"||n$1.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let c$1=e.slice(2);if(c$1.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${n$1.value} ${i.value}" needs an expression on the right, e.g. "${n$1.value} ${i.value} 10".`);let l=n$1.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,n(0));let a=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$8("IDENT",l,[n$1]),b$8(a.type,a.text,[i]),b$8("LPAREN","(",[i]),...c$1,b$8("RPAREN",")",[i])],p=d$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let a=e.slice(0,-1);if(a.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(a.length===1&&(a[0].type==="IDENT"||a[0].type==="UNIT")){let u=a[0].value,p=this.vm.getEquation(u),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t)}return this.simplifySymbolically(a,t)}if(b$9(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(a=>a.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let a=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],a),a}let c$1=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(c$1,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(c$1,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),t$1(`${c$1} stored as an equation \u2014 solve with "${c$1} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let n=e.slice(0,t),i=e.slice(t+1);if(i.some(c=>c.type==="EQUALS"))return null;let s=this.equationUnknowns(n,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(n),this.compileAdHoc(i)),t$1(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let n=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||n.includes(i.value)||n.push(i.value));return n}solveScalarEquation(e,t=-1){let n=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return i$1(n,i,e.variable)}lexToTokens(e,t,n=true){let i=[],s=false;if(n&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,n,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return {kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),l;if(c)l=c.normalizedTokens;else {let b=ze(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let R=t.filter(G=>G.type!=="COMMENT");if(R.length===0)return {kind:"empty"};l=this.normalizer.normalize(R,i);let L=$e(l,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:l}}let a,u=null;try{if(a=this.tryDefineUserUnit(l),a===null){let b=this.tryCompoundAssignment(l,s);b!==null&&(a=b,u=Ce(l));}a===null&&(a=this.trySymbolicGrammar(l,s));}catch(b){let{reads:R,writes:L}=Ce(l);return {kind:"error",stage:"parse",error:d(b),reads:R,writes:L,normalizedTokens:l}}if(a!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:a,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:l};let{reads:p,writes:f}=Ce(l);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:o,cached:true};let m=this.builderPool[this.builderPoolIndex++%this.builderPool.length];m.reset();let d$1,T=null;try{let b=U.track("parser",()=>(this.parseExpression(m,l,n),m.build()));d$1=b.result,T=b.alloc;}catch(b){let R=d(b);return this.rememberFailedParse(e,{error:R,normalizedTokens:l,reads:p,writes:f}),{kind:"error",stage:"parse",error:R,reads:p,writes:f,normalizedTokens:l}}return this.cacheBytecode(e,d$1,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:d$1,cached:false,parserAlloc:T}}preflightAsync(e,t,n,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let a=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",a,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(n,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(n,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,n$1,i){let s=this.prepareExpression(t,n$1,i,void 0,e);if(s.kind==="empty"){let p=n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:c,writes:l,program:a}=s,u=this.preflightAsync(o,a,e,t,c,l);return u.kind==="pending"?u.value:this.executeAndStore(a,e,t,c,l,"_engine")}evaluateLine(e,t){let n=this.evaluateLineWithDebug(e,t);if(n.error)throw n.engineError?n.engineError:c.execution("EVALUATION_ERROR",n.error,{lineNumber:e});return l$1(n.value)}evaluateLineWithDebug(e,t,n="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,n),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,n)}addDiagnosticStage(e,t,n,i,s,o,c,l,a){e.push({stage:t,label:n,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:l,output:a});}evaluateExpressionWithDiagnostic(e,t,n$1="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c$1=U.isEnabled(),l=[],a=[],u=0,p=ze(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$8.PipelineStart,elapsedNs:0,expression:e,inputType:n$1}),this.addDiagnosticStage(a,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:n$1}),this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let f=s?y=>{i.fireTokenEmitted({type:c$8.TokenEmitted,elapsedNs:0,expression:e,token:{type:y.type,value:y.value,offset:y.offset||0,line:y.line||t,col:y.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,f)),d$1=m.result.tokens,T=m.result.hasParens,b=m.result.compiled;if(c$1&&m.alloc&&l.push(m.alloc),s){let y={};for(let O of d$1)y[O.type]=(y[O.type]||0)+1;this.addDiagnosticStage(a,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d$1.length,tokenTypes:y,hasParens:T,locale:this.localeCode,tokens:[...d$1]});let A=[];for(let O=0;O<d$1.length;O++){let se=d$1[O];if(se.type==="INLINE_SOLVE_START"){let M=-1;for(let W=O+1;W<d$1.length;W++)if(d$1[W].type==="BACKTICK_OPEN"){M=W;break}if(M>O){let kr=d$1.slice(O+1,M).map(Sr=>Sr.value).join("");A.push({startTokenIndex:O,endTokenIndex:M,expression:kr,columnNumber:se.col||1}),O=M;}}}this.addDiagnosticStage(a,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&d$1.length===0){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let R=0,L=[],G=new Map,br=s?y=>{R++,L.push(y),G.set(y.rule,(G.get(y.rule)||0)+1),i.fireTokenFused({type:c$8.TokenFused,elapsedNs:0,expression:e,ruleName:y.rule,sourceTokenCount:y.sourceTokens.length,fusedTokenType:y.fusedToken.type,fusedTokenValue:y.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$8.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d$1.length});let D=this.bytecodeCache.get(e);s&&!D&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d$1,T,br,t);b&&v.kind==="ready"&&(d$1=v.normalizedTokens),c$1&&v.kind==="ready"&&v.parserAlloc&&l.push(v.parserAlloc),s&&!D&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d$1:v.normalizedTokens??d$1;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$8.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:R}),this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...G.entries()].map(([y,A])=>({rule:y,count:A})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:d$1.length,fusions:[],rulesApplied:[],tokens:[...d$1],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d$1)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d$1.length,totalOpcodes:0}),v.kind==="empty"){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let re=$e(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:re.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:re.errorMessage}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:re.errorMessage,engineError:re.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:re.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:0});let y={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,y,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:y,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],ne=v.writes??[];if(s&&(this.addDiagnosticStage(a,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:ne,isAssignment:ne.length>0}),this.addDiagnosticStage(a,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!D,cacheSize:this.bytecodeCache.size,cacheKey:e}),D?i.fireCacheHit({type:c$8.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$8.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0}),{value:n(0),tokens:k,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(a,"parser","Parser","\u{1F333}","parser",8,u,!!D,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(a,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!D,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!D}),i.fireBytecodeBuilt({type:c$8.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!D}));let Er=x.hasAsync||this.resolverRegistry.size>0,ie=this.preflightAsync(k,x,t,e,ge,ne);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:ie.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Er?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,ie.value,k,x,null):void 0};let xr=s&&this.config.diagnostic.vmTraceEnabled===true,N;try{let y=U.track("vm",()=>this.executeAndStore(x,t,e,ge,ne,"_engine",xr?i:void 0,e),{cacheHit:!!D});N=y.result,c$1&&y.alloc&&l.push(y.alloc);}catch(y){let A=d(y);return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:n(0),tokens:k,program:x,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let he=N.type===12;if(s){let y=he?"pending":String(N.value??""),A=he?"Pending":N.unit?"Uom":"Number";this.addDiagnosticStage(a,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:y,isPending:he});}if(he)return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:N,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,N,k,x,null):void 0};if(c$1&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!D)),s&&(this.addDiagnosticStage(a,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:ne,dataSourcesRegistered:[]}),this.addDiagnosticStage(a,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(a,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(N.value),formattedValue:String(N.value),valueType:N.type===0?"Number":"Value",unit:N.unit}),i.fireVmHalt({type:c$8.VmHalt,elapsedNs:0,expression:e,result:N?{type:N.type,value:N.value,unit:N.unit}:void 0}),this.addDiagnosticStage(a,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length,cacheHit:!!D}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),O=A;if(A){let se=A.parselets.slice(o),M={};for(let W of se)M[W.parseletCategory]=(M[W.parseletCategory]??0)+1;O={...A,parselets:se,summary:{...A.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:N,tokens:k,program:x,debug:O,diagnostic:this.buildDiagnosticResult(a,N,k,x,null)}}return {value:N,tokens:k,program:x}}buildDiagnosticResult(e,t,n,i,s){return {stages:e,value:t,tokens:n,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let n=this.lineCache.get(e,t);if(!n)return;let i=this.bytecodeCache.get(t);if(!i)return;if(n.bytecode.hasAsync||this.resolverRegistry.size>0){let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let a=c.signal,u=this.resolverRegistry.preflightAll([],n.bytecode,"_engine",a,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return n.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let n=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return n.length===0?[]:this.normalizer.normalize(n)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?a$6.keystrokeSignalSet(e.aborted):a$6.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,c]of this.bytecodeCache)e.push({expression:o,opcodesLength:c.opcodes.length,numbersLength:c.numbers.length,stringsLength:c.strings.length,hasAsync:c.hasAsync});let t=[];for(let o of this.lineCache.keys()){let c=o.indexOf(":"),l=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,a=c>0?o.slice(c+1):void 0,u=a!==void 0?this.lineCache.get(l,a):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let c=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:c}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(n);return Ge({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:n$1}=this.lexToTokens(e),i=this.prepareExpression(e,t,n$1,void 0,-1);if(i.kind==="empty")return n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:n}=t,i=this.prepareExpression(e,t.tokens,n),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$a(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:n}=this.lexToTokens(e);return this.prepareExpression(e,t,n).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return n(0);let n$1=this.executeRaw(e,t);if(n$1.type==="pending")return this.resolveAsync(n$1),O(n$1.queryKey);if(n$1.type==="error")throw n$1.error;return n$1.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let n=this.evaluateLine(-1,e);return n.isFault()?NaN:n.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$b()===this.queryClient&&a$7(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let a of Object.keys(e.dataSourceDeps)){let u=Number(a);Number.isNaN(u)||t.add(u);}let n=this.lineCache.snapshotEntries(),i=new Map;for(let{line:a,entry:u}of n){let p=t.has(a)||u.bytecode.hasAsync;p&&t.add(a);let f=u.writeVariable;if(f){let m=i.get(f);(!m||a>=m.line)&&i.set(f,{line:a,async:p});}}let s={};for(let[a,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(a)?.async)try{s[a]=Me(u,`variable "${a}"`);}catch(p){if(p instanceof b$a&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Ue),c=[];for(let{line:a,expression:u,entry:p}of n){if(t.has(a)||p.result.type===12)continue;let f;try{f=Me(p.result,`line ${a}`);}catch(m){if(m instanceof b$a&&m.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}c.push({line:a,expression:u,result:f,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([a,u])=>({expression:a,program:ue(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:l}}static fromJSON(e,t={}){rr(e);let n=t.locale??e.locale??"en",i=new Y({locale:n,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,n]of Object.entries(e.variables))this.vm.setVar(t,Be(n));for(let t of e.userFunctions){let n=_e(t);this.vm.defineUserFunction(n.name,n.params,n.program);}for(let t of e.lineCache){let n=new K(Be(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,n,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:n}of e.bytecodeCache)this.bytecodeCache.set(t,pe(n));}evaluateIncremental(e,t){let n$1=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,n(t));let i=new Map;for(let s of n$1){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.executeRaw(o.bytecode,s);if(c.type==="pending"){this.resolveAsync(c);continue}if(c.type==="error"){let a=P(c.error.code,c.error.message);i.set(s,a),o.result=a;continue}let l=c.value;i.set(s,l),o.result=l;}return i}};Y.GOAL_SEEK_MAX_NESTING_DEPTH=1,Y.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var vr=Y;export{Jr as a,Or as b,Qt as c,ee as d,Q as e,V as f,cn as g,Fe as h,ke as i,ze as j,$e as k,Ce as l,Cn as m,Tn as n,vr as o};//# sourceMappingURL=chunk-SNYFNARL.js.map
5
+ //# sourceMappingURL=chunk-SNYFNARL.js.map