solve-engine 2.5.0 → 2.6.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 (136) hide show
  1. package/dist/{BytecodeBuilder-DGGeByAP.d.cts → BytecodeBuilder-BGq9ZiO3.d.cts} +2 -1
  2. package/dist/{BytecodeBuilder-DGGeByAP.d.ts → BytecodeBuilder-BGq9ZiO3.d.ts} +2 -1
  3. package/dist/{PackageCompatibility-UsSZIfHs.d.ts → PackageCompatibility-4QtIErfx.d.ts} +1 -1
  4. package/dist/{PackageCompatibility-cEClSSkz.d.cts → PackageCompatibility-CCdud__Q.d.cts} +1 -1
  5. package/dist/{PackageRegistry-B3yJHSxX.d.ts → PackageRegistry-B7wkfSrY.d.ts} +5 -5
  6. package/dist/{PackageRegistry-BsLmAVZJ.d.cts → PackageRegistry-Hx85XD01.d.cts} +5 -5
  7. package/dist/{Parselet-C4Wu055_.d.cts → Parselet-CTNpfuEB.d.cts} +2 -2
  8. package/dist/{Parselet-B-zoPrTa.d.ts → Parselet-DONNUpur.d.ts} +2 -2
  9. package/dist/{ScopeManager-DkpnlKuz.d.ts → ScopeManager-BkbDXK_R.d.ts} +3 -3
  10. package/dist/{ScopeManager-t6SnP6Ce.d.cts → ScopeManager-Cvgypcu4.d.cts} +3 -3
  11. package/dist/{VMCheckpoints-CsHmQVaD.d.ts → VMCheckpoints-9zBQnTsN.d.ts} +3 -3
  12. package/dist/{VMCheckpoints-C_jQvABf.d.cts → VMCheckpoints-CBMGiSqw.d.cts} +3 -3
  13. package/dist/{Value-CCi_Eecs.d.cts → Value-D1XlMwe2.d.cts} +40 -5
  14. package/dist/{Value-CCi_Eecs.d.ts → Value-D1XlMwe2.d.ts} +40 -5
  15. package/dist/chunk-3AVWA5IZ.cjs +2 -0
  16. package/dist/chunk-3AVWA5IZ.cjs.map +1 -0
  17. package/dist/chunk-3DD2RVBI.cjs +3 -0
  18. package/dist/chunk-3DD2RVBI.cjs.map +1 -0
  19. package/dist/{chunk-RDMJNRDO.js → chunk-4XTD4B77.js} +3 -3
  20. package/dist/{chunk-RDMJNRDO.js.map → chunk-4XTD4B77.js.map} +1 -1
  21. package/dist/chunk-5FGOIDLS.cjs +2 -0
  22. package/dist/chunk-5FGOIDLS.cjs.map +1 -0
  23. package/dist/chunk-5OIXCVB2.js +3 -0
  24. package/dist/chunk-5OIXCVB2.js.map +1 -0
  25. package/dist/{chunk-NGJMCVH4.cjs → chunk-B4P4M4ZW.cjs} +3 -3
  26. package/dist/{chunk-NGJMCVH4.cjs.map → chunk-B4P4M4ZW.cjs.map} +1 -1
  27. package/dist/{chunk-TWC7K3ZX.js → chunk-GHW2X7PS.js} +2 -2
  28. package/dist/{chunk-TWC7K3ZX.js.map → chunk-GHW2X7PS.js.map} +1 -1
  29. package/dist/chunk-GKDZ7TSX.cjs +2 -0
  30. package/dist/chunk-GKDZ7TSX.cjs.map +1 -0
  31. package/dist/{chunk-7RTKJMYS.js → chunk-HMEZJXLX.js} +2 -2
  32. package/dist/{chunk-7RTKJMYS.js.map → chunk-HMEZJXLX.js.map} +1 -1
  33. package/dist/{chunk-FDE5HWDI.cjs → chunk-HOQU47MF.cjs} +2 -2
  34. package/dist/{chunk-FDE5HWDI.cjs.map → chunk-HOQU47MF.cjs.map} +1 -1
  35. package/dist/chunk-IO374J6Z.js +2 -0
  36. package/dist/chunk-IO374J6Z.js.map +1 -0
  37. package/dist/{chunk-D5MTMRHS.cjs → chunk-KSDTVFXA.cjs} +4 -4
  38. package/dist/{chunk-D5MTMRHS.cjs.map → chunk-KSDTVFXA.cjs.map} +1 -1
  39. package/dist/{chunk-YUJNMUKM.cjs → chunk-OVQ3V4CG.cjs} +2 -2
  40. package/dist/{chunk-YUJNMUKM.cjs.map → chunk-OVQ3V4CG.cjs.map} +1 -1
  41. package/dist/{chunk-XNIWQHXY.js → chunk-P6BLASAA.js} +2 -2
  42. package/dist/{chunk-XNIWQHXY.js.map → chunk-P6BLASAA.js.map} +1 -1
  43. package/dist/{chunk-AXMQG5TS.cjs → chunk-R7T3NGUE.cjs} +2 -2
  44. package/dist/{chunk-AXMQG5TS.cjs.map → chunk-R7T3NGUE.cjs.map} +1 -1
  45. package/dist/{chunk-CT5TC3JX.cjs → chunk-SOSUS2SK.cjs} +3 -3
  46. package/dist/chunk-SOSUS2SK.cjs.map +1 -0
  47. package/dist/chunk-SWKYVSMP.js +2 -0
  48. package/dist/chunk-SWKYVSMP.js.map +1 -0
  49. package/dist/chunk-T4Y5XOT2.js +3 -0
  50. package/dist/chunk-T4Y5XOT2.js.map +1 -0
  51. package/dist/{chunk-LOM3H5ZD.js → chunk-T52Y5G24.js} +4 -4
  52. package/dist/{chunk-LOM3H5ZD.js.map → chunk-T52Y5G24.js.map} +1 -1
  53. package/dist/{chunk-JFAJN3C2.cjs → chunk-VBSMA7WJ.cjs} +2 -2
  54. package/dist/chunk-VBSMA7WJ.cjs.map +1 -0
  55. package/dist/{chunk-RSF25YSJ.js → chunk-VYWGUMFW.js} +2 -2
  56. package/dist/{chunk-RSF25YSJ.js.map → chunk-VYWGUMFW.js.map} +1 -1
  57. package/dist/chunk-XTM4HTRB.js +2 -0
  58. package/dist/{chunk-LBNX7TXI.js.map → chunk-XTM4HTRB.js.map} +1 -1
  59. package/dist/{chunk-E6Z4NQAS.js → chunk-YNMMRH44.js} +2 -2
  60. package/dist/chunk-YNMMRH44.js.map +1 -0
  61. package/dist/chunk-Z5KBBQOJ.cjs +2 -0
  62. package/dist/{chunk-YFWAR766.cjs.map → chunk-Z5KBBQOJ.cjs.map} +1 -1
  63. package/dist/chunk-ZJPAPBP3.js +2 -0
  64. package/dist/chunk-ZJPAPBP3.js.map +1 -0
  65. package/dist/{chunk-N7N7MPMK.cjs → chunk-ZOOVGXMK.cjs} +2 -2
  66. package/dist/{chunk-N7N7MPMK.cjs.map → chunk-ZOOVGXMK.cjs.map} +1 -1
  67. package/dist/constants.cjs +1 -1
  68. package/dist/constants.js +1 -1
  69. package/dist/engine.cjs +1 -1
  70. package/dist/engine.d.cts +8 -8
  71. package/dist/engine.d.ts +8 -8
  72. package/dist/engine.js +1 -1
  73. package/dist/format.cjs +1 -1
  74. package/dist/format.d.cts +1 -1
  75. package/dist/format.d.ts +1 -1
  76. package/dist/format.js +1 -1
  77. package/dist/index.cjs +1 -1
  78. package/dist/index.d.cts +8 -8
  79. package/dist/index.d.ts +8 -8
  80. package/dist/index.js +1 -1
  81. package/dist/language.d.cts +7 -7
  82. package/dist/language.d.ts +7 -7
  83. package/dist/packages.cjs +1 -1
  84. package/dist/packages.d.cts +7 -7
  85. package/dist/packages.d.ts +7 -7
  86. package/dist/packages.js +1 -1
  87. package/dist/parser.cjs +1 -1
  88. package/dist/parser.d.cts +4 -4
  89. package/dist/parser.d.ts +4 -4
  90. package/dist/parser.js +1 -1
  91. package/dist/{pipeline-72QmQlGx.d.ts → pipeline-BH7BFOTJ.d.ts} +3 -3
  92. package/dist/{pipeline-DCQicwWX.d.cts → pipeline-DY0rhgQG.d.cts} +3 -3
  93. package/dist/resolvers.d.cts +2 -2
  94. package/dist/resolvers.d.ts +2 -2
  95. package/dist/testing.cjs +2 -2
  96. package/dist/testing.d.cts +7 -7
  97. package/dist/testing.d.ts +7 -7
  98. package/dist/testing.js +1 -1
  99. package/dist/uom.cjs +1 -1
  100. package/dist/uom.d.cts +2 -2
  101. package/dist/uom.d.ts +2 -2
  102. package/dist/uom.js +1 -1
  103. package/dist/vm.cjs +1 -1
  104. package/dist/vm.d.cts +7 -7
  105. package/dist/vm.d.ts +7 -7
  106. package/dist/vm.js +1 -1
  107. package/dist/worker.cjs +2 -2
  108. package/dist/worker.cjs.map +1 -1
  109. package/dist/worker.d.cts +22 -6
  110. package/dist/worker.d.ts +22 -6
  111. package/dist/worker.js +2 -2
  112. package/dist/worker.js.map +1 -1
  113. package/package.json +1 -1
  114. package/dist/chunk-2HQWM5OB.js +0 -3
  115. package/dist/chunk-2HQWM5OB.js.map +0 -1
  116. package/dist/chunk-6G3PMEPA.js +0 -2
  117. package/dist/chunk-6G3PMEPA.js.map +0 -1
  118. package/dist/chunk-6INX773F.cjs +0 -2
  119. package/dist/chunk-6INX773F.cjs.map +0 -1
  120. package/dist/chunk-6ZNNPXXE.cjs +0 -3
  121. package/dist/chunk-6ZNNPXXE.cjs.map +0 -1
  122. package/dist/chunk-ANJPS6FF.cjs +0 -2
  123. package/dist/chunk-ANJPS6FF.cjs.map +0 -1
  124. package/dist/chunk-B5NBFGNP.js +0 -3
  125. package/dist/chunk-B5NBFGNP.js.map +0 -1
  126. package/dist/chunk-CT5TC3JX.cjs.map +0 -1
  127. package/dist/chunk-E6Z4NQAS.js.map +0 -1
  128. package/dist/chunk-EVAOPEO4.js +0 -2
  129. package/dist/chunk-EVAOPEO4.js.map +0 -1
  130. package/dist/chunk-JFAJN3C2.cjs.map +0 -1
  131. package/dist/chunk-LBNX7TXI.js +0 -2
  132. package/dist/chunk-PS272DZJ.cjs +0 -2
  133. package/dist/chunk-PS272DZJ.cjs.map +0 -1
  134. package/dist/chunk-QEYTENAK.js +0 -2
  135. package/dist/chunk-QEYTENAK.js.map +0 -1
  136. package/dist/chunk-YFWAR766.cjs +0 -2
@@ -0,0 +1,2 @@
1
+ import {b}from'./chunk-YAYBVVG2.js';import {n}from'./chunk-IO374J6Z.js';var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],m=[157,158],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of m)r[e]=3;return r})();[...u,...E,...m];function C(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??b;}preflight(e,N,U,S,y){let{opcodes:c,strings:l}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n$1=l[p],s=l[i];if(this.exchange.isCurrency(n$1)&&this.exchange.isCurrency(s)&&n$1.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n$1,s)===null){let d=n$1.toUpperCase(),I=s.toUpperCase(),a=[R,d,I];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n$1,s,h).then(T=>n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n$1,toUnit:s}}}}o=C(c,o);}return null}destroy(){}};export{C as a,A as b};//# sourceMappingURL=chunk-SWKYVSMP.js.map
2
+ //# sourceMappingURL=chunk-SWKYVSMP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStrIdx","fromUnit","toUnit","fromUpper","toUpper","cacheKey","resolver","qSignal","rate","numberValue"],"mappings":"wEAwBA,IAAMA,CAAAA,CAAiC,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,EAAA,CAAA,EAwBvC,CAAA,CAOMC,CAAAA,CAAkC,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAOxC,CAAA,CAQMC,CAAAA,CAAoC,CAAA,GAAA,CAAA,GAAwC,CAAA,CAQrEC,CAAAA,CAAAA,CAAoC,IAAM,CACtD,IAAMC,CAAAA,CAAS,IAAI,KAAA,CAAc,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,CAC5C,IAAA,IAAWC,CAAAA,IAAML,CAAAA,CAAaI,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC3C,IAAA,IAAWA,KAAMJ,CAAAA,CAAcG,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC5C,IAAA,IAAWA,CAAAA,IAAMH,CAAAA,CAAgBE,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC9C,OAAOD,CACR,CAAA,GAAG,CAOqD,CACvD,GAAGJ,CAAAA,CACH,GAAGC,CAAAA,CACH,GAAGC,CACJ,EAaO,SAASI,CAAAA,CAAgBC,CAAAA,CAAqBC,CAAAA,CAAuB,CAC3E,OAAOA,CAAAA,CAAQ,CAAA,EAAKL,EAAcI,CAAAA,CAAQC,CAAK,CAAC,CAAA,EAAK,CAAA,CACtD,CC5FA,IAAMC,CAAAA,CAAc,UAAA,CAQPC,CAAAA,CAAN,KAAsD,CAK5D,WAAA,CAAYC,CAAAA,CAAoC,CAJhD,IAAA,CAAS,UAAYF,CAAAA,CAKpB,IAAA,CAAK,QAAA,CAAWE,CAAAA,EAAYC,EAC7B,CAEA,SAAA,CAAUC,CAAAA,CAAkBC,CAAAA,CAA2BC,CAAAA,CAAmBC,CAAAA,CAAqBC,CAAAA,CAAmD,CACjJ,GAAM,CAAE,OAAA,CAAAV,EAAS,OAAA,CAAAW,CAAQ,CAAA,CAAIJ,CAAAA,CACvBK,CAAAA,CAAMZ,CAAAA,CAAQ,MAAA,CAChBa,CAAAA,CAAI,CAAA,CAEJC,CAAAA,CAAa,EAAA,CACbC,CAAAA,CAAa,EAAA,CAEjB,KAAOF,CAAAA,CAAID,CAAAA,EAAK,CACf,IAAMd,CAAAA,CAAKE,CAAAA,CAAQa,CAAC,CAAA,CAkBpB,GAhBIf,CAAAA,GAAO,EAAA,GACViB,EAAaD,CAAAA,CACbA,CAAAA,CAAad,CAAAA,CAAQa,CAAAA,CAAI,CAAC,CAAA,CAAA,CAAA,CAY1Bf,CAAAA,GAAO,EAAA,EAAyBA,IAAO,EAAA,EACvCA,CAAAA,GAAO,EAAA,EAAcA,CAAAA,GAAO,EAAA,EAAcA,CAAAA,GAAO,EAAA,EAAcA,CAAAA,GAAO,EAAA,GAElEiB,CAAAA,EAAc,CAAA,EAAKD,CAAAA,EAAc,CAAA,CAAG,CACvC,IAAME,GAAAA,CAAWL,EAAQI,CAAU,CAAA,CAC7BE,CAAAA,CAASN,CAAAA,CAAQG,CAAU,CAAA,CAEjC,GACC,IAAA,CAAK,QAAA,CAAS,UAAA,CAAWE,GAAQ,CAAA,EACjC,IAAA,CAAK,QAAA,CAAS,UAAA,CAAWC,CAAM,GAC/BD,GAAAA,CAAS,WAAA,EAAY,GAAMC,CAAAA,CAAO,WAAA,EAAY,EAE7B,IAAA,CAAK,QAAA,CAAS,WAAA,CAAYD,GAAAA,CAAUC,CAAM,CAAA,GAC1C,IAAA,CAAM,CACtB,IAAMC,CAAAA,CAAYF,IAAS,WAAA,EAAY,CACjCG,CAAAA,CAAUF,CAAAA,CAAO,WAAA,EAAY,CAG7BG,CAAAA,CAAW,CAAClB,EAAagB,CAAAA,CAAWC,CAAO,CAAA,CACjD,GAAIT,CAAAA,CAAY,YAAA,CAAaU,CAAQ,CAAA,GAAM,OAAW,CACrDP,CAAAA,EAAAA,CACA,QACD,CAGA,IAAMQ,CAAAA,CAAWX,CAAAA,CAAY,UAAA,CAAW,CACvC,QAAA,CAAUU,CAAAA,CACV,OAAA,CAAS,CAAC,CAAE,MAAA,CAAQE,CAAQ,IACpB,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQN,GAAAA,CAAUC,CAAAA,CAAQK,CAAO,CAAA,CAAE,IAAA,CAAMC,CAAAA,EAASC,CAAAA,CAAYD,CAAI,CAAC,CAAA,CAEzF,SAAA,CAAW,GAAA,CAAS,GACrB,CAAC,CAAA,CAED,OAAO,CAAE,QAAA,CAAUH,CAAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAG,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAb,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,GAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-SWKYVSMP.js","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import {b as b$2,a as a$2}from'./chunk-SWKYVSMP.js';import {a as a$4,c as c$5,e as e$2,d,g as g$1,f}from'./chunk-AR7L5OJ2.js';import {a,d as d$1,e as e$3}from'./chunk-YVKHEAFT.js';import {b as b$5,e as e$5}from'./chunk-5FO4PDIG.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,B as B$1,d as d$3,z as z$2,A as A$1}from'./chunk-XTM4HTRB.js';import {c as c$3}from'./chunk-YAYBVVG2.js';import {a as a$3}from'./chunk-HFKDWQUL.js';import {B,i,z,y,q,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 as w$1,x as x$1}from'./chunk-R2ENWQ76.js';import {ta as ta$1,q as q$1,p as p$1,d as d$2,Q as Q$1,e as e$4}from'./chunk-VYWGUMFW.js';import {O,t,K as K$1,G as G$1,n,P,u as u$1,L,z as z$1,J as J$1,I as I$1,g}from'./chunk-IO374J6Z.js';import {c as c$4,e as e$1}from'./chunk-WGZ3FNHI.js';import {a as a$6}from'./chunk-G7TBEQRQ.js';import {c}from'./chunk-IJMNVBIS.js';import {a as a$5}from'./chunk-62LMTO4F.js';import {b as b$1}from'./chunk-TRBXW6HW.js';import {a as a$7}from'./chunk-2JMFUQZH.js';import {c as c$1}from'./chunk-MPB7KUN5.js';var ns=/^\d{1,3}(\.\d{3}){2,}$/,is=/^\d*\.\d*$/,rr=class{constructor(){this.category="Arithmetic";}parse(e,o,t){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(ns.test(a))n=parseFloat(a.split(".").join(""));else {let m=a$5(e.getLocaleCode()),l=m.display.decimalSeparator,u=m.display.thousandsSeparator,c=a;u&&(c=c.split(u).join("")),l&&l!=="."&&(c=c.replace(l,".")),n=parseFloat(c),is.test(c)&&(i=c);}if(i!==null){t.emitOpcode(16),t.emitString(i);return}t.emitOpcode(10),t.emitNumber(n);}};var de=class{constructor(e){this.opcode=e;this.category="Arithmetic";}parse(e,o,t){e.parseExpression(60,t),t.emitOpcode(this.opcode);}};var R=class{constructor(e,o,t=false){this.opcode=o;this.category="Arithmetic";this.bindingPower=e,this.rightBindingPower=t?e-1:e;}parse(e,o,t,n){e.parseExpression(this.rightBindingPower,n),n.emitOpcode(this.opcode);}};var tr=class{constructor(){this.category="Arithmetic";}parse(e,o,t){e.parseExpression(0,t);let n=1;for(;e.match("COMMA");)e.parseExpression(0,t),n++;e.consume("RPAREN"),n>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(n));}};var xe=class{constructor(){this.category="Arithmetic";}parse(e,o,t){let n=o.type==="PI"?Math.PI:Math.E;t.emitOpcode(10),t.emitNumber(n);}};var as={k:3,M:6,G:9,B:9,T:12},ms={thousand:3,thousands:3,million:6,millions:6,mn:6,billion:9,billions:9,bn:9,trillion:12,trillions:12,tn:12},ss=/^\d+(\.\d+)?$/;function ls(r,e){let o=r.indexOf("."),t=o===-1?r:r.slice(0,o),n=o===-1?"":r.slice(o+1);n.length<e&&(n=n.padEnd(e,"0"));let i=t+n.slice(0,e),a=n.slice(e);return a?`${i}.${a}`:i}function Wn(r=65){return {name:"arithmetic:large-number-suffix",priority:r,match(e,o){let t=e[o];if(t.type!=="NUMBER"||!ss.test(t.text))return null;let n=e[o+1];if(!n||n.type!=="IDENT"&&n.type!=="UNIT")return null;let i=t.offset+t.text.length===n.offset,a=n.type==="UNIT"?void 0:ms[n.value.toLowerCase()],m=i?as[n.value]??a:a;if(m===void 0)return null;let l=ls(t.text,m);return {consumed:2,replacement:[b$5("NUMBER",l,e.slice(o,o+2))],ruleName:"arithmetic:large-number-suffix"}}}}var eo={name:"solve-arithmetic",prefixParselets:{NUMBER:new rr,LPAREN:new tr,PI:new xe,E:new xe,PLUS:new de(27),MINUS:new de(26),BIT_NOT:new de(36)},infixParselets:{PLUS:new R(a.Sum,20),AND_CONJ:new R(a.Conjunction,20),MINUS:new R(a.Sum,21),STAR:new R(a.Product,22),SLASH:new R(a.Product,23),MOD:new R(a.Product,24),CARET:new R(a.Exponent,25,true),TIMES_BY:new R(a.Product,22),MULTIPLY_BY:new R(a.Product,22),DIVIDE_BY:new R(a.Product,23),LSHIFT:new R(a.Shift,30),RSHIFT:new R(a.Shift,31),URSHIFT:new R(a.Shift,32),BIT_AND:new R(a.BitwiseAnd,33),BIT_OR:new R(a.BitwiseOr,34),BIT_XOR:new R(a.BitwiseXor,35)},normalizerRules:[Wn()]};var or=class{constructor(){this.category="Percentage";this.bindingPower=a.Prefix;}parse(e,o,t,n){n.emitOpcode(10),n.emitNumber(100),n.emitOpcode(23),n.emitOpcode(74);}};var nr=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){if(jn(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 t=us(e);if(t===null){o.emitOpcode(74);return}e.parseExpression(a.Conditional,o),o.emitOpcode(23),t==="off"?(o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(21)):t==="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")){Yn(e,"what",'"81 is 9 to what power"'),Yn(e,"power",'"81 is 9 to what power"'),o.emitOpcode(51),o.emitIndex($n),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(51),o.emitIndex($n),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(23);return}let t=e.match("OF_WHAT")?"of":e.match("OFF_WHAT")?"off":e.match("ON_WHAT")?"on":null;if(t===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(t==="of"){o.emitOpcode(23);return}o.emitOpcode(10),o.emitNumber(1),t==="off"?(o.emitOpcode(2),o.emitOpcode(21)):o.emitOpcode(20),o.emitOpcode(23);}},$n=5;function jn(r,e){return (r.peek()?.text??"").toLowerCase()===e}function Yn(r,e,o){if(!jn(r,e))throw c$1.parsing("IS_WHAT_EXPECTED_WORD",`Expected "${e}" here, as in ${o}`);r.consume();}function us(r){if(r.match("OF"))return "of";let e=(r.peek()?.text??"").toLowerCase();return e==="off"||e==="on"?(r.consume(),e):null}var Se=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,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 Xn(r=68){return {name:"percentage:on-off",priority:r,match(e,o){if(e[o]?.type!=="PERCENT")return null;let t=e[o+1];if(t?.type!=="IDENT")return null;let n=(t.text??t.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,[t])],ruleName:"percentage:on-off"}}}}var ir=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(22);}};var ar=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23);}};var Le=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,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 we=class{constructor(e){this.multiplier=e;this.category="Percentage";}parse(e,o,t){e.parseExpression(0,t);let n=e.peek();n&&(n.type==="IDENT"||n.type==="BY")&&e.consume(),t.emitOpcode(10),t.emitNumber(1),e.parseExpression(0,t),e.peek()?.type==="PERCENT"&&e.consume(),t.emitOpcode(this.multiplier>0?20:21),t.emitOpcode(22);}};var ve=class{constructor(e){this.multiplier=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,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 mr=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,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 cs={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 ps(r){if(r.type==="NUMBER"){let e=Number(r.value);return Number.isInteger(e)&&e>=0?e:null}return r.type==="IDENT"?cs[r.value.toLowerCase()]??null:null}var ke=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,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(),t=e.peekAt(1);if(!o||!t||t.type!=="STAR"||t.value.toLowerCase()!=="times")return null;let n=ps(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 Qn(r,e){let o=r[e];if(o?.type!=="IDENT")return null;let t=(o.text??o.value??"").toLowerCase();return t!=="up"&&t!=="down"||r[e+1]?.type!=="NUMBER"||r[e+2]?.type!=="PERCENT"?null:b$5(t==="up"?"PCT_UP":"PCT_DOWN",t,[o])}function Zn(r=68){return {name:"percentage:up-down",priority:r,match(e,o){let t=e[o];if(t&&(t.type==="NUMBER"||t.type==="RPAREN")){let i=Qn(e,o+1);if(i)return {consumed:2,replacement:[t,i],ruleName:"percentage:up-down"}}let n=Qn(e,o);return n?{consumed:1,replacement:[n],ruleName:"percentage:up-down"}:null}}}var ro={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 or,IS:new nr,PCT_ON:new Se(1),PCT_OFF:new Se(-1),OF:new ir,OF_WHAT_IS:new ar,ON_WHAT_IS:new Le(1),OFF_WHAT_IS:new Le(-1),TO:new mr,INCREASE_BY:new ve(1),DECREASE_BY:new ve(-1),PCT_UP:new ke(1),PCT_DOWN:new ke(-1)},prefixParselets:{INCREASE:new we(1),DECREASE:new we(-1)},normalizerRules:[Xn(),Zn()]};var to={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},sr=class{constructor(){this.category="Function";}parse(e,o,t){let n=o.value.toLowerCase(),i=to[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,t),a$1++;e.match("COMMA");)e.parseExpression(a.Lowest,t),a$1++;e.consume("RPAREN"),t.emitOpcode(51),t.emitIndex(i),t.emitIndex(a$1);}};var oo={name:"solve-function",prefixParselets:{FUNC:new sr}};var te=class{constructor(e=0){this.category="Date/Time";this.dayOffset=e;}parse(e,o,t){t.emitOpcode(90),this.dayOffset!==0&&(t.emitOpcode(10),t.emitNumber(this.dayOffset),t.emitOpcode(13),t.emitString("days"),t.emitOpcode(80),t.emitOpcode(20));}};var fs={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},Be=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,t){let n=e.peek(),i=n?fs[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(),t.emitOpcode(90),t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(this.direction==="next"?93:94);}};var Me=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,t){let n=o.value;this.direction==="until"?(e.parseExpression(0,t),t.emitOpcode(90)):(t.emitOpcode(90),e.parseExpression(0,t)),t.emitOpcode(21),t.emitOpcode(13),t.emitString(n),t.emitOpcode(84);}};var lr=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.parseExpression(0,t),t.emitPluginCall("workdaysInDuration",1);}};var Ue=class{constructor(e){this.direction=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Sum,n),n.emitOpcode(96),n.emitByte(this.direction==="backward"?1:0);}};var ur=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitOpcode(97);}};var G=class{constructor(e,o){this.functionName=e;this.mode=o;this.category="Date/Time";}parse(e,o,t){this.mode==="in"?(t.emitOpcode(90),e.parseExpression(0,t),t.emitOpcode(20)):e.peek()?e.parseExpression(0,t):t.emitOpcode(90),t.emitPluginCall(this.functionName,1);}};var cr=class{constructor(){this.category="Date/Time";}parse(e,o,t){let n=o.value;e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitPluginCall("spanBetweenDates",2),t.emitOpcode(13),t.emitString(n),t.emitOpcode(84);}};var De=class{constructor(e){this.functionName=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall(this.functionName,1);}};var pr=class{constructor(){this.category="Date/Time";}parse(e,o,t){t.emitOpcode(90),t.emitPluginCall("toTimestampFromAny",1);}};var fr=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall("toDateFromAny",1);}};var dr=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall("toTimestampFromAny",1);}};var Er=class{constructor(){this.category="Date/Time";}parse(e,o,t){t.emitOpcode(95),t.emitNumber(Number(o.value));}};var Nr=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.consume("OF"),e.parseExpression(a.Postfix,t),t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall("nthWeekdayOfMonth",2);}};var Ee=class{constructor(e){this.offsetMonths=e;this.category="Date/Time";}parse(e,o,t){t.emitOpcode(90),t.emitOpcode(10),t.emitNumber(this.offsetMonths),t.emitPluginCall("monthAnchorShift",2);}};var ds=new Set(["year","years","month","months","day","days"]),Tr=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.parseExpression(a.Postfix,t),this.wordIs(e.peek(),"on")?(e.consume(),e.parseExpression(a.Postfix,t)):t.emitOpcode(90);let n=this.consumeBreakdown(e)?"ymd":"years";t.emitOpcode(13),t.emitString(n),t.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 t=e.peek();if(!t)break;let n=String(t.value??t.text??"").toLowerCase();if(t.type==="UNIT"&&ds.has(n))o=true,e.consume();else if(t.type==="COMMA"||t.type==="AND_CONJ"||n==="and")e.consume();else break}return o}};function Es(r){let e=r[0],o;if(e.type===6&&e.unit){if(c$4(e.unit)!=="time")return O("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 t=o<0?-1:1,n$1=Math.abs(o),i=Math.floor(n$1/7),a=n$1-i*7,m=t*(i*5+Math.min(a,5));return n(m)}var Ns=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Fe(r,e){return r.type===4?r.toNumber():O("DATE_FIELD_EXPECTED_DATE",`"${e}" expects a date, got ${g[r.type]??"an unsupported value"}`)}function Ts(r){let e=Fe(r[0],"weekday");return typeof e!="number"?e:t(Ns[new Date(e).getDay()])}var ys=["January","February","March","April","May","June","July","August","September","October","November","December"];function gs(r){let e=Fe(r[0],"month");return typeof e!="number"?e:t(ys[new Date(e).getMonth()])}function Ps(r){let e=Fe(r[0],"week");if(typeof e!="number")return e;let o=new Date(e),t=new Date(Date.UTC(o.getFullYear(),o.getMonth(),o.getDate())),n$1=t.getUTCDay()===0?7:t.getUTCDay();t.setUTCDate(t.getUTCDate()+4-n$1);let i=Date.UTC(t.getUTCFullYear(),0,1),a=Math.floor((t.getTime()-i)/864e5);return n(Math.floor(a/7)+1)}function qn(r){let e=new Date(r).getDay();return e===0||e===6}function _s(r){let e=Fe(r[0],"is a weekend");return typeof e!="number"?e:K$1(qn(e))}function As(r){let e=Fe(r[0],"is a workday");return typeof e!="number"?e:K$1(!qn(e))}function Os(r){return u$1(Math.abs(r[0].toNumber()-r[1].toNumber()),"ms")}function Rs(r){let e=r[0];if(e.type===4)return e;if(e.type===3){let o=c$5(e.value);return o===null?O("INVALID_ISO8601_STRING",`"${e.value}" is not a recognizable ISO8601 date/time string`):L(o)}return L(e$2(e.toNumber()))}function Is(r){let e=r[0];if(e.type===3){let o=c$5(e.value);return o===null?O("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 Jn=Es,no=Ts,io=gs,ao=Ps,ei=_s,ri=As,ti=Os,oi=Rs,ni=Is;function mo(r,e){return new Date(r,e+1,0).getDate()}function mi(r,e,o,t){let n=new Date(r,e,1).getDay(),a=1+(o-n+7)%7+(t-1)*7;return a<1||a>mo(r,e)?null:new Date(r,e,a).getTime()}function si(r,e,o){let t=mo(r,e),i=(new Date(r,e,t).getDay()-o+7)%7;return new Date(r,e,t-i).getTime()}function li(r,e){let o=new Date(r),t=new Date(e),n=t.getFullYear()-o.getFullYear();return (t.getMonth()<o.getMonth()||t.getMonth()===o.getMonth()&&t.getDate()<o.getDate())&&n--,n}function ii(r,e){let o=r.getFullYear(),t=r.getMonth()+e,n=o+Math.floor(t/12),i=(t%12+12)%12,a=Math.min(r.getDate(),mo(n,i));return new Date(n,i,a)}function ai(r){return Math.floor(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate())/864e5)}function ui(r,e){let o=new Date(r),t=new Date(e),n=(t.getFullYear()-o.getFullYear())*12+(t.getMonth()-o.getMonth());ii(o,n)>t&&n--;let i=ii(o,n),a=ai(t)-ai(i);return {years:Math.floor(n/12),months:n%12,days:a}}function ci(r,e){let o=new Date(r);return new Date(o.getFullYear(),o.getMonth()+e,1).getTime()}function gr(r,e){return r.type===4?r.toNumber():O("DATE_EXPECTED",`"${e}" expects a date, got ${g[r.type]??"an unsupported value"}`)}function Cs(r){let e=gr(r[0],"nth weekday of month");if(typeof e!="number")return e;let o=String(r[1].value??""),[t,n]=o.split(":"),i=Number(n),a=new Date(e),m=a.getFullYear(),l=a.getMonth();if(t==="last")return L(si(m,l,i));let u=Number(t),c=mi(m,l,i,u);return c===null?O("NTH_WEEKDAY_OUT_OF_RANGE",`there is no ${t}${hs(u)} occurrence of that weekday in the month`):L(c)}function hs(r){let e=r%100;if(e>=11&&e<=13)return "th";switch(r%10){case 1:return "st";case 2:return "nd";case 3:return "rd";default:return "th"}}function xs(r){let e=gr(r[0],"month anchor");if(typeof e!="number")return e;let o=r[1].toNumber();return L(ci(e,o))}var Ss="ymd";function Ls(r){let e=gr(r[0],"age of");if(typeof e!="number")return e;let o=gr(r[1],"age of");return typeof o!="number"?o:String(r[2].value??"years")===Ss?t(ws(ui(e,o))):u$1(li(e,o),"years")}function ws(r){let e=[];return r.years!==0&&e.push(yr(r.years,"year")),r.months!==0&&e.push(yr(r.months,"month")),r.days!==0&&e.push(yr(r.days,"day")),e.length===0?yr(0,"day"):e.join(", ")}function yr(r,e){return `${r} ${e}${Math.abs(r)===1?"":"s"}`}var pi=Cs,fi=xs,di=Ls;var vs={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},Ei="NTH_WEEKDAY",ks=c(Ei),Bs=/^(\d+)(st|nd|rd|th)$/i;function Ni(r=66){let e="datetime:nth-weekday";return {name:e,priority:r,match(o,t){let n=o[t];if(!n)return null;let i=null,a=0;if(n.type==="LAST")i="last",a=1;else {let f=o[t+1];if(!f||(n.sourceEnd??n.offset+(n.text?.length??0))!==f.offset)return null;let y=(n.text??"")+(f.text??""),T=Bs.exec(y);if(!T)return null;i=String(Number(T[1])),a=2;}let m=o[t+a],l=m?vs[m.type]:void 0;if(l===void 0||o[t+a+1]?.type!=="OF")return null;let u=`${i}:${l}`,c=new a$6(Ei,ks,u,u,n.offset,0,n.line,n.col);return {consumed:a+1,replacement:[c],ruleName:e}}}}function Ti(r=60){return {name:"datetime:until-since",priority:r,match(e,o){if(o+1>=e.length)return null;let t=e[o],n=e[o+1];if(t.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,t.value,[t,n])],ruleName:`datetime:${n.type.toLowerCase()}`}}}}function yi(r=60){return {name:"datetime:between-unit",priority:r,match(e,o){let t=o,n=0;e[o]?.value?.toLowerCase()==="how"&&e[o+1]?.value?.toLowerCase()==="many"&&(t=o+2,n=2);let i=e[t],a=e[t+1];if(!i||!a||i.type!=="UNIT")return null;let m=a.type==="BETWEEN",l=a.type==="UNTIL"||a.type==="SINCE";if(!m&&!l||l&&n===0)return null;let u=e.slice(o,t+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 gi(r=70){return {name:"datetime:workday-rate-denominator",priority:r,match(e,o){let t=e[o];if(t.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:[t,i,n],ruleName:"datetime:workday-rate-denominator"}}}}var Ms={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 Pi(r){return r===void 0||r.type!=="IDENT"&&r.type!=="UNIT"?0:Ms[(r.text??r.value??"").toLowerCase()]??0}var Ve=/^\d+$/;function Pr(r){return r.length===4}function _i(r=64){return {name:"datetime:month-name-date",priority:r,match(e,o){let t="datetime:month-name-date",n=e[o];if(n?.type==="NUMBER"&&Ve.test(n.text??"")){let c=Pi(e[o+1]);if(c===0)return null;let f=Number(n.text);if(f<1||f>31)return null;let N=e[o+2];return N?.type==="NUMBER"&&Ve.test(N.text??"")&&Pr(N.text??"")?g$1(f,c,Number(N.text),e.slice(o,o+3),t):g$1(f,c,new Date().getFullYear(),e.slice(o,o+2),t)}let i=Pi(n);if(i===0)return null;let a=e[o+1];if(a?.type!=="NUMBER"||!Ve.test(a.text??""))return null;if(Pr(a.text??""))return g$1(1,i,Number(a.text),e.slice(o,o+2),t);let m=Number(a.text),l=e[o+2],u=e[o+3];return l?.type==="COMMA"&&u?.type==="NUMBER"&&Ve.test(u.text??"")&&Pr(u.text??"")?g$1(m,i,Number(u.text),e.slice(o,o+4),t):l?.type==="NUMBER"&&Ve.test(l.text??"")&&Pr(l.text??"")?g$1(m,i,Number(l.text),e.slice(o,o+3),t):g$1(m,i,new Date().getFullYear(),e.slice(o,o+2),t)}}}var Us=93,Ds={q1:[1,3],q2:[4,6],q3:[7,9],q4:[10,12]};function so(r,e){return new Date(r,e,0).getDate()}function Fs(r){return so(r,2)===29?366:365}var _r=class{constructor(){this.category="Datetime";}parse(e,o,t){let n=this.readPeriodDays(e);t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(51),t.emitIndex(Us),t.emitIndex(1);}readPeriodDays(e){let o=e.peek(),t=(o?.text??o?.value??"").toLowerCase(),n=Ds[t];if(n!==void 0){e.consume();let a=this.readOptionalYear(e)??new Date().getFullYear(),m=0;for(let l=n[0];l<=n[1];l++)m+=so(a,l);return m}if(o?.type==="DATETIME_LITERAL"){e.consume();let a=new Date(Number(o.value));return so(a.getFullYear(),a.getMonth()+1)}let i=this.readOptionalYear(e);if(i!==null)return Fs(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 t=o.text??o.value??"";return /^\d{4}$/.test(t)?(e.consume(),Number(t)):null}};var Vs=new Set(["q1","q2","q3","q4"]),bs=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 Hs(r){if(r===void 0)return false;if(r.type==="DATETIME_LITERAL")return true;let e=(r.text??r.value??"").toLowerCase();return r.type==="IDENT"||r.type==="UNIT"?Vs.has(e)||bs.has(e):r.type==="NUMBER"&&/^\d{4}$/.test(r.text??"")}function Ai(r=60){return {name:"datetime:days-in-period",priority:r,match(e,o){let t=e[o];return t===void 0||(t.text??t.value??"").toLowerCase()!=="days"||t.type!=="UNIT"&&t.type!=="IDENT"||e[o+1]?.type!=="IN"||!Hs(e[o+2])?null:{consumed:2,replacement:[b$5("DAYS_IN_PERIOD","days in",[t,e[o+1]])],ruleName:"datetime:days-in-period"}}}}function Oi(){return {name:"datetime:daily-note-link",priority:80,match(r,e){return r[e]?.type!=="LBRACKET"||r[e+1]?.type!=="LBRACKET"||r[e+2]?.type!==f||r[e+3]?.type!=="RBRACKET"||r[e+4]?.type!=="RBRACKET"?null:{consumed:5,replacement:[r[e+2]],ruleName:"datetime:daily-note-link"}}}}var lo={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 _r,NOW:new te(0),TODAY:new te(0),TOMORROW:new te(1),YESTERDAY:new te(-1),NEXT:new Be("next"),LAST:new Be("last"),UNTIL_UNIT:new Me("until"),SINCE_UNIT:new Me("since"),WORKDAYS_IN:new lr,WORKDAYS_BETWEEN:new ur,WEEKDAY_ON:new G("weekdayOnDate","on"),WEEKDAY_IN:new G("weekdayOnDate","in"),MONTH_ON:new G("monthOnDate","on"),MONTH_IN:new G("monthOnDate","in"),WEEK_ON:new G("weekOnDate","on"),WEEK_IN:new G("weekOnDate","in"),BETWEEN_UNIT:new cr,CURRENT_TIMESTAMP:new pr,DATETIME_LITERAL:new Er,NTH_WEEKDAY:new Nr,AGE_OF:new Tr,MONTH_ANCHOR_NEXT:new Ee(1),MONTH_ANCHOR_THIS:new Ee(0),MONTH_ANCHOR_LAST:new Ee(-1)},infixParselets:{WORKDAYS_AFTER:new Ue("forward"),WORKDAYS_BEFORE:new Ue("backward"),TO_DATE:new fr,TO_TIMESTAMP:new dr,IS_WEEKEND:new De("isWeekendOnDate"),IS_WORKDAY:new De("isWorkdayOnDate")},normalizerRules:[Ti(),yi(),gi(),_i(),Ni(),Ai(),Oi()],pluginFunctions:{workdaysInDuration:Jn,weekdayOnDate:no,toDateFromAny:oi,toTimestampFromAny:ni,monthOnDate:io,weekOnDate:ao,isWeekendOnDate:ei,isWorkdayOnDate:ri,spanBetweenDates:ti,nthWeekdayOfMonth:pi,monthAnchorShift:fi,ageBetween:di},asConverters:{iso8601:r=>t(d(r.toNumber())),weekday:r=>no([r]),month:r=>io([r]),week:r=>ao([r])},tokenCategories:{NTH_WEEKDAY:"datetime",MONTH_ANCHOR_NEXT:"datetime",MONTH_ANCHOR_THIS:"datetime",MONTH_ANCHOR_LAST:"datetime",AGE_OF:"keyword"}};var zs={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"},uo={"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"},Gs={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"},Ri={...zs,...uo,...Gs};var co="UTCOFFSET:";function po(r){return `${co}${r}`}function be(r){return r.startsWith(co)}function He(r){return parseInt(r.slice(co.length),10)}function Ar(r,e){if(be(r))return He(r);let o=new Intl.DateTimeFormat("en-US",{timeZone:r,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),t={};for(let i of o.formatToParts(new Date(e)))t[i.type]=i.value;let n=Date.UTC(+t.year,+t.month-1,+t.day,+t.hour,+t.minute,+t.second);return Math.round((n-e)/6e4)}function Ci(r,e,o,t,n,i){let a=Date.UTC(r,e,o,t,n,0),m=Ar(i,a);return a-m*6e4}function fo(r,e){if(be(e)){let t=He(e)*6e4;return Ks(new Date(r+t))}return new Intl.DateTimeFormat("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",hour12:true}).format(new Date(r))}function hi(r,e){if(be(e)){let t=He(e)*6e4;return Ws(new Date(r+t))}return new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"long",day:"numeric"}).format(new Date(r))}function Ii(r,e){if(be(e)){let n=new Date(r+He(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"}),t={};for(let n of o.formatToParts(new Date(r)))t[n.type]=n.value;return {year:+t.year,month0:+t.month-1,day:+t.day}}function xi(r,e,o){let t=Ii(r,e),n=Ii(r,o),i=Date.UTC(t.year,t.month0,t.day),a=Date.UTC(n.year,n.month0,n.day);return Math.round((i-a)/864e5)}function Ks(r){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",hour:"numeric",minute:"2-digit",hour12:true}).format(r)}function Ws(r){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",year:"numeric",month:"long",day:"numeric"}).format(r)}function Eo(r){if(be(r)){let o=He(r),t=o>=0?"+":"-",n=Math.abs(o),i=Math.floor(n/60),a=n%60;return a===0?`UTC${t}${i}`:`UTC${t}${i}:${String(a).padStart(2,"0")}`}return (r.split("/").pop()??r).replace(/_/g," ")}function Q(r){let e=r.peek();if(!e)return null;let o=e.value,t=o.toLowerCase();if(t==="gmt"||t==="utc"){r.consume();let i=r.peek();if(i?.type==="PLUS"||i?.type==="MINUS"){let m=i.type==="MINUS";r.consume();let l=r.peek(),u;if(l?.type==="CLOCK_TIME")r.consume(),u=parseInt(l.value,10);else {let f=r.consume("NUMBER");if(u=parseInt(f.value,10)*60,r.peek()?.type==="COLON"){r.consume();let N=r.consume("NUMBER");u+=parseInt(N.value,10);}}let c=po(m?-u:u);return {zoneRef:c,displayName:Eo(c)}}let a=po(0);return {zoneRef:a,displayName:Eo(a)}}let n=Ri[t];if(n){r.consume();let i=o.replace(/\b\w/g,a=>a.toUpperCase());return {zoneRef:n,displayName:i}}return null}var Or="zoneConvert",No="timeInZone",To="dateInZone",Rr="timeDifference";function Si(r){let e=r[0].toNumber(),o=r[1].value,t$1=r[2].value,n=new Date,i=Ci(n.getFullYear(),n.getMonth(),n.getDate(),Math.floor(e/60),e%60,o),a=fo(i,t$1),m=xi(i,t$1,o);if(m===0)return t(a);let l=m>0?"+":"";return t(`${a} (${l}${m} day${Math.abs(m)===1?"":"s"})`)}function Li(r){let e=r[0].value;return t(fo(Date.now(),e))}function wi(r){let e=r[0].value;return t(hi(Date.now(),e))}function vi(r){let e=r[0].value,o=r[1].value,t$1=r[2].value,n=r[3].value,i=Date.now(),a=Ar(e,i),l=Ar(o,i)-a;if(l===0)return t(`${n} and ${t$1} currently share the same UTC offset`);let u=l>0?n:t$1,c=l>0?t$1:n,f=Math.abs(l),N=Math.floor(f/60),y=f%60,T=[];return N>0&&T.push(`${N} hour${N===1?"":"s"}`),y>0&&T.push(`${y} minute${y===1?"":"s"}`),t(`${u} is ${T.join(" ")} ahead of ${c}`)}var Ir=class{constructor(){this.category="Time";}parse(e,o,t){let n=parseInt(o.value,10),i=Q(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=Q(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")');t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(13),t.emitString(i.zoneRef),t.emitOpcode(13),t.emitString(a.zoneRef),t.emitPluginCall(Or,3);return}t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(120);}};var Cr=class{constructor(){this.category="Time";}parse(e,o,t){let[n,i]=o.value.split(":"),a=parseInt(n,10),m=parseInt(i,10),l=m>=a?m-a:1440-a+m;t.emitOpcode(10),t.emitNumber(l),t.emitOpcode(13),t.emitString("minutes"),t.emitOpcode(80);}};var hr=class{constructor(){this.category="Time";}parse(e,o,t){t.emitOpcode(10),t.emitNumber(parseFloat(o.value)),t.emitOpcode(13),t.emitString("frames/s"),t.emitOpcode(80);}};var xr=class{constructor(){this.category="Time";}parse(e,o,t){t.emitOpcode(10),t.emitNumber(parseFloat(o.value)),t.emitOpcode(13),t.emitString("s"),t.emitOpcode(80);}};function yo(r){return {category:"Time",parse(e,o,t){let n=Q(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")`);t.emitOpcode(13),t.emitString(n.zoneRef),t.emitPluginCall(r,1);}}}var Sr=class{constructor(){this.category="Time";}parse(e,o,t){let n=Q(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=Q(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")');t.emitOpcode(13),t.emitString(n.zoneRef),t.emitOpcode(13),t.emitString(i.zoneRef),t.emitOpcode(13),t.emitString(n.displayName),t.emitOpcode(13),t.emitString(i.displayName),t.emitPluginCall(Rr,4);}};var Lr=class{constructor(){this.category="Time";}parse(e,o,t){let[n,i,a,m]=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(m>=f)throw c$1.parsing("TIMECODE_FRAME_OUT_OF_RANGE",`Frame number ${m} is out of range for ${c} fps (must be 0-${f-1})`);let N=(n*3600+i*60+a)*f+m,y=z$1(c);if(e.peek()?.type==="IN"){e.consume();let T=e.peek();if(!T||T.type!=="IDENT"||T.value.toLowerCase()!=="frames")throw c$1.parsing("TIMECODE_EXPECTED_FRAMES",`Expected "frames" after "in" (e.g. "... in frames") but got ${T?`"${T.value}"`:"end of input"}`);e.consume(),y="frames";}t.emitOpcode(10),t.emitNumber(N),t.emitOpcode(13),t.emitString(y),t.emitOpcode(80);}};function ki(r,e){let o=Math.max(1,Math.round(e)),t=c=>String(c).padStart(2,"0"),n=Math.trunc(r),i=(n%o+o)%o,a=Math.floor(n/o),m=Math.floor(a/3600),l=Math.floor(a%3600/60),u=a%60;return `${t(m)}:${t(l)}:${t(u)}:${t(i)}`}var wr=class{constructor(){this.category="Time";}parse(e,o,t){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 m=parseFloat(a.value);t.emitOpcode(13),t.emitString(ki(n,m));return}t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(13),t.emitString("frames"),t.emitOpcode(80);}};function Bi(r,e,o){if(e<0||e>59)return null;if(o){if(r<1||r>12)return null;let t=o.toLowerCase()==="pm";return (r%12+(t?12:0))*60+e}return r<0||r>23?null:r*60+e}function Mi(r){return !!r&&r.type==="IDENT"&&/^(am|pm)$/i.test(r.value)}function Ui(r=65){return {name:"time:clock-time",priority:r,match(e,o){if(e$5(e,o))return null;let t=e[o];if(t.type!=="NUMBER")return null;let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>23)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=Mi(u),f=Bi(n,l,c?u.value:void 0);if(f===null)return null;let N=c?4:3;return {consumed:N,replacement:[b$5("CLOCK_TIME",String(f),e.slice(o,o+N))],ruleName:"time:clock-time"}}let m=e[o+1];if(Mi(m)){let l=Bi(n,0,m.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 Di(r=66){return {name:"time:clock-time-interval",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];return t.type!=="CLOCK_TIME"||n?.type!=="TO"||i?.type!=="CLOCK_TIME"?null:{consumed:3,replacement:[b$5("CLOCK_TIME_INTERVAL",`${t.value}:${i.value}`,e.slice(o,o+3))],ruleName:"time:clock-time-interval"}}}}function Fi(r=65){return {name:"time:fps-rate",priority:r,match(e,o){let t=e[o],n=e[o+1];return t.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="fps"?null:{consumed:2,replacement:[b$5("FPS_RATE",t.value,e.slice(o,o+2))],ruleName:"time:fps-rate"}}}}function Vi(r=70){return {name:"time:laptime",priority:r,match(e,o){if(e$5(e,o))return null;let t=e[o],n=e[o+1],i=e[o+2],a=e[o+3],m=e[o+4];if(t.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||m?.type!=="NUMBER")return null;let l=parseInt(t.value,10),u=parseInt(i.value,10),c=parseFloat(m.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 bi(r=75){return {name:"time:video-timecode",priority:r,match(e,o){if(e$5(e,o))return null;let t=e[o],n=e[o+1],i=e[o+2],a=e[o+3],m=e[o+4],l=e[o+5],u=e[o+6];if(t?.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||m?.type!=="NUMBER"||l?.type!=="COLON"||u?.type!=="NUMBER")return null;let c=parseInt(t.value,10),f=parseInt(i.value,10),N=parseInt(m.value,10),y=parseInt(u.value,10);return [c,f,N,y].some(T=>isNaN(T))||f<0||f>59||N<0||N>59||c<0||y<0?null:{consumed:7,replacement:[b$5("VIDEO_TIMECODE",`${c},${f},${N},${y}`,e.slice(o,o+7))],ruleName:"time:video-timecode"}}}}function Hi(r=65){return {name:"time:frame-count",priority:r,match(e,o){let t=e[o],n=e[o+1];return t.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="frames"?null:{consumed:2,replacement:[b$5("FRAME_COUNT",t.value,e.slice(o,o+2))],ruleName:"time:frame-count"}}}}var $s=14,Ys=[["week","weeks",604800],["day","days",86400],["hour","hours",3600],["minute","minutes",60],["second","seconds",1]];function zi(r){if(r.type===0)return r.toNumber();if(r.type!==6||r.unit===void 0)return null;let e=a$7[r.unit.toLowerCase()];return e===void 0||e[0]!==$s?null:r.toNumber()*e[1]}function Gi(r){let e=zi(r);if(e===null)return t(`"as timespan" needs a duration, got ${r.unit??"a non-duration"}`);let o=e<0,t$1=Math.abs(e),n=[];for(let[a,m,l]of Ys){if(l===1)break;let u=Math.floor(t$1/l);u>0&&(n.push(`${u} ${u===1?a:m}`),t$1-=u*l);}let i=Math.round(t$1*1e3)/1e3;return (i>0||n.length===0)&&n.push(`${i} ${i===1?"second":"seconds"}`),t((o?"-":"")+n.join(" "))}function Po(r){let e=zi(r);if(e===null)return t(`"as laptime" needs a duration, got ${r.unit??"a non-duration"}`);let o=e<0,t$1=Math.round(Math.abs(e)*1e3)/1e3,n=Math.floor(t$1/3600),i=Math.floor(t$1%3600/60),a=t$1%60,m=Math.floor(a),l=Math.round((a-m)*1e3),u=`${go(n)}:${go(i)}:${go(m)}`;return t((o?"-":"")+(l>0?`${u}.${String(l).padStart(3,"0")}`:u))}function go(r){return r<10?`0${r}`:String(r)}var _o={name:"solve-time",asConverters:{timespan:Gi,laptime:Po,lap:Po},phrases:{"time in":"TIME_IN","date in":"DATE_IN","time difference between":"TIME_DIFFERENCE_BETWEEN",...Object.fromEntries(Object.keys(uo).map(r=>[r,"CITY_NAME"]))},prefixParselets:{CLOCK_TIME:new Ir,CLOCK_TIME_INTERVAL:new Cr,FPS_RATE:new hr,LAPTIME:new xr,TIME_IN:yo(No),DATE_IN:yo(To),TIME_DIFFERENCE_BETWEEN:new Sr,VIDEO_TIMECODE:new Lr,FRAME_COUNT:new wr},normalizerRules:[Ui(),Di(),Fi(),Vi(),bi(),Hi()],pluginFunctions:{[Or]:Si,[No]:Li,[To]:wi,[Rr]:vi}};function vr(r){for(let e of r.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:r.category})}return {category:r.category,parse(e,o,t){let n=e.peek(),i=r.alternatives.find(m=>{let l=m.slots[0];return n!==void 0&&l.tokenTypes.includes(n.type)});if(!i){let m=r.alternatives.map(l=>l.slots[0].tokenTypes.join("|")).join(", ");throw c$1.parsing("NO_MATCHING_PHRASE_ALTERNATIVE",`Expected one of [${m}] but got "${n?.type??"end of input"}" ("${n?.value??""}")`,{category:r.category,expected:m,actualType:n?.type,actualValue:n?.value})}let a=[];for(let m of i.slots)if(m.kind==="keyword"){let l=e.peek();if(!l||!m.tokenTypes.includes(l.type))throw c$1.parsing("PHRASE_KEYWORD_MISMATCH",`Expected one of [${m.tokenTypes.join("|")}] but got "${l?.type??"end of input"}" ("${l?.value??""}")`,{category:r.category,expected:m.tokenTypes,actualType:l?.type,actualValue:l?.value});e.consume(),a.push({type:l.type,value:l.value});}else e.parseExpression(m.bindingPower??0,t);i.emit(t,a);}}}var js=37;function kr(r){r.emitOpcode(51),r.emitIndex(js),r.emitIndex(2);}var Xs=vr({category:"Dice",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:kr},{slots:[{kind:"keyword",tokenTypes:["FROM"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["TO"]},{kind:"expr"}],emit:kr},{slots:[{kind:"keyword",tokenTypes:["LPAREN"]},{kind:"expr"},{kind:"keyword",tokenTypes:["COMMA"]},{kind:"expr"},{kind:"keyword",tokenTypes:["RPAREN"]}],emit:kr}]}),Br=class{constructor(){this.category="Dice";}parse(e,o,t){let n=e.peek();if(n&&n.type==="NUMBER"){let i=e.consume();t.emitOpcode(10),t.emitNumber(parseFloat(i.value)),e.consume("MINUS");let a=e.consume();t.emitOpcode(10),t.emitNumber(parseFloat(a.value)),kr(t);return}Xs.parse(e,o,t);}};var Ao={name:"solve-dice",prefixParselets:{ROLL:new Br}};var Mr=class{constructor(){this.category="Variable";}parse(e,o,t){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,t),t.emitOpcode(61),t.emitString(i)):(t.emitOpcode(60),t.emitString(i));}};var ze=class{constructor(){this.category="Variable";}parse(e,o,t){t.emitOpcode(60),t.emitString(o.value);}};var Ur=class{constructor(){this.category="Variable";}parse(e,o,t){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,t),t.emitOpcode(63),t.emitString(i)):(t.emitOpcode(62),t.emitString(i));}};var Dr=class{constructor(){this.namespace="global-variables";this.pending=new Map;}preflight(e,o,t,n,i){let{opcodes:a,strings:m}=o,l=a.length,u=0;for(;u<l;){if(a[u]===62){let f=m[a[u+1]];if(!J.has(f))return this.pendingResultFor(f,t,n)}u=a$2(a,u);}return null}pendingResultFor(e,o,t){let n=this.pending.get(e);return n||(n=new Promise(i=>{let a=J.subscribe((m,l)=>{m===e&&(a(),this.pending.delete(e),i(l));});}),this.pending.set(e,n)),{queryKey:`global:${e}`,resolver:n,packageId:o,signal:t,metadata:{varName:e}}}destroy(){this.pending.clear();}};var Oo={name:"solve-variables",asyncResolvers:[new Dr],prefixParselets:{COLON:new Mr,IDENT:new ze,UNIT:new ze,GLOBAL:new Ur}};var Wi="currency-historical",oe="historicalCurrency",Qs=`solve-currency:${oe}`,Fr={NOT_CONFIGURED:"HISTORICAL_RATES_NOT_CONFIGURED",QUERY_FAILED:"HISTORICAL_RATE_QUERY_FAILED",NOT_PREFLIGHTED:"HISTORICAL_RATE_NOT_PREFLIGHTED",INVALID_OPERAND:"HISTORICAL_CURRENCY_INVALID_OPERAND"},Zs=3e4,$i=1/0,qs=1e4;function Ro(r,e,o){return [Wi,`${r.toUpperCase()}:${e.toUpperCase()}:${o}`]}function Ki(r){return r<10?`0${r}`:String(r)}function Vr(r,e,o){if(!c$3.isCurrency(e)||o!==void 0&&!c$3.isCurrency(o))return null;let t=r.peek();if(!t||t.type!=="IDENT"||t.value.toLowerCase()!=="on")return null;let n=r.peekAt(1);if(!n||n.type!=="DATETIME_LITERAL")return null;r.consume(),r.consume();let i=new Date(Number(n.value));return `${i.getFullYear()}-${Ki(i.getMonth()+1)}-${Ki(i.getDate())}`}async function Yi(r,e,o,t,n$1,i){let a=e.toUpperCase(),m=o.toUpperCase();if(!r)return O(Fr.NOT_CONFIGURED,`Historical exchange rates are not configured. Supply historicalRateProvider via createCurrencyPackage({ ... }) to convert ${a} to ${m} on ${t}.`);let{signal:l,cleanup:u}=a$3(n$1,qs,"Historical currency rate fetch");try{let c=await r(a,m,t,l);return n(c)}catch(c){let f=O(Fr.QUERY_FAILED,`Failed to resolve the historical rate for ${a} to ${m} on ${t}: ${c instanceof Error?c.message:String(c)}`),N=Ro(e,o,t);return setTimeout(()=>{i.getQueryData(N)===f&&i.removeQueries({queryKey:N,exact:true});},Zs).unref?.(),f}finally{u();}}function Io(r){return e=>{let o=e[0],t=e[1],n=e[2],i=P(o);if(i)return i;if(o.type!==6||o.unit===void 0||!c$3.isCurrency(o.unit))return O(Fr.INVALID_OPERAND,'Historical conversion needs an amount in a currency, for example "100 USD in GBP on 2024-01-15".');let a=o.unit,m=String(t.value),l=String(n.value);if(a.toUpperCase()===m.toUpperCase())return u$1(o.toNumber(),m);let u=b$4(),c=Ro(a,m,l),f=u?.getQueryData(c);if(f===void 0)return u?u.fetchQuery({queryKey:c,queryFn:({signal:y})=>Yi(r,a,m,l,y,u),staleTime:$i}):O(Fr.NOT_PREFLIGHTED,`No historical rate resolved for ${a.toUpperCase()} to ${m.toUpperCase()} on ${l}.`);if(f.type===13)return f;let N=f.value;return u$1(o.toNumber()*N,m)}}function ji(r){return {namespace:Wi,preflight(e,o,t,n,i){let{opcodes:a,strings:m}=o,l=a.length,u=F$1(Qs),c=0,f=[];for(;c<l;){let N=a[c];if(N===13)f.push(a[c+1]);else if(N===50){let y=a[c+1],T=a[c+2];if(y===u&&T===3&&f.length>=3){let A=m[f[f.length-1]],B=m[f[f.length-2]],S=new Set;for(let H=0;H<f.length-2;H++){let $=m[f[H]];c$3.isCurrency($)&&S.add($.toUpperCase());}if(S.size===1){let H=S.values().next().value;if(H!==B.toUpperCase()){let $=Ro(H,B,A);if(i.getQueryData($)===void 0){let Kt=i.fetchQuery({queryKey:$,queryFn:({signal:le})=>Yi(r,H,B,A,le,i),staleTime:$i});return {queryKey:$.join(":"),resolver:Kt,packageId:t,signal:n,metadata:{from:H,to:B,isoDate:A}}}}}}f=[];}c=a$2(a,c);}return null},destroy(){}}}function Xi(r){return ta$1(r)??r}var br=class{constructor(){this.category="UoM";this.bindingPower=a.Postfix;}parse(e,o,t,n){let i=Xi(t.value);if(n.emitOpcode(13),n.emitString(i),!(e.infixMinBindingPower>=a.Product)&&(e.peek()?.type==="TO"||e.peek()?.type==="IN")){e.consume();let m=e.peek();if(m?.type==="UNIT"||m?.type==="IN"){e.consume();let l=Xi(m.value),u=Vr(e,l,i);if(u!==null){n.emitOpcode(80),n.emitOpcode(13),n.emitString(l),n.emitOpcode(13),n.emitString(u),n.emitPluginCall(oe,3);return}n.emitOpcode(13),n.emitString(l),n.emitOpcode(81);return}if(m?.type==="QUESTION"){e.consume(),n.emitOpcode(85);return}}if(e.peek()?.type==="BEST"){e.consume(),n.emitOpcode(83);return}n.emitOpcode(80);}};function Co(r){return ta$1(r)??r}var Hr=class{constructor(){this.category="UoM";}parse(e,o,t){e.parseExpression(a.Postfix,t);let n=e.peek();if(n&&n.type==="UNIT"){if(e.consume(),t.emitOpcode(13),t.emitString(Co(n.value)),e.peek()?.type==="TO"){e.consume("TO");let i=e.consume();i?.type==="UNIT"?(t.emitOpcode(13),t.emitString(Co(i.value)),t.emitOpcode(81)):i?.type==="BEST"&&t.emitOpcode(83);}else t.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(),t.emitOpcode(13),t.emitString(Co(i.value)),t.emitOpcode(84)):i?.type==="BEST"&&(e.consume(),t.emitOpcode(83));return}}};var zr=class{constructor(){this.category="UoM";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitOpcode(85);}};function Qi(r=60){return {name:"uom:possibilities",priority:r,match(e,o){if(o+2>=e.length)return null;let t=e[o],n=e[o+1],i=e[o+2];return t.type!=="UNIT"||n.type!=="TO"||i.type!=="QUESTION"?null:{consumed:3,replacement:[b$5("UOM_POSSIBILITIES_QUERY",t.value,[t,n,i])],ruleName:"uom:possibilities"}}}}var Zi=14;function qi(r,e){if(r===void 0||r.type!=="UNIT")return;let o=(r.value??"").toLowerCase();if(o==="m"&&e===Zi)return {kind:Zi,ratio:60,spelling:"minutes"};let t=a$7[o];return t===void 0?void 0:{kind:t[0],ratio:t[1],spelling:o}}var Ji=/^\d+(\.\d+)?$/;function ea(r=63){return {name:"uom:compound-quantity",priority:r,match(e,o){let t=e[o];if(t?.type!=="NUMBER"||!Ji.test(t.text??""))return null;let n=qi(e[o+1]);if(n===void 0)return null;let i=n.kind,a=n.ratio,m=Number(t.text)*a,l=n.spelling,u=e[o+1],c=2;for(;;){let y=e[o+c];if(y?.type!=="NUMBER"||!Ji.test(y.text??""))break;let T=qi(e[o+c+1],i);if(T===void 0||T.kind!==i||T.ratio>=a)break;m+=Number(y.text)*T.ratio,a=T.ratio,l=T.spelling,u=e[o+c+1],c+=2;}if(c===2)return null;let f=e.slice(o,o+c),N=m/a;return {consumed:c,replacement:[b$5("NUMBER",String(N),f),b$5("UNIT",l,[u])],ruleName:"uom:compound-quantity"}}}}function ra(r){return r===void 0||r.type!=="UNIT"?false:a$7[(r.value??"").toLowerCase()]!==void 0}function ta(r=59){return {name:"uom:two-unit-conversion",priority:r,match(e,o){let t=e[o];if(t?.type!=="IN"&&t?.type!=="TO"||!ra(e[o+1])||e[o+2]?.type!=="AND_CONJ"||!ra(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 oa(r=74){return {name:"uom:degree-symbol",priority:r,match(e,o){let t=e[o];if(t?.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:[t,b$5("UNIT","degrees",[n])],ruleName:"uom:degree-symbol"}}}}var Gr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Conditional;}parse(e,o,t,n){let[i,a]=String(t.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 na(r){return r===void 0||r.type!=="UNIT"?false:a$7[(r.value??"").toLowerCase()]!==void 0}var ho=new Set(["per","a","an","each","every"]);function Js(r){if(r===void 0||r.type!=="IDENT")return false;let e=(r.text??r.value??"").toLowerCase();return ho.has(e)?false:/^[a-z][a-z_]{2,}$/.test(e)&&a$7[e]===void 0}function ia(r=75){return {name:"uom:bare-rate-denominator",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;if(t.type==="NUMBER"&&Js(e[o+1])){let l=e[o+1],u=e[o+2];if((u?.type==="SLASH"||u?.type==="IDENT"&&ho.has((u.text??u.value??"").toLowerCase()))&&na(e[o+3]))return {consumed:2,replacement:[t,b$5("UNIT",l.value,[l])],ruleName:"uom:bare-rate-denominator"}}if(!na(e[o+1]))return null;let n=t.type==="SLASH",i=(t.text??t.value??"").toLowerCase(),a=t.type==="IDENT"&&ho.has(i);if(!n&&!a)return null;let m=e[o+1];return {consumed:2,replacement:[b$5("PER_UNIT",m.value,[t,m])],ruleName:"uom:bare-rate-denominator"}}}}var Kr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,t,n){n.emitOpcode(13),n.emitString(String(t.value)),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var Wr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};function el(r){return r===void 0||r.type!=="UNIT"?false:a$7[(r.value??"").toLowerCase()]!==void 0}var rl=new Set(["per","a","an","each","every"]);function tl(r,e){for(let o=e;o<r.length&&o<e+5;o++){let t=r[o];if(t.type==="PER_UNIT")return true;if(t.type==="EOF"||t.type==="COMMA"||t.type==="RATE_AT")return false;let n=(t.text??t.value??"").toLowerCase();if((t.type==="SLASH"||t.type==="IDENT"&&rl.has(n))&&el(r[o+1]))return true}return false}function aa(r=73){return {name:"uom:at-rate",priority:r,match(e,o){return e[o]?.type!=="RATE_AT"||!tl(e,o+1)?null:{consumed:1,replacement:[b$5("AT_RATE","at",[e[o]])],ruleName:"uom:at-rate"}}}}function ol(r){return r===void 0||r.type!=="UNIT"?false:a$7[(r.value??"").toLowerCase()]!==void 0}var nl=new Set(["a","an"]);function ma(r=76){return {name:"uom:for-duration",priority:r,match(e,o){let t=e[o];if(t?.type!=="FOR_DURATION")return null;let n=e[o+1];return n?.type!=="IDENT"||!nl.has((n.text??n.value??"").toLowerCase())||!ol(e[o+2])?null:{consumed:3,replacement:[b$5("STAR","*",[t]),b$5("NUMBER","1",[n]),e[o+2]],ruleName:"uom:for-duration"}}}}function xo(r){return r===void 0||r.type!=="UNIT"?false:a$7[(r.value??"").toLowerCase()]!==void 0}var il=new Set(["a","an"]);function sa(r=61){return {name:"uom:reversed-conversion",priority:r,match(e,o){if(o!==0||!xo(e[o])||e[o+1]?.type!=="IN")return null;let t=e[o],n=e[o+2];if(n===void 0)return null;if(n.type==="NUMBER"&&xo(e[o+3]))return {consumed:4,replacement:[n,e[o+3],e[o+1],t],ruleName:"uom:reversed-conversion"};let i=(n.text??n.value??"").toLowerCase();return n.type==="IDENT"&&il.has(i)&&xo(e[o+3])?{consumed:4,replacement:[b$5("NUMBER","1",[n]),e[o+3],e[o+1],t],ruleName:"uom:reversed-conversion"}:null}}}var al={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},la=2;function ua(r){return al[r.toLowerCase().trim()]}var $r="cookingConvert";function ca(r){let e=r[0],o=r[1].value,t=r[2].value;if(e.type!==6||!e.unit)return O("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),m=c$4(t),l=y=>y==="mass"||y==="volume";if(!l(a))return O("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${n}" is not a recognized mass or volume unit`);if(!l(m))return O("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${t}" is not a recognized mass or volume unit`);if(a===m)return u$1(e$1(i,n,t),t);let u=ua(o);if(u===void 0)return O("COOKING_UNKNOWN_INGREDIENT",`No density data for "${o}" \u2014 cannot convert between mass and volume for this ingredient`);if(a==="mass"){let T=e$1(i,n,"g")/u,A=e$1(T,"ml",t);return u$1(A,t)}let f=e$1(i,n,"ml")*u,N=e$1(f,"g",t);return u$1(N,t)}var Yr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,t,n){let i=t.value;e.consume("IN");let a=e.consume();n.emitOpcode(13),n.emitString(i),n.emitOpcode(13),n.emitString(a.value),n.emitPluginCall($r,3);}};function pa(r=68){return {name:"uom-cooking:ingredient-name",priority:r,match(e,o){let t=e[o-1];if(!t||t.type!=="UNIT")return null;for(let n=la;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,m=e[a];if(!m||m.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 fa(r=78){return {name:"uom:multi-word-unit",priority:r,match(e,o){let t=e[o],n=e[o+1];if(t?.type!=="UNIT"||n?.type!=="UNIT"||t.offset+t.text.length+1!==n.offset)return null;let i=`${t.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 da(r=77){return {name:"uom:compound-unit",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];if(t?.type!=="UNIT"||n?.type!=="SLASH"||i?.type!=="UNIT")return null;let a=`${t.value}/${i.value}`;return {consumed:3,replacement:[b$5("UNIT",a,[t,n,i])],ruleName:"uom:compound-unit"}}}}var So={name:"solve-uom",prefixParselets:{CONVERT:new Hr,UOM_POSSIBILITIES_QUERY:new zr},infixParselets:{IN_TWO_UNITS:new Gr(94),PER_UNIT:new Kr(95),AT_RATE:new Wr(96),UNIT:new br,INGREDIENT_NAME:new Yr},normalizerRules:[fa(),da(),Qi(),ea(),ta(),oa(),aa(),ma(),ia(),sa(),pa()],pluginFunctions:{[$r]:ca}};var V=class{constructor(){this.category="UoM";}parse(e,o,t){let n=ta$1(o.value)??o.value.toUpperCase();e.parseExpression(a.Prefix,t),e.peek()?.type==="UNIT"&&e.consume(),t.emitOpcode(13),t.emitString(n),t.emitOpcode(80);}};var jr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,t,n){let i=e.peek();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$1(i.value)??i.value,m=Vr(e,a);if(m!==null){n.emitOpcode(13),n.emitString(a),n.emitOpcode(13),n.emitString(m),n.emitPluginCall(oe,3);return}n.emitOpcode(13),n.emitString(a),n.emitOpcode(84);}}};function Lo(r={}){return {name:"solve-currency",asyncResolvers:[new b$2,ji(r.historicalRateProvider)],prefixParselets:{DOLLAR:new V,POUND:new V,EURO:new V,YEN:new V,RUBLE:new V,WON:new V,CURRENCY_SYMBOL:new V},infixParselets:{IN:new jr},pluginFunctions:{[oe]:Io(r.historicalRateProvider)}}}var wo=Lo();var Ne=class{constructor(e=0){this.category="Vector";this.dimension=e;}parse(e,o,t){e.consume("LPAREN");let n=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(0,t),n++;e.match("COMMA");)e.parseExpression(0,t),n++;e.consume("RPAREN"),t.emitOpcode(152),t.emitIndex(1),t.emitIndex(this.dimension>0?this.dimension:n);}};var Xr=class{constructor(){this.category="Float";}parse(e,o,t){e.consume("LPAREN"),e.parseExpression(0,t),e.consume("RPAREN"),t.emitOpcode(152),t.emitIndex(1),t.emitIndex(1);}};var vo={name:"solve-vector",prefixParselets:{VEC2:new Ne(2),VEC3:new Ne(3),VEC4:new Ne(4),FLOAT:new Xr}};var Qr=class{constructor(){this.category="Matrix";}parse(e,o,t){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,t),a++;e.match("COMMA");)e.parseExpression(0,t),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"),t.emitOpcode(152),t.emitIndex(n),t.emitIndex(i);}};var Zr=class{constructor(){this.category="Matrix";this.bindingPower=a.Postfix;}parse(e,o,t,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 t=0;;t++){let n=e.peekAt(t);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,t){e.parseExpression(0,o);let n=false;e.match("COLON")&&(e.parseExpression(0,o),n=true),t&&(n||o.emitOpcode(3),o.emitOpcode(156));}};var ko={name:"solve-matrix",prefixParselets:{LBRACKET:new Qr},infixParselets:{LBRACKET:new Zr}};function qr(r,e){let o=r.peek(),t=r.peekAt(1);if(o&&(o.type==="IDENT"||o.type==="UNIT"||o.type==="FUNC")&&t?.type==="COMMA"){r.consume();let a=o.value,m=to[a.toLowerCase()];return m!==void 0?{kind:1,builtinIdx:m}:{kind:2,name:a}}let n=new d$1(e.pluginIndexMap);r.parseExpression(a.Lowest,n),r.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 Ea(r){let e=r.peek(),o=r.peekAt(1);return !!e&&(e.type==="IDENT"||e.type==="UNIT")&&o?.type==="EQUALS"}function Na(r){let e=r.peek();if(e&&(e.type==="IDENT"||e.type==="UNIT"))return r.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 K(r,e){r.parseExpression(0,e),r.match("COLON")&&(r.parseExpression(0,e),e.emitOpcode(156));}function Z(r,e,o,t,n){if(r.emitOpcode(e),r.emitIndex(o.kind),o.kind===0){let i=r.emitAnonymousBody(t,o.program);r.emitIndex(i);}else o.kind===1?r.emitIndex(o.builtinIdx):r.emitString(o.name);r.emitIndex(n);}var Jr=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=qr(e,t);e.consume("COMMA");let i=[];if(Ea(e))do{let a=Na(e);e.consume("EQUALS"),K(e,t),i.push(a);}while(e.match("COMMA"));else K(e,t),i.push("x");e.consume("RPAREN"),Z(t,157,n,i,i.length);}};var et=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=qr(e,t);e.consume("COMMA"),K(e,t);let i=0;e.match("COMMA")&&(e.parseExpression(a.Lowest,t),i=1),e.consume("RPAREN"),Z(t,158,n,["acc","x"],i);}};var rt=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=new d$1(t.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(t),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"),K(e,t),e.consume("RPAREN"),t.emitOpcode(10),t.emitNumber(0),Z(t,158,{kind:0,program:i},["acc","x"],1);}};var tt=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=new d$1(t.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(t),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"),K(e,t),e.consume("RPAREN"),t.emitOpcode(10),t.emitNumber(1),Z(t,158,{kind:0,program:i},["acc","x"],1);}};var ml={map:"MAP",reduce:"REDUCE",sum:"SUM_FN",prod:"PROD_FN"};function sl(r,e){return r?!!(r.type==="LINE_REF"||r.type==="IDENT"&&(/^line\d+$/i.test(r.value)||/^line$/i.test(r.value)&&e?.type==="NUMBER"&&/^\d+$/.test(e.value))):false}function Ta(r=80){return {name:"mapreduce:call",priority:r,match(e,o){let t=e[o];if(!t||t.type!=="IDENT")return null;let n=t.value.toLowerCase(),i=ml[n];return !i||e[o+1]?.type!=="LPAREN"||n==="sum"&&sl(e[o+2],e[o+3])?null:{consumed:1,replacement:[new a$6(i,c(i),t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"mapreduce:call"}}}}var Bo={name:"solve-mapreduce",normalizerRules:[Ta()],prefixParselets:{MAP:new Jr,REDUCE:new et,SUM_FN:new rt,PROD_FN:new tt}};var ot=class{constructor(){this.category="BigInt";}parse(e,o,t){t.emitOpcode(11),t.emitString(e$3(o.value,e.getLocaleCode()));}};var Mo={name:"solve-bigint",prefixParselets:{BIGINT:new ot}};var W=class{constructor(e){this.opcode=e;this.category="Conditionals";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var Te=class{constructor(e,o){this.opcode=e;this.bindingPower=o;this.category="Conditionals";}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var Ge=class{constructor(e){this.value=e;this.category="Conditionals";}parse(e,o,t){t.emitOpcode(14),t.emitByte(this.value?1:0);}};var nt=class{constructor(){this.category="Conditionals";}parse(e,o,t){e.parseExpression(0,t),e.consume("THEN"),e.parseExpression(0,t),e.consume("ELSE"),e.parseExpression(0,t),t.emitOpcode(132);}};var Uo={name:"solve-conditionals",prefixParselets:{TRUE:new Ge(true),FALSE:new Ge(false),IF:new nt},infixParselets:{EQUALITY:new W(40),NEQ:new W(41),LT:new W(42),GT:new W(44),LTE:new W(43),GTE:new W(45),OR:new Te(131,a.LogicalOr),LOGICAL_AND:new Te(130,a.LogicalAnd),LOGICAL_OR:new Te(131,a.LogicalOr)}};var ll={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},ya={2:143,8:144,16:71},it=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,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=ya[u];if(c===void 0)throw c$1.parsing("AS_CONVERTER_UNSUPPORTED_BASE",`"as base ${l?.value??"?"}": only bases ${Object.keys(ya).join(", ")} can be written out`);e.consume(),n.emitOpcode(c);return}let m=ll[a$1];if(m!==void 0){m===141&&e.match("OF")&&(e.parseExpression(a.Conditional,n),n.emitOpcode(23)),n.emitOpcode(m);return}n.emitOpcode(13),n.emitString(a$1),n.emitOpcode(145);}};var ga={ten:10,hundred:100,thousand:1e3,million:1e6,billion:1e9};function Pa(r,e,o){r.emitOpcode(10),r.emitNumber(e),r.emitOpcode(23),_a(r,o),r.emitOpcode(10),r.emitNumber(e),r.emitOpcode(22);}function _a(r,e){let o=e==="up"?cl:e==="down"?pl:ul;r.emitOpcode(51),r.emitIndex(o),r.emitIndex(1);}var ul=8,cl=6,pl=7,fl=97;function dl(r){let o=(r.peek()?.text??"").toLowerCase();return o==="up"?(r.consume(),"up"):o==="down"?(r.consume(),"down"):"nearest"}var at=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){let i=dl(e);if(e.match("TO_NEAREST")){Pa(n,Aa(e),i);return}_a(n,i);}},mt=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){Pa(n,Aa(e),"nearest");}};function Aa(r){let e=r.peek(),o=(e?.text??"").toLowerCase(),t=ga[o];if(t!==void 0)return r.consume(),t;if(e?.type==="NUMBER"){r.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(ga).join(", ")}`)}var st=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){let i=Number(t.value);if(!Number.isFinite(i)||i<0||i>100)throw c$1.parsing("INVALID_DECIMAL_PLACES",`"to ${t.value} dp": expected a place count between 0 and 100`);n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(51),n.emitIndex(fl),n.emitIndex(2);}};var El=new Set(["dp","dps","decimals","digits","digit"]),Nl=new Set(["decimal"]);function Oa(r=66){return {name:"converters:decimal-places",priority:r,match(e,o){if(e[o]?.type!=="TO")return null;let t=e[o+1];if(t?.type!=="NUMBER")return null;let n=e[o+2];if(!n)return null;let i=(n.text??n.value??"").toLowerCase(),a=3;if(Nl.has(i)){let l=(e[o+3]?.text??"").toLowerCase();if(l!=="place"&&l!=="places")return null;a=4;}else if(!El.has(i))return null;return {consumed:a,replacement:[b$5("DECIMAL_PLACES",t.value,e.slice(o,o+a))],ruleName:"converters:decimal-places"}}}}var Tl=new Set(["hex","bin"]);function Ra(r=67){return {name:"converters:preposition",priority:r,match(e,o){let t=e[o];if(t?.type!=="IN"&&t?.type!=="TO")return null;let n=e[o+1];return n?.type==="CONVERTER_NAME"||n?.type==="FUNC"&&Tl.has(n.value.toLowerCase())?{consumed:1,replacement:[b$5("AS","as",[t])],ruleName:"converters:preposition"}:null}}}var Do={name:"solve-converters",phrases:{"to nearest":"TO_NEAREST","to the nearest":"TO_NEAREST"},infixParselets:{AS:new it,ROUNDED:new at,TO_NEAREST:new mt,DECIMAL_PLACES:new st},normalizerRules:[Oa(),Ra()]};var k=class{constructor(e){this.builtinIndex=e;this.category="MathPhrases";}parse(e,o,t){let n=0;for(e.parseExpression(a.Conjunction,t),n++;e.match("COMMA")||e.match("AND_CONJ");)e.parseExpression(a.Conjunction,t),n++;t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(n);}};var lt=class{constructor(e){this.builtinIndex=e;this.category="MathPhrases";}parse(e,o,t){let n=0;do{if(e.parseExpression(a.Conjunction,t),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,t),n++,this.skipWeightLabel(e);}while(e.match("COMMA")||e.match("AND_CONJ"));t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.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 Fo(r){return {category:"MathPhrases",parse(e,o,t){e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(r),t.emitIndex(1);}}}var Ca={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Product,o),!r.match("DIVIDE_BY")&&!r.match("SLASH"))throw c$1.parsing("REMAINDER_EXPECTED_DIVIDED_BY",'Expected "divided by" or "/", as in "remainder of 21 divided by 5"');r.parseExpression(a.Product,o),o.emitOpcode(24);}},ha={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Product,o),!r.match("OF"))throw c$1.parsing("ROOT_EXPECTED_OF",'Expected "of", as in "root 5 of 100"');r.parseExpression(a.Conditional,o),o.emitOpcode(2),o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(23),o.emitOpcode(25);}},xa={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Conditional,o),Ia(o),!r.match("LOG_BASE"))throw c$1.parsing("LOG_EXPECTED_BASE",'Expected "base", as in "log 20 base 4"');r.parseExpression(a.Conditional,o),Ia(o),o.emitOpcode(23);}},yl=5;function Ia(r){r.emitOpcode(51),r.emitIndex(yl),r.emitIndex(1);}function Sa(r=69){return {name:"mathphrases:function-phrase",priority:r,match(e,o){let t=e[o];if(t?.type!=="FUNC")return null;let n=(t.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",[t])],ruleName:"mathphrases:function-phrase"};let i=gl(e,o+1);if(i===-1)return null;let a=e.slice(o,i+1).map((m,l)=>l===0?b$5("LOG_PHRASE","log",[m]):l===i-o?b$5("LOG_BASE","base",[m]):m);return {consumed:i-o+1,replacement:a,ruleName:"mathphrases:function-phrase"}}}}function gl(r,e){for(let o=e;o<r.length&&o<e+8;o++){let t=r[o];if(t.type==="EOF"||t.type==="COMMA"||t.type==="RPAREN")return -1;if((t.text??t.value??"").toLowerCase()==="base")return o}return -1}function Ke(r){return {category:"MathPhrases",parse(e,o,t){e.parseExpression(a.Conjunction,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(r),t.emitIndex(2);}}}var La={category:"MathPhrases",parse(r,e,o){r.parseExpression(a.Lowest,o),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var wa={category:"MathPhrases",parse(r,e,o){r.parseExpression(a.Conjunction,o),r.consume("AND_CONJ"),r.parseExpression(a.Lowest,o),o.emitOpcode(20),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var va=vr({category:"MathPhrases",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:r=>{r.emitOpcode(51),r.emitIndex(37),r.emitIndex(2);}}]});var Pl=47,ut=class{constructor(){this.category="MathPhrases";}parse(e,o,t){e.parseExpression(a.Lowest,t);let n=e.peek();if(n?.type==="BETWEEN")e.consume(),e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t);else if(n?.type==="FROM")e.consume(),e.parseExpression(a.Lowest,t),e.consume("TO"),e.parseExpression(a.Lowest,t);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"}`);t.emitOpcode(51),t.emitIndex(Pl),t.emitIndex(3);}};var _l=46,ct=class{constructor(){this.category="MathPhrases";this.bindingPower=a.Conditional;}parse(e,o,t,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(_l),n.emitIndex(3);}};var Al=42,Ol=43,Rl=44,Il=45,Cl=9,hl=10,xl=101,Sl=102,Ll=103,wl=104,vl=105,kl=106,Bl=107,Ml=38,Ul=39,Dl=0,Fl=21,Vo={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 k(Al),MEDIAN_OF:new k(Ol),TOTAL_OF:new k(Rl),COUNT_OF:new k(Il),LARGER_OF:Ke(hl),SMALLER_OF:Ke(Cl),HALF_OF:La,MIDPOINT_BETWEEN:wa,RANDOM_NUMBER:va,REMAINDER_OF:Ca,NTH_ROOT:ha,LOG_PHRASE:xa,GCD_OF:Ke(Ml),LCM_OF:Ke(Ul),SQUARE_ROOT_OF:Fo(Dl),CUBE_ROOT_OF:Fo(Fl),CLAMP:new ut,STANDARD_DEVIATION_OF:new k(xl),SAMPLE_STANDARD_DEVIATION_OF:new k(Sl),VARIANCE_OF:new k(Ll),SAMPLE_VARIANCE_OF:new k(wl),SPREAD_OF:new k(vl),MODE_OF:new k(kl),WEIGHTED_AVERAGE_OF:new lt(Bl)},infixParselets:{IS_TO:new ct},normalizerRules:[Sa()]};var ka={annually:1,yearly:1,"semi-annually":2,quarterly:4,monthly:12,fortnightly:26,weekly:52,daily:365};function bo(r){if(!r.match("COMPOUNDING"))return 1;let e=r.peek(),o=(e?.text??e?.value??"").toLowerCase(),t=ka[o];if(t===void 0)throw c$1.parsing("UNKNOWN_COMPOUNDING_INTERVAL",`compounding ${o||"?"}: expected one of ${Object.keys(ka).join(", ")}`);return r.consume(),t}var We=class{constructor(e,o){this.annualIndex=e;this.intervalIndex=o;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,n);let i=bo(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);}},pt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,t),t.emitOpcode(2),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}},ft=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.consume("RETURNED"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}},dt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),e.consume("INVESTED"),e.parseExpression(a.Conditional,t),e.consume("RETURNED"),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,t),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}};function Et(r,e,o){return Ma(r,o)?(r.parseExpression(a.Lowest,e),Ba(r),r.parseExpression(a.Lowest,e),{swap:true}):(Ba(r),r.parseExpression(a.Lowest,e),Vl(r,o),r.parseExpression(a.Lowest,e),{swap:false})}function Ma(r,e){for(let o of e)if(r.match(o))return true;return false}function Vl(r,e){Ma(r,e)||r.consume(e[0]);}function Ba(r){r.match("RATE_AT")||r.consume("AT");}var $e=class{constructor(e,o){this.builtinIndex=e;this.intervalIndex=o;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t);let{swap:n}=Et(e,t,["AFTER","FOR_DURATION","OVER"]),i=bo(e);if(n&&t.emitOpcode(2),i===1){t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);return}t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(51),t.emitIndex(this.intervalIndex),t.emitIndex(4);}};var D=class{constructor(e,o){this.builtinIndex=e;this.periodsPerYear=o;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t);let{swap:n}=Et(e,t,["OVER"]);n&&t.emitOpcode(2),t.emitOpcode(10),t.emitNumber(this.periodsPerYear),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(4);}};var Nt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t),e.consume("BETWEEN"),e.parseExpression(a.Lowest,t),e.match("PEOPLE"),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(2);}},Tt=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.consume("WAYS"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var Ua={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 bl(r){let e=r.peek(),o=(e?.text??e?.value??"").toLowerCase(),t=Ua[o];if(t===void 0)throw c$1.parsing("UNKNOWN_SAVINGS_PERIOD",`savings goal: expected a contribution period, one of ${Object.keys(Ua).join(", ")}, not "${o||"?"}".`);return r.consume(),t}var yt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Product,t),e.match("STAR");let n=bl(e);t.emitOpcode(10),t.emitNumber(n.perYear),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,t):(t.emitOpcode(10),t.emitNumber(0)),t.emitOpcode(13),t.emitString(n.unit),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(5);}},gt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("IN"),e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,t):(t.emitOpcode(10),t.emitNumber(0)),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}};var ye=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t),e.consume("RATE_AT"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(2);}};var Hl=60;function zl(r){for(let e=0;;e++){let o=r.peekAt(e);if(!o)return false;if(o.type==="FROM"||o.type==="WORTH_IN")return true}}var Ye=class{constructor(e){this.variant=e;this.category="Finance";}parse(e,o,t){if(!zl(e)){e.parseExpression(a.Lowest,t);return}if(e.parseExpression(a.Product,t),this.variant==="what-was"){e.consume("WORTH_IN"),e.parseExpression(a.Lowest,t),t.emitPluginCall("inflationToYearFromPresent",2);return}let n=e.peek();if(n?.type==="FROM"){e.consume(),e.parseExpression(a.Lowest,t),t.emitPluginCall("inflationFromYearToPresent",2);return}if(n?.type==="IN"){e.consume(),e.parseExpression(a.Lowest,t),e.consume("WORTH_IN"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(Hl),t.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 Pt=class{constructor(){this.category="Finance";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("IN"),e.parseExpression(a.Lowest,t),e.consume("ASSUMING"),e.parseExpression(a.Lowest,t);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(),t.emitPluginCall("inflationFutureValue",3);}};var _t=class{constructor(){this.category="Finance";this.bindingPower=35;}parse(e,o,t,n){let i=Number(t.value);n.emitOpcode(10),n.emitNumber(i),n.emitPluginCall("inflationToYearFromPresent",2);}};function Da(r,e){return O(r,`Year ${e} is outside the bundled CPI table's range (${z$2}-${A$1})`)}function Fa(r){let e=r[0],o=r[1].toNumber(),t=new Date().getFullYear(),n$1=B$1(e.toNumber(),o,t);return n$1===void 0?Da("INFLATION_YEAR_OUT_OF_RANGE",o):e.type===6?u$1(n$1,e.unit):n(n$1)}function Va(r){let e=r[0],o=new Date().getFullYear(),t=r[1].toNumber(),n$1=B$1(e.toNumber(),o,t);return n$1===void 0?Da("INFLATION_YEAR_OUT_OF_RANGE",t):e.type===6?u$1(n$1,e.unit):n(n$1)}function ba(r){let e=r[0],o=r[1].toNumber(),t=r[2].toNumber(),n$1=o-new Date().getFullYear();if(1+t<=0)return O("INVALID_RATE",`inflationFutureValue: rate ${t} makes (1 + rate) non-positive`);let a=e.toNumber()/Math.pow(1+t,n$1);return e.type===6?u$1(a,e.unit):n(a)}function Ha(r=70){return {name:"finance:in-year-dollars",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];if(t.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 Gl={RECURRING_INTERVAL_NOT_POSITIVE:"RECURRING_INTERVAL_NOT_POSITIVE"},Kl={daily:365,weekly:52,monthly:12,yearly:1,annually:1},Wl={day:365,days:365,week:52,weeks:52,month:12,months:12,year:1,years:1},$l=new Set(["a","an"]),Yl=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]);function je(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}function za(r){if(!(r===void 0||r.type!=="UNIT"))return Wl[je(r)]}function jl(r,e){let o=r[e];if(o===void 0)return null;if(o.type==="IDENT"){let t=Kl[je(o)];if(t!==void 0)return {perYear:t,consumed:1};if(je(o)==="every"){let n=r[e+1];if(n?.type!=="NUMBER")return null;let i=za(r[e+2]);if(i===void 0)return null;let a=Number((n.value??"").replace(/,/g,""));if(!(a>0))throw c$1.parsing({code:Gl.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} ${je(r[e+2])}`});return {perYear:i/a,consumed:3}}}return null}function Xl(r,e){let o=r[e];if(o===void 0)return null;let t,n;if(o.type==="NUMBER")t=Number((o.value??"").replace(/,/g,"")),n=e+1;else if(o.type==="IDENT"&&$l.has(je(o)))t=1,n=e+1;else return null;let i=za(r[n]);return i===void 0||!Number.isFinite(t)||t<0?null:{years:t/i,consumed:n-e+1}}function Ql(r,e){let o=r*e,t=Math.round(o);return Math.abs(o-t)<1e-9?t:Math.floor(o)}function Ga(r=78){return {name:"finance:recurring-schedule",priority:r,match(e,o){let t=e[o];if(t===void 0||!Yl.has(t.type))return null;let n=jl(e,o+1);if(n===null)return null;let i=o+1+n.consumed;if(e[i]?.type!=="FOR_DURATION")return null;let a=Xl(e,i+1);if(a===null)return null;let m=Ql(n.perYear,a.years),l=i+1+a.consumed-o,u=e.slice(o,o+l);return {replacement:[t,b$5("STAR","*",u),b$5("NUMBER",String(m),u)],consumed:l,ruleName:"finance:recurring-schedule"}}}}function At(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}var Ka=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]),Wa=new Set(["NUMBER","FLOAT"]);function $a(r=77){return {name:"finance:bill-split",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;if(Ka.has(t.type)){let f=e[o+1],N=e[o+2],y=e[o+3];if(f?.type==="IDENT"&&At(f)==="split"&&N!==void 0&&Wa.has(N.type)&&y?.type==="IDENT"&&At(y)==="ways")return {consumed:4,replacement:[t,b$5("SPLIT_WAYS","split",[f]),N,b$5("WAYS","ways",[y])],ruleName:"finance:bill-split"}}if(t.type!=="IDENT"||At(t)!=="split")return null;let n=e[o-1];if(n!==void 0&&Ka.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||!Wa.has(a.type))return null;let m=i+2,l=e[m]?.type==="IDENT"&&At(e[m])==="people",u=l?m:i+1,c=[b$5("SPLIT","split",[t]),...e.slice(o+1,i+2)];return l&&c.push(b$5("PEOPLE","people",[e[m]])),{consumed:u-o+1,replacement:c,ruleName:"finance:bill-split"}}}}var Ho=51,Zl=52,Ot=55,Rt=56,zo=80,ql=81,Jl=82,eu=83,ru=84,tu=59,ou=85,nu=86,Ya=98,iu=99,au=100,Go={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 pt(Jl),ANNUAL_RETURN_ON:new dt(ru),COMPOUND_INTEREST_ON:new $e(Ho,zo),INTEREST_ON:new $e(Zl,ql),DAILY_REPAYMENT_ON:new D(Ot,365),MONTHLY_REPAYMENT_ON:new D(Ot,12),ANNUAL_REPAYMENT_ON:new D(Ot,1),TOTAL_REPAYMENT_ON:new D(Ot,0),DAILY_LOAN_INTEREST_ON:new D(Rt,365),MONTHLY_LOAN_INTEREST_ON:new D(Rt,12),ANNUAL_LOAN_INTEREST_ON:new D(Rt,1),TOTAL_LOAN_INTEREST_ON:new D(Rt,0),TAX_ON:new ye(nu),TAX_OFF:new ye(tu),TAX_IN_PHRASE:new ye(ou),SPLIT:new Nt(Ya),WHAT_IS:new Ye("what-is"),WHAT_WAS:new Ye("what-was"),VALUE_OF:new Pt,SAVINGS_HOW_LONG:new yt(au),SAVINGS_HOW_MUCH:new gt(iu)},infixParselets:{AFTER:new We(Ho,zo),FOR_DURATION:new We(Ho,zo),INVESTED:new ft(eu),IN_YEAR_DOLLARS:new _t,SPLIT_WAYS:new Tt(Ya)},normalizerRules:[Ha(),Ga(),$a()],pluginFunctions:{inflationFromYearToPresent:Fa,inflationToYearFromPresent:Va,inflationFutureValue:ba}};function mu(r){return (e,o)=>O(`${r.toUpperCase()}_QUERY_FAILED`,`Failed to resolve "${e}": ${o instanceof Error?o.message:String(o)}`)}function ne(r){let e=r.staleTimeMs??3e5,o=r.timeoutMs??1e4,t=r.failureCooldownMs??3e4,n=r.onError??mu(r.namespace),i=u=>[r.namespace,u];async function a(u,c,f){let{signal:N,cleanup:y}=a$3(c,o,`${r.namespace} query`);try{return await r.fetchQuery(u,N)}catch(T){let A=n(u,T);return setTimeout(()=>{f.getQueryData(i(u))===A&&f.removeQueries({queryKey:i(u),exact:true});},t).unref?.(),A}finally{y();}}return {resolver:{namespace:r.namespace,preflight(u,c,f,N,y){let{opcodes:T,strings:A}=c,B=T.length,S=0;for(;S<B;){if(T[S]===50&&S+2<B){let $=T[S+1],Kt=T[S+2];if($===r.pluginFunctionIndex&&Kt>=1&&S>=2&&T[S-2]===13){let le=A[T[S-1]],Ze=i(le);if(y.getQueryData(Ze)===void 0){let os=y.fetchQuery({queryKey:Ze,queryFn:({signal:$t})=>a(le,$t,y),staleTime:e}),Wt={queryKey:Ze.join(":"),resolver:os,packageId:f,signal:N,metadata:{query:le}};return r.refetchIntervalMs!==void 0&&(Wt.refetchIntervalMs=r.refetchIntervalMs,Wt.refetch=()=>y.fetchQuery({queryKey:Ze,queryFn:({signal:$t})=>a(le,$t,y),staleTime:0})),Wt}}S+=3;continue}S=a$2(T,S);}return null},destroy(){}},pluginFunction:u=>{let c=u[0]?.value,f=b$4()?.getQueryData(i(c));return f!==void 0?f:O(`${r.namespace.toUpperCase()}_NOT_PREFLIGHTED`,`No cached result for "${c}"`)}}}function su(r,e){let o=[];for(;r.peek()?.type==="IDENT";)o.push(r.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 ge(r,e){return {category:"Weather",parse(o,t,n){let i=su(o,t.value);n.emitOpcode(13),n.emitString(`${r}:${i}`),n.emitPluginCall(e,1);}}}var lu={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 ja(r){return lu[r]??`weather code ${r}`}var Pe={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"},uu="https://geocoding-api.open-meteo.com/v1/search",cu="https://api.open-meteo.com/v1/forecast",pu=1e4;async function fu(r,e){let o=`${uu}?name=${encodeURIComponent(r)}&count=1&language=en&format=json`,t=await fetch(o,{signal:e});if(!t.ok)throw c$1.external(Pe.GEOCODING_API_ERROR,`Open-Meteo geocoding API returned ${t.status} for "${r}"`,{city:r,status:t.status});let i=(await t.json())?.results?.[0];if(!i)throw c$1.validation(Pe.CITY_NOT_FOUND,`No location found for "${r}"`,{city:r});return {latitude:i.latitude,longitude:i.longitude,name:i.name}}async function du(r,e,o){let t=new URLSearchParams({latitude:String(r),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(`${cu}?${t.toString()}`,{signal:o});if(!n.ok)throw c$1.external(Pe.FORECAST_API_ERROR,`Open-Meteo forecast API returned ${n.status}`,{status:n.status});let i=await n.json(),a=i?.current,m=i?.daily;if(!a||!m)throw c$1.external(Pe.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:m.temperature_2m_max?.[0],low:m.temperature_2m_min?.[0]}}var It=new Map,Eu=6e4;function Xa(r,e){let o=r.trim().toLowerCase(),t=Date.now(),n=It.get(o);if(n&&n.expiresAt>t)return n.promise;let{signal:i,cleanup:a}=a$3(e,pu,"Open-Meteo weather query"),m=(async()=>{try{let l=await fu(r,i),u=await du(l.latitude,l.longitude,i);return {resolvedName:l.name,weatherCode:u.weatherCode,description:ja(u.weatherCode),temperature:u.temperature,apparentTemperature:u.apparentTemperature,high:u.high,low:u.low}}finally{a();}})();return It.set(o,{promise:m,expiresAt:t+Eu}),m.catch(()=>{It.get(o)?.promise===m&&It.delete(o);}),m}var Qa="solve-weather",ie="weather",Nu=F$1(`${Qa}:${ie}`),{resolver:Tu,pluginFunction:yu}=ne({namespace:"weather",pluginFunctionIndex:Nu,staleTimeMs:600*1e3,fetchQuery:async(r,e)=>{let o=r.indexOf(":"),t$1=o===-1?r:r.slice(0,o),n=o===-1?"":r.slice(o+1),i=await Xa(n,e);switch(t$1){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(Pe.UNKNOWN_QUERY_KIND,`Unknown weather query kind "${t$1}"`,{kind:t$1})}}}),Ko={name:Qa,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:ge("current",ie),TEMPERATURE_IN:ge("temperature",ie),FEELS_LIKE_IN:ge("feelslike",ie),HIGH_IN:ge("high",ie),LOW_IN:ge("low",ie)},pluginFunctions:{[ie]:yu},asyncResolvers:[Tu]};var Ct={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 xt(r){return r<10?`0${r}`:String(r)}function Xe(r,e,o,t){let n=new Date(r,e,o);if(n.getFullYear()!==r||n.getMonth()!==e||n.getDate()!==o)throw c$1.parsing("STOCKS_INVALID_DATE",`"${t}" is not a valid calendar date`);return {isoDate:`${r}-${xt(e+1)}-${xt(o)}`,raw:t}}function ht(r,e){if(!/^\d{4}$/.test(r))throw c$1.parsing("STOCKS_INVALID_DATE",`Expected a 4-digit year in "${e}", got "${r}"`);return parseInt(r,10)}function Za(r){let e=r.peek();if(!e)return null;if(e.type==="DATETIME_LITERAL"){r.consume();let o=new Date(Number(e.value));return Number.isNaN(o.getTime())?null:{isoDate:`${o.getFullYear()}-${xt(o.getMonth()+1)}-${xt(o.getDate())}`,raw:e.text??e.value}}if(e.type==="NUMBER"){let o=r.consume(),t=r.peek();if(t&&(t.type==="SLASH"||t.type==="MINUS")){let i=t.type;r.consume();let a=r.consume("NUMBER");r.consume(i);let m=r.consume("NUMBER"),l=`${o.value}${i==="SLASH"?"/":"-"}${a.value}${i==="SLASH"?"/":"-"}${m.value}`;if(i==="SLASH"){let u=parseInt(o.value,10),c=parseInt(a.value,10),f=ht(m.value,l);return Xe(f,u-1,c,l)}else {if(/^\d{4}$/.test(o.value)){let N=parseInt(o.value,10),y=parseInt(a.value,10),T=parseInt(m.value,10);return Xe(N,y-1,T,l)}let u=parseInt(o.value,10),c=parseInt(a.value,10),f=ht(m.value,l);return Xe(f,u-1,c,l)}}let n=r.peek();if(n&&n.type==="IDENT"&&Ct[n.value.toLowerCase()]!==void 0){let i=Ct[n.value.toLowerCase()];r.consume(),r.peek()?.type==="COMMA"&&r.consume();let a=r.consume("NUMBER"),m=`${o.value} ${n.value} ${a.value}`,l=ht(a.value,m);return Xe(l,i,parseInt(o.value,10),m)}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"&&Ct[e.value.toLowerCase()]!==void 0){let o=Ct[e.value.toLowerCase()];r.consume();let t=r.consume("NUMBER");r.peek()?.type==="COMMA"&&r.consume();let n=r.consume("NUMBER"),i=`${e.value} ${t.value}, ${n.value}`,a=ht(n.value,i);return Xe(a,o,parseInt(t.value,10),i)}return null}var qa=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 _e="STOCK_TICKER",gu=c(_e);function Ja(){return {name:"stocks:bare-ticker",priority:20,match(r,e){let o=r[e];return !o||o.type!=="IDENT"||!qa.has(o.value)||e>0&&r[e-1].type==="COLON"?null:{consumed:1,replacement:[new a$6(_e,gu,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"stocks:bare-ticker"}}}}function Pu(r){let e=r.peek();if(!e||e.type!=="IDENT")return null;let o=e.value.toLowerCase(),t="close";if(o==="close"||o==="volume"){t=o,r.consume();let i=r.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")`);r.consume();}else if(o==="on")r.consume();else return null;let n=Za(r);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:t,date:n}}function em(r,e,o,t,n){r.emitOpcode(13),o?(r.emitString(`${o.field}:${e}:${o.date.isoDate}`),r.emitPluginCall(n,1)):(r.emitString(e),r.emitPluginCall(t,1));}function rm(r,e,o,t,n){let i=false;r.peek()?.type==="STAR"&&(r.consume(),i=true);let a$1=Pu(r);if(i&&!a$1){em(e,o,null,t,n),r.parseExpression(a.Product,e),e.emitOpcode(22);return}em(e,o,a$1,t,n);}function tm(r,e){return {category:"Stocks",parse(o,t,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===_e)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"),rm(o,n,a,r,e);}}}function om(r,e){return {category:"Stocks",parse(o,t,n){let i=t.value.toUpperCase();rm(o,n,i,r,e);}}}var Wo="solve-stocks",St="stock",Lt="stockhistorical";function nm(r={}){function e(m){return O("STOCKS_NOT_CONFIGURED",`Stock data provider not configured. Supply ${m} via createStocksPackage({ ... }); see the StocksPackage doc comment.`)}let{resolver:o,pluginFunction:t}=ne({namespace:"stocks-current",pluginFunctionIndex:F$1(`${Wo}:${St}`),staleTimeMs:r.staleTimeMs??6e4,refetchIntervalMs:r.refetchIntervalMs,fetchQuery:async(m,l)=>{if(!r.fetchQuote)return e("fetchQuote");let u=await r.fetchQuote(m,l);return u$1(u.price,u.currency??"USD")}}),{resolver:n$1,pluginFunction:i}=ne({namespace:"stocks-historical",pluginFunctionIndex:F$1(`${Wo}:${Lt}`),staleTimeMs:r.historicalStaleTimeMs??720*60*60*1e3,fetchQuery:async(m,l)=>{let[u,c,f]=m.split(":");if(!r.fetchHistoricalQuote)return e("fetchHistoricalQuote");let N=await r.fetchHistoricalQuote(c,f,l);return u==="volume"?n(N.volume??0):u$1(N.close,N.currency??"USD")}});return {name:Wo,lexerVocabulary:{keywords:{stock:"STOCK_FN"}},prefixParselets:{STOCK_FN:tm(St,Lt),...r.enableBareTickerRecognition?{[_e]:om(St,Lt)}:{}},normalizerRules:r.enableBareTickerRecognition?[Ja()]:[],pluginFunctions:{[St]:t,[Lt]:i},asyncResolvers:[o,n$1]}}function im(r){return {category:"Knowledge",parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall(r,1);}}}function am(r={}){let e="solve-knowledge",o="knowledge",t$1=F$1(`${e}:${o}`),{resolver:n,pluginFunction:i}=ne({namespace:"knowledge",pluginFunctionIndex:t$1,staleTimeMs:r.staleTimeMs??300*1e3,fetchQuery:async(a,m)=>{if(!r.answerQuery)return O("KNOWLEDGE_NOT_CONFIGURED","Knowledge answer provider not configured. Supply answerQuery via createKnowledgePackage({ ... }); see the KnowledgePackage doc comment.");let l=await r.answerQuery(a,m);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:im(o)},pluginFunctions:{[o]:i},asyncResolvers:[n]}}var wt=class{constructor(){this.category="Lines";}parse(e,o,t){t.emitPluginCall("prev",0);}};var vt=class{constructor(){this.category="Lines";}parse(e,o,t){let n=parseInt(o.value,10);t.emitOpcode(10),t.emitNumber(n),t.emitPluginCall("lineRef",1);}};var Qe=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,t){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),m=parseInt(i.value,10);t.emitOpcode(10),t.emitNumber(a),t.emitOpcode(10),t.emitNumber(m),t.emitPluginCall(this.isAverage?"averageRange":"sumRange",2);}};var Ae=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,t){t.emitPluginCall(this.isAverage?"averageAbove":"totalAbove",0);}};var _u=c("LINE_REF"),Au=c("SUM_RANGE_CALL"),Ou=c("AVERAGE_RANGE_CALL");function sm(){return {name:"lines:line-ref",priority:80,match(r,e){if(e>0&&r[e-1].type==="COLON"&&!(e>1&&r[e-2].type==="LINE_REF"))return null;let o=r[e];if(!o)return null;if(o.type==="IDENT"){let t=/^line(\d+)$/i.exec(o.value);if(t)return {consumed:1,replacement:[mm(t[1],o)],ruleName:"lines:line-ref"}}if(o.type==="IDENT"&&/^line$/i.test(o.value)){let t=r[e+1];if(t&&t.type==="NUMBER"&&/^\d+$/.test(t.value))return {consumed:2,replacement:[mm(t.value,o)],ruleName:"lines:line-ref"}}return null}}}function mm(r,e){return new a$6("LINE_REF",_u,r,r,e.offset,0,e.line,e.col)}function lm(){return {name:"lines:range-call",priority:80,match(r,e){let o=r[e];if(!o||o.type!=="IDENT")return null;let t=o.value.toLowerCase();if(t!=="sum"&&t!=="total"&&t!=="average"||r[e+1]?.type!=="LPAREN")return null;let n=t==="average"?"AVERAGE_RANGE_CALL":"SUM_RANGE_CALL",i=t==="average"?Ou:Au;return {consumed:1,replacement:[new a$6(n,i,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"lines:range-call"}}}}function kt(r,e){return r===void 0?O("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet (forward reference, or out of range)`):r.type===12?O("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):r.type===13?O("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function Oe(r){return r?.getLineResult?null:O("LINE_REF_NO_DOCUMENT","Cross-line references require a real document \u2014 not available outside one (e.g. evaluateExpression()'s single-expression path)")}function um(r,e){let o=Oe(e);if(o)return o;let t=e.lineIndex-1,n=e.getLineResult(t);return kt(n,t)??n}function cm(r,e){let o=Oe(e);if(o)return o;let t=r[0].toNumber(),n=e.getLineResult(t);return kt(n,t)??n}function pm(r,e,o,t){let n$1=0,i=0,a,m=false,l=r<=e?1:-1;for(let c=r;l>0?c<=e:c>=e;c+=l){let f=o.getLineResult(c),N=kt(f,c);if(N)return N;if(f.type!==0&&f.type!==6)return O("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(m=true,a===void 0)a=f.unit;else if(f.unit!==a)return O("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=t?n$1/i:n$1;return m?u$1(u,a):n(u)}function fm(r,e){let o=Oe(e);return o||pm(r[0].toNumber(),r[1].toNumber(),e,false)}function dm(r,e){let o=Oe(e);return o||pm(r[0].toNumber(),r[1].toNumber(),e,true)}function Em(r,e){let o=r.isLineBoundary;if(!o)return O("LINE_REF_NO_DOCUMENT",'"above" aggregation requires a real document');let t=0,n$1=0,i,a=false;for(let l=r.lineIndex-1;l>=1&&!o(l);l--){let u=r.getLineResult(l),c=kt(u,l);if(c)return c;if(u.type!==0&&u.type!==6)return O("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 O("LINE_RANGE_MIXED_UNITS",`Line ${l}'s unit (${u.unit}) doesn't match the range's unit (${i})`)}t+=u.toNumber(),n$1++;}if(n$1===0)return O("LINE_RANGE_EMPTY","No lines above to aggregate (hit the top of the document, a blank line, or a heading immediately)");let m=e?t/n$1:t;return a?u$1(m,i):n(m)}function Nm(r,e){let o=Oe(e);return o||Em(e,false)}function Tm(r,e){let o=Oe(e);return o||Em(e,true)}var $o={name:"solve-lines",lexerVocabulary:{keywords:{prev:"PREV"}},phrases:{"total above":"TOTAL_ABOVE","sum above":"SUM_ABOVE","average above":"AVERAGE_ABOVE"},normalizerRules:[sm(),lm()],prefixParselets:{PREV:new wt,LINE_REF:new vt,SUM_RANGE_CALL:new Qe(false),AVERAGE_RANGE_CALL:new Qe(true),TOTAL_ABOVE:new Ae(false),SUM_ABOVE:new Ae(false),AVERAGE_ABOVE:new Ae(true)},pluginFunctions:{prev:um,lineRef:cm,sumRange:fm,averageRange:dm,totalAbove:Nm,averageAbove:Tm}};var w=class{constructor(e){this.pluginFnName=e;this.category="Tables";}parse(e,o,t){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"&&Ru.has(a.value.toLowerCase())){e.consume();continue}break}t.emitOpcode(13),t.emitString(i.value),t.emitPluginCall(this.pluginFnName,1);}},Ru=new Set(["the","table","above"]);function ym(r){return r.trimStart().startsWith("|")}function Iu(r){let e=r.trim();return e.length===0||!e.includes("-")||!e.includes("|")?false:/^[|\s:-]+$/.test(e)}function gm(r){let e=r.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let o=[],t="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="\\"&&n+1<e.length&&e[n+1]==="|"){t+="|",n++;continue}if(i==="|"){o.push(t.trim()),t="";continue}t+=i;}return o.push(t.trim()),o}function Cu(r){if(r===void 0)return null;let e=r.trim();if(e.length===0)return null;let o=e.replace(/,/g,"");if(!/^[+-]?(\d+(\.\d+)?|\.\d+)$/.test(o))return null;let t=Number.parseFloat(o);return Number.isFinite(t)?t:null}function Pm(r,e){let o=-1;for(let m=e-1;m>=1;m--){let l=r(m);if(l===void 0)break;if(ym(l)){o=m;break}}if(o===-1)return null;let t=o;for(;t-1>=1;){let m=r(t-1);if(m===void 0||!ym(m))break;t--;}let n=-1;for(let m=t;m<=o;m++)if(Iu(r(m))){n=m;break}if(n===-1||n===t)return null;let i=gm(r(n-1)),a=[];for(let m=n+1;m<=o;m++)a.push(gm(r(m)));return {header:i,rows:a}}function _m(r,e){let o=e.trim().toLowerCase();for(let t=0;t<r.length;t++)if(r[t].trim().toLowerCase()===o)return t;return -1}function Am(r,e){let o=[];for(let t of r.rows){let n=Cu(t[e]);n!==null&&o.push(n);}return o}var Bt={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 Mt(r,e){let o=r.length;if(o===0)return 0;let t=e?o-1:o;if(t<=0)return 0;let n=r.reduce((i,a)=>i+a,0)/o;return r.reduce((i,a)=>i+(a-n)*(a-n),0)/t}function hu(r,e){switch(r){case "sum":return e.reduce((o,t)=>o+t,0);case "average":return e.reduce((o,t)=>o+t,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),t=Math.floor(o.length/2);return o.length%2===0?(o[t-1]+o[t])/2:o[t]}case "stdev":return Math.sqrt(Mt(e,false));case "sampleStdev":return Math.sqrt(Mt(e,true));case "variance":return Mt(e,false);case "sampleVariance":return Mt(e,true);case "spread":return Math.max(...e)-Math.min(...e);case "mode":{let o=new Map,t=e[0],n=0;for(let i of e){let a=(o.get(i)??0)+1;o.set(i,a),a>n&&(n=a,t=i);}return t}}}function M(r,e,o){let t=o?.getLineText;if(!t||o.lineIndex<1)return O(Bt.TABLE_NO_DOCUMENT,"Reading a table column needs a real document, which the single-expression path (evaluateExpression) does not have");let n$1=Pm(t,o.lineIndex);if(!n$1)return O(Bt.TABLE_NOT_FOUND,'No markdown table found above this line (a table row starts with "|", and needs a "|---|" separator under its header)');let i=_m(n$1.header,e);if(i===-1){let m=n$1.header.map(l=>`"${l}"`).join(", ");return O(Bt.TABLE_COLUMN_NOT_FOUND,`The table above has no column named "${e}". Its columns are: ${m}`)}let a=Am(n$1,i);return r==="count"?n(a.length):a.length===0?O(Bt.TABLE_COLUMN_NO_NUMERIC_CELLS,`Column "${e}" has no plain-number cells to aggregate (currency and unit cells are not read yet)`):n(hu(r,a))}function U(r){let e=r[0];return e&&e.type===3&&typeof e.value=="string"?e.value:String(e?.value??"")}function Om(r,e){return M("sum",U(r),e)}function Rm(r,e){return M("average",U(r),e)}function Im(r,e){return M("min",U(r),e)}function Cm(r,e){return M("max",U(r),e)}function hm(r,e){return M("count",U(r),e)}function xm(r,e){return M("median",U(r),e)}function Sm(r,e){return M("stdev",U(r),e)}function Lm(r,e){return M("sampleStdev",U(r),e)}function wm(r,e){return M("variance",U(r),e)}function vm(r,e){return M("sampleVariance",U(r),e)}function km(r,e){return M("spread",U(r),e)}function Bm(r,e){return M("mode",U(r),e)}var Yo={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 w("TABLE_COLUMN_SUM"),TABLE_COLUMN_AVERAGE:new w("TABLE_COLUMN_AVERAGE"),TABLE_COLUMN_MIN:new w("TABLE_COLUMN_MIN"),TABLE_COLUMN_MAX:new w("TABLE_COLUMN_MAX"),TABLE_COLUMN_COUNT:new w("TABLE_COLUMN_COUNT"),TABLE_COLUMN_MEDIAN:new w("TABLE_COLUMN_MEDIAN"),TABLE_COLUMN_STDEV:new w("TABLE_COLUMN_STDEV"),TABLE_COLUMN_SAMPLE_STDEV:new w("TABLE_COLUMN_SAMPLE_STDEV"),TABLE_COLUMN_VARIANCE:new w("TABLE_COLUMN_VARIANCE"),TABLE_COLUMN_SAMPLE_VARIANCE:new w("TABLE_COLUMN_SAMPLE_VARIANCE"),TABLE_COLUMN_SPREAD:new w("TABLE_COLUMN_SPREAD"),TABLE_COLUMN_MODE:new w("TABLE_COLUMN_MODE")},pluginFunctions:{TABLE_COLUMN_SUM:Om,TABLE_COLUMN_AVERAGE:Rm,TABLE_COLUMN_MIN:Im,TABLE_COLUMN_MAX:Cm,TABLE_COLUMN_COUNT:hm,TABLE_COLUMN_MEDIAN:xm,TABLE_COLUMN_STDEV:Sm,TABLE_COLUMN_SAMPLE_STDEV:Lm,TABLE_COLUMN_VARIANCE:wm,TABLE_COLUMN_SAMPLE_VARIANCE:vm,TABLE_COLUMN_SPREAD:km,TABLE_COLUMN_MODE:Bm}};var Re=class{constructor(e){this.pluginFnName=e;this.category="Tags";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall(this.pluginFnName,1);}};function Ut(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}var Mm={TOTAL_OF:"TAG_SUM",COUNT_OF:"TAG_COUNT",AVERAGE_OF:"TAG_AVERAGE"},xu=new Set(["total","sum","count","average"]);function Um(r=80){return {name:"tags:aggregate",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;let n=Mm[t.type];if(n!==void 0){let i=e[o+1];return i?.type!=="TAG"?null:{consumed:2,replacement:[b$5(n,i.value??"",[t,i])],ruleName:"tags:aggregate"}}if(t.type==="IDENT"&&Ut(t)==="sum"){let i=e[o+1],a=e[o+2];return Ut(i)!=="of"||a?.type!=="TAG"?null:{consumed:3,replacement:[b$5("TAG_SUM",a.value??"",[t,i,a])],ruleName:"tags:aggregate"}}return null}}}function Dm(r=40){return {name:"tags:strip",priority:r,match(e,o){if(e[o]?.type!=="TAG")return null;let t=e[o-1];return t!==void 0&&(Mm[t.type]!==void 0||Ut(t)==="of"&&xu.has(Ut(e[o-2])))?null:{consumed:1,replacement:[],ruleName:"tags:strip"}}}}function Su(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fm(r,e){if(e==="")return false;let t=new RegExp(`(?:^|[^0-9A-Za-z_])#${Su(e)}(?![0-9A-Za-z_-])`,"i").exec(r);if(t===null)return false;let n=t.index+t[0].indexOf("#");return r.slice(0,n).trim().length>0}function Lu(r,e){return r===void 0?O("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet`):r.type===12?O("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):r.type===13?O("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function jo(r){return !r?.getLineResult||!r.getLineText?O("TAG_NO_DOCUMENT","Category tag sums require a real document, not available outside one (e.g. evaluateExpression()'s single-expression path)"):null}function Xo(r,e,o){let t=r.getLineText,n$1=r.getLineResult,i=r.isLineBoundary,a=e.toLowerCase(),m=0,l=0,u,c=false;for(let N=1;;N++){let y=t(N);if(y===void 0)break;if(N===r.lineIndex||i&&i(N)||!Fm(y,a))continue;let T=n$1(N),A=Lu(T,N);if(A)return A;if(o!=="count"){if(T.type!==0&&T.type!==6)return O("TAG_NON_NUMERIC",`Line ${N}, tagged #${e}, is not a plain number or unit value.`);if(T.type===6){if(c=true,u===void 0)u=T.unit;else if(T.unit!==u)return O("TAG_MIXED_UNITS",`Line ${N}'s unit (${T.unit}) doesn't match #${e}'s first unit (${u}), aggregating mixed units would misrepresent the result.`)}m+=T.toNumber();}l++;}if(o==="count")return n(l);if(l===0)return O("TAG_EMPTY",`No lines are tagged #${e}.`);let f=o==="average"?m/l:m;return c?u$1(f,u):n(f)}function Vm(r,e){let o=jo(e);return o||Xo(e,String(r[0].value),"sum")}function bm(r,e){let o=jo(e);return o||Xo(e,String(r[0].value),"average")}function Hm(r,e){let o=jo(e);return o||Xo(e,String(r[0].value),"count")}var Qo={name:"solve-tags",normalizerRules:[Um(),Dm()],prefixParselets:{TAG_SUM:new Re("sum"),TAG_AVERAGE:new Re("average"),TAG_COUNT:new Re("count")},pluginFunctions:{sum:Vm,average:bm,count:Hm}};var Dt=class{constructor(){this.category="operator";this.bindingPower=a.Uncertainty;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(28);}};function zm(r=90){return {name:"uncertainty:ascii-plus-minus",priority:r,match(e,o){let t=e[o];if(t?.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",[t,n,i])],ruleName:"uncertainty:ascii-plus-minus"}}}}var Zo={name:"solve-uncertainty",infixParselets:{PLUS_MINUS:new Dt},normalizerRules:[zm()]};var Gm=1e-9,Km=1e9,wu=100,vu=1e-9,ku=1e-9,Bu=1e-12,Mu=1e-9,Ft="goalseek";function Wm(r,e){let o=e?.evaluateLineWithBinding,t=e?.getLineReads;if(!o||!t)return O("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=r[0].toNumber(),i=typeof r[1].value=="string"?r[1].value:String(r[1].value),a=r[2];if(a.type!==0&&a.type!==6)return O("GOAL_SEEK_TARGET_NOT_NUMERIC",`Goal seek's target must be a number, as in "solve line ${n$1} for ${i} = 900".`);let m=a.toNumber();if(!Number.isFinite(m))return O("GOAL_SEEK_TARGET_NOT_NUMERIC","Goal seek's target is not a finite number.");let l=t(n$1);if(l===void 0)return O("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 O("GOAL_SEEK_VARIABLE_NOT_USED",`Line ${n$1} does not use ${i}, so changing ${i} cannot move its result toward ${m}.`);let u=o(n$1,i,J$1(q$1(i)),true);if(u.type===9){let f=Uu(u.value,m,i);if(f!==null)return n(f)}let c=e.goalSeekMaxIterations??wu;return Du(o,n$1,i,m,c)}function Uu(r,e,o){let t=p$1(d$2(e)),n;try{n=d$3(r,t,o);}catch{return null}if(n.kind!=="roots")return null;let i=[];for(let l of n.exact){let u=Q$1(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)<=Mu&&Number.isFinite(l.re)&&i.push(l.re);if(i.length===0)return null;let a=i.filter(l=>l>=Gm&&l<=Km),m=a.length>0?a:i;return m.sort((l,u)=>Math.abs(l)-Math.abs(u)),m[0]}function Du(r,e,o,t,n$1){let i=y=>{let T=r(e,o,n(y),false);if(T.type===13)return {error:T};if(T.type!==0&&T.type!==6)return {error:O("GOAL_SEEK_TARGET_NOT_NUMERIC",`Line ${e} did not produce a number when ${o} was set to ${y}, so goal seek cannot compare it to the target.`)};let A=T.toNumber();return Number.isFinite(A)?{value:A}:{error:O("GOAL_SEEK_NON_FINITE",`Line ${e}'s result is not finite when ${o} is ${y}.`)}},a=Gm,m=Km,l=i(a);if("error"in l)return l.error;let u=i(m);if("error"in u)return u.error;let c=Math.max(vu,Math.abs(t)*ku),f=l.value-t,N=u.value-t;if(Math.abs(f)<=c)return n(a);if(Math.abs(N)<=c)return n(m);if(Math.sign(f)===Math.sign(N))return O("GOAL_SEEK_NO_SOLUTION",`No value of ${o} between ${a} and ${m} makes line ${e} equal ${t}: across that whole range its result stays on one side of the target.`);for(let y=0;y<n$1;y++){let T=(a+m)/2,A=i(T);if("error"in A)return A.error;let B=A.value-t;if(Math.abs(B)<=c)return n(T);if(m-a<=Bu)return O("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek narrowed ${o} to a single point near ${T} without line ${e} reaching ${t}: the relationship jumps across the target rather than passing through it.`);Math.sign(B)===Math.sign(f)?(a=T,f=B):m=T;}return O("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek did not bring line ${e} within tolerance of ${t} by varying ${o} in ${n$1} steps.`)}var Vt=class{constructor(){this.category="GoalSeek";}parse(e,o,t){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"),t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(13),t.emitString(l.value),e.parseExpression(a.Lowest,t),t.emitPluginCall(Ft,3);}};var Fu=c("GOAL_SEEK");function $m(r=75){return {name:"goalseek:solve-line",priority:r,match(e,o){if(o>0&&e[o-1].type==="COLON")return null;let t=e[o];return !t||t.type!=="IDENT"||t.value.toLowerCase()!=="solve"||e[o+1]?.type!=="LINE_REF"?null:{consumed:1,replacement:[new a$6("GOAL_SEEK",Fu,t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"goalseek:solve-line"}}}}var qo={name:"solve-goalseek",normalizerRules:[$m()],prefixParselets:{GOAL_SEEK:new Vt},pluginFunctions:{[Ft]:Wm}};var bt=class{constructor(){this.category="Colour";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall("colour",1);}};var ae={COLOUR_INVALID:"COLOUR_INVALID",COLOUR_EXPECTED_COLOUR:"COLOUR_EXPECTED_COLOUR",COLOUR_BAD_ARGUMENTS:"COLOUR_BAD_ARGUMENTS"};function I(r){return r&&r.type===14?r.value:null}function x(r){if(!r)return 0;let e=r.toNumber();return r.type===5?e:e>1?e/100:e}function b(r,e){return O(ae.COLOUR_BAD_ARGUMENTS,`${r}(...) expects ${e}`)}function F(r){return O(ae.COLOUR_EXPECTED_COLOUR,`${r}(...) expects a colour as its first argument`)}function Ym(r){let e=r[0];if(!e||e.type!==3||typeof e.value!="string")return b("color",'a string, e.g. color("#ff0000") or color("red")');let o=c$2(e.value);return o?G$1(o):O(ae.COLOUR_INVALID,`"${e.value}" is not a hex colour (#rgb, #rgba, #rrggbb, #rrggbbaa) or a CSS colour name`)}function Vu(r){return r.length!==3?b("rgb","three numbers: rgb(red, green, blue)"):G$1({r:a$1(r[0].toNumber()),g:a$1(r[1].toNumber()),b:a$1(r[2].toNumber()),a:1,format:"rgb"})}function bu(r){return r.length!==4?b("rgba","four numbers: rgba(red, green, blue, alpha)"):G$1({r:a$1(r[0].toNumber()),g:a$1(r[1].toNumber()),b:a$1(r[2].toNumber()),a:b$3(x(r[3])),format:"rgba"})}function Hu(r){if(r.length!==3)return b("hsl","three values: hsl(hue, saturation%, lightness%)");let{r:e$1,g:o,b:t}=e(r[0].toNumber(),x(r[1]),x(r[2]));return G$1({r:e$1,g:o,b:t,a:1,format:"hsl"})}function zu(r){if(r.length!==4)return b("hsla","four values: hsla(hue, saturation%, lightness%, alpha)");let{r:e$1,g:o,b:t}=e(r[0].toNumber(),x(r[1]),x(r[2]));return G$1({r:e$1,g:o,b:t,a:b$3(x(r[3])),format:"hsla"})}function me(r,e){return o=>{let t=I(o[0]);return t?o.length<2?b(r,`a colour and an amount, e.g. ${r}(#3366cc, 20%)`):G$1(e(t,x(o[1]))):F(r)}}var Gu=me("lighten",j),Ku=me("darken",k$1),Wu=me("saturate",l),jm=me("desaturate",m);function Jo(r){let e=I(r[0]);return e?r.length<2?b("rotate","a colour and a hue angle in degrees, e.g. rotate(#ff0000, 90)"):G$1(n$1(e,r[1].toNumber())):F("rotate")}function $u(r){let e=I(r[0]);return e?G$1(o(e)):F("complement")}function Xm(r){let e=I(r[0]);return e?G$1(p(e)):F("grayscale")}function Qm(r){let e=I(r[0]);return e?G$1(q(e,r.length>1?x(r[1]):1)):F("invert")}function Yu(r$1){let e=I(r$1[0]),o=I(r$1[1]);return !e||!o?O(ae.COLOUR_EXPECTED_COLOUR,"mix(...) expects two colours to blend"):G$1(r(e,o,r$1.length>2?x(r$1[2]):.5))}function en(r){let e=I(r[0]);return e?r.length<2?n(e.a):G$1(s(e,x(r[1]))):F("alpha")}function ju(r){let e=I(r[0]),o=I(r[1]);return !e||!o?O(ae.COLOUR_EXPECTED_COLOUR,"contrast(...) expects two colours"):n(i(e,o))}function Xu(r){let e=I(r[0]);return e?n(h(e)):F("luminance")}function Ie(r,e){return o=>{let t=I(o[0]);return t?n(e(t)):F(r)}}var Qu=Ie("red",r=>r.r),Zu=Ie("green",r=>r.g),qu=Ie("blue",r=>r.b),Ju=Ie("hue",r=>d$4(r.r,r.g,r.b).h),ec=Ie("saturation",r=>d$4(r.r,r.g,r.b).s*100),rc=Ie("lightness",r=>d$4(r.r,r.g,r.b).l*100);function Zm(r){if(r.length!==3)return b("hsv","three values: hsv(hue, saturation%, value%)");let{r:e,g:o,b:t}=t$1(r[0].toNumber(),x(r[1]),x(r[2]));return G$1({r:e,g:o,b:t,a:1,format:"hex"})}function tc(r){if(r.length!==4)return b("hsva","four values: hsva(hue, saturation%, value%, alpha)");let{r:e,g:o,b:t}=t$1(r[0].toNumber(),x(r[1]),x(r[2]));return G$1({r:e,g:o,b:t,a:b$3(x(r[3])),format:"hex"})}function oc(r){if(r.length!==3)return b("hwb","three values: hwb(hue, whiteness%, blackness%)");let{r:e,g:o,b:t}=u(r[0].toNumber(),x(r[1]),x(r[2]));return G$1({r:e,g:o,b:t,a:1,format:"hex"})}var nc=me("tint",v),ic=me("shade",w$1),ac=me("tone",x$1);function mc(r){let e=I(r[0]);return e?K$1(y(e)):F("isdark")}function sc(r){let e=I(r[0]);return e?K$1(!y(e)):F("islight")}function rn(r){let e=I(r[0]);return e?G$1(z(e)):F("readable")}function lc(r){if(!r)return A.aa;if(r.type===0)return r.toNumber();if(r.type===3){let e=r.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 uc(r){let e=I(r[0]),o=I(r[1]);return !e||!o?O(ae.COLOUR_EXPECTED_COLOUR,"iscontrastcompliant(...) expects two colours"):K$1(i(e,o)>=lc(r[2]))}function qm(r){let e=I(r[0]),o=I(r[1]);return !e||!o?O(ae.COLOUR_EXPECTED_COLOUR,"wcaglevel(...) expects two colours"):t(B(e,o))}var se={color:Ym,colour:Ym,rgb:Vu,rgba:bu,hsl:Hu,hsla:zu,lighten:Gu,darken:Ku,saturate:Wu,desaturate:jm,desat:jm,rotate:Jo,spin:Jo,adjusthue:Jo,complement:$u,grayscale:Xm,greyscale:Xm,invert:Qm,mix:Yu,alpha:en,opacity:en,fade:en,contrast:ju,luminance:Xu,red:Qu,green:Zu,blue:qu,hue:Ju,saturation:ec,lightness:rc,hsv:Zm,hsb:Zm,hsva:tc,hwb:oc,tint:nc,shade:ic,tone:ac,negate:Qm,isdark:mc,islight:sc,readable:rn,contrastcolor:rn,contrastcolour:rn,iscontrastcompliant:uc,wcaglevel:qm,wcag:qm};var Ht=class{constructor(){this.category="Colour";}parse(e,o,t){let n=o.value.toLowerCase();if(se[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,t),i++;e.match("COMMA");)e.parseExpression(a.Lowest,t),i++;e.consume("RPAREN"),t.emitPluginCall(n,i);}};var cc=new Set(Object.keys(se));function Jm(r=80){return {name:"colour:call",priority:r,match(e,o){let t=e[o];if(!t||t.type!=="IDENT")return null;let n=t.value.toLowerCase();return !cc.has(n)||e[o+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new a$6("COLOUR_CALL",c("COLOUR_CALL"),t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"colour:call"}}}}var zt=r=>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:r})},pc=Object.keys(se).map(r=>({label:r,category:"function",detail:"colour"})),tn={name:"solve-colour",prefixParselets:{HEX_COLOUR:new bt,COLOUR_CALL:new Ht},normalizerRules:[Jm()],pluginFunctions:se,asConverters:{rgb:zt("rgb"),rgba:zt("rgba"),hsl:zt("hsl"),hsla:zt("hsla")},completionItems:pc};var on=32;function fc(r){if(r.hasSymbolic||r.rows!==1&&r.cols!==1)return null;let e=[];for(let o of r.data){if(typeof o!="number"||!Number.isFinite(o))return null;e.push(o);}return e}function dc(r){let e=r.max-r.min+1,o=Math.min(e,on),t=[];for(let n=0;n<o;n++)t.push(r.min+Math.round(n*(e-1)/(o-1)));return t}function Ec(r,e){if(r.length<=e)return [...r];let o=[];for(let t=0;t<e;t++)o.push(r[Math.round(t*(r.length-1)/(e-1))]);return o}function es(r){let e=null;if(r.type===7)e=fc(r.value);else if(r.type===8){let a=r.value;e=a.max-a.min+1>=2?dc(a):null;}if(!e||e.length<2)return null;let o=Ec(e,on),t=Math.min(...e),n=Math.max(...e),i=e.length<=on?`[${e.join(", ")}]`:`sparkline of ${e.length} values`;return {kind:"sparkline",points:o.map((a,m)=>[m,a]),label:i,domain:[0,o.length-1],range:[t,n]}}var Gt=class{constructor(){this.category="Plot";}parse(e,o,t){let n=Nc(e),i=new d$1(t.pluginIndexMap);e.parseExpression(a.Lowest,i),e.setBuilder(t);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,t),e.consume("TO"),e.parseExpression(a.Conditional,t);let m=t.emitAnonymousBody(["x"],a$1);t.emitOpcode(160),t.emitIndex(m),t.emitString(n);}};function Nc(r){let e=[];for(let n=0;;n++){let i=r.peekAt(n);if(!i||i.type==="FROM")break;e.push(i);}if(e.length===0)return "";let o=e[0].offset,t="";for(let n of e){let i=n.offset-o;for(;t.length<i;)t+=" ";t+=n.text??n.value??"";}return t.trim()}var rs="PLOT",Tc=c(rs),yc=new Set(["NUMBER","IDENT","FUNC","UNIT","LPAREN","PI","E"]);function ts(r=80){let e="plot:plot-clause";return {name:e,priority:r,match(o,t){let n=o[t];if(!n||n.type!=="IDENT"||(n.value??"").toLowerCase()!=="plot"||o[t-1]?.type==="COLON")return null;let i=o[t+1];return !i||!yc.has(i.type)?null:{consumed:1,replacement:[new a$6(rs,Tc,n.value,n.value,n.offset,0,n.line,n.col)],ruleName:e}}}}var nn={name:"solve-chart",asConverters:{sparkline:r=>{let e=es(r);return e?I$1(e):O("SPARKLINE_NOT_A_SERIES",'"as sparkline" expects a numeric vector or a range, with at least two values')}},prefixParselets:{PLOT:new Gt},normalizerRules:[ts()],tokenCategories:{PLOT:"keyword"}};var PR=[eo,ro,oo,lo,_o,Ao,Oo,So,wo,vo,ko,Bo,a$4,Mo,Uo,Do,Vo,Go,Zo,Ko,$o,qo,Yo,tn,nn,Qo];
2
+ export{eo as a,ro as b,oo as c,lo as d,_o as e,Ao as f,Oo as g,So as h,Lo as i,wo as j,vo as k,ko as l,Bo as m,Mo as n,Uo as o,Do as p,Vo as q,Go as r,Ko as s,nm as t,am as u,$o as v,Yo as w,Qo as x,PR as y};//# sourceMappingURL=chunk-T4Y5XOT2.js.map
3
+ //# sourceMappingURL=chunk-T4Y5XOT2.js.map