solve-engine 2.0.0 → 2.1.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 (55) hide show
  1. package/dist/{chunk-6KFVG6UY.cjs → chunk-2LFLR3VZ.cjs} +2 -2
  2. package/dist/chunk-2LFLR3VZ.cjs.map +1 -0
  3. package/dist/{chunk-LR4E4A4W.cjs → chunk-32GC2FHC.cjs} +2 -2
  4. package/dist/{chunk-LR4E4A4W.cjs.map → chunk-32GC2FHC.cjs.map} +1 -1
  5. package/dist/{chunk-XR7HEC7B.js → chunk-4E4YVQKK.js} +3 -3
  6. package/dist/{chunk-XR7HEC7B.js.map → chunk-4E4YVQKK.js.map} +1 -1
  7. package/dist/chunk-5FO4PDIG.js +2 -0
  8. package/dist/chunk-5FO4PDIG.js.map +1 -0
  9. package/dist/{chunk-SZGK6RIP.cjs → chunk-7BXPCWKM.cjs} +2 -2
  10. package/dist/{chunk-SZGK6RIP.cjs.map → chunk-7BXPCWKM.cjs.map} +1 -1
  11. package/dist/{chunk-EYRBENHC.js → chunk-E2Q3PQ2G.js} +3 -3
  12. package/dist/{chunk-EYRBENHC.js.map → chunk-E2Q3PQ2G.js.map} +1 -1
  13. package/dist/{chunk-UDQ57ZRX.cjs → chunk-EVI6OHQH.cjs} +2 -2
  14. package/dist/{chunk-UDQ57ZRX.cjs.map → chunk-EVI6OHQH.cjs.map} +1 -1
  15. package/dist/{chunk-UI6IFGBT.js → chunk-G7TBEQRQ.js} +2 -2
  16. package/dist/chunk-G7TBEQRQ.js.map +1 -0
  17. package/dist/{chunk-4J7XZSZJ.cjs → chunk-GK2OHWRF.cjs} +4 -4
  18. package/dist/{chunk-4J7XZSZJ.cjs.map → chunk-GK2OHWRF.cjs.map} +1 -1
  19. package/dist/{chunk-JSPKKNPQ.js → chunk-I52MYCVI.js} +3 -3
  20. package/dist/{chunk-JSPKKNPQ.js.map → chunk-I52MYCVI.js.map} +1 -1
  21. package/dist/{chunk-WN5CMP4T.cjs → chunk-JUIJ6NRD.cjs} +3 -3
  22. package/dist/{chunk-WN5CMP4T.cjs.map → chunk-JUIJ6NRD.cjs.map} +1 -1
  23. package/dist/{chunk-SUXRZWH2.cjs → chunk-OVKDDTXO.cjs} +3 -3
  24. package/dist/{chunk-SUXRZWH2.cjs.map → chunk-OVKDDTXO.cjs.map} +1 -1
  25. package/dist/{chunk-6CY44ZPG.js → chunk-TN5E6JU6.js} +2 -2
  26. package/dist/{chunk-6CY44ZPG.js.map → chunk-TN5E6JU6.js.map} +1 -1
  27. package/dist/{chunk-L3FPQSGN.js → chunk-U4AEVL5Z.js} +2 -2
  28. package/dist/{chunk-L3FPQSGN.js.map → chunk-U4AEVL5Z.js.map} +1 -1
  29. package/dist/chunk-VAGS5JS7.cjs +2 -0
  30. package/dist/chunk-VAGS5JS7.cjs.map +1 -0
  31. package/dist/{chunk-GOIQYUWV.js → chunk-YAHGSBMC.js} +2 -2
  32. package/dist/{chunk-GOIQYUWV.js.map → chunk-YAHGSBMC.js.map} +1 -1
  33. package/dist/constants.cjs +1 -1
  34. package/dist/constants.js +1 -1
  35. package/dist/engine.cjs +1 -1
  36. package/dist/engine.js +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/lexer.cjs +1 -1
  40. package/dist/lexer.js +1 -1
  41. package/dist/normalizer.cjs +1 -1
  42. package/dist/normalizer.js +1 -1
  43. package/dist/packages.cjs +1 -1
  44. package/dist/packages.js +1 -1
  45. package/dist/testing.cjs +2 -2
  46. package/dist/testing.js +1 -1
  47. package/dist/worker.cjs +2 -2
  48. package/dist/worker.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-6KFVG6UY.cjs.map +0 -1
  51. package/dist/chunk-APN442VD.cjs +0 -2
  52. package/dist/chunk-APN442VD.cjs.map +0 -1
  53. package/dist/chunk-QXQE7X4S.js +0 -2
  54. package/dist/chunk-QXQE7X4S.js.map +0 -1
  55. package/dist/chunk-UI6IFGBT.js.map +0 -1
@@ -1 +1 @@
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":"yNAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACXA,EAAA,IAAA,CAAO,MAAA,CACPA,EAAA,MAAA,CAAS,QAAA,CACTA,EAAA,MAAA,CAAS,QAAA,CAHEA,OAAA,EAAA,ECaL,IAAMC,EAAN,KAAY,CAkBjB,YAAYC,CAAAA,CAAa,IAAA,CAAMC,EAA2B,CAf1D,IAAA,CAAQ,aAA2B,MAAA,CAEnC,IAAA,CAAQ,UAAY,KAAA,CAIpB,IAAA,CAAQ,OAAkB,EAAC,CAC3B,KAAQ,QAAA,CAAmB,CAAA,CAYzB,KAAK,eAAA,CAAkB,IAAIC,oBAAgBF,CAAAA,CAAYC,CAAW,EACpE,CAEA,KAAA,CAAME,EAAeC,CAAAA,CAA0B,CAC7C,IAAMC,CAAAA,CAAWD,CAAAA,EAAS,OAQ1B,GAPA,IAAA,CAAK,aAAeC,CAAAA,CACpB,IAAA,CAAK,UAAY,KAAA,CACjB,IAAA,CAAK,YAAc,MAAA,CAKfA,CAAAA,GAAa,OAAiB,CAEhC,GADuB,KAAK,eAAA,CAAgB,YAAA,CAAaF,CAAK,CAAA,CAC3C,IAAA,CAAM,CACvB,IAAA,CAAK,MAAA,CAAS,EAAC,CACf,IAAA,CAAK,SAAW,CAAA,CAChB,MACF,CAEA,IAAA,CAAK,eAAA,CAAgB,MAAMA,CAAK,CAAA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CACf,WAAY,UAAA,CACZ,aAAA,CAAe,cACf,eAAA,CAAiB,aAAA,CACjB,YAAa,WACf,CAAA,CAiBO,SAASC,CAAAA,CAAiBrC,CAAAA,CAAa,KAAmB,CAC/D,IAAMsC,EAAkBC,mBAAAA,CAAUvC,CAAU,EACtCwC,CAAAA,CAAW,IAAI1B,EAGrB,OAAA0B,CAAAA,CAAS,UAAUF,CAAAA,CAAO,UAAA,CAAYF,CAAe,CAAA,CAGrDI,CAAAA,CAAS,SAASC,mBAAU,CAAA,CAGrBD,CAAAA,CAAS,KAAA,EAClB","file":"chunk-LR4E4A4W.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
+ {"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":"yNAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACXA,EAAA,IAAA,CAAO,MAAA,CACPA,EAAA,MAAA,CAAS,QAAA,CACTA,EAAA,MAAA,CAAS,QAAA,CAHEA,OAAA,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CAC3C,IAAMkB,CAAAA,CAAa,IAAI,IAGvB,GAAI,IAAA,CAAK,gBACP,IAAA,IAAWJ,CAAAA,IAAU,OAAO,IAAA,CAAK,IAAA,CAAK,eAAe,CAAA,CAAG,CACtD,IAAMK,CAAAA,CAAQL,CAAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAAE,WAAA,GACnCI,CAAAA,CAAW,GAAA,CAAIC,CAAK,EACtB,CAIF,QAAWT,CAAAA,IAAM,IAAA,CAAK,QACpB,GAAKA,CAAAA,CAAG,QACR,IAAA,IAAWI,CAAAA,IAAU,OAAO,IAAA,CAAKJ,CAAAA,CAAG,OAAO,CAAA,CAAG,CAC5C,IAAMS,CAAAA,CAAQL,CAAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAAE,WAAA,GACnCI,CAAAA,CAAW,GAAA,CAAIC,CAAK,EACtB,CAGF,OAAOD,CACT,CACF,EClOA,IAAME,CAAAA,CAA0C,CAC9C,iBAAA,CAAmB,OAAA,CACnB,WAAY,OAAA,CACZ,aAAA,CAAe,cACf,aAAA,CAAe,aAAA,CACf,WAAY,UAAA,CACZ,aAAA,CAAe,cACf,eAAA,CAAiB,aAAA,CACjB,YAAa,WACf,CAAA,CAiBO,SAASC,CAAAA,CAAiBrC,CAAAA,CAAa,KAAmB,CAC/D,IAAMsC,EAAkBC,mBAAAA,CAAUvC,CAAU,EACtCwC,CAAAA,CAAW,IAAI1B,EAGrB,OAAA0B,CAAAA,CAAS,UAAUF,CAAAA,CAAO,UAAA,CAAYF,CAAe,CAAA,CAGrDI,CAAAA,CAAS,SAASC,mBAAU,CAAA,CAGrBD,CAAAA,CAAS,KAAA,EAClB","file":"chunk-32GC2FHC.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 +1,5 @@
1
- import {b as b$3,a as a$4}from'./chunk-XNIWQHXY.js';import {a as a$2}from'./chunk-7GK3XEZF.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d,c,a as a$1,b}from'./chunk-YJ2OPULK.js';import {a as a$3,b as b$4,c as c$6}from'./chunk-TWC7K3ZX.js';import {c as c$8,a as a$a}from'./chunk-J4LZD4ZY.js';import {b as b$8}from'./chunk-6CY44ZPG.js';import {d as d$1}from'./chunk-YVKHEAFT.js';import {c as c$2,g,d as d$3,b as b$7}from'./chunk-QXQE7X4S.js';import {b as b$6}from'./chunk-76F3LCIL.js';import {c as c$3,a as a$7,b as b$a}from'./chunk-TCZSPH4A.js';import {w,x,F as F$1,H as H$1,I,i,K}from'./chunk-W2JAR233.js';import {_ as _$1,da}from'./chunk-RSF25YSJ.js';import {N,M,t,n,l,m,J,u,L,K as K$1,s,r,g as g$1}from'./chunk-EVAOPEO4.js';import {c as c$1,b as b$1,a as a$5}from'./chunk-L3FPQSGN.js';import {b as b$2,d as d$2,c as c$9}from'./chunk-GOIQYUWV.js';import {b as b$5,c as c$4}from'./chunk-JPFCXLJV.js';import {a as a$8}from'./chunk-UI6IFGBT.js';import {a,c as c$7}from'./chunk-IJMNVBIS.js';import {a as a$9}from'./chunk-62LMTO4F.js';import {d as d$4,c as c$5,b as b$9}from'./chunk-MPB7KUN5.js';function xt(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 Ht(n,e){let t=[];if(xt("prefixParseletTokenType","prefixParselets",n,e,t),xt("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 kt(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Ht(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var Kt=/(\d+)\.(\d+)\.(\d+)/,jt=/^\d+$/;function Ct(n){let e=Kt.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Gt(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Te(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(!jt.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function qt([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 Qt([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Xt(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Te(n.slice(1));return i&&qt(i)}if(n[0]==="~"){let i=Te(n.slice(1));return i&&Qt(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Te(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Tt(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=Xt(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Nt(n){return Tt(n.trim())!==null}function Jt(n,e){let t=Gt(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 wt(n,e){let t=Tt(e.trim());return t===null?false:t.some(r=>r.every(i=>Jt(n,i)))}function Yt(n,e=a$5){if(!n.engineVersion)return {compatible:true};if(!Nt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Ct(e);return t===null||!wt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function At(n,e=a$5){let t=Yt(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c$5.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}}):c$5.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 G="solve-engine/snapshot",H=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 c$5.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 Rt(n){return {coef:n.coef.toString(),scale:n.scale}}function Pt(n){return {coef:BigInt(n.coef),scale:n.scale}}function Zt(n){return {n:n.n.toString(),d:n.d.toString()}}function en(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Lt(n){return g$1[n]??String(n)}function Ne(n,e){throw c$5.validation({code:D.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Lt(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Lt(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 we(n,e){switch(n.type){case 0:{let t={t:0,v:F(n.value)};return n.exact!==void 0&&(t.exact=Rt(n.exact)),n.rational!==void 0&&(t.rational=Zt(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=Rt(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ne(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>tn(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 Ne(n.type,e)}}function tn(n,e){return typeof n=="boolean"?n:typeof n=="number"?F(n):Ne(9,`${e} (symbolic matrix cell)`)}function Ae(n){switch(n.t){case 0:{let e=new m(0,_(n.v));return n.exact!==void 0&&(e.exact=Pt(n.exact)),n.rational!==void 0&&(e.rational=en(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):_(n.v);return new m(1,e,n.base)}case 2:return new m(2,BigInt(n.v));case 3:return new m(3,n.v);case 4:return new m(4,_(n.v));case 5:return new m(5,_(n.v));case 6:{let e=new m(6,_(n.v),n.unit);return n.exact!==void 0&&(e.exact=Pt(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 m(7,t)}case 8:return new m(8,{min:_(n.min),max:_(n.max)});case 10:return new m(10,n.v);case 13:return new m(13,n.code,n.message);default:throw c$5.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 re(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(Re)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:re(t.program)}))),e}function ie(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(Pe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ie(t.program)}))),e}function Re(n){return {name:n.name,params:n.params.slice(),program:re(n.program)}}function Pe(n){return {name:n.name,params:n.params.slice(),program:ie(n.program)}}function Ot(n){if(typeof n!="object"||n===null)throw c$5.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 "${G}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==G)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${G}"`,found:JSON.stringify(e.format)});if(e.version!==H)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${H}.`,expected:`snapshot version ${H}`,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:H,engineVersion:e.engineVersion}})}var W=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},he=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 Le(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 nn(n){if(n instanceof Date)return Le(n.getTime());if(typeof n=="number")return Number.isFinite(n)?Le(n):null;let e=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return e?`${e[1]}-${e[2]}-${e[3]}`:null}function It(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=nn(t);r!==null&&e.add(r);}return t=>e.has(Le(t))}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(`
1
+ import {b as b$3,a as a$4}from'./chunk-XNIWQHXY.js';import {a as a$2}from'./chunk-7GK3XEZF.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d,c,a as a$1,b}from'./chunk-YJ2OPULK.js';import {a as a$3,b as b$4,c as c$6}from'./chunk-TWC7K3ZX.js';import {c as c$8,a as a$a}from'./chunk-J4LZD4ZY.js';import {b as b$8}from'./chunk-TN5E6JU6.js';import {d as d$1}from'./chunk-YVKHEAFT.js';import {c as c$2,g,d as d$3,b as b$7}from'./chunk-5FO4PDIG.js';import {b as b$6}from'./chunk-76F3LCIL.js';import {c as c$3,a as a$7,b as b$a}from'./chunk-TCZSPH4A.js';import {w,x,F as F$1,H as H$1,I,i,K}from'./chunk-W2JAR233.js';import {_ as _$1,da}from'./chunk-RSF25YSJ.js';import {N,M,t,n,l,m,J,u,L,K as K$1,s,r,g as g$1}from'./chunk-EVAOPEO4.js';import {c as c$1,b as b$1,a as a$5}from'./chunk-U4AEVL5Z.js';import {b as b$2,d as d$2,c as c$9}from'./chunk-YAHGSBMC.js';import {b as b$5,c as c$4}from'./chunk-JPFCXLJV.js';import {a as a$8}from'./chunk-G7TBEQRQ.js';import {a,c as c$7}from'./chunk-IJMNVBIS.js';import {a as a$9}from'./chunk-62LMTO4F.js';import {d as d$4,c as c$5,b as b$9}from'./chunk-MPB7KUN5.js';function xt(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 Ht(n,e){let t=[];if(xt("prefixParseletTokenType","prefixParselets",n,e,t),xt("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 kt(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Ht(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var Kt=/(\d+)\.(\d+)\.(\d+)/,jt=/^\d+$/;function Ct(n){let e=Kt.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Gt(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Te(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(!jt.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function qt([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 Qt([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Xt(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Te(n.slice(1));return i&&qt(i)}if(n[0]==="~"){let i=Te(n.slice(1));return i&&Qt(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Te(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Tt(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=Xt(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Nt(n){return Tt(n.trim())!==null}function Jt(n,e){let t=Gt(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 wt(n,e){let t=Tt(e.trim());return t===null?false:t.some(r=>r.every(i=>Jt(n,i)))}function Yt(n,e=a$5){if(!n.engineVersion)return {compatible:true};if(!Nt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Ct(e);return t===null||!wt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function At(n,e=a$5){let t=Yt(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c$5.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}}):c$5.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 G="solve-engine/snapshot",H=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 c$5.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 Rt(n){return {coef:n.coef.toString(),scale:n.scale}}function Pt(n){return {coef:BigInt(n.coef),scale:n.scale}}function Zt(n){return {n:n.n.toString(),d:n.d.toString()}}function en(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Lt(n){return g$1[n]??String(n)}function Ne(n,e){throw c$5.validation({code:D.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Lt(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Lt(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 we(n,e){switch(n.type){case 0:{let t={t:0,v:F(n.value)};return n.exact!==void 0&&(t.exact=Rt(n.exact)),n.rational!==void 0&&(t.rational=Zt(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=Rt(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ne(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>tn(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 Ne(n.type,e)}}function tn(n,e){return typeof n=="boolean"?n:typeof n=="number"?F(n):Ne(9,`${e} (symbolic matrix cell)`)}function Ae(n){switch(n.t){case 0:{let e=new m(0,_(n.v));return n.exact!==void 0&&(e.exact=Pt(n.exact)),n.rational!==void 0&&(e.rational=en(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):_(n.v);return new m(1,e,n.base)}case 2:return new m(2,BigInt(n.v));case 3:return new m(3,n.v);case 4:return new m(4,_(n.v));case 5:return new m(5,_(n.v));case 6:{let e=new m(6,_(n.v),n.unit);return n.exact!==void 0&&(e.exact=Pt(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 m(7,t)}case 8:return new m(8,{min:_(n.min),max:_(n.max)});case 10:return new m(10,n.v);case 13:return new m(13,n.code,n.message);default:throw c$5.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 re(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(Re)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:re(t.program)}))),e}function ie(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(Pe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ie(t.program)}))),e}function Re(n){return {name:n.name,params:n.params.slice(),program:re(n.program)}}function Pe(n){return {name:n.name,params:n.params.slice(),program:ie(n.program)}}function Ot(n){if(typeof n!="object"||n===null)throw c$5.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 "${G}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==G)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${G}"`,found:JSON.stringify(e.format)});if(e.version!==H)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${H}.`,expected:`snapshot version ${H}`,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:H,engineVersion:e.engineVersion}})}var W=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},he=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 Le(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 nn(n){if(n instanceof Date)return Le(n.getTime());if(typeof n=="number")return Number.isFinite(n)?Le(n):null;let e=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return e?`${e[1]}-${e[2]}-${e[3]}`:null}function It(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=nn(t);r!==null&&e.add(r);}return t=>e.has(Le(t))}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
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
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:Oe(o,50),p95WallTimeNs:Oe(o,95),p99WallTimeNs:Oe(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 Oe(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 Ie(n$1,e){if(n$1.length>e.maxExpressionLength){let t=c$5.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n$1.length})`,{expressionLength:n$1.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function Ve(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=c$5.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 se(n){return n.type==="IDENT"||n.type==="UNIT"}function rn(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function Vt(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 sn(n){let e=new Set;for(let t=0;t<n.length;t++){if(!se(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=Vt(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)se(n[i])&&e.add(n[i].value);}return e}function fe(n){let e=[],t=[],r=sn(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"&&se(n[i+2])){let o=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&&se(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(se(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&rn(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let a=Vt(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 $n(n){return c$9.classifyLine(n).skip}function Wn(n,e){return c$9.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}function Bt(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 me=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=Bt(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(Bt(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function Mt(n,e=82){return {name:"uom:user-unit",priority:e,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 a$8("STAR",c$7("STAR"),"*","*",i.offset,0,i.line,i.col),f=new a$8("NUMBER",c$7("NUMBER"),c,c,i.offset,0,i.line,i.col),m=new a$8("UNIT",c$7("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+a.wordCount,replacement:[i,p,f,m],ruleName:"uom:user-unit"}}}}var on=30,an=40,ln=50,cn=24;function un(n){switch(n){case a.PLUS:case a.MINUS:return on;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return an;case a.CARET:return ln;case a.PCT_ON:case a.PCT_OFF:return cn;default:return 0}}function pn(n){switch(n){case a.PLUS:return "plus";case a.MINUS:return "minus";case a.STAR:return "times";case a.SLASH:return "divided by";case a.MOD:return "mod";case a.CARET:return "to the power of";case a.OF:return "of";case a.PCT_ON:return "plus";case a.PCT_OFF:return "less";default:return n.toLowerCase()}}function Dt(n){return n.sourceEnd??n.offset+n.value.length}var gn=new Set([a.NUMBER,a.BIGINT,a.IDENT,a.UNIT,a.PERCENT,a.PI,a.E,a.TRUE,a.FALSE,a.DOLLAR,a.POUND,a.EURO,a.YEN,a.RUBLE,a.WON,a.CURRENCY_SYMBOL]);function dn(n){return !gn.has(n)}var Be=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=un(r.type);if(i===0||i<=e)break;this.next();let s=r.type===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===a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===a.PLUS||this.peek().type===a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!dn(this.peek().type);)i=Dt(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!==a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:Dt(r)}}},Me=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$9(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=pn(e.op);return e.op===a.PCT_ON||e.op===a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=c$8(e,a$a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function De(n){let{expression:e,tokens:t,evaluate:r,locale:i}=n,s=()=>({expression:e,steps:[],result:r(e)}),o;try{o=new Be(t).parseAll();}catch{return s()}try{let{steps:a,result:l}=new Me(e,r,i).build(o);return {expression:e,steps:a,result:l}}catch{return s()}}var oe=class oe{constructor(e={}){this.dag=new a$1;this.lineCache=new he;this.accumulatorNames=new Set;this.scopeManager=new b;this.resolverRegistry=new a$2;this.packageContributions=new Map;this.registeredPackages=new Map;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.userUnits=new me;this.bytecodeCache=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$1(this.pluginFunctionIndexByName),new d$1(this.pluginFunctionIndexByName),new d$1(this.pluginFunctionIndexByName),new d$1(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=c$1(b$1,i??{}),this.lexer=new b$2(t,d$2(t)),this.registry=new b$3,this.context=x(),r?(this.diagnosticPipeline=new a$3,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$3,this.normalizer=new c$2;for(let[a,l]of Object.entries(g))this.normalizer.addPhrase(a,l);this.normalizer.register(d$3(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(Mt(this.userUnits));let o=s??[];for(let a of o)try{this.registerPackage(a);}catch(l){let c=d$4(l);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${c.format()}`);}this.parser=new a$4(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName),this.vm=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,It(this.config.date.holidays)),this.queryClient=c$3(),this.batcher=new ve(this.dag,this.lineCache,this.vm);}setDocumentModel(e){this.documentModel=e;}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 N("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=oe.GOAL_SEEK_MAX_NESTING_DEPTH)return N("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 N("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 N("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=d(a,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?N("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?N(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 N("GOAL_SEEK_TARGET_ERROR",d$4(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){At(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=kt(e,[...this.registeredPackages.values()]);for(let i of t.conflicts)(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:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=F$1(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),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.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$5(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))H$1(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,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)c$4(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)I(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.bytecodeCache.clear(),true}getConfig(){return {...this.config}}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new W(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}),a$6.localControllerCreated("executeAndStore"),this.keystrokeSignal&&a$6.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},a$7(this.queryClient);let f=d(e,this.vm,a,l,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(f.type==="pending"){this.resolveAsync(f),this.dag.registerLineDataSourceDependency(t,f.packageId||o,[f.queryKey]);let m=M(f.queryKey);return this.storeLineResult(t,m,e,i,s,r),m}if(f.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),f.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,f.value,e,i,s,r),f.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),a$6.localControllerCreated("executeRaw"),this.keystrokeSignal&&a$6.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},a$7(this.queryClient);let o=d(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){a$6.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(a){if(s.aborted){a$6.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});}}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(b$6(e,r)>r)throw c$5.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})),f=p.length>0,m={lineNumber:a,text:o,startPosition:l,endPosition:c,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(!u){let g=o.trim().startsWith(":");if(f&&!g)for(let R of p)try{R.result=this.evaluateLine(a,R.expression);}catch(O){let I=O instanceof Error?O.message:String(O);R.error=I;}else {let R=s.classification.contentOffset,I=(R===void 0?o:o.slice(R-l)).trim();if(I)try{let E=this.evaluateLineWithPreTokenized(a,I,s.tokens);m.expression=I,m.result=E[0];}catch(E){let X=E instanceof Error?E.message:String(E);m.error=X;}}}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 c$5.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 c$5.parsing("UNEXPECTED_TRAILING_TOKEN",`Unexpected token after expression: "${s.value}"`,{tokenType:s.type,tokenValue:s.value})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c$5.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 N("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return N("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=_$1(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?N("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_$1(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t$1=1;e[t$1].type==="STAR"&&t$1++;let r=[];for(;t$1<e.length&&e[t$1].type==="IDENT";)r.push(e[t$1].value),t$1++;if(r.length===0||e[t$1]?.type!=="EQUALS"||(t$1++,e[t$1]?.type!=="NUMBER"))return null;let i=e[t$1];if(t$1++,e[t$1]?.type!=="UNIT")return null;let s=e[t$1];return t$1++,t$1!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.bytecodeCache.clear(),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 c$5.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,n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$7("IDENT",l,[r]),b$7(c.type,c.text,[i]),b$7("LPAREN","(",[i]),...a,b$7("RPAREN",")",[i])],p=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 c$5.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=-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 c$5.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),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t$1);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t$1)}return this.simplifySymbolically(c,t$1)}if(b$8(e))return this.simplifySymbolically(e,t$1);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$1);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)),t(`${a} stored as an equation \u2014 solve with "${a} =>"`)}tryStoreScalarEquation(e,t$1){if(e[1]?.type==="LPAREN"||t$1===0||t$1===e.length-1)return null;let r=e.slice(0,t$1),i=e.slice(t$1+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)),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$1=this.executeSymbolicTolerant(e.rhsProgram,t);return i(r,i$1,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=Ie(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=Ve(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=fe(l));}u===null&&(u=this.trySymbolicGrammar(l,s));}catch(E){let{reads:X,writes:P}=fe(l);return {kind:"error",stage:"parse",error:d$4(E),reads:X,writes:P,normalizedTokens:l}}if(u!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:u,reads:p?.reads,writes:p?.writes};let{reads:f,writes:m}=fe(l),g=this.bytecodeCache.get(e);if(g)return {kind:"ready",normalizedTokens:l,reads:f,writes:m,program:g,cached:true};let R=this.builderPool[this.builderPoolIndex++%this.builderPool.length];R.reset();let O,I=null;try{let E=U.track("parser",()=>(this.parseExpression(R,l,r),R.build()));O=E.result,I=E.alloc;}catch(E){return {kind:"error",stage:"parse",error:d$4(E),reads:f,writes:m,normalizedTokens:l}}return this.cacheBytecode(e,O),{kind:"ready",normalizedTokens:l,reads:f,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}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.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]);let p=M(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=n(0);return this.lineCache.set(e,new W(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:c$5.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return 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=Ie(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:c$6.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 f=s?h=>{i.fireTokenEmitted({type:c$6.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,f)),g=m.result.tokens,R=m.result.hasParens;if(a&&m.alloc&&l.push(m.alloc),s){let h={};for(let A of g)h[A.type]=(h[A.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:g.length,tokenTypes:h,hasParens:R,locale:this.localeCode,tokens:[...g]});let N=[];for(let A=0;A<g.length;A++){let ee=g[A];if(ee.type==="INLINE_SOLVE_START"){let V=-1;for(let z=A+1;z<g.length;z++)if(g[z].type==="BACKTICK_OPEN"){V=z;break}if(V>A){let $t=g.slice(A+1,V).map(Wt=>Wt.value).join("");N.push({startTokenIndex:A,endTokenIndex:V,expression:$t,columnNumber:ee.col||1}),A=V;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:N.length>0,inlineSolveSpans:N});}if(g.length===0){let h=n(0);return this.lineCache.set(t,new W(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$6.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,X=s?h=>{O++,I.push(h),E.set(h.rule,(E.get(h.rule)||0)+1),i.fireTokenFused({type:c$6.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:c$6.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,R,X,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:c$6.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,N])=>({rule:h,count:N})),tokens:[...x],phrases:this.normalizer.getPhrases()})):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()})),y.kind==="empty"||y.kind==="error"&&y.stage==="length"){if(s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=n(0);return this.lineCache.set(t,new W(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: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 J=Ve(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:J.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0},errorMessage:J.errorMessage}),i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:J.errorMessage,engineError:J.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:J.complexityScore??x.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0}}),y.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$6.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 ae=y.reads??[],Y=y.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ae,writes:Y,isAssignment:Y.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:c$6.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$6.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value: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 c$5.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:c$6.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:v.opcodes.length,numbersLength:v.numbers.length,stringsLength:v.strings.length,isCached:!!P}));let Ft=v.hasAsync||this.resolverRegistry.size>0,Z=this.preflightAsync(x,v,t,e,ae,Y);if(s&&(Z.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:Z.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Ft?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})),Z.kind==="pending")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:Z.value,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,Z.value,x,v,null):void 0};let zt=s&&this.config.diagnostic.vmTraceEnabled===true,C;try{let h=U.track("vm",()=>this.executeAndStore(v,t,e,ae,Y,"_engine",zt?i:void 0,e),{cacheHit:!!P});C=h.result,a&&h.alloc&&l.push(h.alloc);}catch(h){let N=d$4(h);return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:n(0),tokens:x,program:v,error:N.message,engineError:N,debug:void 0,diagnostic:void 0}}let le=C.type===12;if(s){let h=le?"pending":String(C.value??""),N=le?"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:N,resultValue:h,isPending:le});}if(le)return s&&i.firePipelineEnd({type:c$6.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:ae,writesRegistered:Y,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:c$6.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:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length})),s){let N=i.collectReports()[0]?.toJSON(),A=N;if(N){let ee=N.parselets.slice(o),V={};for(let z of ee)V[z.parseletCategory]=(V[z.parseletCategory]??0)+1;A={...N,parselets:ee,summary:{...N.summary,totalParselets:Object.keys(V).length,parseCategories:V}};}return {value:C,tokens:x,program:v,debug:A,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}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.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}),M(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),M(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?a$6.keystrokeSignalSet(e.aborted):a$6.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 De({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 n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c$5.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 b$9(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 n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),M(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.queryClient.clear(),b$a()===this.queryClient&&a$7(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 f=u.writeVariable;if(f){let m=i.get(f);(!m||c>=m.line)&&i.set(f,{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]=we(u,`variable "${c}"`);}catch(p){if(p instanceof b$9&&p.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Re),a=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let f;try{f=we(p.result,`line ${c}`);}catch(m){if(m instanceof b$9&&m.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}a.push({line:c,expression:u,result:f,bytecode:re(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:re(u)}));return {format:G,version:H,engineVersion:a$5,locale:this.localeCode,variables:s,userFunctions:o,lineCache:a,bytecodeCache:l}}static fromJSON(e,t={}){Ot(e);let r=t.locale??e.locale??"en",i=new oe({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,Ae(r));for(let t of e.userFunctions){let r=Pe(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new W(Ae(t.result),ie(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,ie(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,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=N(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}};oe.GOAL_SEEK_MAX_NESTING_DEPTH=1;var ye=oe;var Ue=(()=>{throw new Error("engine.worker.ts was not processed by esbuild-plugin-inline-worker, so worker offload is unavailable")}),q=null;function hn(){return q||(q=new ye),q}var Q=null;function fn(){return Q||(Q=c(w,200,5e4)),Q}function mn(n){let e={lineId:n.lineId,expression:n.expression,compiledAgainstHash:n.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let t=hn(),{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 yn(n){let e=[],t=[];for(let r of n.items){let i=mn(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 vn(n){let e=fn();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=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 bn(n){let e=[];for(let t of n.items)e.push(vn(t));self.postMessage({id:n.id,type:"EXECUTE_RESULT",results:e});}var En=typeof self<"u"&&typeof window>"u",Sn=n=>{if(n.origin&&self.location&&n.origin!==self.location.origin)return;let e=n.data;switch(e.type){case "COMPILE_BATCH":yn(e);break;case "EXECUTE_BATCH":bn(e);break;case "TERMINATE":{q&&(q.clear(),q=null),Q&&(Q.reset(),Q=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}`});}};En&&(self.onmessage=Sn);var xn=3e4,Ut=50,be=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 Ue().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),f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);r.push({lineNumber:a,opcodesBuffer:p,numbersBuffer:f,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([]);},xn);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=Ue();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 _t(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r(n$1.value);case 2:return s(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return K$1(n$1.value);case 5:return L(n$1.value);case 6:return u(n$1.value,n$1.unit??"");case 7:return n(n$1.value);case 10:return J(n$1.value!==0);case 12:return M(n$1.queryKey??"");case 13:return N("WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var Ee=class Ee{constructor(e,t,r,i=Ee.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=d$4(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>Ut){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=d$4(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 be);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=_t(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=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=N(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=d$4(l),u=N(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{}}};Ee.DEFAULT_HIGH_WATER_MARK=64;var ve=Ee;export{kt as a,Yt as b,At as c,G as d,H as e,D as f,Ue as g,ve as h,Ie as i,Ve as j,fe as k,$n as l,Wn as m,ye as n};//# sourceMappingURL=chunk-XR7HEC7B.js.map
5
- //# sourceMappingURL=chunk-XR7HEC7B.js.map
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})),f=p.length>0,m={lineNumber:a,text:o,startPosition:l,endPosition:c,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(!u){let g=o.trim().startsWith(":");if(f&&!g)for(let R of p)try{R.result=this.evaluateLine(a,R.expression);}catch(O){let I=O instanceof Error?O.message:String(O);R.error=I;}else {let R=s.classification.contentOffset,I=(R===void 0?o:o.slice(R-l)).trim();if(I)try{let E=this.evaluateLineWithPreTokenized(a,I,s.tokens);m.expression=I,m.result=E[0];}catch(E){let X=E instanceof Error?E.message:String(E);m.error=X;}}}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 c$5.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 c$5.parsing("UNEXPECTED_TRAILING_TOKEN",`Unexpected token after expression: "${s.value}"`,{tokenType:s.type,tokenValue:s.value})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c$5.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 N("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return N("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=_$1(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?N("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_$1(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t$1=1;e[t$1].type==="STAR"&&t$1++;let r=[];for(;t$1<e.length&&e[t$1].type==="IDENT";)r.push(e[t$1].value),t$1++;if(r.length===0||e[t$1]?.type!=="EQUALS"||(t$1++,e[t$1]?.type!=="NUMBER"))return null;let i=e[t$1];if(t$1++,e[t$1]?.type!=="UNIT")return null;let s=e[t$1];return t$1++,t$1!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.bytecodeCache.clear(),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 c$5.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,n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$7("IDENT",l,[r]),b$7(c.type,c.text,[i]),b$7("LPAREN","(",[i]),...a,b$7("RPAREN",")",[i])],p=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 c$5.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=-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 c$5.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),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t$1);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t$1)}return this.simplifySymbolically(c,t$1)}if(b$8(e))return this.simplifySymbolically(e,t$1);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$1);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)),t(`${a} stored as an equation \u2014 solve with "${a} =>"`)}tryStoreScalarEquation(e,t$1){if(e[1]?.type==="LPAREN"||t$1===0||t$1===e.length-1)return null;let r=e.slice(0,t$1),i=e.slice(t$1+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)),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$1=this.executeSymbolicTolerant(e.rhsProgram,t);return i(r,i$1,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=Ie(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=Ve(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=fe(l));}u===null&&(u=this.trySymbolicGrammar(l,s));}catch(E){let{reads:X,writes:P}=fe(l);return {kind:"error",stage:"parse",error:d$4(E),reads:X,writes:P,normalizedTokens:l}}if(u!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:u,reads:p?.reads,writes:p?.writes};let{reads:f,writes:m}=fe(l),g=this.bytecodeCache.get(e);if(g)return {kind:"ready",normalizedTokens:l,reads:f,writes:m,program:g,cached:true};let R=this.builderPool[this.builderPoolIndex++%this.builderPool.length];R.reset();let O,I=null;try{let E=U.track("parser",()=>(this.parseExpression(R,l,r),R.build()));O=E.result,I=E.alloc;}catch(E){return {kind:"error",stage:"parse",error:d$4(E),reads:f,writes:m,normalizedTokens:l}}return this.cacheBytecode(e,O),{kind:"ready",normalizedTokens:l,reads:f,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}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.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]);let p=M(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=n(0);return this.lineCache.set(e,new W(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:c$5.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return 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=Ie(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:c$6.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 f=s?h=>{i.fireTokenEmitted({type:c$6.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,f)),g=m.result.tokens,R=m.result.hasParens;if(a&&m.alloc&&l.push(m.alloc),s){let h={};for(let A of g)h[A.type]=(h[A.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:g.length,tokenTypes:h,hasParens:R,locale:this.localeCode,tokens:[...g]});let N=[];for(let A=0;A<g.length;A++){let ee=g[A];if(ee.type==="INLINE_SOLVE_START"){let V=-1;for(let z=A+1;z<g.length;z++)if(g[z].type==="BACKTICK_OPEN"){V=z;break}if(V>A){let $t=g.slice(A+1,V).map(Wt=>Wt.value).join("");N.push({startTokenIndex:A,endTokenIndex:V,expression:$t,columnNumber:ee.col||1}),A=V;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:N.length>0,inlineSolveSpans:N});}if(g.length===0){let h=n(0);return this.lineCache.set(t,new W(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$6.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,X=s?h=>{O++,I.push(h),E.set(h.rule,(E.get(h.rule)||0)+1),i.fireTokenFused({type:c$6.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:c$6.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,R,X,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:c$6.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,N])=>({rule:h,count:N})),tokens:[...x],phrases:this.normalizer.getPhrases()})):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()})),y.kind==="empty"||y.kind==="error"&&y.stage==="length"){if(s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=n(0);return this.lineCache.set(t,new W(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: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 J=Ve(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:J.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0},errorMessage:J.errorMessage}),i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:J.errorMessage,engineError:J.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:J.complexityScore??x.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0}}),y.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$6.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 ae=y.reads??[],Y=y.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ae,writes:Y,isAssignment:Y.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:c$6.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$6.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value: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 c$5.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:c$6.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:v.opcodes.length,numbersLength:v.numbers.length,stringsLength:v.strings.length,isCached:!!P}));let Ft=v.hasAsync||this.resolverRegistry.size>0,Z=this.preflightAsync(x,v,t,e,ae,Y);if(s&&(Z.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:Z.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Ft?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})),Z.kind==="pending")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:Z.value,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,Z.value,x,v,null):void 0};let zt=s&&this.config.diagnostic.vmTraceEnabled===true,C;try{let h=U.track("vm",()=>this.executeAndStore(v,t,e,ae,Y,"_engine",zt?i:void 0,e),{cacheHit:!!P});C=h.result,a&&h.alloc&&l.push(h.alloc);}catch(h){let N=d$4(h);return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:n(0),tokens:x,program:v,error:N.message,engineError:N,debug:void 0,diagnostic:void 0}}let le=C.type===12;if(s){let h=le?"pending":String(C.value??""),N=le?"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:N,resultValue:h,isPending:le});}if(le)return s&&i.firePipelineEnd({type:c$6.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:ae,writesRegistered:Y,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:c$6.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:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length})),s){let N=i.collectReports()[0]?.toJSON(),A=N;if(N){let ee=N.parselets.slice(o),V={};for(let z of ee)V[z.parseletCategory]=(V[z.parseletCategory]??0)+1;A={...N,parselets:ee,summary:{...N.summary,totalParselets:Object.keys(V).length,parseCategories:V}};}return {value:C,tokens:x,program:v,debug:A,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}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.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}),M(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),M(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?a$6.keystrokeSignalSet(e.aborted):a$6.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 De({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 n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c$5.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 b$9(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 n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),M(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.queryClient.clear(),b$a()===this.queryClient&&a$7(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 f=u.writeVariable;if(f){let m=i.get(f);(!m||c>=m.line)&&i.set(f,{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]=we(u,`variable "${c}"`);}catch(p){if(p instanceof b$9&&p.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Re),a=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let f;try{f=we(p.result,`line ${c}`);}catch(m){if(m instanceof b$9&&m.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}a.push({line:c,expression:u,result:f,bytecode:re(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:re(u)}));return {format:G,version:H,engineVersion:a$5,locale:this.localeCode,variables:s,userFunctions:o,lineCache:a,bytecodeCache:l}}static fromJSON(e,t={}){Ot(e);let r=t.locale??e.locale??"en",i=new oe({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,Ae(r));for(let t of e.userFunctions){let r=Pe(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new W(Ae(t.result),ie(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,ie(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,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=N(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}};oe.GOAL_SEEK_MAX_NESTING_DEPTH=1;var ye=oe;var Ue=(()=>{throw new Error("engine.worker.ts was not processed by esbuild-plugin-inline-worker, so worker offload is unavailable")}),q=null;function hn(){return q||(q=new ye),q}var Q=null;function fn(){return Q||(Q=c(w,200,5e4)),Q}function mn(n){let e={lineId:n.lineId,expression:n.expression,compiledAgainstHash:n.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let t=hn(),{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 yn(n){let e=[],t=[];for(let r of n.items){let i=mn(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 vn(n){let e=fn();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=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 bn(n){let e=[];for(let t of n.items)e.push(vn(t));self.postMessage({id:n.id,type:"EXECUTE_RESULT",results:e});}var En=typeof self<"u"&&typeof window>"u",Sn=n=>{if(n.origin&&self.location&&n.origin!==self.location.origin)return;let e=n.data;switch(e.type){case "COMPILE_BATCH":yn(e);break;case "EXECUTE_BATCH":bn(e);break;case "TERMINATE":{q&&(q.clear(),q=null),Q&&(Q.reset(),Q=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}`});}};En&&(self.onmessage=Sn);var xn=3e4,Ut=50,be=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 Ue().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),f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);r.push({lineNumber:a,opcodesBuffer:p,numbersBuffer:f,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([]);},xn);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=Ue();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 _t(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r(n$1.value);case 2:return s(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return K$1(n$1.value);case 5:return L(n$1.value);case 6:return u(n$1.value,n$1.unit??"");case 7:return n(n$1.value);case 10:return J(n$1.value!==0);case 12:return M(n$1.queryKey??"");case 13:return N("WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var Ee=class Ee{constructor(e,t,r,i=Ee.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=d$4(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>Ut){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=d$4(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 be);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=_t(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=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=N(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=d$4(l),u=N(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{}}};Ee.DEFAULT_HIGH_WATER_MARK=64;var ve=Ee;export{kt as a,Yt as b,At as c,G as d,H as e,D as f,Ue as g,ve as h,Ie as i,Ve as j,fe as k,$n as l,Wn as m,ye as n};//# sourceMappingURL=chunk-4E4YVQKK.js.map
5
+ //# sourceMappingURL=chunk-4E4YVQKK.js.map