solve-engine 2.23.0 → 2.24.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 (202) hide show
  1. package/README.md +82 -32
  2. package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
  3. package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
  4. package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-D1kXsjIj.d.cts} +4 -0
  5. package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-D1kXsjIj.d.ts} +4 -0
  6. package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-Bq82y0ZN.d.ts} +1 -1
  7. package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CeAPVHZr.d.cts} +1 -1
  8. package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-B9-7fJGH.d.cts} +16 -11
  9. package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-CDEgfhT_.d.ts} +16 -11
  10. package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-4oH5OuRt.d.cts} +1 -1
  11. package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-BwDqKFfK.d.ts} +1 -1
  12. package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-BQBhlDAu.d.ts} +38 -7
  13. package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-DrXB3Nvm.d.cts} +38 -7
  14. package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-BK32PTl2.d.cts} +2 -2
  15. package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-C5jC92o3.d.ts} +2 -2
  16. package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
  17. package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
  18. package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-CVQbs6_D.d.ts} +1 -1
  19. package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-DaNWQFp1.d.cts} +1 -1
  20. package/dist/chunk-2BXNZM3G.js +2 -0
  21. package/dist/chunk-2BXNZM3G.js.map +1 -0
  22. package/dist/chunk-2JSNWYYA.cjs +3 -0
  23. package/dist/chunk-2JSNWYYA.cjs.map +1 -0
  24. package/dist/{chunk-J7ABVGZH.cjs → chunk-2VE4OW4A.cjs} +2 -2
  25. package/dist/{chunk-J7ABVGZH.cjs.map → chunk-2VE4OW4A.cjs.map} +1 -1
  26. package/dist/{chunk-HMC7FJO7.js → chunk-3SHWTGTP.js} +2 -2
  27. package/dist/{chunk-HMC7FJO7.js.map → chunk-3SHWTGTP.js.map} +1 -1
  28. package/dist/{chunk-EN3CDYOS.cjs → chunk-5GL4SAVH.cjs} +2 -2
  29. package/dist/{chunk-EN3CDYOS.cjs.map → chunk-5GL4SAVH.cjs.map} +1 -1
  30. package/dist/{chunk-SGIDBZ4T.cjs → chunk-72N3ZRVE.cjs} +2 -2
  31. package/dist/chunk-72N3ZRVE.cjs.map +1 -0
  32. package/dist/{chunk-CHSO3DCS.js → chunk-7EP36NXE.js} +3 -3
  33. package/dist/{chunk-CHSO3DCS.js.map → chunk-7EP36NXE.js.map} +1 -1
  34. package/dist/chunk-A4JV7HRB.js +3 -0
  35. package/dist/chunk-A4JV7HRB.js.map +1 -0
  36. package/dist/chunk-AUOE7MFI.cjs +2 -0
  37. package/dist/chunk-AUOE7MFI.cjs.map +1 -0
  38. package/dist/chunk-BDF4VCQX.js +3 -0
  39. package/dist/chunk-BDF4VCQX.js.map +1 -0
  40. package/dist/{chunk-3SSMOVWB.cjs → chunk-CDNJZBM3.cjs} +2 -2
  41. package/dist/{chunk-3SSMOVWB.cjs.map → chunk-CDNJZBM3.cjs.map} +1 -1
  42. package/dist/{chunk-YAONCEAW.cjs → chunk-CMZSK6FY.cjs} +3 -3
  43. package/dist/{chunk-YAONCEAW.cjs.map → chunk-CMZSK6FY.cjs.map} +1 -1
  44. package/dist/chunk-D2Q2VFJ6.js +2 -0
  45. package/dist/chunk-D2Q2VFJ6.js.map +1 -0
  46. package/dist/{chunk-75JLWK4L.cjs → chunk-DA7M6H63.cjs} +2 -2
  47. package/dist/{chunk-75JLWK4L.cjs.map → chunk-DA7M6H63.cjs.map} +1 -1
  48. package/dist/chunk-ELQQKZN3.cjs +3 -0
  49. package/dist/{chunk-PIZQIQVM.js.map → chunk-ELQQKZN3.cjs.map} +1 -1
  50. package/dist/chunk-F7QIBC4B.cjs +3 -0
  51. package/dist/chunk-F7QIBC4B.cjs.map +1 -0
  52. package/dist/chunk-GP4H5OIT.js +3 -0
  53. package/dist/chunk-GP4H5OIT.js.map +1 -0
  54. package/dist/chunk-HQ7BKXG7.js +2 -0
  55. package/dist/chunk-HQ7BKXG7.js.map +1 -0
  56. package/dist/{chunk-KRXO3MOW.cjs → chunk-IHAZL4EF.cjs} +2 -2
  57. package/dist/chunk-IHAZL4EF.cjs.map +1 -0
  58. package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
  59. package/dist/chunk-IJHL3LMH.js.map +1 -0
  60. package/dist/{chunk-3GR46UOX.js → chunk-IPSOWFCA.js} +2 -2
  61. package/dist/{chunk-3GR46UOX.js.map → chunk-IPSOWFCA.js.map} +1 -1
  62. package/dist/chunk-LM6ZQUEU.js +2 -0
  63. package/dist/chunk-LM6ZQUEU.js.map +1 -0
  64. package/dist/{chunk-N37PUZJR.cjs → chunk-LTJV3VJE.cjs} +2 -2
  65. package/dist/{chunk-N37PUZJR.cjs.map → chunk-LTJV3VJE.cjs.map} +1 -1
  66. package/dist/chunk-MWWAKZOD.cjs +3 -0
  67. package/dist/chunk-MWWAKZOD.cjs.map +1 -0
  68. package/dist/chunk-NUF66H57.js +5 -0
  69. package/dist/chunk-NUF66H57.js.map +1 -0
  70. package/dist/{chunk-MRRMIBHE.js → chunk-OMHRBKAT.js} +2 -2
  71. package/dist/{chunk-MRRMIBHE.js.map → chunk-OMHRBKAT.js.map} +1 -1
  72. package/dist/{chunk-4ETS224G.js → chunk-PTQCHMYA.js} +2 -2
  73. package/dist/{chunk-4ETS224G.js.map → chunk-PTQCHMYA.js.map} +1 -1
  74. package/dist/{chunk-4DJJIUQF.js → chunk-PWWQZFAE.js} +2 -2
  75. package/dist/chunk-PWWQZFAE.js.map +1 -0
  76. package/dist/chunk-RE6AIU6Y.js +3 -0
  77. package/dist/chunk-RE6AIU6Y.js.map +1 -0
  78. package/dist/chunk-RECRD45C.cjs +5 -0
  79. package/dist/chunk-RECRD45C.cjs.map +1 -0
  80. package/dist/{chunk-O3BDXOQJ.js → chunk-RENO2AWO.js} +2 -2
  81. package/dist/{chunk-O3BDXOQJ.js.map → chunk-RENO2AWO.js.map} +1 -1
  82. package/dist/chunk-RMCN5WFO.cjs +2 -0
  83. package/dist/chunk-RMCN5WFO.cjs.map +1 -0
  84. package/dist/{chunk-TL545PXW.cjs → chunk-RN3ISTM3.cjs} +2 -2
  85. package/dist/{chunk-TL545PXW.cjs.map → chunk-RN3ISTM3.cjs.map} +1 -1
  86. package/dist/{chunk-JYLNQOPU.cjs → chunk-S46R5QZP.cjs} +2 -2
  87. package/dist/{chunk-JYLNQOPU.cjs.map → chunk-S46R5QZP.cjs.map} +1 -1
  88. package/dist/{chunk-USQ4KL6S.cjs → chunk-UPH22K2T.cjs} +2 -2
  89. package/dist/chunk-UPH22K2T.cjs.map +1 -0
  90. package/dist/{chunk-KEA5HRL3.js → chunk-UXR7JIPX.js} +2 -2
  91. package/dist/{chunk-KEA5HRL3.js.map → chunk-UXR7JIPX.js.map} +1 -1
  92. package/dist/chunk-UY3ID6JF.cjs +2 -0
  93. package/dist/chunk-UY3ID6JF.cjs.map +1 -0
  94. package/dist/{chunk-JVMINMAB.js → chunk-WFOQRPA6.js} +2 -2
  95. package/dist/{chunk-JVMINMAB.js.map → chunk-WFOQRPA6.js.map} +1 -1
  96. package/dist/{chunk-AF7HQN6I.js → chunk-XFJABR3B.js} +2 -2
  97. package/dist/chunk-XFJABR3B.js.map +1 -0
  98. package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
  99. package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
  100. package/dist/constants.cjs +1 -1
  101. package/dist/constants.d.cts +1 -1
  102. package/dist/constants.d.ts +1 -1
  103. package/dist/constants.js +1 -1
  104. package/dist/engine.cjs +1 -1
  105. package/dist/engine.d.cts +9 -9
  106. package/dist/engine.d.ts +9 -9
  107. package/dist/engine.js +1 -1
  108. package/dist/errors.cjs +1 -1
  109. package/dist/errors.d.cts +3 -3
  110. package/dist/errors.d.ts +3 -3
  111. package/dist/errors.js +1 -1
  112. package/dist/format.cjs +1 -1
  113. package/dist/format.d.cts +1 -1
  114. package/dist/format.d.ts +1 -1
  115. package/dist/format.js +1 -1
  116. package/dist/index.cjs +1 -1
  117. package/dist/index.cjs.map +1 -1
  118. package/dist/index.d.cts +11 -9
  119. package/dist/index.d.ts +11 -9
  120. package/dist/index.js +1 -1
  121. package/dist/index.js.map +1 -1
  122. package/dist/language.d.cts +8 -8
  123. package/dist/language.d.ts +8 -8
  124. package/dist/lexer.cjs +1 -1
  125. package/dist/lexer.js +1 -1
  126. package/dist/normalizer.cjs +1 -1
  127. package/dist/normalizer.d.cts +14 -8
  128. package/dist/normalizer.d.ts +14 -8
  129. package/dist/normalizer.js +1 -1
  130. package/dist/packages.cjs +1 -1
  131. package/dist/packages.d.cts +7 -7
  132. package/dist/packages.d.ts +7 -7
  133. package/dist/packages.js +1 -1
  134. package/dist/parser.cjs +1 -1
  135. package/dist/parser.d.cts +3 -3
  136. package/dist/parser.d.ts +3 -3
  137. package/dist/parser.js +1 -1
  138. package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
  139. package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
  140. package/dist/resolvers.cjs +1 -1
  141. package/dist/resolvers.d.cts +18 -2
  142. package/dist/resolvers.d.ts +18 -2
  143. package/dist/resolvers.js +1 -1
  144. package/dist/testing.cjs +2 -2
  145. package/dist/testing.d.cts +8 -8
  146. package/dist/testing.d.ts +8 -8
  147. package/dist/testing.js +1 -1
  148. package/dist/uom.cjs +1 -1
  149. package/dist/uom.d.cts +1 -1
  150. package/dist/uom.d.ts +1 -1
  151. package/dist/uom.js +1 -1
  152. package/dist/vm.cjs +1 -1
  153. package/dist/vm.d.cts +7 -7
  154. package/dist/vm.d.ts +7 -7
  155. package/dist/vm.js +1 -1
  156. package/dist/worker.cjs +2 -2
  157. package/dist/worker.cjs.map +1 -1
  158. package/dist/worker.d.cts +31 -22
  159. package/dist/worker.d.ts +31 -22
  160. package/dist/worker.js +1 -1
  161. package/dist/worker.js.map +1 -1
  162. package/package.json +1 -1
  163. package/dist/chunk-42JXN3BH.js +0 -5
  164. package/dist/chunk-42JXN3BH.js.map +0 -1
  165. package/dist/chunk-4DJJIUQF.js.map +0 -1
  166. package/dist/chunk-6YM67DWH.cjs +0 -3
  167. package/dist/chunk-6YM67DWH.cjs.map +0 -1
  168. package/dist/chunk-7E7NXKQ5.js.map +0 -1
  169. package/dist/chunk-7SZBEE5R.cjs +0 -2
  170. package/dist/chunk-7SZBEE5R.cjs.map +0 -1
  171. package/dist/chunk-A5M4QZIK.js +0 -2
  172. package/dist/chunk-A5M4QZIK.js.map +0 -1
  173. package/dist/chunk-AF7HQN6I.js.map +0 -1
  174. package/dist/chunk-ALY4ZMYO.js +0 -2
  175. package/dist/chunk-ALY4ZMYO.js.map +0 -1
  176. package/dist/chunk-BRJ4RT5U.js +0 -2
  177. package/dist/chunk-BRJ4RT5U.js.map +0 -1
  178. package/dist/chunk-CO2BI6WL.cjs +0 -3
  179. package/dist/chunk-CO2BI6WL.cjs.map +0 -1
  180. package/dist/chunk-EQDT42JG.js +0 -3
  181. package/dist/chunk-EQDT42JG.js.map +0 -1
  182. package/dist/chunk-FMMT5C5H.cjs +0 -3
  183. package/dist/chunk-FMMT5C5H.cjs.map +0 -1
  184. package/dist/chunk-FP6Z6PYR.js +0 -2
  185. package/dist/chunk-FP6Z6PYR.js.map +0 -1
  186. package/dist/chunk-H3JXNH7X.cjs +0 -3
  187. package/dist/chunk-H3JXNH7X.cjs.map +0 -1
  188. package/dist/chunk-HZOLIL5T.js +0 -3
  189. package/dist/chunk-HZOLIL5T.js.map +0 -1
  190. package/dist/chunk-KRXO3MOW.cjs.map +0 -1
  191. package/dist/chunk-KVLJDOZ7.cjs +0 -5
  192. package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
  193. package/dist/chunk-LNZNJSRW.cjs.map +0 -1
  194. package/dist/chunk-PIZQIQVM.js +0 -3
  195. package/dist/chunk-QTSDIDAS.js +0 -3
  196. package/dist/chunk-QTSDIDAS.js.map +0 -1
  197. package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
  198. package/dist/chunk-UNKSCVIL.cjs +0 -2
  199. package/dist/chunk-UNKSCVIL.cjs.map +0 -1
  200. package/dist/chunk-USQ4KL6S.cjs.map +0 -1
  201. package/dist/chunk-XDXIPVZB.cjs +0 -2
  202. package/dist/chunk-XDXIPVZB.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lexer/LexerState.ts","../src/lexer/Lexer.ts","../src/lexer/TokenClassRegistry.ts","../src/lexer/tokenRegistration.ts"],"names":["LexerState","Lexer","localeCode","tokenLookup","ExpressionLexer","input","state","newState","lineText","plugin","text","classification","result","token","getTokenCategory","sharedLexer","TokenClassRegistry","tokenClass","tokenType","c","keywordMap","phraseMap","unitNames","keywordToType","keyword","sorted","a","b","tc","phraseTrie","phraseStartWords","root","phrase","words","node","word","startWords","first","BUILTIN_PHRASES","buildTokenLookup","locale","getLocale","registry","knownUnits"],"mappings":"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","file":"chunk-KRXO3MOW.cjs","sourcesContent":["/**\n * Lexer state machine modes.\n * - Main: document-level scanning with markdown classification\n * - Inline: expression embedded in markdown inline solve (`s\\`...\\``)\n * - String: inside a double-quoted string literal\n */\nexport enum LexerState {\n\tMain = \"main\",\n\tInline = \"inline\",\n\tString = \"string\",\n}\n","import { ExpressionLexer, LineClassification, LexerVocabulary, type ScanLineResult } from \"./ExpressionLexer\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { LexerState } from \"@solve-js/lexer/LexerState\";\nimport { getTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport type { TokenCategory } from \"@solve-js/language/TokenCategory\";\nimport type { TokenLookup } from \"@solve-js/lexer/TokenClassRegistry\";\n\n/**\n * Public tokenizer wrapper around {@link ExpressionLexer}.\n *\n * `ExpressionLexer` does the actual character-by-character scanning;\n * `Lexer` adds a materialized-token-array streaming interface\n * (`next()`/`peek()`) plus line-classification state (`reset()`) so\n * callers can iterate a line's tokens without re-scanning on each peek.\n *\n * Each `ExpressionEngine` instance owns its own `Lexer`, and packages\n * extend it via {@link registerVocabulary} (keywords, operators, units)\n * see `IEnginePackage.lexerVocabulary`.\n */\nexport class Lexer {\n /** Expression-mode lexer (Phase A: V8-optimized, replaces moo) */\n private expressionLexer: ExpressionLexer;\n private currentState: LexerState = LexerState.Main;\n private peekedToken: Token | undefined;\n private hasPeeked = false;\n\n // Materialized token array from the last reset() call, used for\n // next()/peek() streaming access.\n private tokens: Token[] = [];\n private tokenIdx: number = 0;\n\n /**\n * @param localeCode - Locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @param tokenLookup - Optional TokenLookup from TokenClassRegistry.\n * When provided, configures ExpressionLexer to use registry-built\n * keyword/unit/phrase lookups instead of internal instance maps.\n */\n constructor(localeCode = \"en\", tokenLookup?: TokenLookup) {\n // Pass the lookup directly to ExpressionLexer's constructor, it's an\n // instance field now, not a static. Each Lexer instance gets its own\n // isolated lookup, preventing cross-instance corruption.\n this.expressionLexer = new ExpressionLexer(localeCode, tokenLookup);\n }\n\n reset(input: string, state?: LexerState): void {\n const newState = state ?? LexerState.Main;\n this.currentState = newState;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n\n // Phase B: Main state classifies the line with the markdown scanner.\n // Skip lines (headings, fences, HRs, etc.) produce empty token arrays.\n // Expression lines and lines with inline solves are tokenized normally.\n if (newState === LexerState.Main) {\n const classification = this.expressionLexer.classifyLine(input);\n if (classification.skip) {\n this.tokens = [];\n this.tokenIdx = 0;\n return;\n }\n // Expression line or markdown line with inline solves, tokenize.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n } else {\n // Non-main states (Inline, String), expression tokenization.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n }\n\n /**\n * Classify a single line of markdown text (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n classifyLine(lineText: string): LineClassification {\n return this.expressionLexer.classifyLine(lineText);\n }\n\n /**\n * Find all inline solve markers in a line (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n findInlineSolves(lineText: string) {\n return this.expressionLexer.findInlineSolves(lineText);\n }\n\n /**\n * Every keyword this lexer currently recognizes (locale + plugin-contributed),\n * mapped to the token type it lexes to. Delegates to the ExpressionLexer.\n */\n getKeywords(): Record<string, string> {\n return this.expressionLexer.getKeywords();\n }\n\n next(): Token | undefined {\n if (this.hasPeeked) {\n this.hasPeeked = false;\n return this.peekedToken;\n }\n // Materialized token array (ExpressionLexer path).\n if (this.tokenIdx < this.tokens.length) {\n return this.tokens[this.tokenIdx++];\n }\n return undefined;\n }\n\n peek(): Token | undefined {\n if (this.hasPeeked) return this.peekedToken;\n this.peekedToken = this.next();\n this.hasPeeked = true;\n return this.peekedToken;\n }\n\n [Symbol.iterator](): Iterator<Token> {\n return this.tokens[Symbol.iterator]();\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n * Delegates to the underlying ExpressionLexer.\n *\n * @see LexerVocabulary for the supported extension points.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.registerVocabulary(plugin);\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n * Delegates to the underlying ExpressionLexer.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.unregisterVocabulary(plugin);\n }\n\n /**\n * Reset the lexer for expression-only text, skips the classifyLine()\n * overhead in reset() for callers that already know the input is an\n * evaluable expression (e.g., after isEmptyLine() confirmed non-skip).\n */\n resetExpression(input: string): void {\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n\n /**\n * Scan a full document in one pass, classifying each line and\n * tokenizing non-skipped lines. Delegates to ExpressionLexer.\n *\n * @returns ScanLineResult[], one per line, with classification + tokens.\n */\n scanDocument(text: string): ScanLineResult[] {\n return this.expressionLexer.scanDocument(text);\n }\n\n getState(): LexerState {\n return this.currentState;\n }\n\n setState(state: LexerState): void {\n this.currentState = state;\n }\n\n getHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n\n // For blockquote lines, strip the \"> \" prefix and tokenize the expression content.\n // This lets expressions inside blockquotes (e.g., \"> 1 + 2\") get syntax highlighted\n // while pure structural lines (headings, code fences) remain unhighlighted.\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectHighlightTokens(lineText.slice(2));\n }\n\n if (classification.skip) {\n return [];\n }\n\n return this.collectHighlightTokens(lineText);\n }\n\n /**\n * The same tokens {@link getHighlightTokens} reduces, before reduction.\n *\n * Exists because normalization operates on tokens, not on the flattened\n * shape, and a consumer that wants phrase-fused highlighting has to run the\n * normalizer between the two. See `LanguageService.getSemanticTokens`.\n *\n * @param lineText - One line of source.\n * @returns Every token on the line that is worth painting, unreduced.\n */\n getHighlightTokenObjects(lineText: string): Token[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectTokenObjects(lineText.slice(2));\n }\n if (classification.skip) return [];\n return this.collectTokenObjects(lineText);\n }\n\n private collectTokenObjects(lineText: string): Token[] {\n this.resetExpression(lineText);\n const result: Token[] = [];\n for (const token of this) {\n if (token.type === \"WS\" || token.type === \"NEWLINE\") continue;\n if (token.type.startsWith(\"MD_\")) continue;\n if (token.type === \"INLINE_SOLVE_START\" || token.type === \"BACKTICK_CLOSE\") continue;\n result.push(token);\n }\n return result;\n }\n\n private collectHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n return this.collectTokenObjects(lineText).map(token => ({\n type: token.type,\n value: token.value,\n offset: token.offset,\n col: token.col,\n // `text`, not `value`: this is a span into the source, and the two\n // differ for a string literal, whose value is the payload while its\n // text still carries the quote characters the reader typed.\n length: token.text.length,\n category: getTokenCategory(token.type),\n }));\n }\n}\n\n/**\n * A lexer for operations that do not depend on registered vocabulary.\n *\n * Line classification and inline-solve detection read characters looking for\n * headings, comment markers, fences and backtick spans, and never consult the\n * keyword, unit or operator tables. Every lexer therefore returns the same\n * answer, so the callers that have no engine to ask can use this one. Checked\n * by `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n *\n * Do not tokenize with this. An engine's own lexer carries the vocabulary its\n * packages registered; this one carries none.\n */\nexport const sharedLexer = new Lexer(\"en\", undefined);","/**\n * TokenClass, Plugin-extensible keyword registration for the Lexer.\n *\n * Providers call `registry.register(tokenClass)` to teach the lexer about\n * their keywords. The registry merges locale keywords, provider keywords,\n * phrase mappings, and unit names into an optimized TokenLookup structure\n * consumed by the Lexer.\n *\n * @example\n * registry.register({\n * tokenType: 'CARET',\n * keywords: {},\n * phrases: { 'to the power of': true, 'power of': true },\n * priority: 10,\n * description: 'Exponentiation operators (x^y)',\n * });\n */\nexport interface TokenClass {\n /** The token type string produced by the lexer (e.g., \"FUNC\", \"PI\", \"CARET\").\n * Must match a token type that a ParseletRegistry has a parselet for. */\n tokenType: string;\n\n /** Single-word keywords (case-insensitive). The lexer lowercases input\n * before lookup, so these should be lowercase. Example:\n * { sqrt: true, abs: true, sin: true, cos: true } for tokenType \"FUNC\" */\n keywords: Record<string, boolean>;\n\n /** Multi-word phrases (case-insensitive). Matched by the built-in PhraseMatcher\n * via the phrase trie. Example:\n * { \"to the power of\": true, \"power of\": true } for tokenType \"CARET\" */\n phrases?: Record<string, boolean>;\n\n /** Priority for conflict resolution. When two TokenClasses register\n * the same keyword, the higher-priority class wins. Locale keywords\n * have priority 0 (set via setLocale). Providers should use\n * priority >= 10 to override locale defaults. Default: 0 */\n priority?: number;\n\n /** Human-readable description for debugging and introspection */\n description?: string;\n}\n\n// ── Phrase Trie ──────────────────────────────────────────────────────────────\n\n/** Trie node for multi-word phrase matching. */\nexport interface PhraseNode {\n /** Complete phrase token type (null = intermediate node) */\n type?: string;\n children: Map<string, PhraseNode>;\n}\n\n// ── TokenLookup, Optimized lookup structure for the Lexer ──────────────────\n\n/**\n * The optimized lookup structure built by TokenClassRegistry.build().\n * Consumed by the Lexer for O(1) keyword → token type lookups and\n * O(word-count) phrase matching.\n */\nexport interface TokenLookup {\n /** Lowercase keyword → token type. O(1) Map lookup. */\n keywordToType: Map<string, string>;\n\n /** Phrase trie for multi-word matching. Root node with children maps.\n * Null if no phrases registered. */\n phraseTrie: PhraseNode | null;\n\n /** Set of lowercase first-words of all registered phrases.\n * Used by the lexer to emit IDENT (not a phrase keyword) for words\n * that start multi-word phrases, deferring to the PhraseMatcher.\n *\n * Example: \"to\" is in phraseStartWords because \"to the power of\" is a phrase.\n * When the lexer sees \"to\", it emits IDENT and lets the phrase matcher\n * combine \"to the power of\" into a single CARET token.\n *\n * This prevents plugins from accidentally overriding phrase-start words.\n */\n phraseStartWords: Set<string>;\n\n /** Case-sensitive unit names for UNIT fallback after keyword lookup fails. */\n unitNames: ReadonlySet<string>;\n}\n\n// ── TokenClassRegistry ───────────────────────────────────────────────────────\n\n/**\n * Central registry for keyword→token-type mappings.\n *\n * Providers register TokenClasses; locales provide keyword maps;\n * units provide a name set. `build()` merges all sources into an\n * optimized TokenLookup consumed by the Lexer.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider keywords (sorted by priority ascending, higher priority wins)\n *\n * Unit names are stored separately (checked AFTER keyword lookup fails).\n * Phrases are stored in a trie for O(phrase-length) matching.\n */\nexport class TokenClassRegistry {\n private classes: TokenClass[] = [];\n private localeKeywordMap: Record<string, string> | null = null;\n private localePhraseMap: Record<string, string> | null = null;\n private unitNames: ReadonlySet<string> | null = null;\n\n /**\n * Register a provider's TokenClass. Must be called BEFORE build().\n * Can be called multiple times to add more entries.\n *\n * Built-in token types CANNOT be overridden, throws a EngineError\n * if the TokenClass attempts to register a keyword that conflicts\n * with an already-registered token type.\n */\n register(tokenClass: TokenClass): void {\n this.classes.push(tokenClass);\n }\n\n /**\n * Unregister all TokenClasses for a given token type.\n * Useful for plugin unload. Requires rebuild() to take effect.\n */\n unregister(tokenType: string): void {\n this.classes = this.classes.filter(c => c.tokenType !== tokenType);\n }\n\n /**\n * Set the locale's keyword→type map and optional phrase map.\n * Called on locale change. Priority 0 (cannot override providers with higher priority).\n */\n setLocale(keywordMap: Record<string, string>, phraseMap?: Record<string, string>): void {\n this.localeKeywordMap = keywordMap;\n this.localePhraseMap = phraseMap ?? null;\n }\n\n /**\n * Set the unit name set. Called when unit list changes.\n * Units are stored separately (checked AFTER keyword lookup fails).\n *\n * Takes a ReadonlySet because the caller's set is derived from the\n * conversion tables and must not be mutated; this class only ever reads it.\n */\n setUnits(unitNames: ReadonlySet<string>): void {\n this.unitNames = unitNames;\n }\n\n /**\n * Build the optimized TokenLookup from all registered sources.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider classes (sorted by priority ascending)\n *\n * Returns a frozen TokenLookup that the Lexer consumes.\n * Call build() again after register()/setLocale()/setUnits() changes.\n */\n build(): TokenLookup {\n const keywordToType = new Map<string, string>();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n if (this.localeKeywordMap) {\n for (const [keyword, tokenType] of Object.entries(this.localeKeywordMap)) {\n keywordToType.set(keyword.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider keywords (sorted by priority ascending, higher wins)\n const sorted = [...this.classes].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n for (const tc of sorted) {\n for (const keyword of Object.keys(tc.keywords)) {\n keywordToType.set(keyword.toLowerCase(), tc.tokenType);\n }\n }\n\n // Build phrase trie from locale + provider phrases\n const phraseTrie = this.buildPhraseTrie();\n\n // Build phraseStartWords set (first word of every phrase)\n const phraseStartWords = this.buildPhraseStartWords();\n\n return {\n keywordToType,\n phraseTrie,\n phraseStartWords,\n unitNames: this.unitNames ?? new Set(),\n };\n }\n\n // ── Private helpers ─────────────────────────────────────────────────────\n\n private buildPhraseTrie(): PhraseNode | null {\n const root: PhraseNode = { children: new Map() };\n\n // Layer 1: Locale phrases\n if (this.localePhraseMap) {\n for (const [phrase, tokenType] of Object.entries(this.localePhraseMap)) {\n this.insertPhrase(root, phrase.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider phrases\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n this.insertPhrase(root, phrase.toLowerCase(), tc.tokenType);\n }\n }\n\n return root.children.size > 0 ? root : null;\n }\n\n private insertPhrase(root: PhraseNode, phrase: string, tokenType: string): void {\n const words = phrase.split(' ');\n let node = root;\n for (const word of words) {\n if (!node.children.has(word)) {\n node.children.set(word, { children: new Map() });\n }\n node = node.children.get(word)!;\n }\n // Only set type if not already set, first-registered (locale) wins\n if (!node.type) {\n node.type = tokenType;\n }\n }\n\n private buildPhraseStartWords(): Set<string> {\n const startWords = new Set<string>();\n\n // Locale phrase first words\n if (this.localePhraseMap) {\n for (const phrase of Object.keys(this.localePhraseMap)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n // Provider phrase first words\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n return startWords;\n }\n}","/**\n * tokenRegistration.ts, Bootstrap for building TokenLookup from locale, units, and phrases.\n *\n * This module centralizes the assembly of the TokenLookup consumed by ExpressionLexer.\n * It merges:\n * 1. Locale keywords (from ILocale.keywordMap)\n * 2. Built-in phrase patterns (to the power of, increase by, etc.)\n * 3. Known unit names (from units.ts)\n *\n * The resulting TokenLookup is frozen and passed to ExpressionLexer.configuredLookup\n * at construction time, enabling data-driven keyword/unit/phrase resolution.\n */\nimport { TokenClassRegistry } from '@solve-js/lexer/TokenClassRegistry';\nimport type { TokenLookup } from '@solve-js/lexer/TokenClassRegistry';\nimport { getLocale, type ILocale } from '@solve-js/constants/locales';\nimport { knownUnits } from '@solve-js/lexer/units';\n\n// ── Built-in phrase map ───────────────────────────────────────────────────\n// These are the multi-word expressions handled as compound tokens.\n// Matched by the PhraseMatcher (trie-based) in ExpressionLexer.tryMatchPhrase().\nconst BUILTIN_PHRASES: Record<string, string> = {\n 'to the power of': 'CARET',\n 'power of': 'CARET',\n 'increase by': 'INCREASE_BY',\n 'decrease by': 'DECREASE_BY',\n 'times by': 'TIMES_BY',\n 'multiply by': 'MULTIPLY_BY',\n 'multiplied by': 'MULTIPLY_BY',\n 'divide by': 'DIVIDE_BY',\n};\n\n/**\n * Build a TokenLookup from locale keywords, known units, and built-in phrases.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0, lowest, can be overridden by providers)\n * 2. Built-in phrases (via locale phraseMap)\n * 3. Known units (checked AFTER keyword lookup fails, via unitNames set)\n *\n * The resulting TokenLookup replaces the internal keyword map, unit set,\n * phrase trie, and phraseStartWords in ExpressionLexer when set via\n * ExpressionLexer.configuredLookup.\n *\n * @param localeCode - The locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @returns A frozen TokenLookup ready for consumption by the lexer.\n */\nexport function buildTokenLookup(localeCode = 'en'): TokenLookup {\n const locale: ILocale = getLocale(localeCode);\n const registry = new TokenClassRegistry();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n registry.setLocale(locale.keywordMap, BUILTIN_PHRASES);\n\n // Layer 2: Known units (checked after keyword lookup)\n registry.setUnits(knownUnits);\n\n // Build and return the lookup\n return registry.build();\n}\n"]}
@@ -1,5 +0,0 @@
1
- 'use strict';var chunkJYLNQOPU_cjs=require('./chunk-JYLNQOPU.cjs'),chunkLNZNJSRW_cjs=require('./chunk-LNZNJSRW.cjs'),chunkTTFO4YDP_cjs=require('./chunk-TTFO4YDP.cjs'),chunkUNKSCVIL_cjs=require('./chunk-UNKSCVIL.cjs'),chunkHG4NPDN5_cjs=require('./chunk-HG4NPDN5.cjs'),chunkH3JXNH7X_cjs=require('./chunk-H3JXNH7X.cjs'),chunkN37PUZJR_cjs=require('./chunk-N37PUZJR.cjs'),chunkEN3CDYOS_cjs=require('./chunk-EN3CDYOS.cjs'),chunkSGIDBZ4T_cjs=require('./chunk-SGIDBZ4T.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkZLRJ7TDP_cjs=require('./chunk-ZLRJ7TDP.cjs'),chunkXDXIPVZB_cjs=require('./chunk-XDXIPVZB.cjs'),chunkJ7ABVGZH_cjs=require('./chunk-J7ABVGZH.cjs'),chunk75JLWK4L_cjs=require('./chunk-75JLWK4L.cjs'),chunk7SZBEE5R_cjs=require('./chunk-7SZBEE5R.cjs'),chunkKRXO3MOW_cjs=require('./chunk-KRXO3MOW.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkUSQ4KL6S_cjs=require('./chunk-USQ4KL6S.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');function wt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let a=new Set(Object.keys(s));for(let l of Object.keys(o))a.has(l)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Tt(n,e){let t=[];if(wt("prefixParseletTokenType","prefixParselets",n,e,t),wt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let a=n.phrases[s];a!==void 0&&a!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[n.name,e.name]});}if(n.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(n.asConverters).some(a=>a.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[n.name,e.name]});}if(n.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(n.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[n.name,e.name]});}if(n.normalizerRules&&e.normalizerRules){let s=new Set(n.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[n.name,e.name]});}let r=n.lexerVocabulary,i=e.lexerVocabulary;if(r?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let a=r.keywords[s];a!==void 0&&a!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let a=r.operators[s];a!==void 0&&a!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[n.name,e.name]});}if(n.asyncResolvers&&e.asyncResolvers){let s=new Set(n.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${n.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[n.name,e.name]});}if(n.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let a=n.tokenCategories[s];a!==void 0&&a!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[n.name,e.name]});}return t}function Nr(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Tt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var he=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,r=(s,o)=>{let a=s.get(o);a&&a!==e&&a.name!==e.name&&t.add(a);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))r(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))r(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))r(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))r(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))r(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)r(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))r(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))r(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)r(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))r(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Tt(s,e));return i}add(e){let t=(r,i)=>{r.has(i)||r.set(i,e);};if(e.prefixParselets)for(let r of Object.keys(e.prefixParselets))t(this.prefixOwners,r);if(e.infixParselets)for(let r of Object.keys(e.infixParselets))t(this.infixOwners,r);if(e.phrases)for(let r of Object.keys(e.phrases))t(this.phraseOwners,r);if(e.asConverters)for(let r of Object.keys(e.asConverters))t(this.converterOwners,r.toLowerCase());if(e.pluginFunctions)for(let r of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,r);if(e.normalizerRules)for(let r of e.normalizerRules)t(this.ruleOwners,r.name);if(e.lexerVocabulary?.keywords)for(let r of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,r);if(e.lexerVocabulary?.operators)for(let r of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,r);if(e.asyncResolvers)for(let r of e.asyncResolvers)t(this.resolverOwners,r.namespace);if(e.tokenCategories)for(let r of Object.keys(e.tokenCategories))t(this.categoryOwners,r);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Qt=/(\d+)\.(\d+)\.(\d+)/,Xt=/^\d+$/;function Nt(n){let e=Qt.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Jt(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Ne(n){let e=n.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let r=0;r<e.length;r++){if(!Xt.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Yt([n,e,t]){let r=n>0?[n+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[n,e,t]},{op:"<",v:r}]}function Zt([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function er(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Ne(n.slice(1));return i&&Yt(i)}if(n[0]==="~"){let i=Ne(n.slice(1));return i&&Zt(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Ne(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Rt(n){let e=[];for(let t of n.split("||")){let r=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of r){let o=er(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function At(n){return Rt(n.trim())!==null}function tr(n,e){let t=Jt(n,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function Pt(n,e){let t=Rt(e.trim());return t===null?false:t.some(r=>r.every(i=>tr(n,i)))}function rr(n,e=chunk7SZBEE5R_cjs.a){if(!n.engineVersion)return {compatible:true};if(!At(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Nt(e);return t===null||!Pt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function Lt(n,e=chunk7SZBEE5R_cjs.a){let t=rr(n,e);if(!t.compatible)throw t.reason==="invalid-range"?chunkCO2BI6WL_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):chunkCO2BI6WL_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var X="solve-engine/snapshot",K=1;function F(n){return Number.isFinite(n)?n:Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity"}function _(n){if(typeof n=="number")return n;if(n==="NaN")return NaN;if(n==="Infinity")return 1/0;if(n==="-Infinity")return -1/0;throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(n)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(n)})}var D={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Ot(n){return {coef:n.coef.toString(),scale:n.scale}}function It(n){return {coef:BigInt(n.coef),scale:n.scale}}function nr(n){return {n:n.n.toString(),d:n.d.toString()}}function ir(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Vt(n){return chunk75JLWK4L_cjs.g[n]??String(n)}function Re(n,e){throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Vt(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Vt(n)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:n,location:e}})}function Ae(n,e){switch(n.type){case 0:{let t={t:0,v:F(n.value)};return n.exact!==void 0&&(t.exact=Ot(n.exact)),n.rational!==void 0&&(t.rational=nr(n.rational)),t}case 1:{let t=n.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:n.unit}:{t:1,v:F(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:return {t:4,v:F(n.value)};case 5:return {t:5,v:F(n.value)};case 6:{let t={t:6,v:F(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=Ot(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Re(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>sr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:F(t.min),max:F(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Re(n.type,e)}}function sr(n,e){return typeof n=="boolean"?n:typeof n=="number"?F(n):Re(9,`${e} (symbolic matrix cell)`)}function Pe(n){switch(n.t){case 0:{let e=new chunk75JLWK4L_cjs.m(0,_(n.v));return n.exact!==void 0&&(e.exact=It(n.exact)),n.rational!==void 0&&(e.rational=ir(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):_(n.v);return new chunk75JLWK4L_cjs.m(1,e,n.base)}case 2:return new chunk75JLWK4L_cjs.m(2,BigInt(n.v));case 3:return new chunk75JLWK4L_cjs.m(3,n.v);case 4:return new chunk75JLWK4L_cjs.m(4,_(n.v));case 5:return new chunk75JLWK4L_cjs.m(5,_(n.v));case 6:{let e=new chunk75JLWK4L_cjs.m(6,_(n.v),n.unit);return n.exact!==void 0&&(e.exact=It(n.exact)),e}case 7:{let e=n.data.map(r=>typeof r=="boolean"?r:_(r)),t={rows:n.rows,cols:n.cols,data:e,hasSymbolic:false};return new chunk75JLWK4L_cjs.m(7,t)}case 8:return new chunk75JLWK4L_cjs.m(8,{min:_(n.min),max:_(n.max)});case 10:return new chunk75JLWK4L_cjs.m(10,n.v);case 13:return new chunk75JLWK4L_cjs.m(13,n.code,n.message);default:throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(n.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(n.t)})}}function oe(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,F),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Le)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:oe(t.program)}))),e}function ae(n){let e={opcodes:Uint8Array.from(n.opcodes),numbers:Float64Array.from(n.numbers,_),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=new Map(n.constants)),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Oe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ae(t.program)}))),e}function Le(n){return {name:n.name,params:n.params.slice(),program:oe(n.program)}}function Oe(n){return {name:n.name,params:n.params.slice(),program:ae(n.program)}}function Mt(n){if(typeof n!="object"||n===null)throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${X}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==X)throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${X}"`,found:JSON.stringify(e.format)});if(e.version!==K)throw chunkCO2BI6WL_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${K}.`,expected:`snapshot version ${K}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:K,engineVersion:e.engineVersion}})}var j=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},de=class n{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(n.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let r of t.values())return r}set(e,t,r){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=n.exprKey(r);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(n.exprKey(t))??false}remove(e,t){let r=this.byLine.get(e);r&&r.delete(n.exprKey(t))&&(this.count--,r.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,r]of this.byLine)for(let[i,s]of r)e(n.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,r]of this.byLine)for(let[i,s]of r)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,r]of this.byLine)for(let i of r.keys())e.push(n.displayKey(t,i));return e}};function Ie(n){let e=new Date(n),t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return `${e.getFullYear()}-${t}-${r}`}function or(n){if(n instanceof Date)return Ie(n.getTime());if(typeof n=="number")return Number.isFinite(n)?Ie(n):null;let e=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return e?`${e[1]}-${e[2]}-${e[3]}`:null}function Bt(n){if(n===void 0)return;if(typeof n=="function")return t=>n(new Date(t));let e=new Set;for(let t of n){let r=or(t);r!==null&&e.add(r);}return t=>e.has(Ie(t))}function ar(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var me=class n{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&ar(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,r){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),a=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=a?a[0]*1e9+a[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
2
- `);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)r.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,c)=>l+c.totalAllocBytes,0),o=e.reduce((l,c)=>l+c.totalWallTimeNs,0),a=e.filter(l=>l.fastPath).length;return r.push(""),r.push("### Totals"),r.push(""),r.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),r.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),r.push(`- **Fast-path runs:** ${a}/${e.length} (${(a/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.join(`
3
- `)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let r=[];for(let[i,s]of t){let o=s.map(c=>c.wallTimeNs).sort((c,u)=>c-u),a=s.map(c=>c.allocBytes),l=s.length;r.push({stage:i,count:l,meanAllocBytes:a.reduce((c,u)=>c+u,0)/l,meanWallTimeNs:o.reduce((c,u)=>c+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:Ve(o,50),p95WallTimeNs:Ve(o,95),p99WallTimeNs:Ve(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,a)=>o+a.allocBytes,0),s=t.reduce((o,a)=>o+a.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};U.enabled=false;function Ve(n,e){if(n.length===0)return 0;if(n.length===1)return n[0];let t=e/100*(n.length-1),r=Math.floor(t),i=Math.ceil(t);if(r===i)return n[r];let s=t-r;return n[r]*(1-s)+n[i]*s}function Me(n,e){if(n.length>e.maxExpressionLength){let t=chunkCO2BI6WL_cjs.c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n.length})`,{expressionLength:n.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:chunk75JLWK4L_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function Be(n,e){let t=0,r=0,i=0;for(let o of n)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(r++,i=Math.max(i,r)),(o.value===")"||o.type==="RPAREN")&&r--;let s=n.length+t*5+i*10;if(s>e.maxComplexity){let o=chunkCO2BI6WL_cjs.c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function le(n){return n.type==="IDENT"||n.type==="UNIT"}function lr(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function Dt(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r].type==="LPAREN")t++;else if(n[r].type==="RPAREN"&&(t--,t===0))return r;return null}function cr(n){let e=new Set;for(let t=0;t<n.length;t++){if(!le(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=Dt(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)le(n[i])&&e.add(n[i].value);}return e}function ye(n){let e=[],t=[],r=cr(n);for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="GLOBAL"){if(i+2<n.length&&n[i+1].type==="COLON"&&le(n[i+2])){let o=chunkXDXIPVZB_cjs.K(n[i+2].value);e.push(o),i+3<n.length&&n[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&n[i-1].type==="GLOBAL")continue;if(i+1<n.length&&le(n[i+1])){let o=n[i+1].value;e.push(o),i+2<n.length&&n[i+2].type==="EQUALS"&&t.push(o);}}if(le(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&lr(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let a=Dt(n,i+1);if(a!==null&&n[a+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=n[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Gr(n){return chunkKRXO3MOW_cjs.c.classifyLine(n).skip}function Qr(n,e){return chunkKRXO3MOW_cjs.c.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}function Ut(n){let e=n[n.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...n.slice(0,-1),t].join(" ")}var ve=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,r){let i=Ut(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(Ut(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function _t(n,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let g=r+1;g<t.length&&s.length<o&&t[g].type==="IDENT";g++)s.push(t[g].value);if(s.length===0)return null;let a=n.match(s);if(a===null||t[r+1+a.wordCount]?.type==="EQUALS")return null;let{ratioText:c,baseUnit:u}=a.definition,p=new chunkUSQ4KL6S_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col),d=new chunkUSQ4KL6S_cjs.a("NUMBER",chunk5IJD5L3O_cjs.c("NUMBER"),c,c,i.offset,0,i.line,i.col),m=new chunkUSQ4KL6S_cjs.a("UNIT",chunk5IJD5L3O_cjs.c("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+a.wordCount,replacement:[i,p,d,m],ruleName:"uom:user-unit"}}}}var Ft="engine:call-fusion";function zt(n,e=80){return {name:Ft,priority:e,startTokenTypes:["IDENT"],match(t,r){let i=t[r];if(!i||i.type!=="IDENT"||t[r+1]?.type!=="LPAREN"||t[r-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=n.get(s);return o===void 0?null:{consumed:1,replacement:[new chunkUSQ4KL6S_cjs.a(o,chunk5IJD5L3O_cjs.c(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:Ft}}}}var ur=30,pr=40,gr=50,fr=24;function hr(n){switch(n){case chunk5IJD5L3O_cjs.a.PLUS:case chunk5IJD5L3O_cjs.a.MINUS:return ur;case chunk5IJD5L3O_cjs.a.STAR:case chunk5IJD5L3O_cjs.a.SLASH:case chunk5IJD5L3O_cjs.a.MOD:case chunk5IJD5L3O_cjs.a.OF:return pr;case chunk5IJD5L3O_cjs.a.CARET:return gr;case chunk5IJD5L3O_cjs.a.PCT_ON:case chunk5IJD5L3O_cjs.a.PCT_OFF:return fr;default:return 0}}function dr(n){switch(n){case chunk5IJD5L3O_cjs.a.PLUS:return "plus";case chunk5IJD5L3O_cjs.a.MINUS:return "minus";case chunk5IJD5L3O_cjs.a.STAR:return "times";case chunk5IJD5L3O_cjs.a.SLASH:return "divided by";case chunk5IJD5L3O_cjs.a.MOD:return "mod";case chunk5IJD5L3O_cjs.a.CARET:return "to the power of";case chunk5IJD5L3O_cjs.a.OF:return "of";case chunk5IJD5L3O_cjs.a.PCT_ON:return "plus";case chunk5IJD5L3O_cjs.a.PCT_OFF:return "less";default:return n.toLowerCase()}}function $t(n){return n.sourceEnd??n.offset+n.value.length}var mr=new Set([chunk5IJD5L3O_cjs.a.NUMBER,chunk5IJD5L3O_cjs.a.BIGINT,chunk5IJD5L3O_cjs.a.IDENT,chunk5IJD5L3O_cjs.a.UNIT,chunk5IJD5L3O_cjs.a.PERCENT,chunk5IJD5L3O_cjs.a.PI,chunk5IJD5L3O_cjs.a.E,chunk5IJD5L3O_cjs.a.TRUE,chunk5IJD5L3O_cjs.a.FALSE,chunk5IJD5L3O_cjs.a.DOLLAR,chunk5IJD5L3O_cjs.a.POUND,chunk5IJD5L3O_cjs.a.EURO,chunk5IJD5L3O_cjs.a.YEN,chunk5IJD5L3O_cjs.a.RUBLE,chunk5IJD5L3O_cjs.a.WON,chunk5IJD5L3O_cjs.a.CURRENCY_SYMBOL]);function yr(n){return !mr.has(n)}var De=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let r=this.peek();if(!r)break;let i=hr(r.type);if(i===0||i<=e)break;this.next();let s=r.type===chunk5IJD5L3O_cjs.a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:r.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===chunk5IJD5L3O_cjs.a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===chunk5IJD5L3O_cjs.a.PLUS||this.peek().type===chunk5IJD5L3O_cjs.a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===chunk5IJD5L3O_cjs.a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!yr(this.peek().type);)i=$t(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),r=this.peek();if(!r||r.type!==chunk5IJD5L3O_cjs.a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:$t(r)}}},Ue=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=chunkS3DFU33X_cjs.a(r).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=dr(e.op);return e.op===chunk5IJD5L3O_cjs.a.PCT_ON||e.op===chunk5IJD5L3O_cjs.a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=chunkH3JXNH7X_cjs.c(e,chunkH3JXNH7X_cjs.a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function _e(n){let{expression:e,tokens:t,evaluate:r,locale:i}=n,s=()=>({expression:e,steps:[],result:r(e)}),o;try{o=new De(t).parseAll();}catch{return s()}try{let{steps:a,result:l}=new Ue(e,r,i).build(o);return {expression:e,steps:a,result:l}}catch{return s()}}var H=class H{constructor(e={}){this.dag=new chunkUNKSCVIL_cjs.a;this.lineCache=new de;this.accumulatorNames=new Set;this.scopeManager=new chunkUNKSCVIL_cjs.b;this.resolverRegistry=new chunkLNZNJSRW_cjs.a;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.compatIndex=new he;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new ve;this.bytecodeCache=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName),new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName),new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName),new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t="en",diagnostics:r=false,config:i,packages:s}=e;this.localeCode=t,this.config=chunk7SZBEE5R_cjs.c(chunk7SZBEE5R_cjs.b,i??{}),this.lexer=new chunkKRXO3MOW_cjs.b(t,chunkKRXO3MOW_cjs.d(t)),this.registry=new chunkJYLNQOPU_cjs.b,this.context=chunkXDXIPVZB_cjs.x(),r?(this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.timelineCollector=new chunkHG4NPDN5_cjs.b,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.normalizer=new chunkSGIDBZ4T_cjs.c;for(let[a,l]of Object.entries(chunkSGIDBZ4T_cjs.g))this.normalizer.addPhrase(a,l);this.normalizer.register(chunkSGIDBZ4T_cjs.d(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(_t(this.userUnits)),this.normalizer.register(zt(this.callFusions));let o=s??[];for(let a of o)try{this.registerPackage(a);}catch(l){let c=chunkCO2BI6WL_cjs.d(l);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${c.format()}`);}this.registry.hasPrefix("DATETIME_LITERAL")&&this.normalizer.register(chunkN37PUZJR_cjs.h(()=>this.config.date.inputOrder)),this.parser=new chunkJYLNQOPU_cjs.a(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName),this.vm=chunkUNKSCVIL_cjs.c(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,Bt(this.config.date.holidays)),this.queryClient=chunkZLRJ7TDP_cjs.c(),this.batcher=new Ee(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new me(this.dag,(a,l)=>this.batcher.add({queryKey:l,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName);for(let t of H.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let r=[];for(let o of this.lexer)o.type!=="COMMENT"&&r.push(o);let i=this.normalizer.normalize(r);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),chunkUNKSCVIL_cjs.d(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:r?s=>{let o=r[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,a,l)=>this.evaluateLineWithBinding(s,o,a,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,getLineText:t?s=>t.getLineAt(s)?.text:r?s=>r[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return chunk75JLWK4L_cjs.P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=H.GOAL_SEEK_MAX_NESTING_DEPTH)return chunk75JLWK4L_cjs.P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return chunk75JLWK4L_cjs.P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return chunk75JLWK4L_cjs.P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let a=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,r]]),c=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=chunkUNKSCVIL_cjs.d(a,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?chunk75JLWK4L_cjs.P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?chunk75JLWK4L_cjs.P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>c;)this.vm.pop();}}catch(l){return chunk75JLWK4L_cjs.P("GOAL_SEEK_TARGET_ERROR",chunkCO2BI6WL_cjs.d(l).message)}finally{this.goalSeekDepth--;}}cacheBytecode(e,t){let r=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=r){let i=this.bytecodeCache.keys().next().value;i!==void 0&&this.bytecodeCache.delete(i);}this.bytecodeCache.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Lt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let r={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=chunkXDXIPVZB_cjs.F(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),r.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase();this.callFusions.set(o,s),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))chunkY7O4D3BJ_cjs.b(i,s),r.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))chunkXDXIPVZB_cjs.H(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e),this.compatIndex.add(e);}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let r of t.pluginFunctionIndices)delete this.context.pluginFunctions[r],delete this.context.pluginFunctionOwners[r];for(let r of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(r);for(let r of t.resolverNamespaces)this.resolverRegistry.unregister(r);for(let r of t.tokenCategories)chunkY7O4D3BJ_cjs.c(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)chunkXDXIPVZB_cjs.I(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames)this.callFusions.delete(r);return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.bytecodeCache.clear(),true}getConfig(){return {...this.config}}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new j(t,r,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,r,i,s,o,a,l){let c=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("executeAndStore"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},chunkZLRJ7TDP_cjs.a(this.queryClient);let d=chunkUNKSCVIL_cjs.d(e,this.vm,a,l,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(d.type==="pending"){this.resolveAsync(d),this.dag.registerLineDataSourceDependency(t,d.packageId||o,[d.queryKey]);let m=chunk75JLWK4L_cjs.O(d.queryKey);return this.storeLineResult(t,m,e,i,s,r),m}if(d.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),d.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,d.value,e,i,s,r),d.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("executeRaw"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},chunkZLRJ7TDP_cjs.a(this.queryClient);let o=chunkUNKSCVIL_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine";try{if(await r,s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(a){if(s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after error");return}let l=a instanceof Error?a:new Error(String(a));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(chunkUURM7P3P_cjs.b(e,r)>r)throw chunkCO2BI6WL_cjs.c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let c of l.inlineSolves)c.error&&o.errors.push(`Line ${l.lineNumber}: ${c.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,a=s.lineNumber,l=s.startOffset,c=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(g=>({start:g.start,end:g.end,expression:g.expression,lineNumber:a,columnNumber:g.columnNumber})),d=p.length>0,m={lineNumber:a,text:o,startPosition:l,endPosition:c,isEmpty:u,hasInlineSolves:d,inlineSolves:p,expression:null,result:null,error:null};if(!u){let g=o.trim().startsWith(":");if(d&&!g)for(let A of p)try{A.result=this.evaluateLine(a,A.expression);}catch(O){let I=O instanceof Error?O.message:String(O);A.error=I;}else {let A=s.classification.contentOffset,I=(A===void 0?o:o.slice(A-l)).trim();if(I)try{let E=this.evaluateLineWithPreTokenized(a,I,s.tokens);m.expression=I,m.result=E[0];}catch(E){let Z=E instanceof Error?E.message:String(E);m.error=Z;}}}t.push(m);}}finally{this.batchScanResults=r,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,r){let i=[],s=false;for(let o of r)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,r,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?r:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let a=true;for(let l=0;l<o;l++){let c=t[l].type;if(c!=="NUMBER"&&c!=="COLON"){a=false;break}}if(a){let l=t.slice(0,o+2).map(c=>c.value).join("");throw chunkCO2BI6WL_cjs.c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw chunkCO2BI6WL_cjs.c.parsing("UNEXPECTED_TRAILING_TOKEN",`Unexpected token after expression: "${s.value}"`,{tokenType:s.type,tokenValue:s.value})}}compileAdHoc(e){let t=new chunkEN3CDYOS_cjs.d(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=chunkUNKSCVIL_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw chunkCO2BI6WL_cjs.c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let a of e.factorNames){let l=this.vm.getVar(a);if(l===void 0)return chunk75JLWK4L_cjs.P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return chunk75JLWK4L_cjs.P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${a}" must be a Matrix (got a different value type).`);r.push(l);}let i=r[0].value;for(let a=1;a<r.length;a++){let l=chunkJ7ABVGZH_cjs._(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=chunkJ7ABVGZH_cjs.da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?chunk75JLWK4L_cjs.P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):chunkJ7ABVGZH_cjs._(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let r=[];for(;t<e.length&&e[t].type==="IDENT";)r.push(e[t].value),t++;if(r.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.bytecodeCache.clear(),chunk75JLWK4L_cjs.t(`${r.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let r=e[0],i=e[1],s=r.type==="IDENT"||r.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let a=e.slice(2);if(a.length===0)throw chunkCO2BI6WL_cjs.c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let l=r.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,chunk75JLWK4L_cjs.n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[chunkSGIDBZ4T_cjs.b("IDENT",l,[r]),chunkSGIDBZ4T_cjs.b(c.type,c.text,[i]),chunkSGIDBZ4T_cjs.b("LPAREN","(",[i]),...a,chunkSGIDBZ4T_cjs.b("RPAREN",")",[i])],p=chunkUNKSCVIL_cjs.d(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw chunkCO2BI6WL_cjs.c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let c=e.slice(0,-1);if(c.length===0)throw chunkCO2BI6WL_cjs.c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c.length===1&&(c[0].type==="IDENT"||c[0].type==="UNIT")){let u=c[0].value,p=this.vm.getEquation(u),d=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!d)return m}if(d)return this.solveScalarEquation(d,t)}return this.simplifySymbolically(c,t)}if(chunkN37PUZJR_cjs.b(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],c),c}let a=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(a,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(a,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),chunk75JLWK4L_cjs.t(`${a} stored as an equation \u2014 solve with "${a} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(a=>a.type==="EQUALS"))return null;let s=this.equationUnknowns(r,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(r),this.compileAdHoc(i)),chunk75JLWK4L_cjs.t(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let r=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||r.includes(i.value)||r.push(i.value));return r}solveScalarEquation(e,t=-1){let r=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return chunkXDXIPVZB_cjs.i(r,i,e.variable)}lexToTokens(e,t){let r=[],i=false;this.lexer.resetExpression(e);for(let s of this.lexer)s.type!=="COMMENT"&&((s.type==="LPAREN"||s.type==="RPAREN")&&(i=true),r.push(s),t?.(s));return {tokens:r,hasParens:i}}prepareExpression(e,t,r,i,s=-1){let o=Me(e,this.config.validation);if(!o.passed)return {kind:"error",stage:"length",error:o.error.engineError};let a=t.filter(E=>E.type!=="COMMENT");if(a.length===0)return {kind:"empty"};let l=this.normalizer.normalize(a,i),c=Be(l,this.config.validation);if(!c.passed)return {kind:"error",stage:"complexity",error:c.engineError,normalizedTokens:l};let u,p=null;try{if(u=this.tryDefineUserUnit(l),u===null){let E=this.tryCompoundAssignment(l,s);E!==null&&(u=E,p=ye(l));}u===null&&(u=this.trySymbolicGrammar(l,s));}catch(E){let{reads:Z,writes:P}=ye(l);return {kind:"error",stage:"parse",error:chunkCO2BI6WL_cjs.d(E),reads:Z,writes:P,normalizedTokens:l}}if(u!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:u,reads:p?.reads,writes:p?.writes};let{reads:d,writes:m}=ye(l),g=this.bytecodeCache.get(e);if(g)return {kind:"ready",normalizedTokens:l,reads:d,writes:m,program:g,cached:true};let A=this.builderPool[this.builderPoolIndex++%this.builderPool.length];A.reset();let O,I=null;try{let E=U.track("parser",()=>(this.parseExpression(A,l,r),A.build()));O=E.result,I=E.alloc;}catch(E){return {kind:"error",stage:"parse",error:chunkCO2BI6WL_cjs.d(E),reads:d,writes:m,normalizedTokens:l}}return this.cacheBytecode(e,O),{kind:"ready",normalizedTokens:l,reads:d,writes:m,program:O,cached:false,parserAlloc:I}}preflightAsync(e,t,r,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("preflightAsync"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("preflightAsync");let c=a.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=chunk75JLWK4L_cjs.O(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let p=chunk75JLWK4L_cjs.n(0);return this.lineCache.set(e,new j(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:a,writes:l,program:c}=s,u=this.preflightAsync(o,c,e,t,a,l);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,a,l,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:chunkCO2BI6WL_cjs.c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return chunk75JLWK4L_cjs.l(r.value)}evaluateLineWithDebug(e,t,r="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,r),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,r)}addDiagnosticStage(e,t,r,i,s,o,a,l,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:a,skipped:l,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,a=U.isEnabled(),l=[],c=[],u=0,p=Me(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:chunkHG4NPDN5_cjs.c.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let d=s?h=>{i.fireTokenEmitted({type:chunkHG4NPDN5_cjs.c.TokenEmitted,elapsedNs:0,expression:e,token:{type:h.type,value:h.value,offset:h.offset||0,line:h.line||t,col:h.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,d)),g=m.result.tokens,A=m.result.hasParens;if(a&&m.alloc&&l.push(m.alloc),s){let h={};for(let R of g)h[R.type]=(h[R.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:g.length,tokenTypes:h,hasParens:A,locale:this.localeCode,tokens:[...g]});let T=[];for(let R=0;R<g.length;R++){let ne=g[R];if(ne.type==="INLINE_SOLVE_START"){let M=-1;for(let z=R+1;z<g.length;z++)if(g[z].type==="BACKTICK_OPEN"){M=z;break}if(M>R){let qt=g.slice(R+1,M).map(Gt=>Gt.value).join("");T.push({startTokenIndex:R,endTokenIndex:M,expression:qt,columnNumber:ne.col||1}),R=M;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:T.length>0,inlineSolveSpans:T});}if(g.length===0){let h=chunk75JLWK4L_cjs.n(0);return this.lineCache.set(t,new j(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let O=0,I=[],E=new Map,Z=s?h=>{O++,I.push(h),E.set(h.rule,(E.get(h.rule)||0)+1),i.fireTokenFused({type:chunkHG4NPDN5_cjs.c.TokenFused,elapsedNs:0,expression:e,ruleName:h.rule,sourceTokenCount:h.sourceTokens.length,fusedTokenType:h.fusedToken.type,fusedTokenValue:h.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:chunkHG4NPDN5_cjs.c.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:g.length});let P=this.bytecodeCache.get(e);s&&!P&&this.parser.setDiagnosticPipeline(i,e);let y=this.prepareExpression(e,g,A,Z,t);a&&y.kind==="ready"&&y.parserAlloc&&l.push(y.parserAlloc),s&&!P&&this.parser.setDiagnosticPipeline(void 0,"");let x=y.kind==="empty"?g:y.normalizedTokens??g;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:chunkHG4NPDN5_cjs.c.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:x.length,fusionsCount:O}),this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:x.length,fusions:I,rulesApplied:[...E.entries()].map(([h,T])=>({rule:h,count:T})),tokens:[...x],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(x)})):this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:g.length,fusions:[],rulesApplied:[],tokens:[...g],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(g)})),y.kind==="empty"||y.kind==="error"&&y.stage==="length"){if(s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=chunk75JLWK4L_cjs.n(0);return this.lineCache.set(t,new j(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:chunk75JLWK4L_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0}}let ee=Be(x,this.config.validation);if(y.kind==="error"&&y.stage==="complexity")return s&&(this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ee.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0},errorMessage:ee.errorMessage}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:chunk75JLWK4L_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ee.errorMessage,engineError:ee.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ee.complexityScore??x.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0}}),y.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:0});let h={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,y.value,h,y.reads??[],y.writes??[],e),{value:y.value,tokens:x,program:h,debug:void 0,diagnostic:void 0}}let ce=y.reads??[],te=y.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ce,writes:te,isAssignment:te.length>0}),this.addDiagnosticStage(c,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!P,cacheSize:this.bytecodeCache.size,cacheKey:e}),P?i.fireCacheHit({type:chunkHG4NPDN5_cjs.c.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:chunkHG4NPDN5_cjs.c.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value:chunk75JLWK4L_cjs.n(0),tokens:x,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0};if(y.kind!=="ready")throw chunkCO2BI6WL_cjs.c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let v=y.program;s&&(this.addDiagnosticStage(c,"parser","Parser","\u{1F333}","parser",8,u,!!P,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!P,{type:"compiler",opcodeCount:v.opcodes.length,numberConstants:v.numbers.length,stringConstants:v.strings.length,hasAsync:v.hasAsync,cached:!!P}),i.fireBytecodeBuilt({type:chunkHG4NPDN5_cjs.c.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:v.opcodes.length,numbersLength:v.numbers.length,stringsLength:v.strings.length,isCached:!!P}));let Kt=v.hasAsync||this.resolverRegistry.size>0,re=this.preflightAsync(x,v,t,e,ce,te);if(s&&(re.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:re.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Kt?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),re.kind==="pending")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:re.value,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,re.value,x,v,null):void 0};let Ht=s&&this.config.diagnostic.vmTraceEnabled===true,C;try{let h=U.track("vm",()=>this.executeAndStore(v,t,e,ce,te,"_engine",Ht?i:void 0,e),{cacheHit:!!P});C=h.result,a&&h.alloc&&l.push(h.alloc);}catch(h){let T=chunkCO2BI6WL_cjs.d(h);return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:chunk75JLWK4L_cjs.n(0),tokens:x,program:v,error:T.message,engineError:T,debug:void 0,diagnostic:void 0}}let ue=C.type===12;if(s){let h=ue?"pending":String(C.value??""),T=ue?"Pending":C.unit?"Uom":"Number";this.addDiagnosticStage(c,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:v.opcodes.length,stackDepth:this.vm.getStack().length,resultType:T,resultValue:h,isPending:ue});}if(ue)return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:C,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,C,x,v,null):void 0};if(a&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!P)),s&&(this.addDiagnosticStage(c,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ce,writesRegistered:te,dataSourcesRegistered:[]}),this.addDiagnosticStage(c,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(C.value),formattedValue:String(C.value),valueType:C.type===0?"Number":"Value",unit:C.unit}),i.fireVmHalt({type:chunkHG4NPDN5_cjs.c.VmHalt,elapsedNs:0,expression:e,result:C?{type:C.type,value:C.value,unit:C.unit}:void 0}),this.addDiagnosticStage(c,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length,cacheHit:!!P}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length})),s){let T=i.collectReports()[0]?.toJSON(),R=T;if(T){let ne=T.parselets.slice(o),M={};for(let z of ne)M[z.parseletCategory]=(M[z.parseletCategory]??0)+1;R={...T,parselets:ne,summary:{...T.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:C,tokens:x,program:v,debug:R,diagnostic:this.buildDiagnosticResult(c,C,x,v,null)}}return {value:C,tokens:x,program:v}}buildDiagnosticResult(e,t,r,i,s){return {stages:e,value:t,tokens:r,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let r=this.lineCache.get(e,t);if(!r)return;let i=this.bytecodeCache.get(t);if(!i)return;if(r.bytecode.hasAsync||this.resolverRegistry.size>0){let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("reEvaluateLine preflight");let c=a.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),chunk75JLWK4L_cjs.O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),chunk75JLWK4L_cjs.O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?chunkTTFO4YDP_cjs.a.keystrokeSignalSet(e.aborted):chunkTTFO4YDP_cjs.a.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,a]of this.bytecodeCache)e.push({expression:o,opcodesLength:a.opcodes.length,numbersLength:a.numbers.length,stringsLength:a.strings.length,hasAsync:a.hasAsync});let t=[];for(let o of this.lineCache.keys()){let a=o.indexOf(":"),l=a>0?parseInt(o.slice(0,a),10)||0:parseInt(o,10)||0,c=a>0?o.slice(a+1):void 0,u=c!==void 0?this.lineCache.get(l,c):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let a=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:a}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return _e({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode})}evaluateIsolated(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r,void 0,-1);if(i.kind==="empty")return chunk75JLWK4L_cjs.n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw chunkCO2BI6WL_cjs.c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r);if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new chunkCO2BI6WL_cjs.b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:t,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:r}=this.lexToTokens(e);return this.prepareExpression(e,t,r).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return chunk75JLWK4L_cjs.n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),chunk75JLWK4L_cjs.O(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),chunkZLRJ7TDP_cjs.b()===this.queryClient&&chunkZLRJ7TDP_cjs.a(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.bytecodeCache.clear(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let c of Object.keys(e.dataSourceDeps)){let u=Number(c);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:c,entry:u}of r){let p=t.has(c)||u.bytecode.hasAsync;p&&t.add(c);let d=u.writeVariable;if(d){let m=i.get(d);(!m||c>=m.line)&&i.set(d,{line:c,async:p});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Ae(u,`variable "${c}"`);}catch(p){if(p instanceof chunkCO2BI6WL_cjs.b&&p.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Le),a=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let d;try{d=Ae(p.result,`line ${c}`);}catch(m){if(m instanceof chunkCO2BI6WL_cjs.b&&m.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}a.push({line:c,expression:u,result:d,bytecode:oe(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:oe(u)}));return {format:X,version:K,engineVersion:chunk7SZBEE5R_cjs.a,locale:this.localeCode,variables:s,userFunctions:o,lineCache:a,bytecodeCache:l}}static fromJSON(e,t={}){Mt(e);let r=t.locale??e.locale??"en",i=new H({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Pe(r));for(let t of e.userFunctions){let r=Oe(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new j(Pe(t.result),ae(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,ae(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,chunk75JLWK4L_cjs.n(t));let i=new Map;for(let s of r){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.executeRaw(o.bytecode,s);if(a.type==="pending"){this.resolveAsync(a);continue}if(a.type==="error"){let c=chunk75JLWK4L_cjs.P(a.error.code,a.error.message);i.set(s,c),o.result=c;continue}let l=a.value;i.set(s,l),o.result=l;}return i}};H.GOAL_SEEK_MAX_NESTING_DEPTH=1,H.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var be=H;var Fe=(()=>{throw new Error("engine.worker.ts was not processed by esbuild-plugin-inline-worker, so worker offload is unavailable")}),J=null;function vr(){return J||(J=new be),J}var Y=null;function br(){return Y||(Y=chunkUNKSCVIL_cjs.c(chunkXDXIPVZB_cjs.w,200,5e4)),Y}function Er(n){let e={lineId:n.lineId,expression:n.expression,compiledAgainstHash:n.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let t=vr(),{program:r,reads:i,writes:s}=t.compileExpression(n.expression),o=s.length>0,a=r.opcodes,l=r.numbers,c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),u=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);return {...e,opcodesBuffer:c,numbersBuffer:u,opcodesLength:a.length,numbersLength:l.length,strings:[...r.strings],reads:i,writes:s,isVariableDef:o}}catch(t){return {...e,opcodesBuffer:new ArrayBuffer(0),numbersBuffer:new ArrayBuffer(0),opcodesLength:0,numbersLength:0,error:t instanceof Error?t.message:String(t)}}}function xr(n){let e=[],t=[];for(let r of n.items){let i=Er(r);e.push(i),i.opcodesBuffer.byteLength>0&&t.push(i.opcodesBuffer),i.numbersBuffer.byteLength>0&&t.push(i.numbersBuffer);}self.postMessage({id:n.id,type:"COMPILE_RESULT",results:e},t);}function Sr(n){let e=br();e.reset();let t=new Uint8Array(n.opcodesBuffer,0,n.opcodesLength),r=new Float64Array(n.numbersBuffer,0,n.numbersLength),i={opcodes:t,numbers:r,strings:n.strings};try{let s=chunkUNKSCVIL_cjs.d(i,e);if(s.type==="pending")return {lineNumber:n.lineNumber,valueType:12,value:0,isPending:!0,queryKey:s.queryKey};if(s.type==="error")return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:!1,unit:s.error.message};let o=s.value;return {lineNumber:n.lineNumber,valueType:o.type,value:typeof o.value=="number"?o.value:typeof o.value=="bigint"?Number(o.value):0,unit:o.unit,isPending:!1}}catch{return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:false,unit:"Worker execution failed"}}}function kr(n){let e=[];for(let t of n.items)e.push(Sr(t));self.postMessage({id:n.id,type:"EXECUTE_RESULT",results:e});}var Cr=typeof self<"u"&&typeof window>"u",wr=n=>{if(n.origin&&self.location&&n.origin!==self.location.origin)return;let e=n.data;switch(e.type){case "COMPILE_BATCH":xr(e);break;case "EXECUTE_BATCH":kr(e);break;case "TERMINATE":{J&&(J.clear(),J=null),Y&&(Y.reset(),Y=null),self.postMessage({id:e.id,type:"COMPILE_RESULT",results:[]});break}default:self.postMessage({id:-1,type:"COMPILE_RESULT",results:[],error:`Unknown message type: ${e.type}`});}};Cr&&(self.onmessage=wr);var Tr=3e4,jt=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{return Fe().terminate(),this._available=!0,!0}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let l=t.get(a);if(!l||l.bytecode.opcodes.length===0)continue;let c=l.bytecode.opcodes,u=l.bytecode.numbers,p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);r.push({lineNumber:a,opcodesBuffer:p,numbersBuffer:d,opcodesLength:c.length,numbersLength:u.length,strings:[...l.bytecode.strings]});}if(r.length===0)return Promise.resolve([]);let i=[];for(let a of r)a.opcodesBuffer.byteLength>0&&i.push(a.opcodesBuffer),a.numbersBuffer.byteLength>0&&i.push(a.numbersBuffer);let s=this.nextId++,o=this.getNextWorker();return new Promise(a=>{let l=setTimeout(()=>{this.pendingBatches.delete(s),a([]);},Tr);this.pendingBatches.set(s,{id:s,lineNumbers:e,resolve:c=>{clearTimeout(l),a(c);}}),o.postMessage({type:"EXECUTE_BATCH",id:s,items:r},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++){let t=Fe();t.onmessage=r=>{this.handleWorkerMessage(r.data);},t.onerror=r=>{console.error(`[ExecutionPool] Worker ${e} error:`,r.message);for(let[i,s]of this.pendingBatches)s.resolve([]),this.pendingBatches.delete(i);},this.workers.push(t);}}getNextWorker(){let e=this.workers[this.nextWorker];return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Wt(n){switch(n.valueType){case 0:return chunk75JLWK4L_cjs.n(n.value);case 1:return chunk75JLWK4L_cjs.r(n.value);case 2:return chunk75JLWK4L_cjs.s(BigInt(n.value));case 3:return chunk75JLWK4L_cjs.t(String(n.value));case 4:return chunk75JLWK4L_cjs.M(n.value);case 5:return chunk75JLWK4L_cjs.N(n.value);case 6:return chunk75JLWK4L_cjs.u(n.value,n.unit??"");case 7:return chunk75JLWK4L_cjs.n(n.value);case 10:return chunk75JLWK4L_cjs.L(n.value!==0);case 12:return chunk75JLWK4L_cjs.O(n.queryKey??"");case 13:return chunk75JLWK4L_cjs.P("WORKER_EXECUTION_ERROR",n.unit??"Unknown worker error");default:return chunk75JLWK4L_cjs.n(n.value)}}var Se=class Se{constructor(e,t,r,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved but AsyncResolutionBatcher.onLineResult is not set, so the value cannot reach your document and the line will keep showing as pending. Set it to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let r=chunkCO2BI6WL_cjs.d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${r.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let c of e){let u=`${c.packageId}:${c.queryKey}`;t.set(u,c);}let r=[],i=[];for(let c of t.values())c.isError?r.push(c):i.push(c);for(let c of r)c.signal.aborted||this.notifyListeners({type:"error",queryKey:c.queryKey,packageId:c.packageId,error:c.error??new Error("Unknown async resolution error")});let s=new Set,o=[],a=[...i,...r];for(let c of a){if(c.signal.aborted)continue;o.push(c.queryKey);let u=this.dag.getAffectedLinesByDataSource(c.packageId,[c.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>jt){let c=new Map;for(let u of l)c.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,c,o).catch(u=>{let p=chunkCO2BI6WL_cjs.d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let a of e)t.set(a,0),r.set(a,[]);for(let a of e){let l=this.dag.getWrites(a);for(let c of l)i.set(c,a);}for(let a of e){let l=this.dag.getDependencies(a);for(let c of l){let u=i.get(c);u!==void 0&&u!==a&&(r.get(u).push(a),t.set(a,(t.get(a)??0)+1));}}let s=[];for(let[a,l]of t)l===0&&s.push(a);if(s.length===0&&e.length>0)return [...e].sort((a,l)=>a-l);let o=[];for(;s.length>0;){let a=s.shift();o.push(a);for(let l of r.get(a)??[]){let c=(t.get(l)??1)-1;t.set(l,c),c===0&&s.push(l);}}if(o.length<e.length){let a=e.filter(l=>!o.includes(l)).sort((l,c)=>l-c);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,r,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let a of s){let l=t.get(a.lineNumber);if(!l||a.isPending)continue;let c=Wt(a);l.result=c,this.warnIfUnwired(),this.onLineResult?.(a.lineNumber,c),o.push(a.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}reExecuteMainThread(e,t,r){let i=[];for(let s of e){let o=r?r.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let l=chunkUNKSCVIL_cjs.d(o.bytecode,this.vm);for(;this.vm.getStack().length>a;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let c=chunk75JLWK4L_cjs.P(l.error.code,l.error.message);o.result=c,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,c),i.push(s);}}catch(l){for(;this.vm.getStack().length>a;)this.vm.pop();let c=chunkCO2BI6WL_cjs.d(l),u=chunk75JLWK4L_cjs.P(c.code,c.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var Ee=Se;exports.a=Nr;exports.b=rr;exports.c=Lt;exports.d=X;exports.e=K;exports.f=D;exports.g=Fe;exports.h=Ee;exports.i=Me;exports.j=Be;exports.k=ye;exports.l=Gr;exports.m=Qr;exports.n=be;//# sourceMappingURL=chunk-KVLJDOZ7.cjs.map
5
- //# sourceMappingURL=chunk-KVLJDOZ7.cjs.map