solve-engine 2.20.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/chunk-3LUEJHAC.js +3 -0
  2. package/dist/chunk-3LUEJHAC.js.map +1 -0
  3. package/dist/chunk-4CNYGIND.js +2 -0
  4. package/dist/chunk-4CNYGIND.js.map +1 -0
  5. package/dist/{chunk-DLXG73JZ.js → chunk-4DJJIUQF.js} +2 -2
  6. package/dist/{chunk-DLXG73JZ.js.map → chunk-4DJJIUQF.js.map} +1 -1
  7. package/dist/chunk-4UHAGMER.cjs +3 -0
  8. package/dist/chunk-4UHAGMER.cjs.map +1 -0
  9. package/dist/chunk-A5M4QZIK.js +2 -0
  10. package/dist/chunk-A5M4QZIK.js.map +1 -0
  11. package/dist/{chunk-BB5RRSGS.js → chunk-AF7HQN6I.js} +2 -2
  12. package/dist/{chunk-BB5RRSGS.js.map → chunk-AF7HQN6I.js.map} +1 -1
  13. package/dist/{chunk-TLNKERM6.js → chunk-AHPBZTW6.js} +2 -2
  14. package/dist/{chunk-TLNKERM6.js.map → chunk-AHPBZTW6.js.map} +1 -1
  15. package/dist/chunk-ALY4ZMYO.js +2 -0
  16. package/dist/{chunk-YBKMCGJ3.js.map → chunk-ALY4ZMYO.js.map} +1 -1
  17. package/dist/{chunk-6NXOKM2O.js → chunk-CHVGFTO3.js} +2 -2
  18. package/dist/{chunk-6NXOKM2O.js.map → chunk-CHVGFTO3.js.map} +1 -1
  19. package/dist/{chunk-Y6QP576X.js → chunk-DCNGKGOZ.js} +3 -3
  20. package/dist/{chunk-Y6QP576X.js.map → chunk-DCNGKGOZ.js.map} +1 -1
  21. package/dist/{chunk-XB3TWS7J.cjs → chunk-EZKR44MA.cjs} +2 -2
  22. package/dist/chunk-EZKR44MA.cjs.map +1 -0
  23. package/dist/{chunk-6EPJNHSQ.js → chunk-FP6Z6PYR.js} +2 -2
  24. package/dist/{chunk-6EPJNHSQ.js.map → chunk-FP6Z6PYR.js.map} +1 -1
  25. package/dist/{chunk-WOGCCIKZ.js → chunk-GF3Z6DDF.js} +3 -3
  26. package/dist/{chunk-WOGCCIKZ.js.map → chunk-GF3Z6DDF.js.map} +1 -1
  27. package/dist/{chunk-CDIHV3ZS.js → chunk-HMC7FJO7.js} +2 -2
  28. package/dist/{chunk-CDIHV3ZS.js.map → chunk-HMC7FJO7.js.map} +1 -1
  29. package/dist/{chunk-KQQWHGCN.cjs → chunk-IFGF26F4.cjs} +2 -2
  30. package/dist/{chunk-KQQWHGCN.cjs.map → chunk-IFGF26F4.cjs.map} +1 -1
  31. package/dist/{chunk-IXOE2BQG.cjs → chunk-J4LSAHCY.cjs} +2 -2
  32. package/dist/{chunk-IXOE2BQG.cjs.map → chunk-J4LSAHCY.cjs.map} +1 -1
  33. package/dist/{chunk-TM752D4J.cjs → chunk-KRXO3MOW.cjs} +2 -2
  34. package/dist/{chunk-TM752D4J.cjs.map → chunk-KRXO3MOW.cjs.map} +1 -1
  35. package/dist/{chunk-DGAFTYOC.cjs → chunk-LZAW6QB3.cjs} +4 -4
  36. package/dist/{chunk-DGAFTYOC.cjs.map → chunk-LZAW6QB3.cjs.map} +1 -1
  37. package/dist/{chunk-53JLDRXA.cjs → chunk-N37PUZJR.cjs} +2 -2
  38. package/dist/{chunk-53JLDRXA.cjs.map → chunk-N37PUZJR.cjs.map} +1 -1
  39. package/dist/{chunk-6CFYMI6C.cjs → chunk-ORZLXBDK.cjs} +3 -3
  40. package/dist/{chunk-6CFYMI6C.cjs.map → chunk-ORZLXBDK.cjs.map} +1 -1
  41. package/dist/{chunk-MDLR2PWN.js → chunk-PRSXXDTA.js} +2 -2
  42. package/dist/chunk-PRSXXDTA.js.map +1 -0
  43. package/dist/{chunk-KLPKLTJZ.cjs → chunk-SGIDBZ4T.cjs} +2 -2
  44. package/dist/{chunk-KLPKLTJZ.cjs.map → chunk-SGIDBZ4T.cjs.map} +1 -1
  45. package/dist/{chunk-QD2Z5TDD.cjs → chunk-UNKSCVIL.cjs} +2 -2
  46. package/dist/{chunk-QD2Z5TDD.cjs.map → chunk-UNKSCVIL.cjs.map} +1 -1
  47. package/dist/{chunk-EAB6SSAV.cjs → chunk-USQ4KL6S.cjs} +2 -2
  48. package/dist/{chunk-EAB6SSAV.cjs.map → chunk-USQ4KL6S.cjs.map} +1 -1
  49. package/dist/chunk-XDXIPVZB.cjs +2 -0
  50. package/dist/chunk-XDXIPVZB.cjs.map +1 -0
  51. package/dist/chunk-ZKFCKAIX.cjs +2 -0
  52. package/dist/chunk-ZKFCKAIX.cjs.map +1 -0
  53. package/dist/constants.cjs +1 -1
  54. package/dist/constants.js +1 -1
  55. package/dist/engine.cjs +1 -1
  56. package/dist/engine.js +1 -1
  57. package/dist/index.cjs +1 -1
  58. package/dist/index.js +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/language.cjs +1 -1
  61. package/dist/language.js +1 -1
  62. package/dist/lexer.cjs +1 -1
  63. package/dist/lexer.js +1 -1
  64. package/dist/normalizer.cjs +1 -1
  65. package/dist/normalizer.js +1 -1
  66. package/dist/packages.cjs +1 -1
  67. package/dist/packages.d.cts +47 -1
  68. package/dist/packages.d.ts +47 -1
  69. package/dist/packages.js +1 -1
  70. package/dist/testing.cjs +2 -2
  71. package/dist/testing.js +1 -1
  72. package/dist/uom.cjs +1 -1
  73. package/dist/uom.js +1 -1
  74. package/dist/vm.cjs +1 -1
  75. package/dist/vm.js +1 -1
  76. package/dist/worker.cjs +2 -2
  77. package/dist/worker.js +1 -1
  78. package/dist/worker.js.map +1 -1
  79. package/package.json +1 -1
  80. package/dist/chunk-3AES5ZGS.cjs +0 -3
  81. package/dist/chunk-3AES5ZGS.cjs.map +0 -1
  82. package/dist/chunk-6YGRMAQR.js +0 -2
  83. package/dist/chunk-6YGRMAQR.js.map +0 -1
  84. package/dist/chunk-7WX33WM2.js +0 -3
  85. package/dist/chunk-7WX33WM2.js.map +0 -1
  86. package/dist/chunk-BVSATTRX.cjs +0 -2
  87. package/dist/chunk-BVSATTRX.cjs.map +0 -1
  88. package/dist/chunk-HCPZRSHR.cjs +0 -2
  89. package/dist/chunk-HCPZRSHR.cjs.map +0 -1
  90. package/dist/chunk-JMYBZ6JF.js +0 -2
  91. package/dist/chunk-JMYBZ6JF.js.map +0 -1
  92. package/dist/chunk-MDLR2PWN.js.map +0 -1
  93. package/dist/chunk-XB3TWS7J.cjs.map +0 -1
  94. package/dist/chunk-YBKMCGJ3.js +0 -2
@@ -1,2 +0,0 @@
1
- import {a,b,f,e,d,c as c$1}from'./chunk-MDLR2PWN.js';var p=new Map(Object.entries(a)),B=new Map(Object.entries(b));function c(n){return p.get(n)}function m(n,e,t){let r=p.get(e);if(r===void 0)throw new RangeError(`${e} is not a valid unit`);let i=p.get(t);if(i===void 0)throw new RangeError(`${t} is not a valid unit`);return T(n,e,t,r,i)}function T(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],f=B.get(e),g=B.get(t);return f!==void 0?g!==void 0?(n+f)*(u/a)-g:(n+f)*(u/a):g!==void 0?n*(u/a)-g:n*(u/a)}function O(n,e){let t=p.get(e);if(t===void 0)throw new RangeError(`${e} is not a valid unit`);let r=c$1[t[0]],i=r[0][0],s=i,o=m(n,e,i),u=o<0?-o:o;for(let a=0;a<r.length;a++){let f=r[a];if(u>=f[1])s=f[0];else break}return {quantity:m(n,e,s),unit:s}}var D=new Set(["workday","workdays"]),S=7/5;function l(n){return typeof n=="string"&&D.has(n)}function Y(n){return n}function E(n){if(l(n))return E("day");let e$1=f[n];if(e$1)return e$1.measure;let t=c(n);if(t!==void 0)return e[t[0]]}function j(n,e){if(n===e)return true;if(l(n)||l(e)){let o=E(n),u=E(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=f[n],s=f[e];return i!==void 0&&s!==void 0?i.measure===s.measure:U(n,e)||U(e,n)}function U(n,e$1){let t=f[n];if(t===void 0)return false;let r=c(e$1);return r===void 0?false:e[r[0]]===t.measure}function M(n,e,t){if(e===t)return n;let r=c(e),i=c(t);if(r!==void 0&&i!==void 0)return T(n,e,t,r,i);if(l(e)&&l(t))return n;if(l(e)){let u=n*S;return t==="day"?u:M(u,"day",t)}if(l(t))return (e==="day"?n:M(n,e,"day"))/S;let s=f[e],o=f[t];return s!==void 0&&o!==void 0?n*(s.toBase/o.toBase):s!==void 0&&U(e,t)?m(n*s.toBase,k(t),t):o!==void 0&&U(t,e)?m(n,e,k(e))/o.toBase:m(n,e,t)}function k(n){let e=c(n);if(e===void 0)return n;for(let t of Object.keys(a)){let r=a[t];if(r[0]===e[0]&&r[1]===1)return t}return n}function P(n){let e=n,t=c(e);if(t===void 0)return [];let r=d[t[0]];return r?r.filter(i=>i!==e):[]}function W(n){return l(n)||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 A={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 I(n,e){let t=A[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=f[e];return i!==void 0&&i.measure==="speed"?{value:n*i.toBase,numerator:"m",denominator:"s"}:null}function y(n,e){if(n===e)return 1;if(n===""||e==="")return null;let t=E(n),r=E(e);return t===void 0||r===void 0||t!==r?null:M(1,n,e)}function X(n,e,t){let r=I(n,e);if(r===null)return null;let i,s,o,u=A[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 R=f[t];if(R===void 0||R.measure!=="speed")return null;i="m",s="s",o=R.toBase;}let f$1=y(r.numerator,i),g=y(r.denominator,s);if(f$1!==null&&g!==null)return r.value*f$1/g/o;let _=y(r.denominator,i),w=y(r.numerator,s);return _!==null&&w!==null&&r.value!==0?_/w/r.value/o:null}export{l as a,Y as b,E as c,j as d,M as e,P as f,W as g,Q as h,X as i};//# sourceMappingURL=chunk-6YGRMAQR.js.map
2
- //# sourceMappingURL=chunk-6YGRMAQR.js.map
@@ -1 +0,0 @@
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","rateAxisFactor","convertRate","source","targetNumerator","targetDenominator","targetScale","fuelTarget","numeratorFactor","denominatorFactor","crossNumerator","crossDenominator"],"mappings":"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","file":"chunk-6YGRMAQR.js","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 this is always safe.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\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 return null;\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,3 +0,0 @@
1
- import {b as b$2,a as a$3}from'./chunk-MRRMIBHE.js';import {a as a$5,c as c$5,e as e$2,d,g as g$1,f}from'./chunk-CDIHV3ZS.js';import {a,d as d$1,e as e$3}from'./chunk-O3BDXOQJ.js';import {b as b$5,e as e$5}from'./chunk-DLXG73JZ.js';import {a as a$8}from'./chunk-76F3LCIL.js';import {b as b$4}from'./chunk-TCZSPH4A.js';import {F as F$1,J as J$1,B as B$2,d as d$3,z as z$3,A as A$1}from'./chunk-JMYBZ6JF.js';import {c as c$3}from'./chunk-EQDT42JG.js';import {a as a$4}from'./chunk-HFKDWQUL.js';import {B as B$1,i,z as z$1,y,q as q$1,u,t as t$1,b as b$3,h,s,r,p,o,n as n$1,e,a as a$1,c as c$2,A,j,k as k$1,l,m,d as d$4,v,w,x,F as F$2,E,G as G$2,H as H$1,C as C$1}from'./chunk-5TCSFTZD.js';import {ta,q as q$2,p as p$1,d as d$2,Q as Q$2,e as e$4}from'./chunk-KEA5HRL3.js';import {P,t,L,G as G$1,n,Q as Q$1,u as u$1,M,z as z$2,K as K$1,I,J as J$2,m as m$1,C,g}from'./chunk-3GR46UOX.js';import {c as c$4,e as e$1,d as d$5}from'./chunk-6YGRMAQR.js';import {a as a$2}from'./chunk-BB5RRSGS.js';import {c}from'./chunk-IJMNVBIS.js';import {a as a$6}from'./chunk-LHLW7JLS.js';import {b as b$1}from'./chunk-6NXOKM2O.js';import {a as a$7}from'./chunk-MDLR2PWN.js';import {c as c$1}from'./chunk-PIZQIQVM.js';var Uu=/^\d{1,3}(\.\d{3}){2,}$/,Du=/^\d*\.\d*$/,ht=class{constructor(){this.category="Arithmetic";}parse(e,o,r){let n,i=null,a=o.value;if(a.startsWith("0x")||a.startsWith("0X")){if(n=parseInt(a,16),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${a}"`,{raw:a})}else if(a.startsWith("0b")||a.startsWith("0B")){if(n=parseInt(a.slice(2),2),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${a}"`,{raw:a})}else if(a.startsWith("0o")||a.startsWith("0O")){if(n=parseInt(a.slice(2),8),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${a}"`,{raw:a})}else if(Uu.test(a))n=parseFloat(a.split(".").join(""));else {let s=a$6(e.getLocaleCode()),l=s.display.decimalSeparator,u=s.display.thousandsSeparator,c=a;u&&(c=c.split(u).join("")),l&&l!=="."&&(c=c.replace(l,".")),n=parseFloat(c),Du.test(c)&&(i=c);}if(i!==null){r.emitOpcode(16),r.emitString(i);return}r.emitOpcode(10),r.emitNumber(n);}};var he=class{constructor(e){this.opcode=e;this.category="Arithmetic";}parse(e,o,r){e.parseExpression(60,r),r.emitOpcode(this.opcode);}};var k=class{constructor(e,o,r=false){this.opcode=o;this.category="Arithmetic";this.bindingPower=e,this.rightBindingPower=r?e-1:e;}parse(e,o,r,n){e.parseExpression(this.rightBindingPower,n),n.emitOpcode(this.opcode);}};var It=class{constructor(){this.category="Arithmetic";}parse(e,o,r){e.parseExpression(0,r);let n=1;for(;e.match("COMMA");)e.parseExpression(0,r),n++;e.consume("RPAREN"),n>1&&(r.emitOpcode(152),r.emitIndex(1),r.emitIndex(n));}};var We=class{constructor(){this.category="Arithmetic";}parse(e,o,r){let n=o.type==="PI"?Math.PI:Math.E;r.emitOpcode(10),r.emitNumber(n);}};var bu={k:3,M:6,G:9,B:9,T:12},Vu={thousand:3,thousands:3,million:6,millions:6,mn:6,billion:9,billions:9,bn:9,trillion:12,trillions:12,tn:12},Fu=/^\d+(\.\d+)?$/;function Hu(t,e){let o=t.indexOf("."),r=o===-1?t:t.slice(0,o),n=o===-1?"":t.slice(o+1);n.length<e&&(n=n.padEnd(e,"0"));let i=r+n.slice(0,e),a=n.slice(e);return a?`${i}.${a}`:i}function xa(t=65){return {name:"arithmetic:large-number-suffix",priority:t,shape:[{types:["NUMBER"]},{types:["IDENT","UNIT"]}],match(e,o){let r=e[o];if(r.type!=="NUMBER"||!Fu.test(r.text))return null;let n=e[o+1];if(!n||n.type!=="IDENT"&&n.type!=="UNIT")return null;let i=r.offset+r.text.length===n.offset,a=n.type==="UNIT"?void 0:Vu[n.value.toLowerCase()],s=i?bu[n.value]??a:a;if(s===void 0)return null;let l=Hu(r.text,s);return {consumed:2,replacement:[b$5("NUMBER",l,e.slice(o,o+2))],ruleName:"arithmetic:large-number-suffix"}}}}var jo={name:"solve-arithmetic",prefixParselets:{NUMBER:new ht,LPAREN:new It,PI:new We,E:new We,PLUS:new he(27),MINUS:new he(26),BIT_NOT:new he(36)},infixParselets:{PLUS:new k(a.Sum,20),AND_CONJ:new k(a.Conjunction,20),MINUS:new k(a.Sum,21),STAR:new k(a.Product,22),SLASH:new k(a.Product,23),MOD:new k(a.Product,24),CARET:new k(a.Exponent,25,true),TIMES_BY:new k(a.Product,22),MULTIPLY_BY:new k(a.Product,22),DIVIDE_BY:new k(a.Product,23),LSHIFT:new k(a.Shift,30),RSHIFT:new k(a.Shift,31),URSHIFT:new k(a.Shift,32),BIT_AND:new k(a.BitwiseAnd,33),BIT_OR:new k(a.BitwiseOr,34),BIT_XOR:new k(a.BitwiseXor,35)},normalizerRules:[xa()]};var Ct=class{constructor(){this.category="Percentage";this.bindingPower=a.Prefix;}parse(e,o,r,n){n.emitOpcode(10),n.emitNumber(100),n.emitOpcode(23),n.emitOpcode(74);}};var St=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,r,n){if(ha(e,"what")){e.consume(),this.parseWhatRate(e,n);return}this.parseWhatBase(e,n);}parseWhatRate(e,o){if(!e.match("PERCENT"))throw c$1.parsing("IS_WHAT_EXPECTED_PERCENT",'Expected "%" after "is what", as in "20 is what % of 200"');let r=Gu(e);if(r===null){o.emitOpcode(74);return}e.parseExpression(a.Conditional,o),o.emitOpcode(23),r==="off"?(o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(21)):r==="on"&&(o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(21)),o.emitOpcode(74);}parseWhatBase(e,o){if(e.parseExpression(a.Conditional,o),e.match("TO")){Oa(e,"what",'"81 is 9 to what power"'),Oa(e,"power",'"81 is 9 to what power"'),o.emitOpcode(51),o.emitIndex(Ra),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(51),o.emitIndex(Ra),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(23);return}let r=e.match("OF_WHAT")?"of":e.match("OFF_WHAT")?"off":e.match("ON_WHAT")?"on":null;if(r===null)throw c$1.parsing("IS_WHAT_EXPECTED_PREPOSITION",'Expected "of what", "off what" or "on what", as in "20 is 10% of what"');if(r==="of"){o.emitOpcode(23);return}o.emitOpcode(10),o.emitNumber(1),r==="off"?(o.emitOpcode(2),o.emitOpcode(21)):o.emitOpcode(20),o.emitOpcode(23);}},Ra=5;function ha(t,e){return (t.peek()?.text??"").toLowerCase()===e}function Oa(t,e,o){if(!ha(t,e))throw c$1.parsing("IS_WHAT_EXPECTED_WORD",`Expected "${e}" here, as in ${o}`);t.consume();}function Gu(t){if(t.match("OF"))return "of";let e=(t.peek()?.text??"").toLowerCase();return e==="off"||e==="on"?(t.consume(),e):null}var Ye=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(a.Conditional,n),n.emitOpcode(2),n.emitOpcode(10),n.emitNumber(1),this.sign===1?n.emitOpcode(20):(n.emitOpcode(2),n.emitOpcode(21)),n.emitOpcode(22);}};function Ia(t=68){return {name:"percentage:on-off",priority:t,shape:[{types:["PERCENT"]},{types:["IDENT"],values:["on","off"]}],match(e,o){if(e[o]?.type!=="PERCENT")return null;let r=e[o+1];if(r?.type!=="IDENT")return null;let n=(r.text??r.value??"").toLowerCase();return n!=="on"&&n!=="off"||(e[o+2]?.text??"").toLowerCase()==="what"?null:{consumed:2,replacement:[e[o],b$5(n==="on"?"PCT_ON":"PCT_OFF",n,[r])],ruleName:"percentage:on-off"}}}}var Lt=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(22);}};var wt=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23);}};var je=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,r,n){n.emitOpcode(10),n.emitNumber(1),this.sign===1?n.emitOpcode(20):(n.emitOpcode(2),n.emitOpcode(21)),e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23);}};var Xe=class{constructor(e){this.multiplier=e;this.category="Percentage";}parse(e,o,r){e.parseExpression(0,r);let n=e.peek();n&&(n.type==="IDENT"||n.type==="BY")&&e.consume(),r.emitOpcode(10),r.emitNumber(1),e.parseExpression(0,r),e.peek()?.type==="PERCENT"&&e.consume(),r.emitOpcode(this.multiplier>0?20:21),r.emitOpcode(22);}};var Qe=class{constructor(e){this.multiplier=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(2),n.emitOpcode(this.multiplier>0?20:21),n.emitOpcode(22);}};var vt=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,r,n){if(o.type==="UNIT")return;let i=e.peek();if(i&&((i.type==="UNIT"||i.type==="IDENT")&&b$1(i.value)||i.type==="IN")){e.consume(),n.emitOpcode(13),n.emitString(i.value),n.emitOpcode(84);return}e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(21),n.emitOpcode(74);}};var zu={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12};function Ku(t){if(t.type==="NUMBER"){let e=Number(t.value);return Number.isInteger(e)&&e>=0?e:null}return t.type==="IDENT"?zu[t.value.toLowerCase()]??null:null}var qe=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(2),n.emitOpcode(this.sign>0?20:21);let i=this.tryConsumeRepeat(e);i!==null&&(n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(25)),n.emitOpcode(22),this.consumeChainThen(e);}tryConsumeRepeat(e){let o=e.peek(),r=e.peekAt(1);if(!o||!r||r.type!=="STAR"||r.value.toLowerCase()!=="times")return null;let n=Ku(o);return n===null?null:(e.consume(),e.consume(),n)}consumeChainThen(e){if(e.peek()?.type!=="THEN")return;let o=e.peekAt(1)?.type;(o==="PCT_UP"||o==="PCT_DOWN")&&e.consume();}};function Ca(t,e){let o=t[e];if(o?.type!=="IDENT")return null;let r=(o.text??o.value??"").toLowerCase();return r!=="up"&&r!=="down"||t[e+1]?.type!=="NUMBER"||t[e+2]?.type!=="PERCENT"?null:b$5(r==="up"?"PCT_UP":"PCT_DOWN",r,[o])}function Sa(t=68){return {name:"percentage:up-down",priority:t,shape:[{types:["NUMBER","RPAREN","IDENT"]}],match(e,o){let r=e[o];if(r&&(r.type==="NUMBER"||r.type==="RPAREN")){let i=Ca(e,o+1);if(i)return {consumed:2,replacement:[r,i],ruleName:"percentage:up-down"}}let n=Ca(e,o);return n?{consumed:1,replacement:[n],ruleName:"percentage:up-down"}:null}}}var Xo={name:"solve-percentage",phrases:{"of what is":"OF_WHAT_IS","of what":"OF_WHAT","off what":"OFF_WHAT","on what":"ON_WHAT","on what is":"ON_WHAT_IS","off what is":"OFF_WHAT_IS"},infixParselets:{PERCENT:new Ct,IS:new St,PCT_ON:new Ye(1),PCT_OFF:new Ye(-1),OF:new Lt,OF_WHAT_IS:new wt,ON_WHAT_IS:new je(1),OFF_WHAT_IS:new je(-1),TO:new vt,INCREASE_BY:new Qe(1),DECREASE_BY:new Qe(-1),PCT_UP:new qe(1),PCT_DOWN:new qe(-1)},prefixParselets:{INCREASE:new Xe(1),DECREASE:new Xe(-1)},normalizerRules:[Ia(),Sa()]};var Qo={sqrt:0,abs:1,sin:2,cos:3,tan:4,log:5,ceil:6,floor:7,round:8,min:9,max:10,asin:11,acos:12,atan:13,atan2:14,arcsin:11,arccos:12,arctan:13,sind:87,cosd:88,tand:89,asind:90,acosd:91,atand:92,sinh:15,cosh:16,tanh:17,asinh:18,acosh:19,atanh:20,cbrt:21,clz32:22,expm1:23,exp:24,fround:25,hypot:26,imul:27,log10:28,log1p:29,log2:30,pow:31,random:32,sign:33,trunc:34,degtorad:35,radtodeg:36,gcd:38,lcm:39,permutation:40,combination:41,hex:48,bin:49,int:50,compoundinterest:51,interestearned:52,compoundinterestrate:53,compoundinterestyears:54,loanrepayment:55,loaninterest:56,monthlypayment:57,taxadd:58,taxremove:59,inflationadjust:60,root:61,fact:62,factorial:62,transpose:63,det:64,inv:65,dot:66},kt=class{constructor(){this.category="Function";}parse(e,o,r){let n=o.value.toLowerCase(),i=Qo[n];if(i===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown function: ${n}`,{functionName:n});e.consume("LPAREN");let a$1=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),a$1++;e.match("COMMA");)e.parseExpression(a.Lowest,r),a$1++;e.consume("RPAREN"),r.emitOpcode(51),r.emitIndex(i),r.emitIndex(a$1);}};var qo={name:"solve-function",prefixParselets:{FUNC:new kt}};var pe=class{constructor(e=0){this.category="Date/Time";this.dayOffset=e;}parse(e,o,r){r.emitOpcode(90),this.dayOffset!==0&&(r.emitOpcode(10),r.emitNumber(this.dayOffset),r.emitOpcode(13),r.emitString("days"),r.emitOpcode(80),r.emitOpcode(20));}};var $u={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},Ze=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,r){let n=e.peek(),i=n?$u[n.type]:void 0;if(i===void 0)throw c$1.parsing("MISSING_WEEKDAY",`"${o.value}" must be followed by a day of the week (e.g. "${o.value} Saturday")`,{keyword:o.value,actualType:n?.type,actualValue:n?.value});e.consume(),r.emitOpcode(90),r.emitOpcode(10),r.emitNumber(i),r.emitOpcode(this.direction==="next"?93:94);}};var Je=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,r){let n=o.value;this.direction==="until"?(e.parseExpression(0,r),r.emitOpcode(90)):(r.emitOpcode(90),e.parseExpression(0,r)),r.emitOpcode(21),r.emitOpcode(13),r.emitString(n),r.emitOpcode(84);}};var Bt=class{constructor(){this.category="Date/Time";}parse(e,o,r){e.parseExpression(0,r),r.emitPluginCall("workdaysInDuration",1);}};var et=class{constructor(e){this.direction=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(a.Sum,n),n.emitOpcode(96),n.emitByte(this.direction==="backward"?1:0);}};var Mt=class{constructor(){this.category="Date/Time";}parse(e,o,r){e.parseExpression(a.Product,r),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,r),r.emitOpcode(97);}};var J=class{constructor(e,o){this.functionName=e;this.mode=o;this.category="Date/Time";}parse(e,o,r){this.mode==="in"?(r.emitOpcode(90),e.parseExpression(0,r),r.emitOpcode(20)):e.peek()?e.parseExpression(0,r):r.emitOpcode(90),r.emitPluginCall(this.functionName,1);}};var Ut=class{constructor(){this.category="Date/Time";}parse(e,o,r){let n=o.value;e.parseExpression(a.Product,r),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,r),r.emitPluginCall("spanBetweenDates",2),r.emitOpcode(13),r.emitString(n),r.emitOpcode(84);}};var tt=class{constructor(e){this.functionName=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,r,n){n.emitPluginCall(this.functionName,1);}};var Dt=class{constructor(){this.category="Date/Time";}parse(e,o,r){r.emitOpcode(90),r.emitPluginCall("toTimestampFromAny",1);}};var bt=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,r,n){n.emitPluginCall("toDateFromAny",1);}};var Vt=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,r,n){n.emitPluginCall("toTimestampFromAny",1);}};var Ft=class{constructor(){this.category="Date/Time";}parse(e,o,r){r.emitOpcode(95),r.emitNumber(Number(o.value));}};var Ht=class{constructor(){this.category="Date/Time";}parse(e,o,r){e.consume("OF"),e.parseExpression(a.Postfix,r),r.emitOpcode(13),r.emitString(o.value),r.emitPluginCall("nthWeekdayOfMonth",2);}};var Ie=class{constructor(e){this.offsetMonths=e;this.category="Date/Time";}parse(e,o,r){r.emitOpcode(90),r.emitOpcode(10),r.emitNumber(this.offsetMonths),r.emitPluginCall("monthAnchorShift",2);}};var Wu=new Set(["year","years","month","months","day","days"]),Gt=class{constructor(){this.category="Date/Time";}parse(e,o,r){e.parseExpression(a.Postfix,r),this.wordIs(e.peek(),"on")?(e.consume(),e.parseExpression(a.Postfix,r)):r.emitOpcode(90);let n=this.consumeBreakdown(e)?"ymd":"years";r.emitOpcode(13),r.emitString(n),r.emitPluginCall("ageBetween",3);}wordIs(e,o){return e?String(e.value??e.text??"").toLowerCase()===o:false}consumeBreakdown(e){if(e.peek()?.type!=="IN")return false;e.consume();let o=false;for(;;){let r=e.peek();if(!r)break;let n=String(r.value??r.text??"").toLowerCase();if(r.type==="UNIT"&&Wu.has(n))o=true,e.consume();else if(r.type==="COMMA"||r.type==="AND_CONJ"||n==="and")e.consume();else break}return o}};function Yu(t){let e=t[0],o;if(e.type===6&&e.unit){if(c$4(e.unit)!=="time")return P("WORKDAYS_IN_EXPECTED_DURATION",`"workdays in" expects a time duration, got unit "${e.unit}"`);o=e$1(e.toNumber(),e.unit,"day");}else o=e.toNumber();let r=o<0?-1:1,n$1=Math.abs(o),i=Math.floor(n$1/7),a=n$1-i*7,s=r*(i*5+Math.min(a,5));return n(s)}var ju=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function rt(t,e){return t.type===4?t.toNumber():P("DATE_FIELD_EXPECTED_DATE",`"${e}" expects a date, got ${g[t.type]??"an unsupported value"}`)}function Xu(t$1){let e=rt(t$1[0],"weekday");return typeof e!="number"?e:t(ju[new Date(e).getDay()])}var Qu=["January","February","March","April","May","June","July","August","September","October","November","December"];function qu(t$1){let e=rt(t$1[0],"month");return typeof e!="number"?e:t(Qu[new Date(e).getMonth()])}function Zu(t){let e=rt(t[0],"week");if(typeof e!="number")return e;let o=new Date(e),r=new Date(Date.UTC(o.getFullYear(),o.getMonth(),o.getDate())),n$1=r.getUTCDay()===0?7:r.getUTCDay();r.setUTCDate(r.getUTCDate()+4-n$1);let i=Date.UTC(r.getUTCFullYear(),0,1),a=Math.floor((r.getTime()-i)/864e5);return n(Math.floor(a/7)+1)}function La(t){let e=new Date(t).getDay();return e===0||e===6}function Ju(t){let e=rt(t[0],"is a weekend");return typeof e!="number"?e:L(La(e))}function ec(t){let e=rt(t[0],"is a workday");return typeof e!="number"?e:L(!La(e))}function tc(t){return u$1(Math.abs(t[0].toNumber()-t[1].toNumber()),"ms")}function rc(t){let e=t[0];if(e.type===4)return e;if(e.type===3){let o=c$5(e.value);return o===null?P("INVALID_ISO8601_STRING",`"${e.value}" is not a recognizable ISO8601 date/time string`):M(o)}return M(e$2(e.toNumber()))}function oc(t){let e=t[0];if(e.type===3){let o=c$5(e.value);return o===null?P("INVALID_ISO8601_STRING",`"${e.value}" is not a recognizable ISO8601 date/time string`):n(Math.floor(o/1e3))}return n(Math.floor(e.toNumber()/1e3))}var wa=Yu,Zo=Xu,Jo=qu,en=Zu,va=Ju,ka=ec,Ba=tc,Ma=rc,Ua=oc;function tn(t,e){return new Date(t,e+1,0).getDate()}function Va(t,e,o,r){let n=new Date(t,e,1).getDay(),a=1+(o-n+7)%7+(r-1)*7;return a<1||a>tn(t,e)?null:new Date(t,e,a).getTime()}function Fa(t,e,o){let r=tn(t,e),i=(new Date(t,e,r).getDay()-o+7)%7;return new Date(t,e,r-i).getTime()}function Ha(t,e){let o=new Date(t),r=new Date(e),n=r.getFullYear()-o.getFullYear();return (r.getMonth()<o.getMonth()||r.getMonth()===o.getMonth()&&r.getDate()<o.getDate())&&n--,n}function Da(t,e){let o=t.getFullYear(),r=t.getMonth()+e,n=o+Math.floor(r/12),i=(r%12+12)%12,a=Math.min(t.getDate(),tn(n,i));return new Date(n,i,a)}function ba(t){return Math.floor(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())/864e5)}function Ga(t,e){let o=new Date(t),r=new Date(e),n=(r.getFullYear()-o.getFullYear())*12+(r.getMonth()-o.getMonth());Da(o,n)>r&&n--;let i=Da(o,n),a=ba(r)-ba(i);return {years:Math.floor(n/12),months:n%12,days:a}}function za(t,e){let o=new Date(t);return new Date(o.getFullYear(),o.getMonth()+e,1).getTime()}function Kt(t,e){return t.type===4?t.toNumber():P("DATE_EXPECTED",`"${e}" expects a date, got ${g[t.type]??"an unsupported value"}`)}function nc(t){let e=Kt(t[0],"nth weekday of month");if(typeof e!="number")return e;let o=String(t[1].value??""),[r,n]=o.split(":"),i=Number(n),a=new Date(e),s=a.getFullYear(),l=a.getMonth();if(r==="last")return M(Fa(s,l,i));let u=Number(r),c=Va(s,l,i,u);return c===null?P("NTH_WEEKDAY_OUT_OF_RANGE",`there is no ${r}${ic(u)} occurrence of that weekday in the month`):M(c)}function ic(t){let e=t%100;if(e>=11&&e<=13)return "th";switch(t%10){case 1:return "st";case 2:return "nd";case 3:return "rd";default:return "th"}}function ac(t){let e=Kt(t[0],"month anchor");if(typeof e!="number")return e;let o=t[1].toNumber();return M(za(e,o))}var sc="ymd";function mc(t$1){let e=Kt(t$1[0],"age of");if(typeof e!="number")return e;let o=Kt(t$1[1],"age of");return typeof o!="number"?o:String(t$1[2].value??"years")===sc?t(lc(Ga(e,o))):u$1(Ha(e,o),"years")}function lc(t){let e=[];return t.years!==0&&e.push(zt(t.years,"year")),t.months!==0&&e.push(zt(t.months,"month")),t.days!==0&&e.push(zt(t.days,"day")),e.length===0?zt(0,"day"):e.join(", ")}function zt(t,e){return `${t} ${e}${Math.abs(t)===1?"":"s"}`}var Ka=nc,$a=ac,Wa=mc;var uc={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},Ya="NTH_WEEKDAY",cc=c(Ya),pc=/^(\d+)(st|nd|rd|th)$/i;function ja(t=66){let e="datetime:nth-weekday";return {name:e,priority:t,unshapedReason:"Reads an ordinal that may be the LAST keyword, a number, or a word like `third`, so no fixed first-token set describes it.",match(o,r){let n=o[r];if(!n)return null;let i=null,a=0;if(n.type==="LAST")i="last",a=1;else {let f=o[r+1];if(!f||(n.sourceEnd??n.offset+(n.text?.length??0))!==f.offset)return null;let N=(n.text??"")+(f.text??""),E=pc.exec(N);if(!E)return null;i=String(Number(E[1])),a=2;}let s=o[r+a],l=s?uc[s.type]:void 0;if(l===void 0||o[r+a+1]?.type!=="OF")return null;let u=`${i}:${l}`,c=new a$2(Ya,cc,u,u,n.offset,0,n.line,n.col);return {consumed:a+1,replacement:[c],ruleName:e}}}}function Xa(t=60){return {name:"datetime:until-since",priority:t,shape:[{types:["UNIT"]},{types:["UNTIL","SINCE"]}],match(e,o){if(o+1>=e.length)return null;let r=e[o],n=e[o+1];if(r.type!=="UNIT"||n.type!=="UNTIL"&&n.type!=="SINCE")return null;let i=n.type==="UNTIL"?"UNTIL_UNIT":"SINCE_UNIT";return {consumed:2,replacement:[b$5(i,r.value,[r,n])],ruleName:`datetime:${n.type.toLowerCase()}`}}}}function Qa(t=60){return {name:"datetime:between-unit",priority:t,startTokenTypes:["UNIT","IDENT"],match(e,o){let r=o,n=0;e[o]?.value?.toLowerCase()==="how"&&e[o+1]?.value?.toLowerCase()==="many"&&(r=o+2,n=2);let i=e[r],a=e[r+1];if(!i||!a||i.type!=="UNIT")return null;let s=a.type==="BETWEEN",l=a.type==="UNTIL"||a.type==="SINCE";if(!s&&!l||l&&n===0)return null;let u=e.slice(o,r+2);return l?{consumed:n+2,replacement:[i,a],ruleName:"datetime:how-many"}:{consumed:n+2,replacement:[b$5("BETWEEN_UNIT",i.value,u)],ruleName:"datetime:between"}}}}function qa(t=70){return {name:"datetime:workday-rate-denominator",priority:t,shape:[{types:["SLASH"]},{types:["UNIT"],values:["workday","workdays"]}],match(e,o){let r=e[o];if(r.type!=="SLASH")return null;let n=e[o+1];if(!n||n.type!=="UNIT"||n.value!=="workday"&&n.value!=="workdays")return null;let i={...n,type:"NUMBER",typeId:c("NUMBER"),value:"1",text:"1"};return {consumed:2,replacement:[r,i,n],ruleName:"datetime:workday-rate-denominator"}}}}var fc={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 Za(t){return t===void 0||t.type!=="IDENT"&&t.type!=="UNIT"?0:fc[(t.text??t.value??"").toLowerCase()]??0}var ot=/^\d+$/;function $t(t){return t.length===4}function Ja(t=64){return {name:"datetime:month-name-date",priority:t,startTokenTypes:["NUMBER","IDENT","UNIT"],match(e,o){let r="datetime:month-name-date",n=e[o];if(n?.type==="NUMBER"&&ot.test(n.text??"")){let c=Za(e[o+1]);if(c===0)return null;let f=Number(n.text);if(f<1||f>31)return null;let T=e[o+2];return T?.type==="NUMBER"&&ot.test(T.text??"")&&$t(T.text??"")?g$1(f,c,Number(T.text),e.slice(o,o+3),r):g$1(f,c,new Date().getFullYear(),e.slice(o,o+2),r)}let i=Za(n);if(i===0)return null;let a=e[o+1];if(a?.type!=="NUMBER"||!ot.test(a.text??""))return null;if($t(a.text??""))return g$1(1,i,Number(a.text),e.slice(o,o+2),r);let s=Number(a.text),l=e[o+2],u=e[o+3];return l?.type==="COMMA"&&u?.type==="NUMBER"&&ot.test(u.text??"")&&$t(u.text??"")?g$1(s,i,Number(u.text),e.slice(o,o+4),r):l?.type==="NUMBER"&&ot.test(l.text??"")&&$t(l.text??"")?g$1(s,i,Number(l.text),e.slice(o,o+3),r):g$1(s,i,new Date().getFullYear(),e.slice(o,o+2),r)}}}var dc=93,Ec={q1:[1,3],q2:[4,6],q3:[7,9],q4:[10,12]};function rn(t,e){return new Date(t,e,0).getDate()}function Tc(t){return rn(t,2)===29?366:365}var Wt=class{constructor(){this.category="Datetime";}parse(e,o,r){let n=this.readPeriodDays(e);r.emitOpcode(10),r.emitNumber(n),r.emitOpcode(51),r.emitIndex(dc),r.emitIndex(1);}readPeriodDays(e){let o=e.peek(),r=(o?.text??o?.value??"").toLowerCase(),n=Ec[r];if(n!==void 0){e.consume();let a=this.readOptionalYear(e)??new Date().getFullYear(),s=0;for(let l=n[0];l<=n[1];l++)s+=rn(a,l);return s}if(o?.type==="DATETIME_LITERAL"){e.consume();let a=new Date(Number(o.value));return rn(a.getFullYear(),a.getMonth()+1)}let i=this.readOptionalYear(e);if(i!==null)return Tc(i);throw c$1.parsing("DAYS_IN_EXPECTED_PERIOD",'Expected a month, quarter or year, as in "days in February 2020" or "days in Q3"')}readOptionalYear(e){let o=e.peek();if(o?.type!=="NUMBER")return null;let r=o.text??o.value??"";return /^\d{4}$/.test(r)?(e.consume(),Number(r)):null}};var Nc=new Set(["q1","q2","q3","q4"]),yc=new Set(["january","jan","february","feb","march","mar","april","apr","may","june","jun","july","jul","august","aug","september","sep","sept","october","oct","november","nov","december","dec"]);function gc(t){if(t===void 0)return false;if(t.type==="DATETIME_LITERAL")return true;let e=(t.text??t.value??"").toLowerCase();return t.type==="IDENT"||t.type==="UNIT"?Nc.has(e)||yc.has(e):t.type==="NUMBER"&&/^\d{4}$/.test(t.text??"")}function es(t=60){return {name:"datetime:days-in-period",priority:t,shape:[{types:["UNIT","IDENT"],values:["days"]},{types:["IN"]}],match(e,o){let r=e[o];return r===void 0||(r.text??r.value??"").toLowerCase()!=="days"||r.type!=="UNIT"&&r.type!=="IDENT"||e[o+1]?.type!=="IN"||!gc(e[o+2])?null:{consumed:2,replacement:[b$5("DAYS_IN_PERIOD","days in",[r,e[o+1]])],ruleName:"datetime:days-in-period"}}}}function ts(){return {name:"datetime:daily-note-link",priority:80,shape:[{types:["LBRACKET"]},{types:["LBRACKET"]}],match(t,e){return t[e]?.type!=="LBRACKET"||t[e+1]?.type!=="LBRACKET"||t[e+2]?.type!==f||t[e+3]?.type!=="RBRACKET"||t[e+4]?.type!=="RBRACKET"?null:{consumed:5,replacement:[t[e+2]],ruleName:"datetime:daily-note-link"}}}}var on={name:"solve-datetime",phrases:{"workdays in":"WORKDAYS_IN","working days after":"WORKDAYS_AFTER","business days after":"WORKDAYS_AFTER","working day after":"WORKDAYS_AFTER","business day after":"WORKDAYS_AFTER","working days from":"WORKDAYS_AFTER","business days from":"WORKDAYS_AFTER","working day from":"WORKDAYS_AFTER","business day from":"WORKDAYS_AFTER","working days before":"WORKDAYS_BEFORE","business days before":"WORKDAYS_BEFORE","working day before":"WORKDAYS_BEFORE","business day before":"WORKDAYS_BEFORE","working days between":"WORKDAYS_BETWEEN","business days between":"WORKDAYS_BETWEEN","day of the week on":"WEEKDAY_ON","weekday on":"WEEKDAY_ON","current timestamp":"CURRENT_TIMESTAMP","to date":"TO_DATE","to timestamp":"TO_TIMESTAMP","what day is it":"WEEKDAY_ON","what day is it on":"WEEKDAY_ON","what day will it be on":"WEEKDAY_ON","what day is it in":"WEEKDAY_IN","what day will it be in":"WEEKDAY_IN","what month is it":"MONTH_ON","what month is it on":"MONTH_ON","month of":"MONTH_ON","what month is it in":"MONTH_IN","what month will it be in":"MONTH_IN","what week is it":"WEEK_ON","what week is it on":"WEEK_ON","week of":"WEEK_ON","week number on":"WEEK_ON","week number of":"WEEK_ON","week number":"WEEK_ON","what week is it in":"WEEK_IN","what week will it be in":"WEEK_IN","is a weekend":"IS_WEEKEND","is on a weekend":"IS_WEEKEND","is a workday":"IS_WORKDAY","is a weekday":"IS_WORKDAY","is a business day":"IS_WORKDAY","age of":"AGE_OF","next month":"MONTH_ANCHOR_NEXT","this month":"MONTH_ANCHOR_THIS","last month":"MONTH_ANCHOR_LAST"},prefixParselets:{DAYS_IN_PERIOD:new Wt,NOW:new pe(0),TODAY:new pe(0),TOMORROW:new pe(1),YESTERDAY:new pe(-1),NEXT:new Ze("next"),LAST:new Ze("last"),UNTIL_UNIT:new Je("until"),SINCE_UNIT:new Je("since"),WORKDAYS_IN:new Bt,WORKDAYS_BETWEEN:new Mt,WEEKDAY_ON:new J("weekdayOnDate","on"),WEEKDAY_IN:new J("weekdayOnDate","in"),MONTH_ON:new J("monthOnDate","on"),MONTH_IN:new J("monthOnDate","in"),WEEK_ON:new J("weekOnDate","on"),WEEK_IN:new J("weekOnDate","in"),BETWEEN_UNIT:new Ut,CURRENT_TIMESTAMP:new Dt,DATETIME_LITERAL:new Ft,NTH_WEEKDAY:new Ht,AGE_OF:new Gt,MONTH_ANCHOR_NEXT:new Ie(1),MONTH_ANCHOR_THIS:new Ie(0),MONTH_ANCHOR_LAST:new Ie(-1)},infixParselets:{WORKDAYS_AFTER:new et("forward"),WORKDAYS_BEFORE:new et("backward"),TO_DATE:new bt,TO_TIMESTAMP:new Vt,IS_WEEKEND:new tt("isWeekendOnDate"),IS_WORKDAY:new tt("isWorkdayOnDate")},normalizerRules:[Xa(),Qa(),qa(),Ja(),ja(),es(),ts()],pluginFunctions:{workdaysInDuration:wa,weekdayOnDate:Zo,toDateFromAny:Ma,toTimestampFromAny:Ua,monthOnDate:Jo,weekOnDate:en,isWeekendOnDate:va,isWorkdayOnDate:ka,spanBetweenDates:Ba,nthWeekdayOfMonth:Ka,monthAnchorShift:$a,ageBetween:Wa},asConverters:{iso8601:t$1=>t(d(t$1.toNumber())),weekday:t=>Zo([t]),month:t=>Jo([t]),week:t=>en([t])},tokenCategories:{NTH_WEEKDAY:"datetime",MONTH_ANCHOR_NEXT:"datetime",MONTH_ANCHOR_THIS:"datetime",MONTH_ANCHOR_LAST:"datetime",AGE_OF:"keyword"}};var Pc={sydney:"Australia/Sydney",melbourne:"Australia/Melbourne",brisbane:"Australia/Brisbane",perth:"Australia/Perth",adelaide:"Australia/Adelaide",canberra:"Australia/Sydney",auckland:"Pacific/Auckland",wellington:"Pacific/Auckland",fiji:"Pacific/Fiji",chicago:"America/Chicago",seattle:"America/Los_Angeles",denver:"America/Denver",phoenix:"America/Phoenix",toronto:"America/Toronto",montreal:"America/Toronto",vancouver:"America/Vancouver",ottawa:"America/Toronto",honolulu:"Pacific/Honolulu",anchorage:"America/Anchorage",miami:"America/New_York",boston:"America/New_York",atlanta:"America/New_York",dallas:"America/Chicago",houston:"America/Chicago",lima:"America/Lima",bogota:"America/Bogota",caracas:"America/Caracas",santiago:"America/Santiago",montevideo:"America/Montevideo",quito:"America/Guayaquil",london:"Europe/London",paris:"Europe/Paris",berlin:"Europe/Berlin",madrid:"Europe/Madrid",rome:"Europe/Rome",amsterdam:"Europe/Amsterdam",dublin:"Europe/Dublin",lisbon:"Europe/Lisbon",vienna:"Europe/Vienna",zurich:"Europe/Zurich",geneva:"Europe/Zurich",moscow:"Europe/Moscow",istanbul:"Europe/Istanbul",athens:"Europe/Athens",stockholm:"Europe/Stockholm",oslo:"Europe/Oslo",helsinki:"Europe/Helsinki",warsaw:"Europe/Warsaw",prague:"Europe/Prague",budapest:"Europe/Budapest",brussels:"Europe/Brussels",copenhagen:"Europe/Copenhagen",reykjavik:"Atlantic/Reykjavik",kiev:"Europe/Kyiv",kyiv:"Europe/Kyiv",tokyo:"Asia/Tokyo",osaka:"Asia/Tokyo",beijing:"Asia/Shanghai",shanghai:"Asia/Shanghai",seoul:"Asia/Seoul",singapore:"Asia/Singapore",bangkok:"Asia/Bangkok",jakarta:"Asia/Jakarta",manila:"Asia/Manila",mumbai:"Asia/Kolkata",delhi:"Asia/Kolkata",bangalore:"Asia/Kolkata",dubai:"Asia/Dubai",abudhabi:"Asia/Dubai",karachi:"Asia/Karachi",dhaka:"Asia/Dhaka",hanoi:"Asia/Ho_Chi_Minh",taipei:"Asia/Taipei",islamabad:"Asia/Karachi",riyadh:"Asia/Riyadh",telaviv:"Asia/Jerusalem",jerusalem:"Asia/Jerusalem",cairo:"Africa/Cairo",lagos:"Africa/Lagos",nairobi:"Africa/Nairobi",johannesburg:"Africa/Johannesburg",casablanca:"Africa/Casablanca",accra:"Africa/Accra",tunis:"Africa/Tunis",addisababa:"Africa/Addis_Ababa",france:"Europe/Paris",germany:"Europe/Berlin",spain:"Europe/Madrid",italy:"Europe/Rome",japan:"Asia/Tokyo",china:"Asia/Shanghai",india:"Asia/Kolkata",brazil:"America/Sao_Paulo",russia:"Europe/Moscow",australia:"Australia/Sydney",canada:"America/Toronto",mexico:"America/Mexico_City",uk:"Europe/London",usa:"America/New_York",ireland:"Europe/Dublin",netherlands:"Europe/Amsterdam",sweden:"Europe/Stockholm",norway:"Europe/Oslo",poland:"Europe/Warsaw",turkey:"Europe/Istanbul",egypt:"Africa/Cairo",nigeria:"Africa/Lagos"},nn={"new york":"America/New_York","los angeles":"America/Los_Angeles","san francisco":"America/Los_Angeles","las vegas":"America/Los_Angeles","mexico city":"America/Mexico_City","hong kong":"Asia/Hong_Kong","kuala lumpur":"Asia/Kuala_Lumpur","sao paulo":"America/Sao_Paulo","buenos aires":"America/Argentina/Buenos_Aires","rio de janeiro":"America/Sao_Paulo","cape town":"Africa/Johannesburg","new delhi":"Asia/Kolkata","united kingdom":"Europe/London","united states":"America/New_York","south africa":"Africa/Johannesburg"},_c={pst:"America/Los_Angeles",pdt:"America/Los_Angeles",est:"America/New_York",edt:"America/New_York",cst:"America/Chicago",cdt:"America/Chicago",mst:"America/Denver",mdt:"America/Denver",hst:"Pacific/Honolulu",bst:"Europe/London",cet:"Europe/Paris",cest:"Europe/Paris",jst:"Asia/Tokyo",ist:"Asia/Kolkata",aest:"Australia/Sydney",aedt:"Australia/Sydney"},rs={...Pc,...nn,..._c};var an="UTCOFFSET:";function sn(t){return `${an}${t}`}function nt(t){return t.startsWith(an)}function it(t){return parseInt(t.slice(an.length),10)}function Yt(t,e){if(nt(t))return it(t);let o=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r={};for(let i of o.formatToParts(new Date(e)))r[i.type]=i.value;let n=Date.UTC(+r.year,+r.month-1,+r.day,+r.hour,+r.minute,+r.second);return Math.round((n-e)/6e4)}function ns(t,e,o,r,n,i){let a=Date.UTC(t,e,o,r,n,0),s=Yt(i,a);return a-s*6e4}function mn(t,e){if(nt(e)){let r=it(e)*6e4;return Ac(new Date(t+r))}return new Intl.DateTimeFormat("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",hour12:true}).format(new Date(t))}function is(t,e){if(nt(e)){let r=it(e)*6e4;return xc(new Date(t+r))}return new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"long",day:"numeric"}).format(new Date(t))}function os(t,e){if(nt(e)){let n=new Date(t+it(e)*6e4);return {year:n.getUTCFullYear(),month0:n.getUTCMonth(),day:n.getUTCDate()}}let o=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}),r={};for(let n of o.formatToParts(new Date(t)))r[n.type]=n.value;return {year:+r.year,month0:+r.month-1,day:+r.day}}function as(t,e,o){let r=os(t,e),n=os(t,o),i=Date.UTC(r.year,r.month0,r.day),a=Date.UTC(n.year,n.month0,n.day);return Math.round((i-a)/864e5)}function Ac(t){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",hour:"numeric",minute:"2-digit",hour12:true}).format(t)}function xc(t){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",year:"numeric",month:"long",day:"numeric"}).format(t)}function ln(t){if(nt(t)){let o=it(t),r=o>=0?"+":"-",n=Math.abs(o),i=Math.floor(n/60),a=n%60;return a===0?`UTC${r}${i}`:`UTC${r}${i}:${String(a).padStart(2,"0")}`}return (t.split("/").pop()??t).replace(/_/g," ")}function ne(t){let e=t.peek();if(!e)return null;let o=e.value,r=o.toLowerCase();if(r==="gmt"||r==="utc"){t.consume();let i=t.peek();if(i?.type==="PLUS"||i?.type==="MINUS"){let s=i.type==="MINUS";t.consume();let l=t.peek(),u;if(l?.type==="CLOCK_TIME")t.consume(),u=parseInt(l.value,10);else {let f=t.consume("NUMBER");if(u=parseInt(f.value,10)*60,t.peek()?.type==="COLON"){t.consume();let T=t.consume("NUMBER");u+=parseInt(T.value,10);}}let c=sn(s?-u:u);return {zoneRef:c,displayName:ln(c)}}let a=sn(0);return {zoneRef:a,displayName:ln(a)}}let n=rs[r];if(n){t.consume();let i=o.replace(/\b\w/g,a=>a.toUpperCase());return {zoneRef:n,displayName:i}}return null}var jt="zoneConvert",un="timeInZone",cn="dateInZone",Xt="timeDifference";function ss(t$1){let e=t$1[0].toNumber(),o=t$1[1].value,r=t$1[2].value,n=new Date,i=ns(n.getFullYear(),n.getMonth(),n.getDate(),Math.floor(e/60),e%60,o),a=mn(i,r),s=as(i,r,o);if(s===0)return t(a);let l=s>0?"+":"";return t(`${a} (${l}${s} day${Math.abs(s)===1?"":"s"})`)}function ms(t$1){let e=t$1[0].value;return t(mn(Date.now(),e))}function ls(t$1){let e=t$1[0].value;return t(is(Date.now(),e))}function us(t$1){let e=t$1[0].value,o=t$1[1].value,r=t$1[2].value,n=t$1[3].value,i=Date.now(),a=Yt(e,i),l=Yt(o,i)-a;if(l===0)return t(`${n} and ${r} currently share the same UTC offset`);let u=l>0?n:r,c=l>0?r:n,f=Math.abs(l),T=Math.floor(f/60),N=f%60,E=[];return T>0&&E.push(`${T} hour${T===1?"":"s"}`),N>0&&E.push(`${N} minute${N===1?"":"s"}`),t(`${u} is ${E.join(" ")} ahead of ${c}`)}var Qt=class{constructor(){this.category="Time";}parse(e,o,r){let n=parseInt(o.value,10),i=ne(e);if(i!==null){if(e.peek()?.type!=="IN")throw c$1.parsing("TIME_ZONE_EXPECTED_IN",`Expected "in <city>" after the zone name (e.g. "6pm Sydney in Chicago") but got ${e.peek()?`"${e.peek().value}"`:"end of input"}`);e.consume();let a=ne(e);if(a===null)throw c$1.parsing("TIME_ZONE_EXPECTED_TARGET",'Expected a city or zone name after "in" (e.g. "6pm Sydney in Chicago")');r.emitOpcode(10),r.emitNumber(n),r.emitOpcode(13),r.emitString(i.zoneRef),r.emitOpcode(13),r.emitString(a.zoneRef),r.emitPluginCall(jt,3);return}r.emitOpcode(10),r.emitNumber(n),r.emitOpcode(120);}};var qt=class{constructor(){this.category="Time";}parse(e,o,r){let[n,i]=o.value.split(":"),a=parseInt(n,10),s=parseInt(i,10),l=s>=a?s-a:1440-a+s;r.emitOpcode(10),r.emitNumber(l),r.emitOpcode(13),r.emitString("minutes"),r.emitOpcode(80);}};var Zt=class{constructor(){this.category="Time";}parse(e,o,r){r.emitOpcode(10),r.emitNumber(parseFloat(o.value)),r.emitOpcode(13),r.emitString("frames/s"),r.emitOpcode(80);}};var Jt=class{constructor(){this.category="Time";}parse(e,o,r){r.emitOpcode(10),r.emitNumber(parseFloat(o.value)),r.emitOpcode(13),r.emitString("s"),r.emitOpcode(80);}};function pn(t){return {category:"Time",parse(e,o,r){let n=ne(e);if(n===null)throw c$1.parsing("TIME_ZONE_EXPECTED_CITY",`Expected a city or zone name after "${o.value}" (e.g. "time in Paris")`);r.emitOpcode(13),r.emitString(n.zoneRef),r.emitPluginCall(t,1);}}}var er=class{constructor(){this.category="Time";}parse(e,o,r){let n=ne(e);if(n===null)throw c$1.parsing("TIME_DIFFERENCE_EXPECTED_CITY",'Expected a city or zone name after "time difference between" (e.g. "time difference between Seattle and Moscow")');e.consume("AND_CONJ");let i=ne(e);if(i===null)throw c$1.parsing("TIME_DIFFERENCE_EXPECTED_SECOND_CITY",'Expected a second city or zone name after "and" (e.g. "time difference between Seattle and Moscow")');r.emitOpcode(13),r.emitString(n.zoneRef),r.emitOpcode(13),r.emitString(i.zoneRef),r.emitOpcode(13),r.emitString(n.displayName),r.emitOpcode(13),r.emitString(i.displayName),r.emitPluginCall(Xt,4);}};var tr=class{constructor(){this.category="Time";}parse(e,o,r){let[n,i,a,s]=o.value.split(",").map(Number),l=e.peek();if(!l||l.type!=="RATE_AT"&&l.type!=="AT")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`A video timecode must specify a frame rate, e.g. "${o.value.split(",").join(":")} at 30 fps" or "... @ 30 fps"`);e.consume();let u=e.peek();if(!u||u.type!=="FPS_RATE")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`Expected "<number> fps" after "${l.value}" (e.g. "at 30 fps")`);e.consume();let c=parseFloat(u.value),f=Math.round(c);if(s>=f)throw c$1.parsing("TIMECODE_FRAME_OUT_OF_RANGE",`Frame number ${s} is out of range for ${c} fps (must be 0-${f-1})`);let T=(n*3600+i*60+a)*f+s,N=z$2(c);if(e.peek()?.type==="IN"){e.consume();let E=e.peek();if(!E||E.type!=="IDENT"||E.value.toLowerCase()!=="frames")throw c$1.parsing("TIMECODE_EXPECTED_FRAMES",`Expected "frames" after "in" (e.g. "... in frames") but got ${E?`"${E.value}"`:"end of input"}`);e.consume(),N="frames";}r.emitOpcode(10),r.emitNumber(T),r.emitOpcode(13),r.emitString(N),r.emitOpcode(80);}};function cs(t,e){let o=Math.max(1,Math.round(e)),r=c=>String(c).padStart(2,"0"),n=Math.trunc(t),i=(n%o+o)%o,a=Math.floor(n/o),s=Math.floor(a/3600),l=Math.floor(a%3600/60),u=a%60;return `${r(s)}:${r(l)}:${r(u)}:${r(i)}`}var rr=class{constructor(){this.category="Time";}parse(e,o,r){let n=parseFloat(o.value),i=e.peek();if(i&&(i.type==="RATE_AT"||i.type==="AT")){e.consume();let a=e.peek();if(!a||a.type!=="FPS_RATE")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`Expected "<number> fps" after "${i.value}" (e.g. "@ 30 fps")`);e.consume();let s=parseFloat(a.value);r.emitOpcode(13),r.emitString(cs(n,s));return}r.emitOpcode(10),r.emitNumber(n),r.emitOpcode(13),r.emitString("frames"),r.emitOpcode(80);}};function ps(t,e,o){if(e<0||e>59)return null;if(o){if(t<1||t>12)return null;let r=o.toLowerCase()==="pm";return (t%12+(r?12:0))*60+e}return t<0||t>23?null:t*60+e}function fs(t){return !!t&&t.type==="IDENT"&&/^(am|pm)$/i.test(t.value)}function ds(t=65){return {name:"time:clock-time",priority:t,shape:[{types:["NUMBER"]},{types:["COLON","IDENT"]}],match(e,o){let r=e[o];if(r.type!=="NUMBER")return null;let n=parseInt(r.value,10);if(isNaN(n)||n<0||n>23||e$5(e,o))return null;let i=e[o+1],a=e[o+2];if(i?.type==="COLON"&&a?.type==="NUMBER"){let l=parseInt(a.value,10),u=e[o+3],c=fs(u),f=ps(n,l,c?u.value:void 0);if(f===null)return null;let T=c?4:3;return {consumed:T,replacement:[b$5("CLOCK_TIME",String(f),e.slice(o,o+T))],ruleName:"time:clock-time"}}let s=e[o+1];if(fs(s)){let l=ps(n,0,s.value);return l===null?null:{consumed:2,replacement:[b$5("CLOCK_TIME",String(l),e.slice(o,o+2))],ruleName:"time:clock-time"}}return null}}}function Es(t=66){return {name:"time:clock-time-interval",priority:t,shape:[{types:["CLOCK_TIME"]},{types:["TO"]}],match(e,o){let r=e[o],n=e[o+1],i=e[o+2];return r.type!=="CLOCK_TIME"||n?.type!=="TO"||i?.type!=="CLOCK_TIME"?null:{consumed:3,replacement:[b$5("CLOCK_TIME_INTERVAL",`${r.value}:${i.value}`,e.slice(o,o+3))],ruleName:"time:clock-time-interval"}}}}function Ts(t=65){return {name:"time:fps-rate",priority:t,shape:[{types:["NUMBER"]},{types:["IDENT"],values:["fps"]}],match(e,o){let r=e[o],n=e[o+1];return r.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="fps"?null:{consumed:2,replacement:[b$5("FPS_RATE",r.value,e.slice(o,o+2))],ruleName:"time:fps-rate"}}}}function Ns(t=70){return {name:"time:laptime",priority:t,shape:[{types:["NUMBER"]},{types:["COLON"]}],match(e,o){let r=e[o],n=e[o+1],i=e[o+2],a=e[o+3],s=e[o+4];if(r.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||s?.type!=="NUMBER"||e$5(e,o))return null;let l=parseInt(r.value,10),u=parseInt(i.value,10),c=parseFloat(s.value);if(isNaN(l)||isNaN(u)||isNaN(c)||u<0||u>59||c<0||c>=60)return null;let f=l*3600+u*60+c;return {consumed:5,replacement:[b$5("LAPTIME",String(f),e.slice(o,o+5))],ruleName:"time:laptime"}}}}function ys(t=75){return {name:"time:video-timecode",priority:t,shape:[{types:["NUMBER"]},{types:["COLON"]}],match(e,o){let r=e[o],n=e[o+1],i=e[o+2],a=e[o+3],s=e[o+4],l=e[o+5],u=e[o+6];if(r?.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||s?.type!=="NUMBER"||l?.type!=="COLON"||u?.type!=="NUMBER"||e$5(e,o))return null;let c=parseInt(r.value,10),f=parseInt(i.value,10),T=parseInt(s.value,10),N=parseInt(u.value,10);return [c,f,T,N].some(E=>isNaN(E))||f<0||f>59||T<0||T>59||c<0||N<0?null:{consumed:7,replacement:[b$5("VIDEO_TIMECODE",`${c},${f},${T},${N}`,e.slice(o,o+7))],ruleName:"time:video-timecode"}}}}function gs(t=65){return {name:"time:frame-count",priority:t,shape:[{types:["NUMBER"]},{types:["IDENT"],values:["frames"]}],match(e,o){let r=e[o],n=e[o+1];return r.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="frames"?null:{consumed:2,replacement:[b$5("FRAME_COUNT",r.value,e.slice(o,o+2))],ruleName:"time:frame-count"}}}}var Rc=14,Oc=[["week","weeks",604800],["day","days",86400],["hour","hours",3600],["minute","minutes",60],["second","seconds",1]];function Ps(t){if(t.type===0)return t.toNumber();if(t.type!==6||t.unit===void 0)return null;let e=a$7[t.unit.toLowerCase()];return e===void 0||e[0]!==Rc?null:t.toNumber()*e[1]}function _s(t$1){let e=Ps(t$1);if(e===null)return t(`"as timespan" needs a duration, got ${t$1.unit??"a non-duration"}`);let o=e<0,r=Math.abs(e),n=[];for(let[a,s,l]of Oc){if(l===1)break;let u=Math.floor(r/l);u>0&&(n.push(`${u} ${u===1?a:s}`),r-=u*l);}let i=Math.round(r*1e3)/1e3;return (i>0||n.length===0)&&n.push(`${i} ${i===1?"second":"seconds"}`),t((o?"-":"")+n.join(" "))}function dn(t$1){let e=Ps(t$1);if(e===null)return t(`"as laptime" needs a duration, got ${t$1.unit??"a non-duration"}`);let o=e<0,r=Math.round(Math.abs(e)*1e3)/1e3,n=Math.floor(r/3600),i=Math.floor(r%3600/60),a=r%60,s=Math.floor(a),l=Math.round((a-s)*1e3),u=`${fn(n)}:${fn(i)}:${fn(s)}`;return t((o?"-":"")+(l>0?`${u}.${String(l).padStart(3,"0")}`:u))}function fn(t){return t<10?`0${t}`:String(t)}var En={name:"solve-time",asConverters:{timespan:_s,laptime:dn,lap:dn},phrases:{"time in":"TIME_IN","date in":"DATE_IN","time difference between":"TIME_DIFFERENCE_BETWEEN",...Object.fromEntries(Object.keys(nn).map(t=>[t,"CITY_NAME"]))},prefixParselets:{CLOCK_TIME:new Qt,CLOCK_TIME_INTERVAL:new qt,FPS_RATE:new Zt,LAPTIME:new Jt,TIME_IN:pn(un),DATE_IN:pn(cn),TIME_DIFFERENCE_BETWEEN:new er,VIDEO_TIMECODE:new tr,FRAME_COUNT:new rr},normalizerRules:[ds(),Es(),Ts(),Ns(),ys(),gs()],pluginFunctions:{[jt]:ss,[un]:ms,[cn]:ls,[Xt]:us}};function or(t){for(let e of t.alternatives){let o=e.slots[0];if(!o||o.kind!=="keyword")throw c$1.config("INVALID_PHRASE_PATTERN","Every PhraseAlternative's first slot must be a `keyword` slot \u2014 alternatives are chosen by peeking the next token, which only works if the choice is decidable from one leading keyword.",{category:t.category})}return {category:t.category,parse(e,o,r){let n=e.peek(),i=t.alternatives.find(s=>{let l=s.slots[0];return n!==void 0&&l.tokenTypes.includes(n.type)});if(!i){let s=t.alternatives.map(l=>l.slots[0].tokenTypes.join("|")).join(", ");throw c$1.parsing("NO_MATCHING_PHRASE_ALTERNATIVE",`Expected one of [${s}] but got "${n?.type??"end of input"}" ("${n?.value??""}")`,{category:t.category,expected:s,actualType:n?.type,actualValue:n?.value})}let a=[];for(let s of i.slots)if(s.kind==="keyword"){let l=e.peek();if(!l||!s.tokenTypes.includes(l.type))throw c$1.parsing("PHRASE_KEYWORD_MISMATCH",`Expected one of [${s.tokenTypes.join("|")}] but got "${l?.type??"end of input"}" ("${l?.value??""}")`,{category:t.category,expected:s.tokenTypes,actualType:l?.type,actualValue:l?.value});e.consume(),a.push({type:l.type,value:l.value});}else e.parseExpression(s.bindingPower??0,r);i.emit(r,a);}}}var hc=37;function nr(t){t.emitOpcode(51),t.emitIndex(hc),t.emitIndex(2);}var Ic=or({category:"Dice",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:nr},{slots:[{kind:"keyword",tokenTypes:["FROM"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["TO"]},{kind:"expr"}],emit:nr},{slots:[{kind:"keyword",tokenTypes:["LPAREN"]},{kind:"expr"},{kind:"keyword",tokenTypes:["COMMA"]},{kind:"expr"},{kind:"keyword",tokenTypes:["RPAREN"]}],emit:nr}]}),ir=class{constructor(){this.category="Dice";}parse(e,o,r){let n=e.peek();if(n&&n.type==="NUMBER"){let i=e.consume();r.emitOpcode(10),r.emitNumber(parseFloat(i.value)),e.consume("MINUS");let a=e.consume();r.emitOpcode(10),r.emitNumber(parseFloat(a.value)),nr(r);return}Ic.parse(e,o,r);}};var Tn={name:"solve-dice",prefixParselets:{ROLL:new ir}};var ar=class{constructor(){this.category="Variable";}parse(e,o,r){let n=e.consume();if(n.type!=="IDENT"&&n.type!=="UNIT")throw c$1.parsing("EXPECTED_IDENTIFIER",`Expected identifier or unit after colon, got ${n.type}`,{tokenType:n.type});let i=n.value;e.peek()?.type==="EQUALS"?(e.consume("EQUALS"),e.parseExpression(0,r),r.emitOpcode(61),r.emitString(i)):(r.emitOpcode(60),r.emitString(i));}};var at=class{constructor(){this.category="Variable";}parse(e,o,r){r.emitOpcode(60),r.emitString(o.value);}};var sr=class{constructor(){this.category="Variable";}parse(e,o,r){e.consume("COLON");let n=e.consume();if(n.type!=="IDENT"&&n.type!=="UNIT")throw c$1.parsing("EXPECTED_IDENTIFIER",`Expected identifier after 'global :', got ${n.type}`,{tokenType:n.type});let i=n.value;e.peek()?.type==="EQUALS"?(e.consume("EQUALS"),e.parseExpression(0,r),r.emitOpcode(63),r.emitString(i)):(r.emitOpcode(62),r.emitString(i));}};var mr=class{constructor(){this.namespace="global-variables";this.pending=new Map;}preflight(e,o,r,n,i){let{opcodes:a,strings:s}=o,l=a.length,u=0;for(;u<l;){if(a[u]===62){let f=s[a[u+1]];if(!J$1.has(f))return this.pendingResultFor(f,r,n)}u=a$3(a,u);}return null}pendingResultFor(e,o,r){let n=this.pending.get(e);return n||(n=new Promise(i=>{let a=J$1.subscribe((s,l)=>{s===e&&(a(),this.pending.delete(e),i(l));});}),this.pending.set(e,n)),{queryKey:`global:${e}`,resolver:n,packageId:o,signal:r,metadata:{varName:e}}}destroy(){this.pending.clear();}};var Nn={name:"solve-variables",asyncResolvers:[new mr],prefixParselets:{COLON:new ar,IDENT:new at,UNIT:new at,GLOBAL:new sr}};var xs="currency-historical",fe="historicalCurrency",Cc=`solve-currency:${fe}`,lr={NOT_CONFIGURED:"HISTORICAL_RATES_NOT_CONFIGURED",QUERY_FAILED:"HISTORICAL_RATE_QUERY_FAILED",NOT_PREFLIGHTED:"HISTORICAL_RATE_NOT_PREFLIGHTED",INVALID_OPERAND:"HISTORICAL_CURRENCY_INVALID_OPERAND"},Sc=3e4,Rs=1/0,Lc=1e4;function yn(t,e,o){return [xs,`${t.toUpperCase()}:${e.toUpperCase()}:${o}`]}function As(t){return t<10?`0${t}`:String(t)}function ur(t,e,o){if(!c$3.isCurrency(e)||o!==void 0&&!c$3.isCurrency(o))return null;let r=t.peek();if(!r||r.type!=="IDENT"||r.value.toLowerCase()!=="on")return null;let n=t.peekAt(1);if(!n||n.type!=="DATETIME_LITERAL")return null;t.consume(),t.consume();let i=new Date(Number(n.value));return `${i.getFullYear()}-${As(i.getMonth()+1)}-${As(i.getDate())}`}async function Os(t,e,o,r,n$1,i){let a=e.toUpperCase(),s=o.toUpperCase();if(!t)return P(lr.NOT_CONFIGURED,`Historical exchange rates are not configured. Supply historicalRateProvider via createCurrencyPackage({ ... }) to convert ${a} to ${s} on ${r}.`);let{signal:l,cleanup:u}=a$4(n$1,Lc,"Historical currency rate fetch");try{let c=await t(a,s,r,l);return n(c)}catch(c){let f=P(lr.QUERY_FAILED,`Failed to resolve the historical rate for ${a} to ${s} on ${r}: ${c instanceof Error?c.message:String(c)}`),T=yn(e,o,r);return setTimeout(()=>{i.getQueryData(T)===f&&i.removeQueries({queryKey:T,exact:true});},Sc).unref?.(),f}finally{u();}}function gn(t){return e=>{let o=e[0],r=e[1],n=e[2],i=Q$1(o);if(i)return i;if(o.type!==6||o.unit===void 0||!c$3.isCurrency(o.unit))return P(lr.INVALID_OPERAND,'Historical conversion needs an amount in a currency, for example "100 USD in GBP on 2024-01-15".');let a=o.unit,s=String(r.value),l=String(n.value);if(a.toUpperCase()===s.toUpperCase())return u$1(o.toNumber(),s);let u=b$4(),c=yn(a,s,l),f=u?.getQueryData(c);if(f===void 0)return u?u.fetchQuery({queryKey:c,queryFn:({signal:N})=>Os(t,a,s,l,N,u),staleTime:Rs}):P(lr.NOT_PREFLIGHTED,`No historical rate resolved for ${a.toUpperCase()} to ${s.toUpperCase()} on ${l}.`);if(f.type===13)return f;let T=f.value;return u$1(o.toNumber()*T,s)}}function hs(t){return {namespace:xs,preflight(e,o,r,n,i){let{opcodes:a,strings:s}=o,l=a.length,u=F$1(Cc),c=0,f=[];for(;c<l;){let T=a[c];if(T===13)f.push(a[c+1]);else if(T===50){let N=a[c+1],E=a[c+2];if(N===u&&E===3&&f.length>=3){let A=s[f[f.length-1]],R=s[f[f.length-2]],O=new Set;for(let g=0;g<f.length-2;g++){let P=s[f[g]];c$3.isCurrency(P)&&O.add(P.toUpperCase());}if(O.size===1){let g=O.values().next().value;if(g!==R.toUpperCase()){let P=yn(g,R,A);if(i.getQueryData(P)===void 0){let C=i.fetchQuery({queryKey:P,queryFn:({signal:S})=>Os(t,g,R,A,S,i),staleTime:Rs});return {queryKey:P.join(":"),resolver:C,packageId:r,signal:n,metadata:{from:g,to:R,isoDate:A}}}}}}f=[];}c=a$3(a,c);}return null},destroy(){}}}function Is(t){return ta(t)??t}var cr=class{constructor(){this.category="UoM";this.bindingPower=a.Postfix;}parse(e,o,r,n){let i=Is(r.value);if(n.emitOpcode(13),n.emitString(i),!(e.infixMinBindingPower>=a.Product)&&(e.peek()?.type==="TO"||e.peek()?.type==="IN")){e.consume();let s=e.peek();if(s?.type==="UNIT"||s?.type==="IN"){e.consume();let l=Is(s.value),u=ur(e,l,i);if(u!==null){n.emitOpcode(80),n.emitOpcode(13),n.emitString(l),n.emitOpcode(13),n.emitString(u),n.emitPluginCall(fe,3);return}n.emitOpcode(13),n.emitString(l),n.emitOpcode(81);return}if(s?.type==="QUESTION"){e.consume(),n.emitOpcode(85);return}}if(e.peek()?.type==="BEST"){e.consume(),n.emitOpcode(83);return}n.emitOpcode(80);}};function Pn(t){return ta(t)??t}var pr=class{constructor(){this.category="UoM";}parse(e,o,r){e.parseExpression(a.Postfix,r);let n=e.peek();if(n&&n.type==="UNIT"){if(e.consume(),r.emitOpcode(13),r.emitString(Pn(n.value)),e.peek()?.type==="TO"){e.consume("TO");let i=e.consume();i?.type==="UNIT"?(r.emitOpcode(13),r.emitString(Pn(i.value)),r.emitOpcode(81)):i?.type==="BEST"&&r.emitOpcode(83);}else r.emitOpcode(80);return}if(n&&(n.type==="TO"||n.type==="IN")){e.consume();let i=e.peek();i?.type==="UNIT"||i?.type==="IN"||i?.type==="DOLLAR"||i?.type==="POUND"||i?.type==="EURO"||i?.type==="YEN"||i?.type==="RUBLE"||i?.type==="WON"||i?.type==="CURRENCY_SYMBOL"||i?.type==="IDENT"?(e.consume(),r.emitOpcode(13),r.emitString(Pn(i.value)),r.emitOpcode(84)):i?.type==="BEST"&&(e.consume(),r.emitOpcode(83));return}}};var fr=class{constructor(){this.category="UoM";}parse(e,o,r){r.emitOpcode(13),r.emitString(o.value),r.emitOpcode(85);}};function Cs(t=60){return {name:"uom:possibilities",priority:t,shape:[{types:["UNIT"]},{types:["TO"]}],match(e,o){if(o+2>=e.length)return null;let r=e[o],n=e[o+1],i=e[o+2];return r.type!=="UNIT"||n.type!=="TO"||i.type!=="QUESTION"?null:{consumed:3,replacement:[b$5("UOM_POSSIBILITIES_QUERY",r.value,[r,n,i])],ruleName:"uom:possibilities"}}}}var Ss=14;function Ls(t,e){if(t===void 0||t.type!=="UNIT")return;let o=(t.value??"").toLowerCase();if(o==="m"&&e===Ss)return {kind:Ss,ratio:60,spelling:"minutes"};let r=a$7[o];return r===void 0?void 0:{kind:r[0],ratio:r[1],spelling:o}}var ws=/^\d+(\.\d+)?$/;function vs(t=63){return {name:"uom:compound-quantity",priority:t,shape:[{types:["NUMBER"]},{types:["UNIT"]}],match(e,o){let r=e[o];if(r?.type!=="NUMBER"||!ws.test(r.text??""))return null;let n=Ls(e[o+1]);if(n===void 0)return null;let i=n.kind,a=n.ratio,s=Number(r.text)*a,l=n.spelling,u=e[o+1],c=2;for(;;){let N=e[o+c];if(N?.type!=="NUMBER"||!ws.test(N.text??""))break;let E=Ls(e[o+c+1],i);if(E===void 0||E.kind!==i||E.ratio>=a)break;s+=Number(N.text)*E.ratio,a=E.ratio,l=E.spelling,u=e[o+c+1],c+=2;}if(c===2)return null;let f=e.slice(o,o+c),T=s/a;return {consumed:c,replacement:[b$5("NUMBER",String(T),f),b$5("UNIT",l,[u])],ruleName:"uom:compound-quantity"}}}}function ks(t){return t===void 0||t.type!=="UNIT"?false:a$7[(t.value??"").toLowerCase()]!==void 0}function Bs(t=59){return {name:"uom:two-unit-conversion",priority:t,shape:[{types:["IN","TO"]},{types:["UNIT"]}],match(e,o){let r=e[o];if(r?.type!=="IN"&&r?.type!=="TO"||!ks(e[o+1])||e[o+2]?.type!=="AND_CONJ"||!ks(e[o+3]))return null;let n=e[o+1].value,i=e[o+3].value;return {consumed:4,replacement:[b$5("IN_TWO_UNITS",`${n} ${i}`,e.slice(o,o+4))],ruleName:"uom:two-unit-conversion"}}}}function Ms(t=74){return {name:"uom:degree-symbol",priority:t,shape:[{types:["NUMBER"]},{types:["IDENT"],values:["\xB0"]}],match(e,o){let r=e[o];if(r?.type!=="NUMBER")return null;let n=e[o+1];return n===void 0||n.type!=="IDENT"||(n.text??n.value??"")!=="\xB0"?null:{consumed:2,replacement:[r,b$5("UNIT","degrees",[n])],ruleName:"uom:degree-symbol"}}}}var dr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Conditional;}parse(e,o,r,n){let[i,a]=String(r.value).split(" ");n.emitOpcode(13),n.emitString(i),n.emitOpcode(13),n.emitString(a),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(3);}};function Us(t){return t===void 0||t.type!=="UNIT"?false:a$7[(t.value??"").toLowerCase()]!==void 0}var _n=new Set(["per","a","an","each","every"]);function wc(t){if(t===void 0||t.type!=="IDENT")return false;let e=(t.text??t.value??"").toLowerCase();return _n.has(e)?false:/^[a-z][a-z_]{2,}$/.test(e)&&a$7[e]===void 0}function Ds(t=75){return {name:"uom:bare-rate-denominator",priority:t,unshapedReason:"Fires after any value-ending token, a set broad enough that naming it would filter nothing.",match(e,o){let r=e[o];if(r===void 0)return null;if(r.type==="NUMBER"&&wc(e[o+1])){let l=e[o+1],u=e[o+2];if((u?.type==="SLASH"||u?.type==="IDENT"&&_n.has((u.text??u.value??"").toLowerCase()))&&Us(e[o+3]))return {consumed:2,replacement:[r,b$5("UNIT",l.value,[l])],ruleName:"uom:bare-rate-denominator"}}if(!Us(e[o+1]))return null;let n=r.type==="SLASH",i=(r.text??r.value??"").toLowerCase(),a=r.type==="IDENT"&&_n.has(i);if(!n&&!a)return null;let s=e[o+1];return {consumed:2,replacement:[b$5("PER_UNIT",s.value,[r,s])],ruleName:"uom:bare-rate-denominator"}}}}var Er=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,r,n){n.emitOpcode(13),n.emitString(String(r.value)),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var Tr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,r,n){e.parseExpression(a.Conditional,n),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};function vc(t){return t===void 0||t.type!=="UNIT"?false:a$7[(t.value??"").toLowerCase()]!==void 0}var kc=new Set(["per","a","an","each","every"]);function Bc(t,e){for(let o=e;o<t.length&&o<e+5;o++){let r=t[o];if(r.type==="PER_UNIT")return true;if(r.type==="EOF"||r.type==="COMMA"||r.type==="RATE_AT")return false;let n=(r.text??r.value??"").toLowerCase();if((r.type==="SLASH"||r.type==="IDENT"&&kc.has(n))&&vc(t[o+1]))return true}return false}function bs(t=73){return {name:"uom:at-rate",priority:t,shape:[{types:["RATE_AT"]}],match(e,o){return e[o]?.type!=="RATE_AT"||!Bc(e,o+1)?null:{consumed:1,replacement:[b$5("AT_RATE","at",[e[o]])],ruleName:"uom:at-rate"}}}}function Mc(t){return t===void 0||t.type!=="UNIT"?false:a$7[(t.value??"").toLowerCase()]!==void 0}var Uc=new Set(["a","an"]);function Vs(t=76){return {name:"uom:for-duration",priority:t,shape:[{types:["FOR_DURATION"]},{types:["IDENT"]}],match(e,o){let r=e[o];if(r?.type!=="FOR_DURATION")return null;let n=e[o+1];return n?.type!=="IDENT"||!Uc.has((n.text??n.value??"").toLowerCase())||!Mc(e[o+2])?null:{consumed:3,replacement:[b$5("STAR","*",[r]),b$5("NUMBER","1",[n]),e[o+2]],ruleName:"uom:for-duration"}}}}function An(t){return t===void 0||t.type!=="UNIT"?false:a$7[(t.value??"").toLowerCase()]!==void 0}var Dc=new Set(["a","an"]);function Fs(t=61){return {name:"uom:reversed-conversion",priority:t,shape:[{types:["UNIT"]},{types:["IN"]}],match(e,o){if(o!==0||!An(e[o])||e[o+1]?.type!=="IN")return null;let r=e[o],n=e[o+2];if(n===void 0)return null;if(n.type==="NUMBER"&&An(e[o+3]))return {consumed:4,replacement:[n,e[o+3],e[o+1],r],ruleName:"uom:reversed-conversion"};let i=(n.text??n.value??"").toLowerCase();return n.type==="IDENT"&&Dc.has(i)&&An(e[o+3])?{consumed:4,replacement:[b$5("NUMBER","1",[n]),e[o+3],e[o+1],r],ruleName:"uom:reversed-conversion"}:null}}}var bc={water:1,milk:1.03,"whole milk":1.03,"skim milk":1.035,buttermilk:1.03,"heavy cream":1,"whipping cream":1,"sour cream":.96,yogurt:1.03,"greek yogurt":1.05,"cream cheese":1.01,"condensed milk":1.3,"evaporated milk":1.06,"coconut milk":.97,"almond milk":1.03,"soy milk":1.03,butter:.9595,margarine:.96,"vegetable oil":.92,"olive oil":.913,"canola oil":.92,"coconut oil":.92,"sunflower oil":.92,"sesame oil":.92,mayonnaise:.91,sugar:.845,"granulated sugar":.845,"brown sugar":.93,"powdered sugar":.51,"icing sugar":.51,honey:1.42,"maple syrup":1.32,"corn syrup":1.38,molasses:1.4,nutella:1.14,"peanut butter":1.09,flour:.53,"all-purpose flour":.53,"all purpose flour":.53,"bread flour":.54,"cake flour":.47,"whole wheat flour":.55,cornstarch:.53,cornmeal:.65,semolina:.6,rice:.79,"white rice":.79,"brown rice":.8,oats:.34,"rolled oats":.38,breadcrumbs:.43,yeast:.68,"dry yeast":.68,salt:1.2,"table salt":1.2,"kosher salt":.96,"baking powder":.9,"baking soda":.99,"cream of tartar":.68,cinnamon:.56,ginger:.5,"vanilla extract":.88,"lemon juice":1.03,"lime juice":1.02,"orange juice":1.04,vinegar:1.01,cocoa:.41,"cocoa powder":.41,"chocolate chips":.72,"chocolate chunks":.72,coconut:.35,"shredded coconut":.35,raisins:.68,almonds:.55,walnuts:.5,pecans:.5,pistachios:.55,peanuts:.6,"shredded cheese":.4,parmesan:.44,"tomato paste":1.06,"tomato sauce":1.02,ketchup:1.14,broth:1,stock:1,wine:.99,beer:1.01},Hs=2;function Gs(t){return bc[t.toLowerCase().trim()]}var Nr="cookingConvert";function zs(t){let e=t[0],o=t[1].value,r=t[2].value;if(e.type!==6||!e.unit)return P("COOKING_CONVERSION_REQUIRES_UNIT",'Expected a value with a mass or volume unit (e.g. "300g", "10 cups"), got a plain number');let n=e.unit,i=e.toNumber(),a=c$4(n),s=c$4(r),l=N=>N==="mass"||N==="volume";if(!l(a))return P("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${n}" is not a recognized mass or volume unit`);if(!l(s))return P("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${r}" is not a recognized mass or volume unit`);if(a===s)return u$1(e$1(i,n,r),r);let u=Gs(o);if(u===void 0)return P("COOKING_UNKNOWN_INGREDIENT",`No density data for "${o}" \u2014 cannot convert between mass and volume for this ingredient`);if(a==="mass"){let E=e$1(i,n,"g")/u,A=e$1(E,"ml",r);return u$1(A,r)}let f=e$1(i,n,"ml")*u,T=e$1(f,"g",r);return u$1(T,r)}var yr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,r,n){let i=r.value;e.consume("IN");let a=e.consume();n.emitOpcode(13),n.emitString(i),n.emitOpcode(13),n.emitString(a.value),n.emitPluginCall(Nr,3);}};function Ks(t=68){return {name:"uom-cooking:ingredient-name",priority:t,shape:[{types:["IDENT"]}],match(e,o){let r=e[o-1];if(!r||r.type!=="UNIT")return null;for(let n=Hs;n>=1;n--){if(o+n>e.length)continue;let i=e.slice(o,o+n);if(!i.every(c=>c.type==="IDENT"))continue;let a=o+n,s=e[a];if(!s||s.type!=="IN")continue;let l=e[a+1];if(!l||l.type!=="UNIT"&&l.type!=="IDENT")continue;let u=i.map(c=>c.value.toLowerCase()).join(" ");return {consumed:n,replacement:[b$5("INGREDIENT_NAME",u,i)],ruleName:"uom-cooking:ingredient-name"}}return null}}}function $s(t=78){return {name:"uom:multi-word-unit",priority:t,shape:[{types:["UNIT"]},{types:["UNIT"]}],match(e,o){let r=e[o],n=e[o+1];if(r?.type!=="UNIT"||n?.type!=="UNIT"||r.offset+r.text.length+1!==n.offset)return null;let i=`${r.value} ${n.value}`;return a$7[i]===void 0?null:{consumed:2,replacement:[b$5("UNIT",i,e.slice(o,o+2))],ruleName:"uom:multi-word-unit"}}}}function Ws(t=77){return {name:"uom:compound-unit",priority:t,shape:[{types:["UNIT"]},{types:["SLASH"]}],match(e,o){let r=e[o],n=e[o+1],i=e[o+2];if(r?.type!=="UNIT"||n?.type!=="SLASH"||i?.type!=="UNIT")return null;let a=`${r.value}/${i.value}`;return {consumed:3,replacement:[b$5("UNIT",a,[r,n,i])],ruleName:"uom:compound-unit"}}}}var xn={name:"solve-uom",prefixParselets:{CONVERT:new pr,UOM_POSSIBILITIES_QUERY:new fr},infixParselets:{IN_TWO_UNITS:new dr(94),PER_UNIT:new Er(95),AT_RATE:new Tr(96),UNIT:new cr,INGREDIENT_NAME:new yr},normalizerRules:[$s(),Ws(),Cs(),vs(),Bs(),Ms(),bs(),Vs(),Ds(),Fs(),Ks()],pluginFunctions:{[Nr]:zs}};var Q=class{constructor(){this.category="UoM";}parse(e,o,r){let n=ta(o.value)??o.value.toUpperCase();e.parseExpression(a.Prefix,r),e.peek()?.type==="UNIT"&&e.consume(),r.emitOpcode(13),r.emitString(n),r.emitOpcode(80);}};var gr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,r,n){let i=e.peek();if(i?.type==="IP_CIDR"){e.parseExpression(a.Prefix,n),n.emitPluginCall("ipInCidr",2);return}if(i&&(i.type==="UNIT"||i.type==="DOLLAR"||i.type==="POUND"||i.type==="EURO"||i.type==="YEN"||i.type==="RUBLE"||i.type==="WON"||i.type==="CURRENCY_SYMBOL"||i.type==="IDENT"||i.type==="IN")){e.consume();let a=ta(i.value)??i.value,s=ur(e,a);if(s!==null){n.emitOpcode(13),n.emitString(a),n.emitOpcode(13),n.emitString(s),n.emitPluginCall(fe,3);return}n.emitOpcode(13),n.emitString(a),n.emitOpcode(84);}}};function Rn(t={}){return {name:"solve-currency",asyncResolvers:[new b$2,hs(t.historicalRateProvider)],prefixParselets:{DOLLAR:new Q,POUND:new Q,EURO:new Q,YEN:new Q,RUBLE:new Q,WON:new Q,CURRENCY_SYMBOL:new Q},infixParselets:{IN:new gr},pluginFunctions:{[fe]:gn(t.historicalRateProvider)}}}var On=Rn();var Ce=class{constructor(e=0){this.category="Vector";this.dimension=e;}parse(e,o,r){e.consume("LPAREN");let n=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(0,r),n++;e.match("COMMA");)e.parseExpression(0,r),n++;e.consume("RPAREN"),r.emitOpcode(152),r.emitIndex(1),r.emitIndex(this.dimension>0?this.dimension:n);}};var Pr=class{constructor(){this.category="Float";}parse(e,o,r){e.consume("LPAREN"),e.parseExpression(0,r),e.consume("RPAREN"),r.emitOpcode(152),r.emitIndex(1),r.emitIndex(1);}};var hn={name:"solve-vector",prefixParselets:{VEC2:new Ce(2),VEC3:new Ce(3),VEC4:new Ce(4),FLOAT:new Pr}};var _r=class{constructor(){this.category="Matrix";}parse(e,o,r){let n=0,i=-1;if(e.peek()?.type==="RBRACKET")throw c$1.parsing("EMPTY_MATRIX_LITERAL","A matrix literal cannot be empty \u2014 `[]` has no valid shape.",{});for(;;){let a=0;for(e.parseExpression(0,r),a++;e.match("COMMA");)e.parseExpression(0,r),a++;if(i===-1)i=a;else if(a!==i)throw c$1.parsing("RAGGED_MATRIX_LITERAL",`Matrix literal rows must all have the same number of columns \u2014 row ${n+1} has ${a}, but a previous row has ${i}.`,{expectedCols:i,actualCols:a,row:n+1});if(n++,!e.match("SEMICOLON"))break}e.consume("RBRACKET"),r.emitOpcode(152),r.emitIndex(n),r.emitIndex(i);}};var Ar=class{constructor(){this.category="Matrix";this.bindingPower=a.Postfix;}parse(e,o,r,n){let i=this.hasTopLevelColon(e);this.parseIndexArg(e,n,i);let a=1;if(e.match("COMMA")&&(this.parseIndexArg(e,n,i),a=2),e.consume("RBRACKET"),!i){a===1?n.emitOpcode(153):n.emitOpcode(154);return}if(a!==2)throw c$1.parsing("INVALID_MATRIX_SLICE_ARITY",`Range-based matrix slicing needs exactly 2 arguments ("a[rowRange, colRange]"), got ${a}.`,{argCount:a});n.emitOpcode(155);}hasTopLevelColon(e){let o=0;for(let r=0;;r++){let n=e.peekAt(r);if(!n)return false;if(n.type==="LBRACKET"||n.type==="LPAREN")o++;else if(n.type==="RBRACKET"||n.type==="RPAREN"){if(o===0)return false;o--;}else if(n.type==="COLON"&&o===0)return true}}parseIndexArg(e,o,r){e.parseExpression(0,o);let n=false;e.match("COLON")&&(e.parseExpression(0,o),n=true),r&&(n||o.emitOpcode(3),o.emitOpcode(156));}};var In={name:"solve-matrix",prefixParselets:{LBRACKET:new _r},infixParselets:{LBRACKET:new Ar}};function xr(t,e){let o=t.peek(),r=t.peekAt(1);if(o&&(o.type==="IDENT"||o.type==="UNIT"||o.type==="FUNC")&&r?.type==="COMMA"){t.consume();let a=o.value,s=Qo[a.toLowerCase()];return s!==void 0?{kind:1,builtinIdx:s}:{kind:2,name:a}}let n=new d$1(e.pluginIndexMap);t.parseExpression(a.Lowest,n),t.setBuilder(e);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","map/reduce transform expressions must be synchronous (no weather/stocks/currency calls).");return {kind:0,program:i}}function Ys(t){let e=t.peek(),o=t.peekAt(1);return !!e&&(e.type==="IDENT"||e.type==="UNIT")&&o?.type==="EQUALS"}function js(t){let e=t.peek();if(e&&(e.type==="IDENT"||e.type==="UNIT"))return t.consume(),e.value;throw c$1.parsing("MAP_REDUCE_EXPECTED_COLLECTION_NAME",`Expected a collection name (e.g. "x" in "x=[1,2,3]") but got ${e?`"${e.value}"`:"end of input"}.`)}function ee(t,e){t.parseExpression(0,e),t.match("COLON")&&(t.parseExpression(0,e),e.emitOpcode(156));}function ie(t,e,o,r,n){if(t.emitOpcode(e),t.emitIndex(o.kind),o.kind===0){let i=t.emitAnonymousBody(r,o.program);t.emitIndex(i);}else o.kind===1?t.emitIndex(o.builtinIdx):t.emitString(o.name);t.emitIndex(n);}var Rr=class{constructor(){this.category="MapReduce";}parse(e,o,r){e.consume("LPAREN");let n=xr(e,r);e.consume("COMMA");let i=[];if(Ys(e))do{let a=js(e);e.consume("EQUALS"),ee(e,r),i.push(a);}while(e.match("COMMA"));else ee(e,r),i.push("x");e.consume("RPAREN"),ie(r,157,n,i,i.length);}};var Or=class{constructor(){this.category="MapReduce";}parse(e,o,r){e.consume("LPAREN");let n=xr(e,r);e.consume("COMMA"),ee(e,r);let i=0;e.match("COMMA")&&(e.parseExpression(a.Lowest,r),i=1),e.consume("RPAREN"),ie(r,158,n,["acc","x"],i);}};var hr=class{constructor(){this.category="MapReduce";}parse(e,o,r){e.consume("LPAREN");let n=new d$1(r.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(r),n.emitOpcode(20);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","sum's element expression must be synchronous (no weather/stocks/currency calls).");e.consume("COMMA"),ee(e,r),e.consume("RPAREN"),r.emitOpcode(10),r.emitNumber(0),ie(r,158,{kind:0,program:i},["acc","x"],1);}};var Ir=class{constructor(){this.category="MapReduce";}parse(e,o,r){e.consume("LPAREN");let n=new d$1(r.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(r),n.emitOpcode(22);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","prod's element expression must be synchronous (no weather/stocks/currency calls).");e.consume("COMMA"),ee(e,r),e.consume("RPAREN"),r.emitOpcode(10),r.emitNumber(1),ie(r,158,{kind:0,program:i},["acc","x"],1);}};var Vc={map:"MAP",reduce:"REDUCE",sum:"SUM_FN",prod:"PROD_FN"};function Fc(t,e){return t?!!(t.type==="LINE_REF"||t.type==="IDENT"&&(/^line\d+$/i.test(t.value)||/^line$/i.test(t.value)&&e?.type==="NUMBER"&&/^\d+$/.test(e.value))):false}function Xs(t=80){return {name:"mapreduce:call",priority:t,startTokenTypes:["IDENT"],match(e,o){let r=e[o];if(!r||r.type!=="IDENT")return null;let n=r.value.toLowerCase(),i=Vc[n];return !i||e[o+1]?.type!=="LPAREN"||n==="sum"&&Fc(e[o+2],e[o+3])?null:{consumed:1,replacement:[new a$2(i,c(i),r.value,r.value,r.offset,0,r.line,r.col)],ruleName:"mapreduce:call"}}}}var Cn={name:"solve-mapreduce",normalizerRules:[Xs()],prefixParselets:{MAP:new Rr,REDUCE:new Or,SUM_FN:new hr,PROD_FN:new Ir}};var Cr=class{constructor(){this.category="BigInt";}parse(e,o,r){r.emitOpcode(11),r.emitString(e$3(o.value,e.getLocaleCode()));}};var Sn={name:"solve-bigint",prefixParselets:{BIGINT:new Cr}};var te=class{constructor(e){this.opcode=e;this.category="Conditionals";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var Se=class{constructor(e,o){this.opcode=e;this.bindingPower=o;this.category="Conditionals";}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var st=class{constructor(e){this.value=e;this.category="Conditionals";}parse(e,o,r){r.emitOpcode(14),r.emitByte(this.value?1:0);}};var Sr=class{constructor(){this.category="Conditionals";}parse(e,o,r){e.parseExpression(0,r),e.consume("THEN"),e.parseExpression(0,r),e.consume("ELSE"),e.parseExpression(0,r),r.emitOpcode(132);}};var Ln={name:"solve-conditionals",prefixParselets:{TRUE:new st(true),FALSE:new st(false),IF:new Sr},infixParselets:{EQUALITY:new te(40),NEQ:new te(41),LT:new te(42),GT:new te(44),LTE:new te(43),GTE:new te(45),OR:new Se(131,a.LogicalOr),LOGICAL_AND:new Se(130,a.LogicalAnd),LOGICAL_OR:new Se(131,a.LogicalOr)}};var Hc={percent:74,percentage:74,decimal:70,dec:70,number:70,hex:71,fraction:140,multiplier:141,x:141,sci:142,scientific:142,binary:143,bin:143,octal:144,oct:144},Qs={2:143,8:144,16:71},Lr=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,r,n){let i=e.peek();if(i?.type==="PERCENT"){e.consume(),n.emitOpcode(74);return}if(!i||i.type!=="CONVERTER_NAME"&&i.type!=="IDENT"&&i.type!=="FUNC"&&i.type!=="UNIT")throw c$1.parsing("AS_CONVERTER_EXPECTED_NAME",`Expected a converter name after "as" (e.g. "as hex", "as decimal") but got ${i?`"${i.value}"`:"end of input"}`);e.consume();let a$1=i.value.toLowerCase();if(a$1==="base"){let l=e.peek(),u=l?.type==="NUMBER"?Number(l.value):NaN,c=Qs[u];if(c===void 0)throw c$1.parsing("AS_CONVERTER_UNSUPPORTED_BASE",`"as base ${l?.value??"?"}": only bases ${Object.keys(Qs).join(", ")} can be written out`);e.consume(),n.emitOpcode(c);return}let s=Hc[a$1];if(s!==void 0){s===141&&e.match("OF")&&(e.parseExpression(a.Conditional,n),n.emitOpcode(23)),n.emitOpcode(s);return}n.emitOpcode(13),n.emitString(a$1),n.emitOpcode(145);}};var qs={ten:10,hundred:100,thousand:1e3,million:1e6,billion:1e9};function Zs(t,e,o){t.emitOpcode(10),t.emitNumber(e),t.emitOpcode(23),Js(t,o),t.emitOpcode(10),t.emitNumber(e),t.emitOpcode(22);}function Js(t,e){let o=e==="up"?zc:e==="down"?Kc:Gc;t.emitOpcode(51),t.emitIndex(o),t.emitIndex(1);}var Gc=8,zc=6,Kc=7,$c=97;function Wc(t){let o=(t.peek()?.text??"").toLowerCase();return o==="up"?(t.consume(),"up"):o==="down"?(t.consume(),"down"):"nearest"}var wr=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,r,n){let i=Wc(e);if(e.match("TO_NEAREST")){Zs(n,em(e),i);return}Js(n,i);}},vr=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,r,n){Zs(n,em(e),"nearest");}};function em(t){let e=t.peek(),o=(e?.text??"").toLowerCase(),r=qs[o];if(r!==void 0)return t.consume(),r;if(e?.type==="NUMBER"){t.consume();let n=Number(e.value);if(Number.isFinite(n)&&n>0)return n}throw c$1.parsing("INVALID_ROUNDING_INCREMENT",`"to nearest ${e?.value??"?"}": expected a positive number or one of ${Object.keys(qs).join(", ")}`)}var kr=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,r,n){let i=Number(r.value);if(!Number.isFinite(i)||i<0||i>100)throw c$1.parsing("INVALID_DECIMAL_PLACES",`"to ${r.value} dp": expected a place count between 0 and 100`);n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(51),n.emitIndex($c),n.emitIndex(2);}};var Yc=new Set(["dp","dps","decimals","digits","digit"]),jc=new Set(["decimal"]);function tm(t=66){return {name:"converters:decimal-places",priority:t,shape:[{types:["TO"]},{types:["NUMBER"]}],match(e,o){if(e[o]?.type!=="TO")return null;let r=e[o+1];if(r?.type!=="NUMBER")return null;let n=e[o+2];if(!n)return null;let i=(n.text??n.value??"").toLowerCase(),a=3;if(jc.has(i)){let l=(e[o+3]?.text??"").toLowerCase();if(l!=="place"&&l!=="places")return null;a=4;}else if(!Yc.has(i))return null;return {consumed:a,replacement:[b$5("DECIMAL_PLACES",r.value,e.slice(o,o+a))],ruleName:"converters:decimal-places"}}}}var Xc=new Set(["hex","bin"]);function rm(t=67){return {name:"converters:preposition",priority:t,shape:[{types:["IN","TO"]},{types:["CONVERTER_NAME","FUNC"]}],match(e,o){let r=e[o];if(r?.type!=="IN"&&r?.type!=="TO")return null;let n=e[o+1];return n?.type==="CONVERTER_NAME"||n?.type==="FUNC"&&Xc.has(n.value.toLowerCase())?{consumed:1,replacement:[b$5("AS","as",[r])],ruleName:"converters:preposition"}:null}}}var wn={name:"solve-converters",phrases:{"to nearest":"TO_NEAREST","to the nearest":"TO_NEAREST"},infixParselets:{AS:new Lr,ROUNDED:new wr,TO_NEAREST:new vr,DECIMAL_PLACES:new kr},normalizerRules:[tm(),rm()]};var H=class{constructor(e){this.builtinIndex=e;this.category="MathPhrases";}parse(e,o,r){let n=0;for(e.parseExpression(a.Conjunction,r),n++;e.match("COMMA")||e.match("AND_CONJ");)e.parseExpression(a.Conjunction,r),n++;r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(n);}};var Br=class{constructor(e){this.builtinIndex=e;this.category="MathPhrases";}parse(e,o,r){let n=0;do{if(e.parseExpression(a.Conjunction,r),n++,!e.match("RATE_AT")&&!e.match("AT")){let i=e.peek();throw c$1.parsing("WEIGHTED_AVERAGE_MISSING_WEIGHT",'weighted average: each value needs a weight, as in "72 at 30%"',{actualType:i?.type,actualValue:i?.value})}e.parseExpression(a.Product,r),n++,this.skipWeightLabel(e);}while(e.match("COMMA")||e.match("AND_CONJ"));r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(n);}skipWeightLabel(e){for(;;){let o=e.peek();if(!o)return;if(o.type==="STAR"||o.type==="IDENT"||o.type==="UNIT"){e.consume();continue}return}}};function vn(t){return {category:"MathPhrases",parse(e,o,r){e.parseExpression(a.Lowest,r),r.emitOpcode(51),r.emitIndex(t),r.emitIndex(1);}}}var nm={category:"MathPhrases",parse(t,e,o){if(t.parseExpression(a.Product,o),!t.match("DIVIDE_BY")&&!t.match("SLASH"))throw c$1.parsing("REMAINDER_EXPECTED_DIVIDED_BY",'Expected "divided by" or "/", as in "remainder of 21 divided by 5"');t.parseExpression(a.Product,o),o.emitOpcode(24);}},im={category:"MathPhrases",parse(t,e,o){if(t.parseExpression(a.Product,o),!t.match("OF"))throw c$1.parsing("ROOT_EXPECTED_OF",'Expected "of", as in "root 5 of 100"');t.parseExpression(a.Conditional,o),o.emitOpcode(2),o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(23),o.emitOpcode(25);}},am={category:"MathPhrases",parse(t,e,o){if(t.parseExpression(a.Conditional,o),om(o),!t.match("LOG_BASE"))throw c$1.parsing("LOG_EXPECTED_BASE",'Expected "base", as in "log 20 base 4"');t.parseExpression(a.Conditional,o),om(o),o.emitOpcode(23);}},Qc=5;function om(t){t.emitOpcode(51),t.emitIndex(Qc),t.emitIndex(1);}function sm(t=69){return {name:"mathphrases:function-phrase",priority:t,shape:[{types:["FUNC"],values:["root","log"]}],match(e,o){let r=e[o];if(r?.type!=="FUNC")return null;let n=(r.value??"").toLowerCase();if(n!=="root"&&n!=="log"||e[o+1]?.type==="LPAREN")return null;if(n==="root")return {consumed:1,replacement:[b$5("NTH_ROOT","root",[r])],ruleName:"mathphrases:function-phrase"};let i=qc(e,o+1);if(i===-1)return null;let a=e.slice(o,i+1).map((s,l)=>l===0?b$5("LOG_PHRASE","log",[s]):l===i-o?b$5("LOG_BASE","base",[s]):s);return {consumed:i-o+1,replacement:a,ruleName:"mathphrases:function-phrase"}}}}function qc(t,e){for(let o=e;o<t.length&&o<e+8;o++){let r=t[o];if(r.type==="EOF"||r.type==="COMMA"||r.type==="RPAREN")return -1;if((r.text??r.value??"").toLowerCase()==="base")return o}return -1}function mt(t){return {category:"MathPhrases",parse(e,o,r){e.parseExpression(a.Conjunction,r),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,r),r.emitOpcode(51),r.emitIndex(t),r.emitIndex(2);}}}var mm={category:"MathPhrases",parse(t,e,o){t.parseExpression(a.Lowest,o),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var lm={category:"MathPhrases",parse(t,e,o){t.parseExpression(a.Conjunction,o),t.consume("AND_CONJ"),t.parseExpression(a.Lowest,o),o.emitOpcode(20),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var um=or({category:"MathPhrases",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:t=>{t.emitOpcode(51),t.emitIndex(37),t.emitIndex(2);}}]});var Zc=47,Mr=class{constructor(){this.category="MathPhrases";}parse(e,o,r){e.parseExpression(a.Lowest,r);let n=e.peek();if(n?.type==="BETWEEN")e.consume(),e.parseExpression(a.Product,r),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,r);else if(n?.type==="FROM")e.consume(),e.parseExpression(a.Lowest,r),e.consume("TO"),e.parseExpression(a.Lowest,r);else throw c$1.parsing("CLAMP_EXPECTED_BETWEEN_OR_FROM",`Expected "between" or "from" after "clamp <value>" but got ${n?`"${n.value}"`:"end of input"}`);r.emitOpcode(51),r.emitIndex(Zc),r.emitIndex(3);}};var Jc=46,Ur=class{constructor(){this.category="MathPhrases";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),e.consume("AS"),e.parseExpression(this.bindingPower,n),e.consume("IS_TO");let i=e.consume();if(!i||i.value.toLowerCase()!=="what")throw c$1.parsing("PROPORTION_EXPECTED_WHAT",`Expected "what" but got ${i?`"${i.value}"`:"end of input"}`);n.emitOpcode(51),n.emitIndex(Jc),n.emitIndex(3);}};var ep=42,tp=43,rp=44,op=45,np=9,ip=10,ap=101,sp=102,mp=103,lp=104,up=105,cp=106,pp=107,fp=38,dp=39,Ep=0,Tp=21,kn={name:"solve-mathphrases",phrases:{"average of":"AVERAGE_OF","median of":"MEDIAN_OF","total of":"TOTAL_OF","count of":"COUNT_OF","larger of":"LARGER_OF","greater of":"LARGER_OF","smaller of":"SMALLER_OF","lesser of":"SMALLER_OF","half of":"HALF_OF","midpoint between":"MIDPOINT_BETWEEN","random number":"RANDOM_NUMBER","is to":"IS_TO","remainder of":"REMAINDER_OF","gcd of":"GCD_OF","lcm of":"LCM_OF","square root of":"SQUARE_ROOT_OF","cube root of":"CUBE_ROOT_OF","standard deviation of":"STANDARD_DEVIATION_OF","stdev of":"STANDARD_DEVIATION_OF","sample standard deviation of":"SAMPLE_STANDARD_DEVIATION_OF","sample stdev of":"SAMPLE_STANDARD_DEVIATION_OF","variance of":"VARIANCE_OF","sample variance of":"SAMPLE_VARIANCE_OF","spread of":"SPREAD_OF","mode of":"MODE_OF","weighted average of":"WEIGHTED_AVERAGE_OF","weighted mean of":"WEIGHTED_AVERAGE_OF"},prefixParselets:{AVERAGE_OF:new H(ep),MEDIAN_OF:new H(tp),TOTAL_OF:new H(rp),COUNT_OF:new H(op),LARGER_OF:mt(ip),SMALLER_OF:mt(np),HALF_OF:mm,MIDPOINT_BETWEEN:lm,RANDOM_NUMBER:um,REMAINDER_OF:nm,NTH_ROOT:im,LOG_PHRASE:am,GCD_OF:mt(fp),LCM_OF:mt(dp),SQUARE_ROOT_OF:vn(Ep),CUBE_ROOT_OF:vn(Tp),CLAMP:new Mr,STANDARD_DEVIATION_OF:new H(ap),SAMPLE_STANDARD_DEVIATION_OF:new H(sp),VARIANCE_OF:new H(mp),SAMPLE_VARIANCE_OF:new H(lp),SPREAD_OF:new H(up),MODE_OF:new H(cp),WEIGHTED_AVERAGE_OF:new Br(pp)},infixParselets:{IS_TO:new Ur},normalizerRules:[sm()]};var cm={annually:1,yearly:1,"semi-annually":2,quarterly:4,monthly:12,fortnightly:26,weekly:52,daily:365};function Bn(t){if(!t.match("COMPOUNDING"))return 1;let e=t.peek(),o=(e?.text??e?.value??"").toLowerCase(),r=cm[o];if(r===void 0)throw c$1.parsing("UNKNOWN_COMPOUNDING_INTERVAL",`compounding ${o||"?"}: expected one of ${Object.keys(cm).join(", ")}`);return t.consume(),r}var lt=class{constructor(e,o){this.annualIndex=e;this.intervalIndex=o;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(a.Conditional,n),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,n);let i=Bn(e);if(n.emitOpcode(2),i===1){n.emitOpcode(51),n.emitIndex(this.annualIndex),n.emitIndex(3);return}n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(51),n.emitIndex(this.intervalIndex),n.emitIndex(4);}},Dr=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Conditional,r),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,r),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,r),r.emitOpcode(2),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(3);}},br=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(a.Conditional,n),e.consume("RETURNED"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}},Vr=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Conditional,r),e.consume("INVESTED"),e.parseExpression(a.Conditional,r),e.consume("RETURNED"),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,r),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(3);}};function Fr(t,e,o){return fm(t,o)?(t.parseExpression(a.Lowest,e),pm(t),t.parseExpression(a.Lowest,e),{swap:true}):(pm(t),t.parseExpression(a.Lowest,e),Np(t,o),t.parseExpression(a.Lowest,e),{swap:false})}function fm(t,e){for(let o of e)if(t.match(o))return true;return false}function Np(t,e){fm(t,e)||t.consume(e[0]);}function pm(t){t.match("RATE_AT")||t.consume("AT");}var ut=class{constructor(e,o){this.builtinIndex=e;this.intervalIndex=o;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Conditional,r);let{swap:n}=Fr(e,r,["AFTER","FOR_DURATION","OVER"]),i=Bn(e);if(n&&r.emitOpcode(2),i===1){r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(3);return}r.emitOpcode(10),r.emitNumber(i),r.emitOpcode(51),r.emitIndex(this.intervalIndex),r.emitIndex(4);}};var W=class{constructor(e,o){this.builtinIndex=e;this.periodsPerYear=o;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Lowest,r);let{swap:n}=Fr(e,r,["OVER"]);n&&r.emitOpcode(2),r.emitOpcode(10),r.emitNumber(this.periodsPerYear),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(4);}};var Hr=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Lowest,r),e.consume("BETWEEN"),e.parseExpression(a.Lowest,r),e.match("PEOPLE"),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(2);}},Gr=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,r,n){e.parseExpression(a.Conditional,n),e.consume("WAYS"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var dm={daily:{perYear:365,unit:"days"},weekly:{perYear:52,unit:"weeks"},monthly:{perYear:12,unit:"months"},yearly:{perYear:1,unit:"years"},annually:{perYear:1,unit:"years"}};function yp(t){let e=t.peek(),o=(e?.text??e?.value??"").toLowerCase(),r=dm[o];if(r===void 0)throw c$1.parsing("UNKNOWN_SAVINGS_PERIOD",`savings goal: expected a contribution period, one of ${Object.keys(dm).join(", ")}, not "${o||"?"}".`);return t.consume(),r}var zr=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Conditional,r),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Product,r),e.match("STAR");let n=yp(e);r.emitOpcode(10),r.emitNumber(n.perYear),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,r):(r.emitOpcode(10),r.emitNumber(0)),r.emitOpcode(13),r.emitString(n.unit),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(5);}},Kr=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Product,r),e.consume("IN"),e.parseExpression(a.Conditional,r),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,r):(r.emitOpcode(10),r.emitNumber(0)),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(3);}};var Le=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,r){e.parseExpression(a.Lowest,r),e.consume("RATE_AT"),e.parseExpression(a.Lowest,r),r.emitOpcode(51),r.emitIndex(this.builtinIndex),r.emitIndex(2);}};var gp=60;function Pp(t){for(let e=0;;e++){let o=t.peekAt(e);if(!o)return false;if(o.type==="FROM"||o.type==="WORTH_IN")return true}}var ct=class{constructor(e){this.variant=e;this.category="Finance";}parse(e,o,r){if(!Pp(e)){e.parseExpression(a.Lowest,r);return}if(e.parseExpression(a.Product,r),this.variant==="what-was"){e.consume("WORTH_IN"),e.parseExpression(a.Lowest,r),r.emitPluginCall("inflationToYearFromPresent",2);return}let n=e.peek();if(n?.type==="FROM"){e.consume(),e.parseExpression(a.Lowest,r),r.emitPluginCall("inflationFromYearToPresent",2);return}if(n?.type==="IN"){e.consume(),e.parseExpression(a.Lowest,r),e.consume("WORTH_IN"),e.parseExpression(a.Lowest,r),r.emitOpcode(51),r.emitIndex(gp),r.emitIndex(3);return}let i=n?n.type:"end of input";throw c$1.parsing("INFLATION_EXPECTED_FROM_OR_IN",`Expected "from <year>" or "in <year> worth in <year>" after "what is <amount>", got ${i}`)}};var $r=class{constructor(){this.category="Finance";}parse(e,o,r){e.parseExpression(a.Product,r),e.consume("IN"),e.parseExpression(a.Lowest,r),e.consume("ASSUMING"),e.parseExpression(a.Lowest,r);let n=e.peek();if((n&&n.type==="IDENT"?n.value.toLowerCase():void 0)!=="inflation"){let a=n?n.value:"end of input";throw c$1.parsing("INFLATION_EXPECTED_INFLATION_WORD",`Expected the word "inflation" after "assuming <rate>%", got "${a}"`)}e.consume(),r.emitPluginCall("inflationFutureValue",3);}};var Wr=class{constructor(){this.category="Finance";this.bindingPower=35;}parse(e,o,r,n){let i=Number(r.value);n.emitOpcode(10),n.emitNumber(i),n.emitPluginCall("inflationToYearFromPresent",2);}};function Em(t,e){return P(t,`Year ${e} is outside the bundled CPI table's range (${z$3}-${A$1})`)}function Tm(t){let e=t[0],o=t[1].toNumber(),r=new Date().getFullYear(),n$1=B$2(e.toNumber(),o,r);return n$1===void 0?Em("INFLATION_YEAR_OUT_OF_RANGE",o):e.type===6?u$1(n$1,e.unit):n(n$1)}function Nm(t){let e=t[0],o=new Date().getFullYear(),r=t[1].toNumber(),n$1=B$2(e.toNumber(),o,r);return n$1===void 0?Em("INFLATION_YEAR_OUT_OF_RANGE",r):e.type===6?u$1(n$1,e.unit):n(n$1)}function ym(t){let e=t[0],o=t[1].toNumber(),r=t[2].toNumber(),n$1=o-new Date().getFullYear();if(1+r<=0)return P("INVALID_RATE",`inflationFutureValue: rate ${r} makes (1 + rate) non-positive`);let a=e.toNumber()/Math.pow(1+r,n$1);return e.type===6?u$1(a,e.unit):n(a)}function gm(t=70){return {name:"finance:in-year-dollars",priority:t,shape:[{types:["IN"]},{types:["NUMBER"]}],match(e,o){let r=e[o],n=e[o+1],i=e[o+2];if(r.type!=="IN"||n?.type!=="NUMBER"||i?.type!=="IDENT"&&i?.type!=="UNIT")return null;let a=i.value.toLowerCase();return a!=="dollars"&&a!=="dollar"?null:{consumed:3,replacement:[b$5("IN_YEAR_DOLLARS",n.value,e.slice(o,o+3))],ruleName:"finance:in-year-dollars"}}}}var _p={RECURRING_INTERVAL_NOT_POSITIVE:"RECURRING_INTERVAL_NOT_POSITIVE"},Ap={daily:365,weekly:52,monthly:12,yearly:1,annually:1},xp={day:365,days:365,week:52,weeks:52,month:12,months:12,year:1,years:1},Rp=new Set(["a","an"]),Op=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]);function pt(t){return t===void 0?"":(t.text??t.value??"").toLowerCase()}function Pm(t){if(!(t===void 0||t.type!=="UNIT"))return xp[pt(t)]}function hp(t,e){let o=t[e];if(o===void 0)return null;if(o.type==="IDENT"){let r=Ap[pt(o)];if(r!==void 0)return {perYear:r,consumed:1};if(pt(o)==="every"){let n=t[e+1];if(n?.type!=="NUMBER")return null;let i=Pm(t[e+2]);if(i===void 0)return null;let a=Number((n.value??"").replace(/,/g,""));if(!(a>0))throw c$1.parsing({code:_p.RECURRING_INTERVAL_NOT_POSITIVE,message:`A recurring interval must be a positive number, not "${n.value}".`,expected:"a positive interval, e.g. every 2 weeks",found:`every ${n.value} ${pt(t[e+2])}`});return {perYear:i/a,consumed:3}}}return null}function Ip(t,e){let o=t[e];if(o===void 0)return null;let r,n;if(o.type==="NUMBER")r=Number((o.value??"").replace(/,/g,"")),n=e+1;else if(o.type==="IDENT"&&Rp.has(pt(o)))r=1,n=e+1;else return null;let i=Pm(t[n]);return i===void 0||!Number.isFinite(r)||r<0?null:{years:r/i,consumed:n-e+1}}function Cp(t,e){let o=t*e,r=Math.round(o);return Math.abs(o-r)<1e-9?r:Math.floor(o)}function _m(t=78){return {name:"finance:recurring-schedule",priority:t,unshapedReason:"Scans forward through a period and a duration sub-grammar of unbounded length, so no fixed leading shape describes it.",match(e,o){let r=e[o];if(r===void 0||!Op.has(r.type))return null;let n=hp(e,o+1);if(n===null)return null;let i=o+1+n.consumed;if(e[i]?.type!=="FOR_DURATION")return null;let a=Ip(e,i+1);if(a===null)return null;let s=Cp(n.perYear,a.years),l=i+1+a.consumed-o,u=e.slice(o,o+l);return {replacement:[r,b$5("STAR","*",u),b$5("NUMBER",String(s),u)],consumed:l,ruleName:"finance:recurring-schedule"}}}}function Yr(t){return t===void 0?"":(t.text??t.value??"").toLowerCase()}var Am=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]),xm=new Set(["NUMBER","FLOAT"]);function Rm(t=77){return {name:"finance:bill-split",priority:t,unshapedReason:"Scans forward an unbounded distance for the BETWEEN keyword, and starts at any value-ending token.",match(e,o){let r=e[o];if(r===void 0)return null;if(Am.has(r.type)){let f=e[o+1],T=e[o+2],N=e[o+3];if(f?.type==="IDENT"&&Yr(f)==="split"&&T!==void 0&&xm.has(T.type)&&N?.type==="IDENT"&&Yr(N)==="ways")return {consumed:4,replacement:[r,b$5("SPLIT_WAYS","split",[f]),T,b$5("WAYS","ways",[N])],ruleName:"finance:bill-split"}}if(r.type!=="IDENT"||Yr(r)!=="split")return null;let n=e[o-1];if(n!==void 0&&Am.has(n.type))return null;let i=-1;for(let f=o+1;f<e.length;f++)if(e[f].type==="BETWEEN"){i=f;break}if(i===-1)return null;let a=e[i+1];if(a===void 0||!xm.has(a.type))return null;let s=i+2,l=e[s]?.type==="IDENT"&&Yr(e[s])==="people",u=l?s:i+1,c=[b$5("SPLIT","split",[r]),...e.slice(o+1,i+2)];return l&&c.push(b$5("PEOPLE","people",[e[s]])),{consumed:u-o+1,replacement:c,ruleName:"finance:bill-split"}}}}var Mn=51,Sp=52,jr=55,Xr=56,Un=80,Lp=81,wp=82,vp=83,kp=84,Bp=59,Mp=85,Up=86,Om=98,Dp=99,bp=100,Dn={name:"solve-finance",phrases:{"compound interest on":"COMPOUND_INTEREST_ON","interest on":"INTEREST_ON","daily repayment on":"DAILY_REPAYMENT_ON","monthly repayment on":"MONTHLY_REPAYMENT_ON","annual repayment on":"ANNUAL_REPAYMENT_ON","total repayment on":"TOTAL_REPAYMENT_ON","daily interest on":"DAILY_LOAN_INTEREST_ON","monthly interest on":"MONTHLY_LOAN_INTEREST_ON","annual interest on":"ANNUAL_LOAN_INTEREST_ON","total interest on":"TOTAL_LOAN_INTEREST_ON","tax on":"TAX_ON","tax off":"TAX_OFF","tax in":"TAX_IN_PHRASE","tax of":"TAX_IN_PHRASE","tax from":"TAX_IN_PHRASE","vat in":"TAX_IN_PHRASE","vat of":"TAX_IN_PHRASE","vat from":"TAX_IN_PHRASE","vat on":"TAX_ON","vat off":"TAX_OFF","what is":"WHAT_IS","what was":"WHAT_WAS","present value of":"PRESENT_VALUE_OF","annual return on":"ANNUAL_RETURN_ON","value of":"VALUE_OF","worth in":"WORTH_IN","how long to save":"SAVINGS_HOW_LONG","how much per month to save":"SAVINGS_HOW_MUCH","how much per month to reach":"SAVINGS_HOW_MUCH",assuming:"ASSUMING"},prefixParselets:{PRESENT_VALUE_OF:new Dr(wp),ANNUAL_RETURN_ON:new Vr(kp),COMPOUND_INTEREST_ON:new ut(Mn,Un),INTEREST_ON:new ut(Sp,Lp),DAILY_REPAYMENT_ON:new W(jr,365),MONTHLY_REPAYMENT_ON:new W(jr,12),ANNUAL_REPAYMENT_ON:new W(jr,1),TOTAL_REPAYMENT_ON:new W(jr,0),DAILY_LOAN_INTEREST_ON:new W(Xr,365),MONTHLY_LOAN_INTEREST_ON:new W(Xr,12),ANNUAL_LOAN_INTEREST_ON:new W(Xr,1),TOTAL_LOAN_INTEREST_ON:new W(Xr,0),TAX_ON:new Le(Up),TAX_OFF:new Le(Bp),TAX_IN_PHRASE:new Le(Mp),SPLIT:new Hr(Om),WHAT_IS:new ct("what-is"),WHAT_WAS:new ct("what-was"),VALUE_OF:new $r,SAVINGS_HOW_LONG:new zr(bp),SAVINGS_HOW_MUCH:new Kr(Dp)},infixParselets:{AFTER:new lt(Mn,Un),FOR_DURATION:new lt(Mn,Un),INVESTED:new br(vp),IN_YEAR_DOLLARS:new Wr,SPLIT_WAYS:new Gr(Om)},normalizerRules:[gm(),_m(),Rm()],pluginFunctions:{inflationFromYearToPresent:Tm,inflationToYearFromPresent:Nm,inflationFutureValue:ym}};function Vp(t){return (e,o)=>P(`${t.toUpperCase()}_QUERY_FAILED`,`Failed to resolve "${e}": ${o instanceof Error?o.message:String(o)}`)}function de(t){let e=t.staleTimeMs??3e5,o=t.timeoutMs??1e4,r=t.failureCooldownMs??3e4,n=t.onError??Vp(t.namespace),i=u=>[t.namespace,u];async function a(u,c,f){let{signal:T,cleanup:N}=a$4(c,o,`${t.namespace} query`);try{return await t.fetchQuery(u,T)}catch(E){let A=n(u,E);return setTimeout(()=>{f.getQueryData(i(u))===A&&f.removeQueries({queryKey:i(u),exact:true});},r).unref?.(),A}finally{N();}}return {resolver:{namespace:t.namespace,preflight(u,c,f,T,N){let{opcodes:E,strings:A}=c,R=E.length,O=0;for(;O<R;){if(E[O]===50&&O+2<R){let P=E[O+1],C=E[O+2];if(P===t.pluginFunctionIndex&&C>=1&&O>=2&&E[O-2]===13){let S=A[E[O-1]],j=i(S);if(N.getQueryData(j)===void 0){let ze=N.fetchQuery({queryKey:j,queryFn:({signal:Fo})=>a(S,Fo,N),staleTime:e}),me={queryKey:j.join(":"),resolver:ze,packageId:f,signal:T,metadata:{query:S}};return t.refetchIntervalMs!==void 0&&(me.refetchIntervalMs=t.refetchIntervalMs,me.refetch=()=>N.fetchQuery({queryKey:j,queryFn:({signal:Fo})=>a(S,Fo,N),staleTime:0})),me}}O+=3;continue}O=a$3(E,O);}return null},destroy(){}},pluginFunction:u=>{let c=u[0]?.value,f=b$4()?.getQueryData(i(c));return f!==void 0?f:P(`${t.namespace.toUpperCase()}_NOT_PREFLIGHTED`,`No cached result for "${c}"`)}}}function Fp(t,e){let o=[];for(;t.peek()?.type==="IDENT";)o.push(t.consume().value);if(o.length===0)throw c$1.parsing("WEATHER_EXPECTED_CITY",`Expected a city name after "${e}" (e.g. "${e} London")`);return o.join(" ")}function we(t,e){return {category:"Weather",parse(o,r,n){let i=Fp(o,r.value);n.emitOpcode(13),n.emitString(`${t}:${i}`),n.emitPluginCall(e,1);}}}var Hp={0:"clear sky",1:"mainly clear",2:"partly cloudy",3:"overcast",45:"fog",48:"depositing rime fog",51:"light drizzle",53:"moderate drizzle",55:"dense drizzle",56:"light freezing drizzle",57:"dense freezing drizzle",61:"slight rain",63:"moderate rain",65:"heavy rain",66:"light freezing rain",67:"heavy freezing rain",71:"slight snow fall",73:"moderate snow fall",75:"heavy snow fall",77:"snow grains",80:"slight rain showers",81:"moderate rain showers",82:"violent rain showers",85:"slight snow showers",86:"heavy snow showers",95:"thunderstorm",96:"thunderstorm with slight hail",99:"thunderstorm with heavy hail"};function hm(t){return Hp[t]??`weather code ${t}`}var ve={GEOCODING_API_ERROR:"WEATHER_GEOCODING_API_ERROR",CITY_NOT_FOUND:"WEATHER_CITY_NOT_FOUND",FORECAST_API_ERROR:"WEATHER_FORECAST_API_ERROR",FORECAST_RESPONSE_MALFORMED:"WEATHER_FORECAST_RESPONSE_MALFORMED",UNKNOWN_QUERY_KIND:"WEATHER_UNKNOWN_QUERY_KIND"},Gp="https://geocoding-api.open-meteo.com/v1/search",zp="https://api.open-meteo.com/v1/forecast",Kp=1e4;async function $p(t,e){let o=`${Gp}?name=${encodeURIComponent(t)}&count=1&language=en&format=json`,r=await fetch(o,{signal:e});if(!r.ok)throw c$1.external(ve.GEOCODING_API_ERROR,`Open-Meteo geocoding API returned ${r.status} for "${t}"`,{city:t,status:r.status});let i=(await r.json())?.results?.[0];if(!i)throw c$1.validation(ve.CITY_NOT_FOUND,`No location found for "${t}"`,{city:t});return {latitude:i.latitude,longitude:i.longitude,name:i.name}}async function Wp(t,e,o){let r=new URLSearchParams({latitude:String(t),longitude:String(e),current:"temperature_2m,apparent_temperature,weather_code",daily:"temperature_2m_max,temperature_2m_min",timezone:"auto",forecast_days:"1"}),n=await fetch(`${zp}?${r.toString()}`,{signal:o});if(!n.ok)throw c$1.external(ve.FORECAST_API_ERROR,`Open-Meteo forecast API returned ${n.status}`,{status:n.status});let i=await n.json(),a=i?.current,s=i?.daily;if(!a||!s)throw c$1.external(ve.FORECAST_RESPONSE_MALFORMED,"Open-Meteo forecast response missing current/daily blocks");return {weatherCode:a.weather_code,temperature:a.temperature_2m,apparentTemperature:a.apparent_temperature,high:s.temperature_2m_max?.[0],low:s.temperature_2m_min?.[0]}}var Qr=new Map,Yp=6e4;function Im(t,e){let o=t.trim().toLowerCase(),r=Date.now(),n=Qr.get(o);if(n&&n.expiresAt>r)return n.promise;let{signal:i,cleanup:a}=a$4(e,Kp,"Open-Meteo weather query"),s=(async()=>{try{let l=await $p(t,i),u=await Wp(l.latitude,l.longitude,i);return {resolvedName:l.name,weatherCode:u.weatherCode,description:hm(u.weatherCode),temperature:u.temperature,apparentTemperature:u.apparentTemperature,high:u.high,low:u.low}}finally{a();}})();return Qr.set(o,{promise:s,expiresAt:r+Yp}),s.catch(()=>{Qr.get(o)?.promise===s&&Qr.delete(o);}),s}var Cm="solve-weather",Ee="weather",jp=F$1(`${Cm}:${Ee}`),{resolver:Xp,pluginFunction:Qp}=de({namespace:"weather",pluginFunctionIndex:jp,staleTimeMs:600*1e3,fetchQuery:async(t$1,e)=>{let o=t$1.indexOf(":"),r=o===-1?t$1:t$1.slice(0,o),n=o===-1?"":t$1.slice(o+1),i=await Im(n,e);switch(r){case "current":return t(`${Math.round(i.temperature)}\xB0C, ${i.description}`);case "temperature":return u$1(i.temperature,"C");case "feelslike":return u$1(i.apparentTemperature,"C");case "high":return u$1(i.high,"C");case "low":return u$1(i.low,"C");default:throw c$1.internal(ve.UNKNOWN_QUERY_KIND,`Unknown weather query kind "${r}"`,{kind:r})}}}),bn={name:Cm,phrases:{"weather in":"WEATHER_IN","temperature in":"TEMPERATURE_IN","feels like in":"FEELS_LIKE_IN","high in":"HIGH_IN","low in":"LOW_IN"},prefixParselets:{WEATHER_IN:we("current",Ee),TEMPERATURE_IN:we("temperature",Ee),FEELS_LIKE_IN:we("feelslike",Ee),HIGH_IN:we("high",Ee),LOW_IN:we("low",Ee)},pluginFunctions:{[Ee]:Qp},asyncResolvers:[Xp]};var qr={jan:0,january:0,feb:1,february:1,mar:2,march:2,apr:3,april:3,may:4,jun:5,june:5,jul:6,july:6,aug:7,august:7,sep:8,sept:8,september:8,oct:9,october:9,nov:10,november:10,dec:11,december:11};function Jr(t){return t<10?`0${t}`:String(t)}function ft(t,e,o,r){let n=new Date(t,e,o);if(n.getFullYear()!==t||n.getMonth()!==e||n.getDate()!==o)throw c$1.parsing("STOCKS_INVALID_DATE",`"${r}" is not a valid calendar date`);return {isoDate:`${t}-${Jr(e+1)}-${Jr(o)}`,raw:r}}function Zr(t,e){if(!/^\d{4}$/.test(t))throw c$1.parsing("STOCKS_INVALID_DATE",`Expected a 4-digit year in "${e}", got "${t}"`);return parseInt(t,10)}function Sm(t){let e=t.peek();if(!e)return null;if(e.type==="DATETIME_LITERAL"){t.consume();let o=new Date(Number(e.value));return Number.isNaN(o.getTime())?null:{isoDate:`${o.getFullYear()}-${Jr(o.getMonth()+1)}-${Jr(o.getDate())}`,raw:e.text??e.value}}if(e.type==="NUMBER"){let o=t.consume(),r=t.peek();if(r&&(r.type==="SLASH"||r.type==="MINUS")){let i=r.type;t.consume();let a=t.consume("NUMBER");t.consume(i);let s=t.consume("NUMBER"),l=`${o.value}${i==="SLASH"?"/":"-"}${a.value}${i==="SLASH"?"/":"-"}${s.value}`;if(i==="SLASH"){let u=parseInt(o.value,10),c=parseInt(a.value,10),f=Zr(s.value,l);return ft(f,u-1,c,l)}else {if(/^\d{4}$/.test(o.value)){let T=parseInt(o.value,10),N=parseInt(a.value,10),E=parseInt(s.value,10);return ft(T,N-1,E,l)}let u=parseInt(o.value,10),c=parseInt(a.value,10),f=Zr(s.value,l);return ft(f,u-1,c,l)}}let n=t.peek();if(n&&n.type==="IDENT"&&qr[n.value.toLowerCase()]!==void 0){let i=qr[n.value.toLowerCase()];t.consume(),t.peek()?.type==="COMMA"&&t.consume();let a=t.consume("NUMBER"),s=`${o.value} ${n.value} ${a.value}`,l=Zr(a.value,s);return ft(l,i,parseInt(o.value,10),s)}throw c$1.parsing("STOCKS_INVALID_DATE",`Expected a date after "on" (e.g. "April 12, 2005" or "4/12/2005"), got "${o.value}"`)}if(e.type==="IDENT"&&qr[e.value.toLowerCase()]!==void 0){let o=qr[e.value.toLowerCase()];t.consume();let r=t.consume("NUMBER");t.peek()?.type==="COMMA"&&t.consume();let n=t.consume("NUMBER"),i=`${e.value} ${r.value}, ${n.value}`,a=Zr(n.value,i);return ft(a,o,parseInt(r.value,10),i)}return null}var Lm=new Set(["AAPL","MSFT","GOOGL","GOOG","AMZN","META","NVDA","TSLA","NFLX","ADBE","CRM","ORCL","IBM","INTC","AMD","CSCO","PYPL","UBER","ABNB","SPOT","SHOP","SQ","COIN","PLTR","SNOW","ZM","JPM","V","MA","BAC","WFC","GS","MS","AXP","WMT","COST","HD","NKE","SBUX","MCD","KO","PEP","DIS","TGT","BA","GE","F","GM","XOM","CVX","PFE","JNJ","UNH","MRNA","TSM","ASML","BABA"]);var ke="STOCK_TICKER",qp=c(ke);function wm(){return {name:"stocks:bare-ticker",priority:20,startTokenTypes:["IDENT"],match(t,e){let o=t[e];return !o||o.type!=="IDENT"||!Lm.has(o.value)||e>0&&t[e-1].type==="COLON"?null:{consumed:1,replacement:[new a$2(ke,qp,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"stocks:bare-ticker"}}}}function Zp(t){let e=t.peek();if(!e||e.type!=="IDENT")return null;let o=e.value.toLowerCase(),r="close";if(o==="close"||o==="volume"){r=o,t.consume();let i=t.peek();if(!i||i.type!=="IDENT"||i.value.toLowerCase()!=="on")throw c$1.parsing("STOCKS_EXPECTED_ON",`Expected "on <date>" after "${o}" (e.g. "AAPL ${o} on April 12, 2005")`);t.consume();}else if(o==="on")t.consume();else return null;let n=Sm(t);if(!n)throw c$1.parsing("STOCKS_EXPECTED_DATE",'Expected a date after "on" (e.g. "April 12, 2005" or "4/12/2005")');return {field:r,date:n}}function vm(t,e,o,r,n){t.emitOpcode(13),o?(t.emitString(`${o.field}:${e}:${o.date.isoDate}`),t.emitPluginCall(n,1)):(t.emitString(e),t.emitPluginCall(r,1));}function km(t,e,o,r,n){let i=false;t.peek()?.type==="STAR"&&(t.consume(),i=true);let a$1=Zp(t);if(i&&!a$1){vm(e,o,null,r,n),t.parseExpression(a.Product,e),e.emitOpcode(22);return}vm(e,o,a$1,r,n);}function Bm(t,e){return {category:"Stocks",parse(o,r,n){o.consume("LPAREN");let i=o.consume(),a;if(i.type==="STRING")a=a$8(i.value).toUpperCase();else if(i.type==="IDENT"||i.type===ke)a=i.value.toUpperCase();else throw c$1.parsing("STOCKS_INVALID_TICKER",`Expected a ticker symbol inside stock(...), got "${i.value}" (${i.type})`);o.consume("RPAREN"),km(o,n,a,t,e);}}}function Mm(t,e){return {category:"Stocks",parse(o,r,n){let i=r.value.toUpperCase();km(o,n,i,t,e);}}}var Vn="solve-stocks",eo="stock",to="stockhistorical";function Um(t={}){function e(s){return P("STOCKS_NOT_CONFIGURED",`Stock data provider not configured. Supply ${s} via createStocksPackage({ ... }); see the StocksPackage doc comment.`)}let{resolver:o,pluginFunction:r}=de({namespace:"stocks-current",pluginFunctionIndex:F$1(`${Vn}:${eo}`),staleTimeMs:t.staleTimeMs??6e4,refetchIntervalMs:t.refetchIntervalMs,fetchQuery:async(s,l)=>{if(!t.fetchQuote)return e("fetchQuote");let u=await t.fetchQuote(s,l);return u$1(u.price,u.currency??"USD")}}),{resolver:n$1,pluginFunction:i}=de({namespace:"stocks-historical",pluginFunctionIndex:F$1(`${Vn}:${to}`),staleTimeMs:t.historicalStaleTimeMs??720*60*60*1e3,fetchQuery:async(s,l)=>{let[u,c,f]=s.split(":");if(!t.fetchHistoricalQuote)return e("fetchHistoricalQuote");let T=await t.fetchHistoricalQuote(c,f,l);return u==="volume"?n(T.volume??0):u$1(T.close,T.currency??"USD")}});return {name:Vn,lexerVocabulary:{keywords:{stock:"STOCK_FN"}},prefixParselets:{STOCK_FN:Bm(eo,to),...t.enableBareTickerRecognition?{[ke]:Mm(eo,to)}:{}},normalizerRules:t.enableBareTickerRecognition?[wm()]:[],pluginFunctions:{[eo]:r,[to]:i},asyncResolvers:[o,n$1]}}function Dm(t){return {category:"Knowledge",parse(e,o,r){r.emitOpcode(13),r.emitString(o.value),r.emitPluginCall(t,1);}}}function bm(t$1={}){let e="solve-knowledge",o="knowledge",r=F$1(`${e}:${o}`),{resolver:n,pluginFunction:i}=de({namespace:"knowledge",pluginFunctionIndex:r,staleTimeMs:t$1.staleTimeMs??300*1e3,fetchQuery:async(a,s)=>{if(!t$1.answerQuery)return P("KNOWLEDGE_NOT_CONFIGURED","Knowledge answer provider not configured. Supply answerQuery via createKnowledgePackage({ ... }); see the KnowledgePackage doc comment.");let l=await t$1.answerQuery(a,s);return t(l)}});return {name:e,lexerVocabulary:{rawLinePatterns:[{pattern:/^(?:search|ask|google)\s*:\s*(.+)$/i,tokenType:"KNOWLEDGE_QUERY"},{pattern:/^(.+?)=\s*\?\s*$/,tokenType:"KNOWLEDGE_QUERY"}]},prefixParselets:{KNOWLEDGE_QUERY:Dm(o)},pluginFunctions:{[o]:i},asyncResolvers:[n]}}var ro=class{constructor(){this.category="Lines";}parse(e,o,r){r.emitPluginCall("prev",0);}};var oo=class{constructor(){this.category="Lines";}parse(e,o,r){let n=parseInt(o.value,10);r.emitOpcode(10),r.emitNumber(n),r.emitPluginCall("lineRef",1);}};var dt=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,r){e.consume("LPAREN");let n=e.consume("LINE_REF");e.consume("COLON");let i=e.consume("LINE_REF");e.consume("RPAREN");let a=parseInt(n.value,10),s=parseInt(i.value,10);r.emitOpcode(10),r.emitNumber(a),r.emitOpcode(10),r.emitNumber(s),r.emitPluginCall(this.isAverage?"averageRange":"sumRange",2);}};var Be=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,r){r.emitPluginCall(this.isAverage?"averageAbove":"totalAbove",0);}};var Jp=c("LINE_REF"),ef=c("SUM_RANGE_CALL"),tf=c("AVERAGE_RANGE_CALL");function Fm(){return {name:"lines:line-ref",priority:80,startTokenTypes:["IDENT"],match(t,e){if(e>0&&t[e-1].type==="COLON"&&!(e>1&&t[e-2].type==="LINE_REF"))return null;let o=t[e];if(!o)return null;if(o.type==="IDENT"){let r=/^line(\d+)$/i.exec(o.value);if(r)return {consumed:1,replacement:[Vm(r[1],o)],ruleName:"lines:line-ref"}}if(o.type==="IDENT"&&/^line$/i.test(o.value)){let r=t[e+1];if(r&&r.type==="NUMBER"&&/^\d+$/.test(r.value))return {consumed:2,replacement:[Vm(r.value,o)],ruleName:"lines:line-ref"}}return null}}}function Vm(t,e){return new a$2("LINE_REF",Jp,t,t,e.offset,0,e.line,e.col)}function Hm(){return {name:"lines:range-call",priority:80,shape:[{types:["IDENT"],values:["sum","total","average"]},{types:["LPAREN"]}],match(t,e){let o=t[e];if(!o||o.type!=="IDENT")return null;let r=o.value.toLowerCase();if(r!=="sum"&&r!=="total"&&r!=="average"||t[e+1]?.type!=="LPAREN")return null;let n=r==="average"?"AVERAGE_RANGE_CALL":"SUM_RANGE_CALL",i=r==="average"?tf:ef;return {consumed:1,replacement:[new a$2(n,i,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"lines:range-call"}}}}function no(t,e){return t===void 0?P("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet (forward reference, or out of range)`):t.type===12?P("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):t.type===13?P("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function Me(t){return t?.getLineResult?null:P("LINE_REF_NO_DOCUMENT","Cross-line references require a real document \u2014 not available outside one (e.g. evaluateExpression()'s single-expression path)")}function Gm(t,e){let o=Me(e);if(o)return o;let r=e.lineIndex-1,n=e.getLineResult(r);return no(n,r)??n}function zm(t,e){let o=Me(e);if(o)return o;let r=t[0].toNumber(),n=e.getLineResult(r);return no(n,r)??n}function Km(t,e,o,r){let n$1=0,i=0,a,s=false,l=t<=e?1:-1;for(let c=t;l>0?c<=e:c>=e;c+=l){let f=o.getLineResult(c),T=no(f,c);if(T)return T;if(f.type!==0&&f.type!==6)return P("LINE_RANGE_NON_NUMERIC",`Line ${c} is not a plain number or unit value \u2014 cannot include it in a sum/total/average range`);if(f.type===6){if(s=true,a===void 0)a=f.unit;else if(f.unit!==a)return P("LINE_RANGE_MIXED_UNITS",`Line ${c}'s unit (${f.unit}) doesn't match the range's first unit (${a}) \u2014 aggregating mixed units would silently misrepresent the result`)}n$1+=f.toNumber(),i++;}let u=r?n$1/i:n$1;return s?u$1(u,a):n(u)}function $m(t,e){let o=Me(e);return o||Km(t[0].toNumber(),t[1].toNumber(),e,false)}function Wm(t,e){let o=Me(e);return o||Km(t[0].toNumber(),t[1].toNumber(),e,true)}function Ym(t,e){let o=t.isLineBoundary;if(!o)return P("LINE_REF_NO_DOCUMENT",'"above" aggregation requires a real document');let r=0,n$1=0,i,a=false;for(let l=t.lineIndex-1;l>=1&&!o(l);l--){let u=t.getLineResult(l),c=no(u,l);if(c)return c;if(u.type!==0&&u.type!==6)return P("LINE_RANGE_NON_NUMERIC",`Line ${l} is not a plain number or unit value \u2014 cannot include it in "above" aggregation`);if(u.type===6){if(a=true,i===void 0)i=u.unit;else if(u.unit!==i)return P("LINE_RANGE_MIXED_UNITS",`Line ${l}'s unit (${u.unit}) doesn't match the range's unit (${i})`)}r+=u.toNumber(),n$1++;}if(n$1===0)return P("LINE_RANGE_EMPTY","No lines above to aggregate (hit the top of the document, a blank line, or a heading immediately)");let s=e?r/n$1:r;return a?u$1(s,i):n(s)}function jm(t,e){let o=Me(e);return o||Ym(e,false)}function Xm(t,e){let o=Me(e);return o||Ym(e,true)}var Fn={name:"solve-lines",lexerVocabulary:{keywords:{prev:"PREV"}},phrases:{"total above":"TOTAL_ABOVE","sum above":"SUM_ABOVE","average above":"AVERAGE_ABOVE"},normalizerRules:[Fm(),Hm()],prefixParselets:{PREV:new ro,LINE_REF:new oo,SUM_RANGE_CALL:new dt(false),AVERAGE_RANGE_CALL:new dt(true),TOTAL_ABOVE:new Be(false),SUM_ABOVE:new Be(false),AVERAGE_ABOVE:new Be(true)},pluginFunctions:{prev:Gm,lineRef:zm,sumRange:$m,averageRange:Wm,totalAbove:jm,averageAbove:Xm}};var b=class{constructor(e){this.pluginFnName=e;this.category="Tables";}parse(e,o,r){let n=e.peek();if(!n||n.type!=="STRING")throw c$1.parsing("TABLE_COLUMN_NAME_EXPECTED",`Expected a quoted column name after "... of column" but got ${n?`"${n.value}"`:"end of input"}`);let i=e.consume("STRING");for(;;){let a=e.peek();if(!a)break;if(a.type==="IN"){e.consume();continue}if(a.type==="IDENT"&&rf.has(a.value.toLowerCase())){e.consume();continue}break}r.emitOpcode(13),r.emitString(i.value),r.emitPluginCall(this.pluginFnName,1);}},rf=new Set(["the","table","above"]);function Qm(t){return t.trimStart().startsWith("|")}function of(t){let e=t.trim();return e.length===0||!e.includes("-")||!e.includes("|")?false:/^[|\s:-]+$/.test(e)}function qm(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let o=[],r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="\\"&&n+1<e.length&&e[n+1]==="|"){r+="|",n++;continue}if(i==="|"){o.push(r.trim()),r="";continue}r+=i;}return o.push(r.trim()),o}function nf(t){if(t===void 0)return null;let e=t.trim();if(e.length===0)return null;let o=e.replace(/,/g,"");if(!/^[+-]?(\d+(\.\d+)?|\.\d+)$/.test(o))return null;let r=Number.parseFloat(o);return Number.isFinite(r)?r:null}function Zm(t,e){let o=-1;for(let s=e-1;s>=1;s--){let l=t(s);if(l===void 0)break;if(Qm(l)){o=s;break}}if(o===-1)return null;let r=o;for(;r-1>=1;){let s=t(r-1);if(s===void 0||!Qm(s))break;r--;}let n=-1;for(let s=r;s<=o;s++)if(of(t(s))){n=s;break}if(n===-1||n===r)return null;let i=qm(t(n-1)),a=[];for(let s=n+1;s<=o;s++)a.push(qm(t(s)));return {header:i,rows:a}}function Jm(t,e){let o=e.trim().toLowerCase();for(let r=0;r<t.length;r++)if(t[r].trim().toLowerCase()===o)return r;return -1}function el(t,e){let o=[];for(let r of t.rows){let n=nf(r[e]);n!==null&&o.push(n);}return o}var io={TABLE_NO_DOCUMENT:"TABLE_NO_DOCUMENT",TABLE_NOT_FOUND:"TABLE_NOT_FOUND",TABLE_COLUMN_NOT_FOUND:"TABLE_COLUMN_NOT_FOUND",TABLE_COLUMN_NO_NUMERIC_CELLS:"TABLE_COLUMN_NO_NUMERIC_CELLS"};function ao(t,e){let o=t.length;if(o===0)return 0;let r=e?o-1:o;if(r<=0)return 0;let n=t.reduce((i,a)=>i+a,0)/o;return t.reduce((i,a)=>i+(a-n)*(a-n),0)/r}function af(t,e){switch(t){case "sum":return e.reduce((o,r)=>o+r,0);case "average":return e.reduce((o,r)=>o+r,0)/e.length;case "min":return Math.min(...e);case "max":return Math.max(...e);case "count":return e.length;case "median":{let o=[...e].sort((n,i)=>n-i),r=Math.floor(o.length/2);return o.length%2===0?(o[r-1]+o[r])/2:o[r]}case "stdev":return Math.sqrt(ao(e,false));case "sampleStdev":return Math.sqrt(ao(e,true));case "variance":return ao(e,false);case "sampleVariance":return ao(e,true);case "spread":return Math.max(...e)-Math.min(...e);case "mode":{let o=new Map,r=e[0],n=0;for(let i of e){let a=(o.get(i)??0)+1;o.set(i,a),a>n&&(n=a,r=i);}return r}}}function z(t,e,o){let r=o?.getLineText;if(!r||o.lineIndex<1)return P(io.TABLE_NO_DOCUMENT,"Reading a table column needs a real document, which the single-expression path (evaluateExpression) does not have");let n$1=Zm(r,o.lineIndex);if(!n$1)return P(io.TABLE_NOT_FOUND,'No markdown table found above this line (a table row starts with "|", and needs a "|---|" separator under its header)');let i=Jm(n$1.header,e);if(i===-1){let s=n$1.header.map(l=>`"${l}"`).join(", ");return P(io.TABLE_COLUMN_NOT_FOUND,`The table above has no column named "${e}". Its columns are: ${s}`)}let a=el(n$1,i);return t==="count"?n(a.length):a.length===0?P(io.TABLE_COLUMN_NO_NUMERIC_CELLS,`Column "${e}" has no plain-number cells to aggregate (currency and unit cells are not read yet)`):n(af(t,a))}function K(t){let e=t[0];return e&&e.type===3&&typeof e.value=="string"?e.value:String(e?.value??"")}function tl(t,e){return z("sum",K(t),e)}function rl(t,e){return z("average",K(t),e)}function ol(t,e){return z("min",K(t),e)}function nl(t,e){return z("max",K(t),e)}function il(t,e){return z("count",K(t),e)}function al(t,e){return z("median",K(t),e)}function sl(t,e){return z("stdev",K(t),e)}function ml(t,e){return z("sampleStdev",K(t),e)}function ll(t,e){return z("variance",K(t),e)}function ul(t,e){return z("sampleVariance",K(t),e)}function cl(t,e){return z("spread",K(t),e)}function pl(t,e){return z("mode",K(t),e)}var Hn={name:"solve-tables",phrases:{"sum of column":"TABLE_COLUMN_SUM","total of column":"TABLE_COLUMN_SUM","average of column":"TABLE_COLUMN_AVERAGE","mean of column":"TABLE_COLUMN_AVERAGE","min of column":"TABLE_COLUMN_MIN","minimum of column":"TABLE_COLUMN_MIN","max of column":"TABLE_COLUMN_MAX","maximum of column":"TABLE_COLUMN_MAX","count of column":"TABLE_COLUMN_COUNT","median of column":"TABLE_COLUMN_MEDIAN","standard deviation of column":"TABLE_COLUMN_STDEV","stdev of column":"TABLE_COLUMN_STDEV","sample standard deviation of column":"TABLE_COLUMN_SAMPLE_STDEV","variance of column":"TABLE_COLUMN_VARIANCE","sample variance of column":"TABLE_COLUMN_SAMPLE_VARIANCE","spread of column":"TABLE_COLUMN_SPREAD","mode of column":"TABLE_COLUMN_MODE"},prefixParselets:{TABLE_COLUMN_SUM:new b("TABLE_COLUMN_SUM"),TABLE_COLUMN_AVERAGE:new b("TABLE_COLUMN_AVERAGE"),TABLE_COLUMN_MIN:new b("TABLE_COLUMN_MIN"),TABLE_COLUMN_MAX:new b("TABLE_COLUMN_MAX"),TABLE_COLUMN_COUNT:new b("TABLE_COLUMN_COUNT"),TABLE_COLUMN_MEDIAN:new b("TABLE_COLUMN_MEDIAN"),TABLE_COLUMN_STDEV:new b("TABLE_COLUMN_STDEV"),TABLE_COLUMN_SAMPLE_STDEV:new b("TABLE_COLUMN_SAMPLE_STDEV"),TABLE_COLUMN_VARIANCE:new b("TABLE_COLUMN_VARIANCE"),TABLE_COLUMN_SAMPLE_VARIANCE:new b("TABLE_COLUMN_SAMPLE_VARIANCE"),TABLE_COLUMN_SPREAD:new b("TABLE_COLUMN_SPREAD"),TABLE_COLUMN_MODE:new b("TABLE_COLUMN_MODE")},pluginFunctions:{TABLE_COLUMN_SUM:tl,TABLE_COLUMN_AVERAGE:rl,TABLE_COLUMN_MIN:ol,TABLE_COLUMN_MAX:nl,TABLE_COLUMN_COUNT:il,TABLE_COLUMN_MEDIAN:al,TABLE_COLUMN_STDEV:sl,TABLE_COLUMN_SAMPLE_STDEV:ml,TABLE_COLUMN_VARIANCE:ll,TABLE_COLUMN_SAMPLE_VARIANCE:ul,TABLE_COLUMN_SPREAD:cl,TABLE_COLUMN_MODE:pl}};var Ue=class{constructor(e){this.pluginFnName=e;this.category="Tags";}parse(e,o,r){r.emitOpcode(13),r.emitString(o.value),r.emitPluginCall(this.pluginFnName,1);}};function so(t){return t===void 0?"":(t.text??t.value??"").toLowerCase()}var fl={TOTAL_OF:"TAG_SUM",COUNT_OF:"TAG_COUNT",AVERAGE_OF:"TAG_AVERAGE"},sf=new Set(["total","sum","count","average"]);function dl(t=80){return {name:"tags:aggregate",priority:t,shape:[{types:["TOTAL_OF","COUNT_OF","AVERAGE_OF","IDENT"]}],match(e,o){let r=e[o];if(r===void 0)return null;let n=fl[r.type];if(n!==void 0){let i=e[o+1];return i?.type!=="TAG"?null:{consumed:2,replacement:[b$5(n,i.value??"",[r,i])],ruleName:"tags:aggregate"}}if(r.type==="IDENT"&&so(r)==="sum"){let i=e[o+1],a=e[o+2];return so(i)!=="of"||a?.type!=="TAG"?null:{consumed:3,replacement:[b$5("TAG_SUM",a.value??"",[r,i,a])],ruleName:"tags:aggregate"}}return null}}}function El(t=40){return {name:"tags:strip",priority:t,shape:[{types:["TAG"]}],match(e,o){if(e[o]?.type!=="TAG")return null;let r=e[o-1];return r!==void 0&&(fl[r.type]!==void 0||so(r)==="of"&&sf.has(so(e[o-2])))?null:{consumed:1,replacement:[],ruleName:"tags:strip"}}}}function mf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tl(t,e){if(e==="")return false;let r=new RegExp(`(?:^|[^0-9A-Za-z_])#${mf(e)}(?![0-9A-Za-z_-])`,"i").exec(t);if(r===null)return false;let n=r.index+r[0].indexOf("#");return t.slice(0,n).trim().length>0}function lf(t,e){return t===void 0?P("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet`):t.type===12?P("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):t.type===13?P("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function Gn(t){return !t?.getLineResult||!t.getLineText?P("TAG_NO_DOCUMENT","Category tag sums require a real document, not available outside one (e.g. evaluateExpression()'s single-expression path)"):null}function zn(t,e,o){let r=t.getLineText,n$1=t.getLineResult,i=t.isLineBoundary,a=e.toLowerCase(),s=0,l=0,u,c=false;for(let T=1;;T++){let N=r(T);if(N===void 0)break;if(T===t.lineIndex||i&&i(T)||!Tl(N,a))continue;let E=n$1(T),A=lf(E,T);if(A)return A;if(o!=="count"){if(E.type!==0&&E.type!==6)return P("TAG_NON_NUMERIC",`Line ${T}, tagged #${e}, is not a plain number or unit value.`);if(E.type===6){if(c=true,u===void 0)u=E.unit;else if(E.unit!==u)return P("TAG_MIXED_UNITS",`Line ${T}'s unit (${E.unit}) doesn't match #${e}'s first unit (${u}), aggregating mixed units would misrepresent the result.`)}s+=E.toNumber();}l++;}if(o==="count")return n(l);if(l===0)return P("TAG_EMPTY",`No lines are tagged #${e}.`);let f=o==="average"?s/l:s;return c?u$1(f,u):n(f)}function Nl(t,e){let o=Gn(e);return o||zn(e,String(t[0].value),"sum")}function yl(t,e){let o=Gn(e);return o||zn(e,String(t[0].value),"average")}function gl(t,e){let o=Gn(e);return o||zn(e,String(t[0].value),"count")}var Kn={name:"solve-tags",normalizerRules:[dl(),El()],prefixParselets:{TAG_SUM:new Ue("sum"),TAG_AVERAGE:new Ue("average"),TAG_COUNT:new Ue("count")},pluginFunctions:{sum:Nl,average:yl,count:gl}};var Et=class{constructor(e){this.fn=e;this.category="Payroll";}parse(e,o,r){e.parseExpression(a.Lowest,r),r.emitPluginCall(this.fn,1);}},Tt=class{constructor(e){this.fn=e;this.category="Payroll";this.bindingPower=a.Conditional;}parse(e,o,r,n){n.emitPluginCall(this.fn,1);}};function uf(t,e){if(t<=e.personalAllowanceTaperFrom)return e.personalAllowance;let o=(t-e.personalAllowanceTaperFrom)/2;return Math.max(0,e.personalAllowance-o)}function cf(t,e){let o=Math.max(0,t-uf(t,e)),r=Math.min(o,e.basicRateLimit),n=Math.min(Math.max(0,o-e.basicRateLimit),e.higherRateLimit-e.basicRateLimit),i=Math.max(0,o-e.higherRateLimit);return r*e.basicRate+n*e.higherRate+i*e.additionalRate}function pf(t,e){if(t<=e.niPrimaryThreshold)return 0;let o=Math.min(t,e.niUpperEarningsLimit)-e.niPrimaryThreshold,r=Math.max(0,t-e.niUpperEarningsLimit);return o*e.niMainRate+r*e.niUpperRate}function $n(t,e){return t-cf(t,e)-pf(t,e)}var ff=1920;function Pl(t){return t/ff}var df={personalAllowance:12570,personalAllowanceTaperFrom:1e5,basicRateLimit:37700,higherRateLimit:125140,basicRate:.2,higherRate:.4,additionalRate:.45,niPrimaryThreshold:12570,niUpperEarningsLimit:50270,niMainRate:.08,niUpperRate:.02},Wn=df;function Yn(t,e){let o=e(t.toNumber());return t.type===6?u$1(o,t.unit):n(o)}var jn={name:"solve-payroll",phrases:{"take home on":"TAKE_HOME_ON","hourly for":"HOURLY_FOR","after tax":"AFTER_TAX","salary after tax":"AFTER_TAX","per month after tax":"AFTER_TAX_MONTHLY","monthly after tax":"AFTER_TAX_MONTHLY","salary per month after tax":"AFTER_TAX_MONTHLY"},prefixParselets:{TAKE_HOME_ON:new Et("payrollTakeHome"),HOURLY_FOR:new Et("payrollHourly")},infixParselets:{AFTER_TAX:new Tt("payrollTakeHome"),AFTER_TAX_MONTHLY:new Tt("payrollTakeHomeMonthly")},pluginFunctions:{payrollTakeHome:t=>Yn(t[0],e=>$n(e,Wn)),payrollTakeHomeMonthly:t=>Yn(t[0],e=>$n(e,Wn)/12),payrollHourly:t=>Yn(t[0],Pl)},tokenCategories:{TAKE_HOME_ON:"function",HOURLY_FOR:"function",AFTER_TAX:"operator",AFTER_TAX_MONTHLY:"operator"}};var mo=class{constructor(){this.category="operator";this.bindingPower=a.Uncertainty;}parse(e,o,r,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(28);}};function _l(t=90){return {name:"uncertainty:ascii-plus-minus",priority:t,shape:[{types:["PLUS"]},{types:["SLASH"]}],match(e,o){let r=e[o];if(r?.type!=="PLUS")return null;let n=e[o+1];if(n?.type!=="SLASH")return null;let i=e[o+2];return i?.type!=="MINUS"?null:{consumed:3,replacement:[b$5("PLUS_MINUS","\xB1",[r,n,i])],ruleName:"uncertainty:ascii-plus-minus"}}}}var Xn={name:"solve-uncertainty",infixParselets:{PLUS_MINUS:new mo},normalizerRules:[_l()]};var Al=1e-9,xl=1e9,Ef=100,Tf=1e-9,Nf=1e-9,yf=1e-12,gf=1e-9,lo="goalseek";function Rl(t,e){let o=e?.evaluateLineWithBinding,r=e?.getLineReads;if(!o||!r)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek only works inside a document, since it re-runs another line. The single-expression entry point has no document to solve against.");let n$1=t[0].toNumber(),i=typeof t[1].value=="string"?t[1].value:String(t[1].value),a=t[2];if(a.type!==0&&a.type!==6)return P("GOAL_SEEK_TARGET_NOT_NUMERIC",`Goal seek's target must be a number, as in "solve line ${n$1} for ${i} = 900".`);let s=a.toNumber();if(!Number.isFinite(s))return P("GOAL_SEEK_TARGET_NOT_NUMERIC","Goal seek's target is not a finite number.");let l=r(n$1);if(l===void 0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${n$1} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(!l.includes(i))return P("GOAL_SEEK_VARIABLE_NOT_USED",`Line ${n$1} does not use ${i}, so changing ${i} cannot move its result toward ${s}.`);let u=o(n$1,i,K$1(q$2(i)),true);if(u.type===9){let f=Pf(u.value,s,i);if(f!==null)return n(f)}let c=e.goalSeekMaxIterations??Ef;return _f(o,n$1,i,s,c)}function Pf(t,e,o){let r=p$1(d$2(e)),n;try{n=d$3(t,r,o);}catch{return null}if(n.kind!=="roots")return null;let i=[];for(let l of n.exact){let u=Q$2(l);if(u.kind==="const"){let c=e$4(u.value);Number.isFinite(c)&&i.push(c);}}for(let l of n.approximate)Math.abs(l.im)<=gf&&Number.isFinite(l.re)&&i.push(l.re);if(i.length===0)return null;let a=i.filter(l=>l>=Al&&l<=xl),s=a.length>0?a:i;return s.sort((l,u)=>Math.abs(l)-Math.abs(u)),s[0]}function _f(t,e,o,r,n$1){let i=N=>{let E=t(e,o,n(N),false);if(E.type===13)return {error:E};if(E.type!==0&&E.type!==6)return {error:P("GOAL_SEEK_TARGET_NOT_NUMERIC",`Line ${e} did not produce a number when ${o} was set to ${N}, so goal seek cannot compare it to the target.`)};let A=E.toNumber();return Number.isFinite(A)?{value:A}:{error:P("GOAL_SEEK_NON_FINITE",`Line ${e}'s result is not finite when ${o} is ${N}.`)}},a=Al,s=xl,l=i(a);if("error"in l)return l.error;let u=i(s);if("error"in u)return u.error;let c=Math.max(Tf,Math.abs(r)*Nf),f=l.value-r,T=u.value-r;if(Math.abs(f)<=c)return n(a);if(Math.abs(T)<=c)return n(s);if(Math.sign(f)===Math.sign(T))return P("GOAL_SEEK_NO_SOLUTION",`No value of ${o} between ${a} and ${s} makes line ${e} equal ${r}: across that whole range its result stays on one side of the target.`);for(let N=0;N<n$1;N++){let E=(a+s)/2,A=i(E);if("error"in A)return A.error;let R=A.value-r;if(Math.abs(R)<=c)return n(E);if(s-a<=yf)return P("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek narrowed ${o} to a single point near ${E} without line ${e} reaching ${r}: the relationship jumps across the target rather than passing through it.`);Math.sign(R)===Math.sign(f)?(a=E,f=R):s=E;}return P("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek did not bring line ${e} within tolerance of ${r} by varying ${o} in ${n$1} steps.`)}var uo=class{constructor(){this.category="GoalSeek";}parse(e,o,r){let n=e.peek();if(!n||n.type!=="LINE_REF")throw c$1.parsing("GOAL_SEEK_SYNTAX",'Goal seek reads "solve line N for <var> = <target>", for example "solve line 4 for rate = 900".',{found:n?.type??"end of input"});e.consume();let i=parseInt(n.value,10),a$1=e.peek();if(!(!!a$1&&(a$1.type==="FOR_DURATION"||a$1.type==="IDENT"&&a$1.value.toLowerCase()==="for")))throw c$1.parsing("GOAL_SEEK_SYNTAX",'Goal seek reads "solve line N for <var> = <target>". Expected "for" after the line reference.',{found:a$1?.type??"end of input"});e.consume();let l=e.peek();if(!l||l.type!=="IDENT"&&l.type!=="UNIT")throw c$1.parsing("GOAL_SEEK_REQUIRES_VARIABLE_NAME",'Goal seek needs the name of the variable to vary here, as in "solve line 4 for rate = 900".',{found:l?.type??"end of input"});e.consume(),e.consume("EQUALS"),r.emitOpcode(10),r.emitNumber(i),r.emitOpcode(13),r.emitString(l.value),e.parseExpression(a.Lowest,r),r.emitPluginCall(lo,3);}};var Af=c("GOAL_SEEK");function Ol(t=75){return {name:"goalseek:solve-line",priority:t,shape:[{types:["IDENT"],values:["solve"]},{types:["LINE_REF"]}],match(e,o){if(o>0&&e[o-1].type==="COLON")return null;let r=e[o];return !r||r.type!=="IDENT"||r.value.toLowerCase()!=="solve"||e[o+1]?.type!=="LINE_REF"?null:{consumed:1,replacement:[new a$2("GOAL_SEEK",Af,r.value,r.value,r.offset,0,r.line,r.col)],ruleName:"goalseek:solve-line"}}}}var Qn={name:"solve-goalseek",normalizerRules:[Ol()],prefixParselets:{GOAL_SEEK:new uo},pluginFunctions:{[lo]:Rl}};var co=class{constructor(){this.category="Colour";}parse(e,o,r){r.emitOpcode(13),r.emitString(o.value),r.emitPluginCall("colour",1);}};var Te={COLOUR_INVALID:"COLOUR_INVALID",COLOUR_EXPECTED_COLOUR:"COLOUR_EXPECTED_COLOUR",COLOUR_BAD_ARGUMENTS:"COLOUR_BAD_ARGUMENTS"};function B(t){return t&&t.type===14?t.value:null}function U(t){if(!t)return 0;let e=t.toNumber();return t.type===5?e:e>1?e/100:e}function q(t,e){return P(Te.COLOUR_BAD_ARGUMENTS,`${t}(...) expects ${e}`)}function Y(t){return P(Te.COLOUR_EXPECTED_COLOUR,`${t}(...) expects a colour as its first argument`)}function hl(t){let e=t[0];if(!e||e.type!==3||typeof e.value!="string")return q("color",'a string, e.g. color("#ff0000") or color("red")');let o=c$2(e.value);return o?G$1(o):P(Te.COLOUR_INVALID,`"${e.value}" is not a hex colour (#rgb, #rgba, #rrggbb, #rrggbbaa) or a CSS colour name`)}function xf(t){return t.length!==3?q("rgb","three numbers: rgb(red, green, blue)"):G$1({r:a$1(t[0].toNumber()),g:a$1(t[1].toNumber()),b:a$1(t[2].toNumber()),a:1,format:"rgb"})}function Rf(t){return t.length!==4?q("rgba","four numbers: rgba(red, green, blue, alpha)"):G$1({r:a$1(t[0].toNumber()),g:a$1(t[1].toNumber()),b:a$1(t[2].toNumber()),a:b$3(U(t[3])),format:"rgba"})}function Of(t){if(t.length!==3)return q("hsl","three values: hsl(hue, saturation%, lightness%)");let{r:e$1,g:o,b:r}=e(t[0].toNumber(),U(t[1]),U(t[2]));return G$1({r:e$1,g:o,b:r,a:1,format:"hsl"})}function hf(t){if(t.length!==4)return q("hsla","four values: hsla(hue, saturation%, lightness%, alpha)");let{r:e$1,g:o,b:r}=e(t[0].toNumber(),U(t[1]),U(t[2]));return G$1({r:e$1,g:o,b:r,a:b$3(U(t[3])),format:"hsla"})}function Ne(t,e){return o=>{let r=B(o[0]);return r?o.length<2?q(t,`a colour and an amount, e.g. ${t}(#3366cc, 20%)`):G$1(e(r,U(o[1]))):Y(t)}}var If=Ne("lighten",j),Cf=Ne("darken",k$1),Sf=Ne("saturate",l),Il=Ne("desaturate",m);function qn(t){let e=B(t[0]);return e?t.length<2?q("rotate","a colour and a hue angle in degrees, e.g. rotate(#ff0000, 90)"):G$1(n$1(e,t[1].toNumber())):Y("rotate")}function Lf(t){let e=B(t[0]);return e?G$1(o(e)):Y("complement")}function Cl(t){let e=B(t[0]);return e?G$1(p(e)):Y("grayscale")}function Sl(t){let e=B(t[0]);return e?G$1(q$1(e,t.length>1?U(t[1]):1)):Y("invert")}function wf(t){let e=B(t[0]),o=B(t[1]);return !e||!o?P(Te.COLOUR_EXPECTED_COLOUR,"mix(...) expects two colours to blend"):G$1(r(e,o,t.length>2?U(t[2]):.5))}function Zn(t){let e=B(t[0]);return e?t.length<2?n(e.a):G$1(s(e,U(t[1]))):Y("alpha")}function vf(t){let e=B(t[0]),o=B(t[1]);return !e||!o?P(Te.COLOUR_EXPECTED_COLOUR,"contrast(...) expects two colours"):n(i(e,o))}function kf(t){let e=B(t[0]);return e?n(h(e)):Y("luminance")}function De(t,e){return o=>{let r=B(o[0]);return r?n(e(r)):Y(t)}}var Bf=De("red",t=>t.r),Mf=De("green",t=>t.g),Uf=De("blue",t=>t.b),Df=De("hue",t=>d$4(t.r,t.g,t.b).h),bf=De("saturation",t=>d$4(t.r,t.g,t.b).s*100),Vf=De("lightness",t=>d$4(t.r,t.g,t.b).l*100);function Ll(t){if(t.length!==3)return q("hsv","three values: hsv(hue, saturation%, value%)");let{r:e,g:o,b:r}=t$1(t[0].toNumber(),U(t[1]),U(t[2]));return G$1({r:e,g:o,b:r,a:1,format:"hex"})}function Ff(t){if(t.length!==4)return q("hsva","four values: hsva(hue, saturation%, value%, alpha)");let{r:e,g:o,b:r}=t$1(t[0].toNumber(),U(t[1]),U(t[2]));return G$1({r:e,g:o,b:r,a:b$3(U(t[3])),format:"hex"})}function Hf(t){if(t.length!==3)return q("hwb","three values: hwb(hue, whiteness%, blackness%)");let{r:e,g:o,b:r}=u(t[0].toNumber(),U(t[1]),U(t[2]));return G$1({r:e,g:o,b:r,a:1,format:"hex"})}var Gf=Ne("tint",v),zf=Ne("shade",w),Kf=Ne("tone",x);function $f(t){let e=B(t[0]);return e?L(y(e)):Y("isdark")}function Wf(t){let e=B(t[0]);return e?L(!y(e)):Y("islight")}function Jn(t){let e=B(t[0]);return e?G$1(z$1(e)):Y("readable")}function Yf(t){if(!t)return A.aa;if(t.type===0)return t.toNumber();if(t.type===3){let e=t.value.trim().toLowerCase();if(e==="aaa")return A.aaa;if(e==="aa large"||e==="aa-large"||e==="large")return A.aaLarge;if(e==="aaa large"||e==="aaa-large")return A.aaaLarge}return A.aa}function jf(t){let e=B(t[0]),o=B(t[1]);return !e||!o?P(Te.COLOUR_EXPECTED_COLOUR,"iscontrastcompliant(...) expects two colours"):L(i(e,o)>=Yf(t[2]))}function wl(t$1){let e=B(t$1[0]),o=B(t$1[1]);return !e||!o?P(Te.COLOUR_EXPECTED_COLOUR,"wcaglevel(...) expects two colours"):t(B$1(e,o))}var ye={color:hl,colour:hl,rgb:xf,rgba:Rf,hsl:Of,hsla:hf,lighten:If,darken:Cf,saturate:Sf,desaturate:Il,desat:Il,rotate:qn,spin:qn,adjusthue:qn,complement:Lf,grayscale:Cl,greyscale:Cl,invert:Sl,mix:wf,alpha:Zn,opacity:Zn,fade:Zn,contrast:vf,luminance:kf,red:Bf,green:Mf,blue:Uf,hue:Df,saturation:bf,lightness:Vf,hsv:Ll,hsb:Ll,hsva:Ff,hwb:Hf,tint:Gf,shade:zf,tone:Kf,negate:Sl,isdark:$f,islight:Wf,readable:Jn,contrastcolor:Jn,contrastcolour:Jn,iscontrastcompliant:jf,wcaglevel:wl,wcag:wl};var po=class{constructor(){this.category="Colour";}parse(e,o,r){let n=o.value.toLowerCase();if(ye[n]===void 0)throw c$1.execution("UNKNOWN_COLOUR_FUNCTION",`Unknown colour function: ${n}`,{functionName:n});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),i++;e.match("COMMA");)e.parseExpression(a.Lowest,r),i++;e.consume("RPAREN"),r.emitPluginCall(n,i);}};var vl=new Set(Object.keys(ye));function kl(t=80){return {name:"colour:call",priority:t,shape:[{types:["IDENT"],values:[...vl]},{types:["LPAREN"]}],match(e,o){let r=e[o];if(!r||r.type!=="IDENT")return null;let n=r.value.toLowerCase();return !vl.has(n)||e[o+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new a$2("COLOUR_CALL",c("COLOUR_CALL"),r.value,r.value,r.offset,0,r.line,r.col)],ruleName:"colour:call"}}}}var fo=t=>e=>{if(e.type!==14)return e;let o=e.value;return G$1({r:o.r,g:o.g,b:o.b,a:o.a,format:t})},Xf=Object.keys(ye).map(t=>({label:t,category:"function",detail:"colour"})),ei={name:"solve-colour",prefixParselets:{HEX_COLOUR:new co,COLOUR_CALL:new po},normalizerRules:[kl()],pluginFunctions:ye,asConverters:{rgb:fo("rgb"),rgba:fo("rgba"),hsl:fo("hsl"),hsla:fo("hsla")},completionItems:Xf};var ti=32;function Qf(t){if(t.hasSymbolic||t.rows!==1&&t.cols!==1)return null;let e=[];for(let o of t.data){if(typeof o!="number"||!Number.isFinite(o))return null;e.push(o);}return e}function qf(t){let e=t.max-t.min+1,o=Math.min(e,ti),r=[];for(let n=0;n<o;n++)r.push(t.min+Math.round(n*(e-1)/(o-1)));return r}function Zf(t,e){if(t.length<=e)return [...t];let o=[];for(let r=0;r<e;r++)o.push(t[Math.round(r*(t.length-1)/(e-1))]);return o}function Bl(t){let e=null;if(t.type===7)e=Qf(t.value);else if(t.type===8){let a=t.value;e=a.max-a.min+1>=2?qf(a):null;}if(!e||e.length<2)return null;let o=Zf(e,ti),r=Math.min(...e),n=Math.max(...e),i=e.length<=ti?`[${e.join(", ")}]`:`sparkline of ${e.length} values`;return {kind:"sparkline",points:o.map((a,s)=>[s,a]),label:i,domain:[0,o.length-1],range:[r,n]}}var Eo=class{constructor(){this.category="Plot";}parse(e,o,r){let n=Jf(e),i=new d$1(r.pluginIndexMap);e.parseExpression(a.Lowest,i),e.setBuilder(r);let a$1=i.build();if(a$1.hasAsync)throw c$1.parsing("PLOT_EXPR_MUST_BE_SYNCHRONOUS","a plot expression must be synchronous (no weather, stocks or currency calls).");e.consume("FROM"),e.parseExpression(a.Conditional,r),e.consume("TO"),e.parseExpression(a.Conditional,r);let s=r.emitAnonymousBody(["x"],a$1);r.emitOpcode(160),r.emitIndex(s),r.emitString(n);}};function Jf(t){let e=[];for(let n=0;;n++){let i=t.peekAt(n);if(!i||i.type==="FROM")break;e.push(i);}if(e.length===0)return "";let o=e[0].offset,r="";for(let n of e){let i=n.offset-o;for(;r.length<i;)r+=" ";r+=n.text??n.value??"";}return r.trim()}var Ml="PLOT",ed=c(Ml),td=new Set(["NUMBER","IDENT","FUNC","UNIT","LPAREN","PI","E"]);function Ul(t=80){let e="plot:plot-clause";return {name:e,priority:t,startTokenTypes:["IDENT"],match(o,r){let n=o[r];if(!n||n.type!=="IDENT"||(n.value??"").toLowerCase()!=="plot"||o[r-1]?.type==="COLON")return null;let i=o[r+1];return !i||!td.has(i.type)?null:{consumed:1,replacement:[new a$2(Ml,ed,n.value,n.value,n.offset,0,n.line,n.col)],ruleName:e}}}}var ri={name:"solve-chart",asConverters:{sparkline:t=>{let e=Bl(t);return e?I(e):P("SPARKLINE_NOT_A_SERIES",'"as sparkline" expects a numeric vector or a range, with at least two values')}},prefixParselets:{PLOT:new Eo},normalizerRules:[Ul()],tokenCategories:{PLOT:"keyword"}};var Nt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function oi(t){let e=new TextEncoder().encode(t),o="";for(let r=0;r<e.length;r+=3){let n=e[r],i=r+1<e.length?e[r+1]:0,a=r+2<e.length?e[r+2]:0;o+=Nt[n>>2],o+=Nt[(n&3)<<4|i>>4],o+=r+1<e.length?Nt[(i&15)<<2|a>>6]:"=",o+=r+2<e.length?Nt[a&63]:"=";}return o}function ni(t){let e=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let o=e.replace(/=+$/,""),r=[],n=0,i=0;for(let a of o){let s=Nt.indexOf(a);if(s<0)return null;i=i<<6|s,n+=6,n>=8&&(n-=8,r.push(i>>n&255));}try{return new TextDecoder("utf-8",{fatal:!0}).decode(new Uint8Array(r))}catch{return null}}function Dl(t){return encodeURIComponent(t)}function bl(t){try{return decodeURIComponent(t)}catch{return null}}function Vl(t){return Array.from(new TextEncoder().encode(t)).map(e=>e.toString(16).padStart(2,"0")).join(" ")}function ii(t){let e=t.trim().split(/[\s,]+/).filter(r=>r.length>0),o=[];for(let r of e){if(!/^[0-9a-fA-F]{1,2}$/.test(r))return null;o.push(parseInt(r,16));}try{return new TextDecoder("utf-8",{fatal:!0}).decode(new Uint8Array(o))}catch{return null}}function rd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),o=e.length%4;return o===0?e:e+"=".repeat(4-o)}function ai(t){let e=t.trim().split(".");if(e.length<2||e[1]==="")return null;let o=ni(rd(e[1]));if(o===null)return null;try{let r=JSON.parse(o);return r===null||typeof r!="object"||Array.isArray(r)?null:JSON.stringify(r)}catch{return null}}function si(t){let e=t.trim().replace(/^\?/,"");if(e==="")return "{}";let o={};for(let r of e.split("&")){if(r==="")continue;let n=r.indexOf("="),i=n===-1?r:r.slice(0,n),a=n===-1?"":r.slice(n+1);try{o[decodeURIComponent(i.replace(/\+/g," "))]=decodeURIComponent(a.replace(/\+/g," "));}catch{return null}}return JSON.stringify(o)}var To=class{constructor(){this.category="Encoding";this.bindingPower=a.Conditional;}parse(e,o,r,n){let i=(r.value??"").replace(/^from\s+/i,"").toLowerCase();n.emitOpcode(13),n.emitString(i),n.emitPluginCall("fromEncoding",2);}};var be=class{constructor(e){this.fn=e;this.category="Encoding";}parse(e,o,r){e.consume("LPAREN"),e.parseExpression(a.Lowest,r),e.consume("RPAREN"),r.emitPluginCall(this.fn,1);}};function yo(t){return t.type===3?t.value:null}function No(t$1,e){return o=>{let r=yo(o);return r===null?P("ENCODING_EXPECTED_TEXT",`"as ${t$1}" expects text (a "quoted string")`):t(e(r))}}var od={base64:ni,url:bl,"hex bytes":ii,hexbytes:ii,jwt:ai,query:si},mi={name:"solve-encoding",phrases:{"hex bytes":"CONVERTER_NAME","from base64":"FROM_ENCODING","from url":"FROM_ENCODING","from hex bytes":"FROM_ENCODING","from jwt":"FROM_ENCODING","from query":"FROM_ENCODING"},asConverters:{base64:No("base64",oi),url:No("url",Dl),"hex bytes":No("hex bytes",Vl)},infixParselets:{FROM_ENCODING:new To},prefixParselets:{BASE64_FN:new be("base64"),JWT_FN:new be("jwt"),QUERY_FN:new be("query")},callFusions:{base64:"BASE64_FN",jwt:"JWT_FN",query:"QUERY_FN"},pluginFunctions:{base64:t=>No("base64",oi)(t[0]),jwt:t$1=>{let e=yo(t$1[0]);if(e===null)return P("ENCODING_EXPECTED_TEXT",'jwt(...) expects text (a "quoted string")');let o=ai(e);return o===null?P("ENCODING_DECODE_FAILED","jwt(...): the input is not a valid JSON Web Token"):t(o)},query:t$1=>{let e=yo(t$1[0]);if(e===null)return P("ENCODING_EXPECTED_TEXT",'query(...) expects text (a "quoted string")');let o=si(e);return o===null?P("ENCODING_DECODE_FAILED","query(...): the input is not a valid query string"):t(o)},fromEncoding:t$1=>{let e=yo(t$1[0]),o=String(t$1[1].value??"");if(e===null)return P("ENCODING_EXPECTED_TEXT",`"from ${o}" expects text (a "quoted string")`);let r=od[o];if(!r)return P("UNKNOWN_ENCODING",`"from ${o}" is not a known encoding (try base64, url or hex bytes)`);let n=r(e);return n===null?P("ENCODING_DECODE_FAILED",`"from ${o}": the input is not valid ${o}`):t(n)}},tokenCategories:{BASE64_FN:"function",JWT_FN:"function",QUERY_FN:"function"}};var go=class{constructor(){this.category="IP";}parse(e,o,r){r.emitOpcode(13),r.emitString(o.value),r.emitPluginCall("ipLiteral",1);}};var Ve=class{constructor(e){this.pluginFn=e;this.category="IP";}parse(e,o,r){let n=e.peek(),i=e.peekAt(1);n?.type==="SLASH"&&i?.type==="NUMBER"?(e.consume(),e.consume(),r.emitOpcode(13),r.emitString(`|${i.value}`),r.emitPluginCall("ipLiteral",1)):e.parseExpression(a.Prefix,r),r.emitPluginCall(this.pluginFn,1);}};var Fl="IP_CIDR",nd=c(Fl),id=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{1,2})?/,ad=8;function Hl(t=72){let e="ip:ip-cidr-literal";return {name:e,priority:t,shape:[{types:["NUMBER"]}],match(o,r){let n=o[r];if(!n||n.type!=="NUMBER"||n.sourceEnd!==void 0||!/^\d{1,3}\./.test(n.text??""))return null;let i=n.text??"",a=n.offset+i.length,s=[n];for(let E=r+1;E<o.length&&s.length<ad;E++){let A=o[E];if(A.sourceEnd!==void 0||A.offset!==a||A.type!=="NUMBER"&&A.type!=="SLASH")break;i+=A.text??"",a=A.offset+(A.text?.length??0),s.push(A);}let l=id.exec(i);if(l===null)return null;let u=C$1(l[0]);if(u===null||u.addr===void 0)return null;let c=0,f=0;for(let E of s)if(f+=E.text?.length??0,c++,f>=l[0].length)break;if(f!==l[0].length)return null;let T=`${u.addr}|${u.prefix??""}`,N=new a$2(Fl,nd,T,l[0],n.offset,0,n.line,n.col,n.offset+l[0].length);return {consumed:c,replacement:[N],ruleName:e}}}}function yt(t,e){return t.type===17?t.value:P("IP_EXPECTED",`"${e}" expects an IP address or subnet (e.g. 192.168.1.0/24)`)}function Gl(t){let[e,o]=String(t[0].value??"").split("|"),r={...e!==""?{addr:Number(e)}:{},...o!==""?{prefix:Number(o)}:{}};return J$2(r)}function zl(t){let e=yt(t[0],"hosts in");return e instanceof m$1?e:e.prefix===void 0?P("IP_NO_PREFIX",'"hosts in" needs a subnet with a prefix, e.g. 192.168.1.0/24'):n(F$2(e.prefix))}function Kl(t){let e=yt(t[0],"netmask of");return e instanceof m$1?e:e.prefix===void 0?P("IP_NO_PREFIX",'"netmask of" needs a prefix, e.g. /24 or 192.168.1.0/24'):J$2({addr:E(e.prefix)})}function $l(t){let e=yt(t[0],"broadcast of");return e instanceof m$1?e:e.addr===void 0||e.prefix===void 0?P("IP_NEEDS_ADDRESS_AND_PREFIX",'"broadcast of" needs an address and a prefix, e.g. 192.168.1.0/24'):J$2({addr:G$2(e.addr,e.prefix)})}function Wl(t){let e=yt(t[0],"in");if(e instanceof m$1)return e;let o=yt(t[1],"in");return o instanceof m$1?o:e.addr===void 0?P("IP_EXPECTED_ADDRESS",'"in" expects an address on the left'):o.addr===void 0||o.prefix===void 0?P("IP_EXPECTED_BLOCK",'"in" expects a subnet on the right, e.g. 10.0.0.0/8'):L(H$1(e.addr,o.addr,o.prefix))}function Yl(t){if(t.type===17){let e=t.value;return n(e.addr??0)}return n(Math.trunc(t.toNumber()))}var li={name:"solve-ip",phrases:{"hosts in":"HOSTS_IN","netmask of":"NETMASK_OF","broadcast of":"BROADCAST_OF"},prefixParselets:{IP_CIDR:new go,HOSTS_IN:new Ve("hostsIn"),NETMASK_OF:new Ve("netmaskOf"),BROADCAST_OF:new Ve("broadcastOf")},normalizerRules:[Hl()],pluginFunctions:{ipLiteral:Gl,hostsIn:zl,netmaskOf:Kl,broadcastOf:$l,ipInCidr:Wl},asConverters:{int:Yl},tokenCategories:{IP_CIDR:"number",HOSTS_IN:"keyword",NETMASK_OF:"keyword",BROADCAST_OF:"keyword"}};var sd=c("UNIT");function jl(t=82){let e="fuel:l-per-100km";return {name:e,priority:t,shape:[{types:["UNIT","IDENT"],values:["l"]},{types:["SLASH"]}],match(o,r){let n=o[r],i=o[r+1],a=o[r+2],s=o[r+3];return !n||n.type!=="UNIT"&&n.type!=="IDENT"||(n.value??"").toLowerCase()!=="l"||i?.type!=="SLASH"||a?.type!=="NUMBER"||a.value!=="100"||s?.type!=="UNIT"||(s.value??"").toLowerCase()!=="km"?null:{consumed:4,replacement:[new a$2("UNIT",sd,"l100km","l/100km",n.offset,0,n.line,n.col)],ruleName:e}}}}var ui={name:"solve-fuel",normalizerRules:[jl()]};var md=c("UNIT");function Xl(t=82){let e="derived:acceleration";return {name:e,priority:t,shape:[{types:["UNIT"],values:["m"]},{types:["SLASH"]}],match(o,r){let n=o[r],i=o[r+1],a=o[r+2],s=o[r+3],l=o[r+4];return !n||n.type!=="UNIT"||(n.value??"")!=="m"||i?.type!=="SLASH"||a?.type!=="UNIT"||(a.value??"")!=="s"||s?.type!=="CARET"||l?.type!=="NUMBER"||l.value!=="2"?null:{consumed:5,replacement:[new a$2("UNIT",md,"mps2","m/s^2",n.offset,0,n.line,n.col)],ruleName:e}}}}function D(t){return e=>e.type!==6||!e.unit?P("AS_UNIT_EXPECTED_QUANTITY",`"as ${t}" expects a quantity with a unit`):e.unit===t?e:d$5(e.unit,t)?u$1(e$1(e.toNumber(),e.unit,t),t):P("AS_UNIT_INCOMPATIBLE",`${e.unit} cannot be expressed as ${t}: they do not measure the same thing`)}var ci={name:"solve-derived-units",normalizerRules:[Xl()],asConverters:{n:D("N"),kn:D("kN"),j:D("J"),kj:D("kJ"),mj:D("MJ"),wh:D("Wh"),kwh:D("kWh"),w:D("W"),kw:D("kW"),mw:D("MW"),pa:D("Pa"),kpa:D("kPa"),mpa:D("MPa"),v:D("V"),mv:D("mV"),kv:D("kV")}};function pi(t){return [...t].length}function Ql(t){return t.trim()}function ql(t){return [...t].reverse().join("")}function Zl(t,e){return t.includes(e)}function Jl(t,e){return t.startsWith(e)}function eu(t,e){return t.endsWith(e)}function tu(t,e,o){return e===""?t:t.split(e).join(o)}function ru(t,e){let o=Math.trunc(e);return o<=0?"":t.repeat(o)}function Po(t){return t.toUpperCase()}function _o(t){return t.toLowerCase()}function Ao(t){return t.replace(/\S+/g,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())}function xo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ou(t){let e=t.trim();return e===""?0:e.split(/\s+/).length}function nu(t){return t===""?0:t.split(/\r\n|\r|\n/).length}function ae(t){return t?.type===3?t.value:null}function gt(t){return P("TEXT_EXPECTED",`${t} expects text (a "quoted string")`)}function Ro(t,e){return o=>{let r=ae(o[0]);return r===null?gt(t):n(e(r))}}function Fe(t$1,e){return o=>{let r=ae(o[0]);return r===null?gt(t$1):t(e(r))}}function fi(t,e){return o=>{let r=ae(o[0]),n=ae(o[1]);return r===null||n===null?gt(t):L(e(r,n))}}var iu={textLength:Ro("length",pi),textWordCount:Ro("words in",ou),textCharCount:Ro("characters in",pi),textLineCount:Ro("lines in",nu),textTrim:Fe("trim",Ql),textReverse:Fe("reverse",ql),textUpper:Fe('"as upper"',Po),textLower:Fe('"as lower"',_o),textTitle:Fe('"as title"',Ao),textSlug:Fe('"as slug"',xo),textContains:fi("contains",Zl),textStartsWith:fi("starts with",Jl),textEndsWith:fi("ends with",eu),textReplace:t$1=>{let e=ae(t$1[0]),o=ae(t$1[1]),r=ae(t$1[2]);return e===null||o===null||r===null?gt("replace"):t(tu(e,o,r))},textRepeat:t$1=>{let e=ae(t$1[0]);if(e===null)return gt("repeat");let o=t$1[1];return o?.type!==0?P("TEXT_EXPECTED","repeat expects a count (a number)"):t(ru(e,o.value))}};function ge(t,e){return {category:"Text",parse(o,r,n){o.parseExpression(e,n),n.emitPluginCall(t,1);}}}function Oo(t){return {category:"Text",bindingPower:a.Conditional,parse(e,o,r,n){e.parseExpression(a.Conditional,n),n.emitPluginCall(t,2);}}}var au={category:"Text",bindingPower:a.Conditional,parse(t,e,o,r){t.parseExpression(a.Prefix,r);let n=t.peek();n?.type==="STAR"&&(n.value??"").toLowerCase()==="times"&&t.consume(),r.emitPluginCall("textRepeat",2);}};var ho={length:"textLength",upper:"textUpper",uppercase:"textUpper",lower:"textLower",lowercase:"textLower",title:"textTitle",titlecase:"textTitle",slug:"textSlug",slugify:"textSlug",replace:"textReplace",repeat:"textRepeat",words:"textWordCount",wordcount:"textWordCount",characters:"textCharCount",charcount:"textCharCount",lines:"textLineCount",linecount:"textLineCount"};var Io=class{constructor(){this.category="Text";}parse(e,o,r){let n=ho[o.value];if(n===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown text function: ${o.value}`,{functionName:o.value});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),i++;e.match("COMMA");)e.parseExpression(a.Lowest,r),i++;e.consume("RPAREN"),r.emitPluginCall(n,i);}};function Co(t$1,e){return o=>o.type!==3?P("TEXT_EXPECTED",`"as ${t$1}" expects text (a "quoted string")`):t(e(o.value))}var di={name:"solve-text",phrases:{"length of":"LENGTH_OF","words in":"WORDS_IN","characters in":"CHARACTERS_IN","lines in":"LINES_IN","starts with":"STARTS_WITH","ends with":"ENDS_WITH"},lexerVocabulary:{keywords:{trim:"TRIM",reverse:"REVERSE",contains:"CONTAINS",repeated:"REPEATED"}},prefixParselets:{LENGTH_OF:ge("textLength",a.Lowest),WORDS_IN:ge("textWordCount",a.Lowest),CHARACTERS_IN:ge("textCharCount",a.Lowest),LINES_IN:ge("textLineCount",a.Lowest),TRIM:ge("textTrim",a.Prefix),REVERSE:ge("textReverse",a.Prefix),TEXT_CALL:new Io},infixParselets:{CONTAINS:Oo("textContains"),STARTS_WITH:Oo("textStartsWith"),ENDS_WITH:Oo("textEndsWith"),REPEATED:au},asConverters:{upper:Co("upper",Po),lower:Co("lower",_o),title:Co("title",Ao),slug:Co("slug",xo)},callFusions:Object.fromEntries(Object.keys(ho).map(t=>[t,"TEXT_CALL"])),pluginFunctions:iu,tokenCategories:{LENGTH_OF:"function",WORDS_IN:"function",CHARACTERS_IN:"function",LINES_IN:"function",TRIM:"function",REVERSE:"function",TEXT_CALL:"function",CONTAINS:"operator",STARTS_WITH:"operator",ENDS_WITH:"operator",REPEATED:"operator"}};function Pt(t){return new TextEncoder().encode(t)}function Ei(t){let e="";for(let o of t)e+=o.toString(16).padStart(2,"0");return e}var ld=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let o=e;for(let r=0;r<8;r++)o=o&1?3988292384^o>>>1:o>>>1;t[e]=o>>>0;}return t})();function su(t){let e=Pt(t),o=4294967295;for(let r of e)o=ld[(o^r)&255]^o>>>8;return o=(o^4294967295)>>>0,o.toString(16).padStart(8,"0")}function ud(t){let e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],o=new Int32Array(64);for(let N=0;N<64;N++)o[N]=Math.floor(Math.abs(Math.sin(N+1))*4294967296);let r=t.length*8,n=new Uint8Array(((t.length+8>>6)+1)*64);n.set(t),n[t.length]=128;let i=new DataView(n.buffer);i.setUint32(n.length-8,r>>>0,true),i.setUint32(n.length-4,Math.floor(r/4294967296)>>>0,true);let a=1732584193,s=4023233417,l=2562383102,u=271733878,c=(N,E)=>N<<E|N>>>32-E;for(let N=0;N<n.length;N+=64){let E=new Int32Array(16);for(let P=0;P<16;P++)E[P]=i.getUint32(N+P*4,true);let A=a,R=s,O=l,g=u;for(let P=0;P<64;P++){let C,S;P<16?(C=R&O|~R&g,S=P):P<32?(C=g&R|~g&O,S=(5*P+1)%16):P<48?(C=R^O^g,S=(3*P+5)%16):(C=O^(R|~g),S=7*P%16),C=C+A+o[P]+E[S]|0,A=g,g=O,O=R,R=R+c(C,e[P])|0;}a=a+A|0,s=s+R|0,l=l+O|0,u=u+g|0;}let f=new Uint8Array(16),T=new DataView(f.buffer);return T.setUint32(0,a>>>0,true),T.setUint32(4,s>>>0,true),T.setUint32(8,l>>>0,true),T.setUint32(12,u>>>0,true),f}function mu(t){return Ei(ud(Pt(t)))}function cd(t){let e=t.length*8,o=new Uint8Array(((t.length+8>>6)+1)*64);o.set(t),o[t.length]=128;let r=new DataView(o.buffer);r.setUint32(o.length-8,Math.floor(e/4294967296)>>>0),r.setUint32(o.length-4,e>>>0);let n=1732584193,i=4023233417,a=2562383102,s=271733878,l=3285377520,u=(N,E)=>N<<E|N>>>32-E,c=new Int32Array(80);for(let N=0;N<o.length;N+=64){for(let P=0;P<16;P++)c[P]=r.getUint32(N+P*4);for(let P=16;P<80;P++)c[P]=u(c[P-3]^c[P-8]^c[P-14]^c[P-16],1);let E=n,A=i,R=a,O=s,g=l;for(let P=0;P<80;P++){let C,S;P<20?(C=A&R|~A&O,S=1518500249):P<40?(C=A^R^O,S=1859775393):P<60?(C=A&R|A&O|R&O,S=2400959708):(C=A^R^O,S=3395469782);let j=u(E,5)+C+g+S+c[P]|0;g=O,O=R,R=u(A,30),A=E,E=j;}n=n+E|0,i=i+A|0,a=a+R|0,s=s+O|0,l=l+g|0;}let f=new Uint8Array(20),T=new DataView(f.buffer);return [n,i,a,s,l].forEach((N,E)=>T.setUint32(E*4,N>>>0)),f}function lu(t){return Ei(cd(Pt(t)))}var pd=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function fd(t){let e=t.length*8,o=new Uint8Array(((t.length+8>>6)+1)*64);o.set(t),o[t.length]=128;let r=new DataView(o.buffer);r.setUint32(o.length-8,Math.floor(e/4294967296)>>>0),r.setUint32(o.length-4,e>>>0);let n=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=(u,c)=>u>>>c|u<<32-c,a=new Uint32Array(64);for(let u=0;u<o.length;u+=64){for(let g=0;g<16;g++)a[g]=r.getUint32(u+g*4);for(let g=16;g<64;g++){let P=i(a[g-15],7)^i(a[g-15],18)^a[g-15]>>>3,C=i(a[g-2],17)^i(a[g-2],19)^a[g-2]>>>10;a[g]=a[g-16]+P+a[g-7]+C|0;}let[c,f,T,N,E,A,R,O]=n;for(let g=0;g<64;g++){let P=i(E,6)^i(E,11)^i(E,25),C=E&A^~E&R,S=O+P+C+pd[g]+a[g]|0,j=i(c,2)^i(c,13)^i(c,22),ze=c&f^c&T^f&T,me=j+ze|0;O=R,R=A,A=E,E=N+S|0,N=T,T=f,f=c,c=S+me|0;}n[0]=n[0]+c|0,n[1]=n[1]+f|0,n[2]=n[2]+T|0,n[3]=n[3]+N|0,n[4]=n[4]+E|0,n[5]=n[5]+A|0,n[6]=n[6]+R|0,n[7]=n[7]+O|0;}let s=new Uint8Array(32),l=new DataView(s.buffer);for(let u=0;u<8;u++)l.setUint32(u*4,n[u]>>>0);return s}function uu(t){return Ei(fd(Pt(t)))}var V=(1n<<64n)-1n,dd=[0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n];function cu(t){let e=Pt(t),o=((e.length+16>>7)+1)*128,r=new Uint8Array(o);r.set(e),r[e.length]=128;let n=BigInt(e.length)*8n,i=new DataView(r.buffer);i.setUint32(r.length-4,Number(n&0xffffffffn)),i.setUint32(r.length-8,Number(n>>32n&0xffffffffn));let a=[0x6a09e667f3bcc908n,0xbb67ae8584caa73bn,0x3c6ef372fe94f82bn,0xa54ff53a5f1d36f1n,0x510e527fade682d1n,0x9b05688c2b3e6c1fn,0x1f83d9abfb41bd6bn,0x5be0cd19137e2179n],s=(u,c)=>(u>>c|u<<64n-c)&V,l=new Array(80);for(let u=0;u<r.length;u+=128){for(let g=0;g<16;g++){let P=BigInt(i.getUint32(u+g*8)),C=BigInt(i.getUint32(u+g*8+4));l[g]=P<<32n|C;}for(let g=16;g<80;g++){let P=s(l[g-15],1n)^s(l[g-15],8n)^l[g-15]>>7n,C=s(l[g-2],19n)^s(l[g-2],61n)^l[g-2]>>6n;l[g]=l[g-16]+P+l[g-7]+C&V;}let[c,f,T,N,E,A,R,O]=a;for(let g=0;g<80;g++){let P=s(E,14n)^s(E,18n)^s(E,41n),C=E&A^~E&V&R,S=O+P+C+dd[g]+l[g]&V,j=s(c,28n)^s(c,34n)^s(c,39n),ze=c&f^c&T^f&T,me=j+ze&V;O=R,R=A,A=E,E=N+S&V,N=T,T=f,f=c,c=S+me&V;}a[0]=a[0]+c&V,a[1]=a[1]+f&V,a[2]=a[2]+T&V,a[3]=a[3]+N&V,a[4]=a[4]+E&V,a[5]=a[5]+A&V,a[6]=a[6]+R&V,a[7]=a[7]+O&V;}return a.map(u=>u.toString(16).padStart(16,"0")).join("")}var So={md5:"hashMd5",sha1:"hashSha1",sha256:"hashSha256",sha512:"hashSha512",crc32:"hashCrc32"};function _t(t$1,e){return o=>{let r=o[0];return r?.type!==3?P("HASH_EXPECTED_TEXT",`${t$1}(...) expects text (a "quoted string")`):t(e(r.value))}}var pu={hashMd5:_t("md5",mu),hashSha1:_t("sha1",lu),hashSha256:_t("sha256",uu),hashSha512:_t("sha512",cu),hashCrc32:_t("crc32",su)};var Lo=class{constructor(){this.category="Hash";}parse(e,o,r){let n=So[o.value];if(n===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown hash function: ${o.value}`,{functionName:o.value});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),i++;e.match("COMMA");)e.parseExpression(a.Lowest,r),i++;e.consume("RPAREN"),r.emitPluginCall(n,i);}};var Ti={name:"solve-hash",prefixParselets:{HASH_CALL:new Lo},callFusions:Object.fromEntries(Object.keys(So).map(t=>[t,"HASH_CALL"])),pluginFunctions:pu,tokenCategories:{HASH_CALL:"function"}};var fu="0123456789abcdef";function du(){return fu[Math.floor(Math.random()*16)]}function Ed(){let t="";for(let e=0;e<36;e++)e===8||e===13||e===18||e===23?t+="-":e===14?t+="4":e===19?t+=fu[Math.floor(Math.random()*16)&3|8]:t+=du();return t}function Td(t){let e="";for(let o=0;o<t;o++)e+=du();return e}var Eu={randomUuid:()=>t(Ed()),randomCoin:()=>t(Math.random()<.5?"heads":"tails"),randomHex:t$1=>{let e=t$1[0];if(e?.type!==0)return P("RANDOM_EXPECTED_COUNT","random hex expects a number of digits");let o=Math.trunc(e.value);return o<0?P("RANDOM_EXPECTED_COUNT","random hex needs a count of 0 or more"):t(Td(o))},randomPick:t=>t.length===0?P("RANDOM_PICK_EMPTY","pick needs at least one option"):t[Math.floor(Math.random()*t.length)],randomShuffle:t=>{let e=t[0];if(e?.type!==7)return P("RANDOM_SHUFFLE_EXPECTED_LIST","shuffle expects a list, e.g. shuffle [1, 2, 3]");let o=e.value;if(o.rows!==1&&o.cols!==1)return P("RANDOM_SHUFFLE_EXPECTED_LIST","shuffle expects a single row or column, not a full matrix");let r=o.data.slice();for(let n=r.length-1;n>0;n--){let i=Math.floor(Math.random()*(n+1));[r[n],r[i]]=[r[i],r[n]];}return C(o.rows,o.cols,r)}};function Ni(t){return {category:"Random",parse(e,o,r){r.emitPluginCall(t,0);}}}function yi(t){return {category:"Random",parse(e,o,r){e.parseExpression(a.Prefix,r),r.emitPluginCall(t,1);}}}var Tu={category:"Random",parse(t,e,o){t.consume("LPAREN");let r=0;if(t.peek()?.type!=="RPAREN")for(t.parseExpression(a.Lowest,o),r++;t.match("COMMA");)t.parseExpression(a.Lowest,o),r++;t.consume("RPAREN"),o.emitPluginCall("randomPick",r);}};var gi={name:"solve-random",phrases:{"random hex":"RANDOM_HEX"},lexerVocabulary:{keywords:{uuid:"UUID",coin:"COIN",shuffle:"SHUFFLE"}},prefixParselets:{UUID:Ni("randomUuid"),COIN:Ni("randomCoin"),RANDOM_HEX:yi("randomHex"),SHUFFLE:yi("randomShuffle"),PICK_CALL:Tu},callFusions:{pick:"PICK_CALL"},pluginFunctions:Eu,tokenCategories:{UUID:"function",COIN:"function",RANDOM_HEX:"function",SHUFFLE:"function",PICK_CALL:"function"}};function se(t){return t.reduce((e,o)=>e+o,0)/t.length}function Nd(t){let e=se(t);return t.reduce((o,r)=>o+(r-e)*(r-e),0)/t.length}function yd(t){return Math.sqrt(Nd(t))}function Pi(t,e){let o=se(t),r=se(e),n=0,i=0,a=0;for(let l=0;l<t.length;l++){let u=t[l]-o,c=e[l]-r;n+=u*c,i+=u*u,a+=c*c;}let s=Math.sqrt(i*a);return s===0?NaN:n/s}function _i(t,e){let o=se(t),r=se(e),n=0,i=0;for(let a=0;a<t.length;a++){let s=t[a]-o;n+=s*(e[a]-r),i+=s*s;}return i===0?NaN:n/i}function Nu(t,e){return se(e)-_i(t,e)*se(t)}function yu(t,e){let o=Pi(t,e);return o*o}function gu(t,e){let o=[...t].sort((a,s)=>a-s);if(o.length===1)return o[0];let r=e/100*(o.length-1),n=Math.floor(r),i=Math.ceil(r);return n===i?o[n]:o[n]+(r-n)*(o[i]-o[n])}function Pu(t,e){let o=yd(e);return o===0?NaN:(t-se(e))/o}function gd(t){let e=t<0?-1:1,o=1/(1+.3275911*Math.abs(t)),r=1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-t*t);return e*r}function _u(t){return .5*(1+gd(t/Math.SQRT2))}function Au(t){return Math.exp(-0.5*t*t)/Math.sqrt(2*Math.PI)}function vo(t){if(!t)return null;if(t.type===7){let e=t.value;return e.hasSymbolic||e.rows!==1&&e.cols!==1?null:e.data.slice()}if(t.type===8){let e=t.value,o=[];for(let r=Math.ceil(e.min);r<=e.max;r++)o.push(r);return o}return t.type===0?[t.value]:null}function wo(t,e){return o=>{let r=vo(o[0]),n$1=vo(o[1]);return r===null||n$1===null?P("STAT_EXPECTED_LISTS",`${t} expects two lists, e.g. ${t} of [1, 2, 3] and [2, 4, 6]`):r.length!==n$1.length?P("STAT_LENGTH_MISMATCH",`${t}: the two lists must be the same length (got ${r.length} and ${n$1.length})`):r.length<2?P("STAT_TOO_FEW",`${t} needs at least two paired points`):n(e(r,n$1))}}var xu={statCorrelation:wo("correlation",Pi),statSlope:wo("slope",_i),statIntercept:wo("intercept",Nu),statRSquared:wo("r squared",yu),statPercentile:t=>{let e=vo(t[0]),o=t[1];if(e===null)return P("STAT_EXPECTED_LIST","percentile expects a list, e.g. percentile([1, 2, 3], 90)");if(e.length===0)return P("STAT_EMPTY","percentile needs at least one value");if(o?.type!==0)return P("STAT_EXPECTED_PERCENT","percentile needs a percentage, e.g. percentile([...], 90)");let r=o.value;return r<0||r>100?P("STAT_PERCENT_RANGE","a percentile is between 0 and 100"):n(gu(e,r))},statZScore:t=>{let e=t[0],o=vo(t[1]);return e?.type!==0?P("STAT_EXPECTED_VALUE","zscore expects a value first, e.g. zscore(5, [1, 2, 3])"):o===null||o.length<2?P("STAT_EXPECTED_LIST","zscore expects a list of at least two values"):n(Pu(e.value,o))},statNormalCdf:t=>{let e=t[0];return e?.type!==0?P("STAT_EXPECTED_VALUE","normalcdf expects a number"):n(_u(e.value))},statNormalPdf:t=>{let e=t[0];return e?.type!==0?P("STAT_EXPECTED_VALUE","normalpdf expects a number"):n(Au(e.value))}};function ko(t){return {category:"Statistics",parse(e,o,r){e.parseExpression(a.Conjunction,r),e.consume("AND_CONJ"),e.parseExpression(a.Conjunction,r),r.emitPluginCall(t,2);}}}var Bo={correlation:"statCorrelation",slope:"statSlope",intercept:"statIntercept",rsquared:"statRSquared",percentile:"statPercentile",zscore:"statZScore",normalcdf:"statNormalCdf",normalpdf:"statNormalPdf"};var Mo=class{constructor(){this.category="Statistics";}parse(e,o,r){let n=Bo[o.value];if(n===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown statistics function: ${o.value}`,{functionName:o.value});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),i++;e.match("COMMA");)e.parseExpression(a.Lowest,r),i++;e.consume("RPAREN"),r.emitPluginCall(n,i);}};var Ai={name:"solve-statistics",phrases:{"correlation of":"CORRELATION_OF","slope of":"SLOPE_OF","intercept of":"INTERCEPT_OF"},prefixParselets:{CORRELATION_OF:ko("statCorrelation"),SLOPE_OF:ko("statSlope"),INTERCEPT_OF:ko("statIntercept"),STAT_CALL:new Mo},callFusions:Object.fromEntries(Object.keys(Bo).map(t=>[t,"STAT_CALL"])),pluginFunctions:xu,tokenCategories:{CORRELATION_OF:"function",SLOPE_OF:"function",INTERCEPT_OF:"function",STAT_CALL:"function"}};var Pd=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],Ru={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3};function xi(t){if(!Number.isInteger(t)||t<1||t>3999)return null;let e="",o=t;for(let[r,n]of Pd)for(;o>=r;)e+=n,o-=r;return e}function Ou(t){let e=t.trim().toUpperCase();if(e===""||!/^[MDCLXVI]+$/.test(e))return null;let o=0;for(let r=0;r<e.length;r++){let n=Ru[e[r]],i=r+1<e.length?Ru[e[r+1]]:0;o+=n<i?-n:n;}return xi(o)===e?o:null}function hu(t){if(!Number.isInteger(t))return null;let e=Math.abs(t),o=e%100,r=e%10,n="th";return (o<11||o>13)&&(r===1?n="st":r===2?n="nd":r===3&&(n="rd")),`${t}${n}`}var Uo=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],_d=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],Ad=["","thousand","million","billion","trillion","quadrillion"];function xd(t){if(t<20)return Uo[t];let e=Math.floor(t/10),o=t%10;return _d[e]+(o?`-${Uo[o]}`:"")}function Rd(t){let e=Math.floor(t/100),o=t%100,r=[];return e&&r.push(`${Uo[e]} hundred`),o&&(e&&r.push("and"),r.push(xd(o))),r.join(" ")}function Od(t){if(t===0)return "zero";let e=[],o=t;for(;o>0;)e.push(o%1e3),o=Math.floor(o/1e3);let r=[];for(let i=e.length-1;i>=0;i--){if(e[i]===0)continue;let a=Rd(e[i]);i>0&&(a+=` ${Ad[i]}`),r.push({scale:i,group:e[i],words:a});}let n="";for(let i=0;i<r.length;i++){if(i>0){let a=i===r.length-1;n+=a&&r[i].scale===0&&r[i].group<100?" and ":" ";}n+=r[i].words;}return n}function Iu(t){if(!Number.isFinite(t))return null;let e=Math.abs(t).toString();if(e.includes("e")||e.includes("E"))return null;let[o,r]=e.split("."),n=Od(parseInt(o,10));return r&&(n+=" point "+[...r].map(i=>Uo[Number(i)]).join(" ")),(t<0?"minus ":"")+n}var Do=class{constructor(){this.category="Numerals";this.bindingPower=a.Conditional;}parse(e,o,r,n){n.emitPluginCall("romanFromString",1);}};function Ri(t$1,e){return o=>{if(o.type!==0)return P("NUMERAL_EXPECTED_NUMBER",`"as ${t$1}" expects a number`);let r=e(o.value);return r===null?P("NUMERAL_OUT_OF_RANGE",`${o.value} cannot be written as ${t$1}`):t(r)}}var Oi={name:"solve-numerals",phrases:{"from roman":"FROM_ROMAN"},asConverters:{roman:Ri("roman",xi),ordinal:Ri("ordinal",hu),words:Ri("words",Iu)},infixParselets:{FROM_ROMAN:new Do},pluginFunctions:{romanFromString:t=>{let e=t[0];if(e?.type!==3)return P("NUMERAL_EXPECTED_TEXT",'"from roman" expects text, e.g. "MMXXIV" from roman');let o=Ou(e.value);return o===null?P("NUMERAL_INVALID_ROMAN",`"${e.value}" is not a valid Roman numeral`):n(o)}},tokenCategories:{FROM_ROMAN:"operator"}};function hd(t,e){for(t=Math.abs(t),e=Math.abs(e);e;)[t,e]=[e,t%e];return t}function Cu(t){if(t.length<2||t.some(o=>!Number.isInteger(o)||o<=0))return null;let e=t.reduce((o,r)=>hd(o,r),0)||1;return t.map(o=>o/e).join(":")}var Su={category:"Ratio",parse(t,e,o){t.consume("LPAREN");let r=0;if(t.peek()?.type!=="RPAREN")for(t.parseExpression(a.Lowest,o),r++;t.match("COMMA");)t.parseExpression(a.Lowest,o),r++;t.consume("RPAREN"),o.emitPluginCall("ratioReduce",r);}};var hi={name:"solve-ratio",prefixParselets:{RATIO_CALL:Su},callFusions:{ratio:"RATIO_CALL"},pluginFunctions:{ratioReduce:t$1=>{let e=[];for(let r of t$1){if(r.type!==0)return P("RATIO_EXPECTED_NUMBERS","ratio expects whole numbers, e.g. ratio(16, 9)");e.push(r.value);}let o=Cu(e);return o===null?P("RATIO_INVALID","ratio needs at least two whole positive numbers"):t(o)}},tokenCategories:{RATIO_CALL:"function"}};var Pe=Math.PI;function F(t,e){let o=[];for(let r of e){if(!(r in t))return null;o.push(t[r]);}return o}var Ii=["circle","square","rectangle","triangle","sphere","cube","cylinder","cone"],Lu=["radius","side","width","height","base","length"];function wu(t,e,o){let r=i=>({error:`the ${t} of a ${e} needs its ${i}`}),n={error:`the ${t} of a ${e} is not one of the shapes this supports`};switch(`${t}:${e}`){case "area:circle":{let i=F(o,["radius"]);return i?{value:Pe*i[0]**2}:r("radius")}case "perimeter:circle":case "circumference:circle":{let i=F(o,["radius"]);return i?{value:2*Pe*i[0]}:r("radius")}case "area:square":{let i=F(o,["side"]);return i?{value:i[0]**2}:r("side")}case "perimeter:square":{let i=F(o,["side"]);return i?{value:4*i[0]}:r("side")}case "area:rectangle":{let i=F(o,["width","height"]);return i?{value:i[0]*i[1]}:r("width and height")}case "perimeter:rectangle":{let i=F(o,["width","height"]);return i?{value:2*(i[0]+i[1])}:r("width and height")}case "area:triangle":{let i=F(o,["base","height"]);return i?{value:.5*i[0]*i[1]}:r("base and height")}case "volume:sphere":{let i=F(o,["radius"]);return i?{value:4/3*Pe*i[0]**3}:r("radius")}case "surface:sphere":{let i=F(o,["radius"]);return i?{value:4*Pe*i[0]**2}:r("radius")}case "volume:cube":{let i=F(o,["side"]);return i?{value:i[0]**3}:r("side")}case "surface:cube":{let i=F(o,["side"]);return i?{value:6*i[0]**2}:r("side")}case "volume:cylinder":{let i=F(o,["radius","height"]);return i?{value:Pe*i[0]**2*i[1]}:r("radius and height")}case "surface:cylinder":{let i=F(o,["radius","height"]);return i?{value:2*Pe*i[0]*(i[0]+i[1])}:r("radius and height")}case "volume:cone":{let i=F(o,["radius","height"]);return i?{value:1/3*Pe*i[0]**2*i[1]}:r("radius and height")}default:return n}}var Id=new Set(Ii),Cd=new Set(Lu);function He(t){return {category:"Geometry",parse(e,o,r){let n=e.peek(),i=(n?.value??"").toLowerCase();if(!n||n.type!=="IDENT"||!Id.has(i))throw c$1.parsing("GEOMETRY_EXPECTED_SHAPE",`Expected a shape (${Ii.join(", ")}) after "${t} of" but got ${n?`"${n.value}"`:"end of input"}`);e.consume(),r.emitOpcode(13),r.emitString(t),r.emitOpcode(13),r.emitString(i);let a$1=2;for(;;){let s=e.peek(),l=(s?.value??"").toLowerCase();if(!s||s.type!=="IDENT"||!Cd.has(l))break;e.consume(),r.emitOpcode(13),r.emitString(l),a$1++,e.parseExpression(a.Call,r),a$1++,e.peek()?.type==="COMMA"&&e.consume();}r.emitPluginCall("geometryCompute",a$1);}}}var Ci={name:"solve-geometry",phrases:{"area of":"AREA_OF","perimeter of":"PERIMETER_OF","circumference of":"CIRCUMFERENCE_OF","volume of":"VOLUME_OF","surface area of":"SURFACE_AREA_OF"},prefixParselets:{AREA_OF:He("area"),PERIMETER_OF:He("perimeter"),CIRCUMFERENCE_OF:He("circumference"),VOLUME_OF:He("volume"),SURFACE_AREA_OF:He("surface")},pluginFunctions:{geometryCompute:t=>{let e=String(t[0]?.value??""),o=String(t[1]?.value??""),r={};for(let i=2;i+1<t.length;i+=2){let a=String(t[i]?.value??""),s=t[i+1];if(s?.type===13)return s;r[a]=s?.toNumber()??NaN;}let n$1=wu(e,o,r);return n$1.error!==void 0?P("GEOMETRY_ERROR",n$1.error):n(n$1.value)}},tokenCategories:{AREA_OF:"function",PERIMETER_OF:"function",CIRCUMFERENCE_OF:"function",VOLUME_OF:"function",SURFACE_AREA_OF:"function"}};var Sd={"speed of light":{value:299792458,unit:"m/s"},gravity:{value:9.80665,unit:"mps2"},"electron mass":{value:91093837015e-41,unit:"kg"},"proton mass":{value:167262192369e-38,unit:"kg"},avogadro:{value:602214076e15},planck:{value:662607015e-42},boltzmann:{value:1380649e-29},"elementary charge":{value:1602176634e-28},"gas constant":{value:8.314462618},tau:{value:6.283185307179586},"golden ratio":{value:1.618033988749895},phi:{value:1.618033988749895}};function vu(t){return Sd[t.toLowerCase()]??null}function G(t){return {category:"Constants",parse(e,o,r){r.emitOpcode(13),r.emitString(t),r.emitPluginCall("constantValue",1);}}}var Si={name:"solve-constants",phrases:{"speed of light":"SPEED_OF_LIGHT","electron mass":"ELECTRON_MASS","proton mass":"PROTON_MASS","elementary charge":"ELEMENTARY_CHARGE","gas constant":"GAS_CONSTANT","golden ratio":"GOLDEN_RATIO"},lexerVocabulary:{keywords:{gravity:"GRAVITY",avogadro:"AVOGADRO",planck:"PLANCK",boltzmann:"BOLTZMANN",tau:"TAU",phi:"PHI"}},prefixParselets:{SPEED_OF_LIGHT:G("speed of light"),ELECTRON_MASS:G("electron mass"),PROTON_MASS:G("proton mass"),ELEMENTARY_CHARGE:G("elementary charge"),GAS_CONSTANT:G("gas constant"),GOLDEN_RATIO:G("golden ratio"),GRAVITY:G("gravity"),AVOGADRO:G("avogadro"),PLANCK:G("planck"),BOLTZMANN:G("boltzmann"),TAU:G("tau"),PHI:G("phi")},pluginFunctions:{constantValue:t=>{let e=t[0]?.type===3?t[0].value:"",o=vu(e);return o===null?P("UNKNOWN_CONSTANT",`"${e}" is not a known constant`):o.unit?u$1(o.value,o.unit):n(o.value)}},tokenCategories:{SPEED_OF_LIGHT:"keyword",ELECTRON_MASS:"keyword",PROTON_MASS:"keyword",ELEMENTARY_CHARGE:"keyword",GAS_CONSTANT:"keyword",GOLDEN_RATIO:"keyword",GRAVITY:"keyword",AVOGADRO:"keyword",PLANCK:"keyword",BOLTZMANN:"keyword",TAU:"keyword",PHI:"keyword"}};function ku(t,e){return t/(e*e)}function Bu(t,e){return t*60/e}function Mu(t,e){let o=e/t,r=Math.floor(o),n=Math.round((o-r)*60);return n===60&&(r+=1,n=0),`${r}:${n.toString().padStart(2,"0")}`}var bo={bmi:"healthBmi",pace:"healthPace",speed:"healthSpeed"};var Vo=class{constructor(){this.category="Health";}parse(e,o,r){let n=bo[o.value];if(n===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown health function: ${o.value}`,{functionName:o.value});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,r),i++;e.match("COMMA");)e.parseExpression(a.Lowest,r),i++;e.consume("RPAREN"),r.emitPluginCall(n,i);}};function Ge(t){return t?.type===0?t.value:t?.type===6?t.toNumber():null}var Li={name:"solve-health",prefixParselets:{HEALTH_CALL:new Vo},callFusions:Object.fromEntries(Object.keys(bo).map(t=>[t,"HEALTH_CALL"])),pluginFunctions:{healthBmi:t=>{let e=Ge(t[0]),o=Ge(t[1]);return e===null||o===null||o===0?P("HEALTH_BAD_INPUT","bmi(weight in kg, height in m), e.g. bmi(70, 1.75)"):n(ku(e,o))},healthPace:t$1=>{let e=Ge(t$1[0]),o=Ge(t$1[1]);return e===null||o===null||e===0?P("HEALTH_BAD_INPUT","pace(distance in km, time in min), e.g. pace(10, 50)"):t(`${Mu(e,o)} /km`)},healthSpeed:t=>{let e=Ge(t[0]),o=Ge(t[1]);return e===null||o===null||o===0?P("HEALTH_BAD_INPUT","speed(distance in km, time in min), e.g. speed(10, 50)"):u$1(Bu(e,o),"km/h")}},tokenCategories:{HEALTH_CALL:"function"}};var ZL=[jo,Xo,qo,on,En,Tn,Nn,xn,On,hn,In,Cn,a$5,Sn,Ln,wn,kn,Dn,jn,Xn,bn,Fn,Qn,Hn,ei,ri,mi,li,ui,ci,Kn,di,Ti,gi,Ai,Oi,hi,Ci,Si,Li];
2
- export{jo as a,Xo as b,qo as c,on as d,En as e,Tn as f,Nn as g,xn as h,Rn as i,On as j,hn as k,In as l,Cn as m,Sn as n,Ln as o,wn as p,kn as q,Dn as r,bn as s,Um as t,bm as u,Fn as v,Hn as w,Kn as x,ZL as y};//# sourceMappingURL=chunk-7WX33WM2.js.map
3
- //# sourceMappingURL=chunk-7WX33WM2.js.map