solve-engine 2.38.14 → 2.38.16

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 (62) hide show
  1. package/dist/{PackageCompatibility-ByCnkoxf.d.cts → PackageCompatibility-C-3vPMKp.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-WzScL1Av.d.ts → PackageCompatibility-zdsKvwQI.d.ts} +1 -1
  3. package/dist/{PackageRegistry-11ThI3Qg.d.ts → PackageRegistry-CStmqgw_.d.ts} +1 -1
  4. package/dist/{PackageRegistry-BN4zOado.d.cts → PackageRegistry-DiHxyxrn.d.cts} +1 -1
  5. package/dist/{VMBuiltins-5ATHQ045.d.cts → VMBuiltins-BwqFO2TY.d.cts} +12 -0
  6. package/dist/{VMBuiltins-BbNZtVJc.d.ts → VMBuiltins-h09nijID.d.ts} +12 -0
  7. package/dist/chunk-25JO4SYL.cjs +5 -0
  8. package/dist/chunk-25JO4SYL.cjs.map +1 -0
  9. package/dist/chunk-3TXVKQLL.js +5 -0
  10. package/dist/chunk-3TXVKQLL.js.map +1 -0
  11. package/dist/chunk-44BWHZ5V.js +2 -0
  12. package/dist/chunk-44BWHZ5V.js.map +1 -0
  13. package/dist/chunk-H4EJRCXT.js +3 -0
  14. package/dist/chunk-H4EJRCXT.js.map +1 -0
  15. package/dist/chunk-HFES6BF5.cjs +2 -0
  16. package/dist/chunk-HFES6BF5.cjs.map +1 -0
  17. package/dist/{chunk-VR35R5MV.cjs → chunk-OUMFZQ6N.cjs} +3 -3
  18. package/dist/chunk-OUMFZQ6N.cjs.map +1 -0
  19. package/dist/{chunk-54MEZ574.cjs → chunk-TOCCIZVE.cjs} +2 -2
  20. package/dist/{chunk-54MEZ574.cjs.map → chunk-TOCCIZVE.cjs.map} +1 -1
  21. package/dist/{chunk-5M4F7PCU.js → chunk-ZOS4RCB7.js} +2 -2
  22. package/dist/{chunk-5M4F7PCU.js.map → chunk-ZOS4RCB7.js.map} +1 -1
  23. package/dist/constants.cjs +1 -1
  24. package/dist/constants.js +1 -1
  25. package/dist/engine.cjs +1 -1
  26. package/dist/engine.d.cts +4 -4
  27. package/dist/engine.d.ts +4 -4
  28. package/dist/engine.js +1 -1
  29. package/dist/engine.worker.cjs +1 -1
  30. package/dist/engine.worker.js +1 -1
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +4 -4
  33. package/dist/index.d.ts +4 -4
  34. package/dist/index.js +1 -1
  35. package/dist/language.d.cts +3 -3
  36. package/dist/language.d.ts +3 -3
  37. package/dist/packages.d.cts +2 -2
  38. package/dist/packages.d.ts +2 -2
  39. package/dist/testing.cjs +2 -2
  40. package/dist/testing.d.cts +3 -3
  41. package/dist/testing.d.ts +3 -3
  42. package/dist/testing.js +1 -1
  43. package/dist/vm.cjs +1 -1
  44. package/dist/vm.d.cts +1 -1
  45. package/dist/vm.d.ts +1 -1
  46. package/dist/vm.js +1 -1
  47. package/dist/worker.cjs +2 -2
  48. package/dist/worker.d.cts +2 -2
  49. package/dist/worker.d.ts +2 -2
  50. package/dist/worker.js +1 -1
  51. package/package.json +1 -1
  52. package/dist/chunk-CH6NLOVG.js +0 -2
  53. package/dist/chunk-CH6NLOVG.js.map +0 -1
  54. package/dist/chunk-NGHH4QKV.js +0 -5
  55. package/dist/chunk-NGHH4QKV.js.map +0 -1
  56. package/dist/chunk-OXZWX5WY.cjs +0 -2
  57. package/dist/chunk-OXZWX5WY.cjs.map +0 -1
  58. package/dist/chunk-UM5A6VXI.js +0 -3
  59. package/dist/chunk-UM5A6VXI.js.map +0 -1
  60. package/dist/chunk-V52TAWYV.cjs +0 -5
  61. package/dist/chunk-V52TAWYV.cjs.map +0 -1
  62. package/dist/chunk-VR35R5MV.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","keep","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","value","result"],"mappings":"AAuFO,IAAMA,CAAAA,CAAN,KAAqB,CAM3B,WAAA,CAAYC,EAAQ,CAJpB,IAAA,CAAQ,WAAA,CAA8B,EAAC,CAKtC,IAAA,CAAK,GAAKA,EACX,CAqBA,QAAA,CACCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACsB,CACtB,GAAIA,CAAAA,CAAc,MAAA,GAAW,CAAA,CAAG,OAAO,IAAA,CAiBvC,IAAIC,CAAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAA,CAC5B,KAAOA,CAAAA,CAAO,GAAK,IAAA,CAAK,WAAA,CAAYA,CAAAA,CAAO,CAAC,CAAA,CAAE,UAAA,EAAcH,GAAYG,CAAAA,EAAAA,CACpEA,CAAAA,GAAS,IAAA,CAAK,WAAA,CAAY,MAAA,GAAQ,IAAA,CAAK,YAAY,MAAA,CAASA,CAAAA,CAAAA,CAEhE,IAAMC,CAAAA,CAASD,CAAAA,CAAO,CAAA,CAAI,KAAK,WAAA,CAAYA,CAAAA,CAAO,CAAC,CAAA,CAAI,IAAA,CAgBjDE,CAAAA,CAAmC,OAAO,MAAA,CAAO,IAAI,CAAA,CACrDC,CAAAA,CAA6C,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA,CAMrE,IAAA,IAAWC,CAAAA,IAAQL,CAAAA,CAAe,CACjC,GAAI,KAAK,EAAA,CAAG,eAAA,CAAgBK,CAAI,CAAA,CAAG,CAClC,IAAMC,EAAK,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBD,CAAI,CAAA,CACnCC,CAAAA,GAAIF,EAAUC,CAAI,CAAA,CAAIC,CAAAA,CAAAA,CAC1B,QACD,CACA,IAAMC,EAAM,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOF,CAAI,CAAA,CAC3BE,CAAAA,GAAQ,SACXJ,CAAAA,CAAUE,CAAI,CAAA,CAAIE,CAAAA,EAEpB,CAEA,IAAMC,EAA2B,CAChC,UAAA,CAAAV,EACA,MAAA,CAAAC,CAAAA,CACA,UAAAI,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,MAAA,CAAAF,CACD,CAAA,CACA,YAAK,WAAA,CAAY,IAAA,CAAKM,CAAU,CAAA,CACzBA,CACR,CAqBA,UAAUV,CAAAA,CAA0B,CACnC,IAAMW,CAAAA,CAAS,IAAA,CAAK,oBAAA,CAAqBX,CAAU,CAAA,CACnD,GAAI,CAACW,CAAAA,CAAQ,CACZ,IAAA,CAAK,GAAG,KAAA,EAAM,CACd,MACD,CAIA,IAAMC,CAAAA,CAAwB,EAAC,CAC3BC,CAAAA,CAA+BF,CAAAA,CACnC,KAAOE,CAAAA,EACND,CAAAA,CAAM,QAAQC,CAAO,CAAA,CACrBA,CAAAA,CAAUA,CAAAA,CAAQ,MAAA,CAGnB,IAAA,CAAK,GAAG,KAAA,EAAM,CACd,IAAA,IAAWC,CAAAA,IAAMF,CAAAA,CAAO,CAGvB,QAAWG,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAG,SAAS,CAAA,CACzC,KAAK,EAAA,CAAG,MAAA,CAAOC,CAAAA,CAAKD,CAAAA,CAAG,SAAA,CAAUC,CAAG,CAAC,CAAA,CAKtC,IAAA,IAAWA,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAG,SAAS,CAAA,CAAG,CAC5C,IAAMN,CAAAA,CAAKM,CAAAA,CAAG,SAAA,CAAUC,CAAG,CAAA,CAC3B,IAAA,CAAK,EAAA,CAAG,kBAAA,CAAmBP,CAAAA,CAAG,IAAA,CAAMA,EAAG,MAAA,CAAQA,CAAAA,CAAG,OAAO,EAC1D,CACD,CACD,CAqBA,kBAAA,CAAmBR,CAAAA,CAAoBE,CAAAA,CAAkC,CACxE,IAAMQ,CAAAA,CAAa,KAAK,eAAA,CAAgBV,CAAU,EAClD,GAAI,CAACU,EAAY,OAAO,MAAA,CACxB,IAAA,IAAWH,CAAAA,IAAQL,CAAAA,CAAe,CACjC,GAAI,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBK,CAAI,CAAA,CAAG,CAClC,IAAMC,CAAAA,CAAK,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBD,CAAI,CAAA,CACnCC,IAAIE,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAAIC,CAAAA,CAAAA,CACrC,QACD,CACA,IAAMQ,CAAAA,CAAQ,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOT,CAAI,EAC7BS,CAAAA,GAAU,MAAA,GAAWN,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAAIS,GACvD,CACA,OAAO,KACR,CAeA,iBAAA,CAAkBhB,CAAAA,CAA6B,CAC9C,IAAMU,CAAAA,CAAa,IAAA,CAAK,eAAA,CAAgBV,CAAU,CAAA,CAClD,GAAI,CAACU,CAAAA,CAAY,OAAO,MAAA,CACxB,IAAA,IAAWK,CAAAA,IAAO,OAAO,IAAA,CAAKL,CAAAA,CAAW,SAAS,CAAA,CACjD,IAAA,CAAK,EAAA,CAAG,OAAOK,CAAAA,CAAKL,CAAAA,CAAW,SAAA,CAAUK,CAAG,CAAC,CAAA,CAE9C,QAAWA,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKL,CAAAA,CAAW,SAAS,CAAA,CAAG,CACpD,IAAMF,CAAAA,CAAKE,CAAAA,CAAW,SAAA,CAAUK,CAAG,CAAA,CACnC,KAAK,EAAA,CAAG,kBAAA,CAAmBP,CAAAA,CAAG,IAAA,CAAMA,CAAAA,CAAG,MAAA,CAAQA,EAAG,OAAO,EAC1D,CACA,OAAO,KACR,CAaA,qBAAqBR,CAAAA,CAAyC,CAC7D,IAAIiB,CAAAA,CAA8B,IAAA,CAClC,QAAWH,CAAAA,IAAM,IAAA,CAAK,WAAA,CACrB,GAAIA,CAAAA,CAAG,UAAA,EAAcd,EACpBiB,CAAAA,CAASH,CAAAA,CAAAA,KAET,MAGF,OAAOG,CACR,CAMA,gBAAgBjB,CAAAA,CAA8C,CAC7D,OAAO,IAAA,CAAK,WAAA,CAAY,IAAA,CAAMc,GAAOA,CAAAA,CAAG,UAAA,GAAed,CAAU,CAClE,CAMA,iBAAA,EAA6C,CAC5C,OAAO,IAAA,CAAK,WACb,CAgBA,cAAA,CAAeO,CAAAA,CAAiC,CAC/C,GAAI,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CAAA,CAAG,OAEnC,IAAIG,CAAAA,CAAkC,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,WAAA,CAAY,MAAA,CAAS,CAAC,CAAA,CAClF,KAAOA,CAAAA,EAAY,CAClB,GAAI,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAKA,CAAAA,CAAW,SAAA,CAAWH,CAAI,CAAA,CAClE,OAAOG,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAEjCG,CAAAA,CAAaA,CAAAA,CAAW,OACzB,CAED,CAQA,KAAA,EAAc,CACb,IAAA,CAAK,WAAA,CAAc,GACpB,CAGA,IAAI,KAAA,EAAgB,CACnB,OAAO,KAAK,WAAA,CAAY,MACzB,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CACpC,CAGA,IAAI,YAAiB,CACpB,OAAO,IAAA,CAAK,EACb,CACD","file":"chunk-CH6NLOVG.js","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Each checkpoint holds only the variables that CHANGED at its line, and\n * reaches the rest through its `parent` link. A lookup walks that chain until\n * it finds the name; a restore walks it from the root applying each link's own\n * bindings in turn, so a later line's value naturally overwrites an earlier\n * one's.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } parent → 0\n * Checkpoint 2 (:y=8): { y: 8 } parent → 1\n * Checkpoint 3 (:x=3): { x: 3 } parent → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk parent to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Only the variables set or updated at this line; the rest are reached\n\t * through {@link VMCheckpoint.parent}.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Records only what this line wrote; the rest is reached through the\n\t * parent link rather than copied.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// Everything at or after this line goes before the new checkpoint is\n\t\t// taken.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so appending on a re-run broke both halves of that. Editing\n\t\t// line 2 of a document whose lines 1, 2 and 3 each define something\n\t\t// left the list as [1, 2, 3, 2]: `getNearestCheckpoint(2)` stops at the\n\t\t// first entry past its target, so it found the stale line 2 and\n\t\t// restored the old value, and the new line 2 inherited from line 3, a\n\t\t// chain running backwards through the document that would have defined\n\t\t// a variable from a line that had not run yet.\n\t\t//\n\t\t// Nothing is lost by dropping them. A pass runs in document order and\n\t\t// every line that writes takes a checkpoint, so the ones removed here\n\t\t// are re-taken by this same pass as it continues past this line.\n\t\tlet keep = this.checkpoints.length;\n\t\twhile (keep > 0 && this.checkpoints[keep - 1].lineNumber >= lineNumber) keep--;\n\t\tif (keep !== this.checkpoints.length) this.checkpoints.length = keep;\n\n\t\tconst parent = keep > 0 ? this.checkpoints[keep - 1] : null;\n\n\t\t// Each checkpoint holds only what its line wrote, and reaches the rest\n\t\t// through `parent`. It used to reach it through the prototype chain\n\t\t// instead, which held the same entries and cost the same memory, and\n\t\t// made the chain as deep as the document has definitions: a null\n\t\t// prototype is a flat object, and one per definition is a chain two\n\t\t// thousand deep on a document of two thousand definitions. Creating and\n\t\t// reading those took a pass over such a document from 6.0 ms to 23.1 ms.\n\t\t//\n\t\t// Nothing needed the inheritance. `restoreTo` walks `parent` and applies\n\t\t// each checkpoint's OWN keys, which is the same set either way, and the\n\t\t// one reader that did walk the prototype now walks `parent` too.\n\t\t//\n\t\t// Null-prototyped rather than `{}`, so a variable named `constructor` or\n\t\t// `toString` is a key like any other.\n\t\tconst variables: Record<string, Value> = Object.create(null) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(null) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(total variable definitions before the line), since\n\t * each checkpoint in the chain contributes only the names its own line\n\t * wrote.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Only the names this checkpoint's own line wrote; the ones before\n\t\t\t// it are applied by their own links earlier in this same walk.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Record what `lineNumber` has just written, without disturbing the chain\n\t * after it.\n\t *\n\t * {@link snapshot} drops every checkpoint at or after the line, which is\n\t * right for a pass running forward in document order: it re-takes them as it\n\t * goes. A caller re-running a few lines out of a document does not, and\n\t * dropping the entries for lines it will never visit would lose the very\n\t * bindings it is sweeping through them to collect. So this overwrites in\n\t * place instead.\n\t *\n\t * Safe against the prototype chain, because it replaces only the\n\t * checkpoint's OWN bindings: a later checkpoint that also writes the name\n\t * holds its own copy and goes on shadowing this one.\n\t *\n\t * @param lineNumber 1-based line whose recorded bindings are refreshed.\n\t * @param variableNames The names it wrote.\n\t * @returns Whether a checkpoint existed at that line to update.\n\t */\n\tupdateCheckpointAt(lineNumber: number, variableNames: string[]): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) checkpoint.functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst value = this.vm.getVar(name);\n\t\t\tif (value !== undefined) checkpoint.variables[name] = value;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Apply the bindings recorded AT `lineNumber`, leaving the rest of the VM\n\t * alone.\n\t *\n\t * {@link restoreTo} rebuilds the whole prefix, which costs the chain every\n\t * time it is called. A caller moving forward through the document already\n\t * holds the prefix up to the line before, and needs only what this line\n\t * added: restoring once and then applying each line in turn as it is passed\n\t * costs the chain once rather than once per line.\n\t *\n\t * @param lineNumber 1-based line whose own bindings are applied.\n\t * @returns Whether a checkpoint existed at that line.\n\t */\n\tapplyCheckpointAt(lineNumber: number): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const key of Object.keys(checkpoint.variables)) {\n\t\t\tthis.vm.setVar(key, checkpoint.variables[key]);\n\t\t}\n\t\tfor (const key of Object.keys(checkpoint.functions)) {\n\t\t\tconst fn = checkpoint.functions[key];\n\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tlet checkpoint: VMCheckpoint | null = this.checkpoints[this.checkpoints.length - 1];\n\t\twhile (checkpoint) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(checkpoint.variables, name)) {\n\t\t\t\treturn checkpoint.variables[name];\n\t\t\t}\n\t\t\tcheckpoint = checkpoint.parent;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
@@ -1,5 +0,0 @@
1
- import {b as b$3,a as a$5}from'./chunk-RU3KGJRA.js';import {a as a$3}from'./chunk-RMDCGYZM.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {c as c$1,a as a$2,b as b$6}from'./chunk-ZXNM355C.js';import {a as a$4,b as b$4,c as c$8}from'./chunk-JP4JMQOG.js';import {c as c$a,a as a$b}from'./chunk-SSS3ZMKX.js';import {k,w,s,r,q as q$1,o,l,p,n as n$1,a as a$7,b as b$9,e,t as t$1,v,j as j$1,u as u$1,m as m$1}from'./chunk-IUCUBHFW.js';import {d as d$1}from'./chunk-U5MESNRT.js';import {c as c$4,d as d$2,b as b$a}from'./chunk-DB5ISONG.js';import {b as b$8}from'./chunk-76F3LCIL.js';import {c as c$6,a as a$8,b as b$c}from'./chunk-TCZSPH4A.js';import {N,b,A,I,K,L,k as k$1}from'./chunk-AFNK2LUO.js';import {_ as _$1,da}from'./chunk-IHPYXJIY.js';import {b as b$5}from'./chunk-EOO6M65F.js';import {P,n,O,t,l as l$1,L as L$1,u,N as N$1,M,s as s$1,r as r$1,m,g as g$1}from'./chunk-A34R65WT.js';import {a as a$1,c as c$3,b as b$1}from'./chunk-5M4F7PCU.js';import {c as c$2,b as b$2}from'./chunk-6NL7RBAG.js';import {b as b$7,c as c$7}from'./chunk-JPFCXLJV.js';import {c as c$5,a as a$9}from'./chunk-APYRNAU2.js';import {a,c as c$9}from'./chunk-FAO6DQ74.js';import {a as a$a}from'./chunk-LHLW7JLS.js';import {c,d,b as b$b}from'./chunk-6G2NES2I.js';function Kt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let a of Object.keys(o))c.has(a)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${a}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Gt(n,e){let t=[];if(Kt("prefixParseletTokenType","prefixParselets",n,e,t),Kt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=n.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${c}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[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(c=>c.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 c=r.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=r.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${c}") 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 c=n.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${c}") 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 tr(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Gt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var be=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,r=(s,o)=>{let c=s.get(o);c&&c!==e&&c.name!==e.name&&t.add(c);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))r(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))r(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))r(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))r(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))r(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)r(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))r(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))r(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)r(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))r(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Gt(s,e));return i}add(e){let t=(r,i)=>{r.has(i)||r.set(i,e);};if(e.prefixParselets)for(let r of Object.keys(e.prefixParselets))t(this.prefixOwners,r);if(e.infixParselets)for(let r of Object.keys(e.infixParselets))t(this.infixOwners,r);if(e.phrases)for(let r of Object.keys(e.phrases))t(this.phraseOwners,r);if(e.asConverters)for(let r of Object.keys(e.asConverters))t(this.converterOwners,r.toLowerCase());if(e.pluginFunctions)for(let r of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,r);if(e.normalizerRules)for(let r of e.normalizerRules)t(this.ruleOwners,r.name);if(e.lexerVocabulary?.keywords)for(let r of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,r);if(e.lexerVocabulary?.operators)for(let r of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,r);if(e.asyncResolvers)for(let r of e.asyncResolvers)t(this.resolverOwners,r.namespace);if(e.tokenCategories)for(let r of Object.keys(e.tokenCategories))t(this.categoryOwners,r);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var wn=/(\d+)\.(\d+)\.(\d+)/,Nn=/^\d+$/;function qt(n){let e=wn.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function An(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Me(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(!Nn.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Pn([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 Ln([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function On(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Me(n.slice(1));return i&&Pn(i)}if(n[0]==="~"){let i=Me(n.slice(1));return i&&Ln(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Me(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Yt(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=On(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Qt(n){return Yt(n.trim())!==null}function In(n,e){let t=An(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 Xt(n,e){let t=Yt(e.trim());return t===null?false:t.some(r=>r.every(i=>In(n,i)))}function Dn(n,e=a$1){if(!n.engineVersion)return {compatible:true};if(!Qt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=qt(e);return t===null||!Xt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function Jt(n,e=a$1){let t=Dn(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function W(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.validation({code:V.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 V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Zt(n){return {coef:n.coef.toString(),scale:n.scale}}function en(n){return {coef:BigInt(n.coef),scale:n.scale}}function Mn(n){return {n:n.n.toString(),d:n.d.toString()}}function Vn(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function tn(n){return g$1[n]??String(n)}function Ve(n,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${tn(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${tn(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 Be(n,e){switch(n.type){case 0:{let t={t:0,v:W(n.value)};return n.exact!==void 0&&(t.exact=Zt(n.exact)),n.rational!==void 0&&(t.rational=Mn(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:W(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:{let t={t:4,v:W(n.value)};return n.grain!==void 0&&(t.g=n.grain),n.zone!==void 0&&(t.z=n.zone),t}case 5:return {t:5,v:W(n.value)};case 6:{let t={t:6,v:W(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=Zt(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>Bn(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:W(t.min),max:W(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Ve(n.type,e)}}function Bn(n,e){return typeof n=="boolean"?n:typeof n=="number"?W(n):Ve(9,`${e} (symbolic matrix cell)`)}function Fe(n){switch(n.t){case 0:{let e=new m(0,$(n.v));return n.exact!==void 0&&(e.exact=en(n.exact)),n.rational!==void 0&&(e.rational=Vn(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:{let e=new m(4,$(n.v));return n.g!==void 0&&(e.grain=n.g),n.z!==void 0&&(e.zone=n.z),e}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=en(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.validation({code:V.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 pe(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,W),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(_e)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function de(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(Ue)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:de(t.program)}))),e}function _e(n){return {name:n.name,params:n.params.slice(),program:pe(n.program)}}function Ue(n){return {name:n.name,params:n.params.slice(),program:de(n.program)}}function on(n){if(typeof n!="object"||n===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Un(n);}var nn=32;function Fn(n){return n===null?"null":Array.isArray(n)?`an array of ${n.length}`:typeof n=="object"?"an object":`${typeof n} ${JSON.stringify(n)}`.slice(0,80)}function g(n,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${n}: expected ${e}.`,expected:e,found:Fn(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:n}})}function H(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function j(n){return typeof n=="number"||n==="NaN"||n==="Infinity"||n==="-Infinity"}function ue(n){return typeof n=="string"&&/^-?\d+$/.test(n)}function Ee(n,e){(!Array.isArray(n)||!n.every(t=>typeof t=="string"))&&g(e,"an array of strings",n);}function rn(n,e){(!H(n)||!ue(n.coef)||typeof n.scale!="number")&&g(e,"a decimal as { coef: digits, scale: number }",n);}function _n(n,e){(!H(n)||!ue(n.n)||!ue(n.d))&&g(e,"a rational as { n: digits, d: digits }",n);}function sn(n,e){switch(H(n)||g(e,"a serialised value object",n),n.t){case 0:j(n.v)||g(`${e}.v`,"a number",n.v),n.exact!==void 0&&rn(n.exact,`${e}.exact`),n.rational!==void 0&&_n(n.rational,`${e}.rational`);return;case 1:(n.big?!ue(n.v):!j(n.v))&&g(`${e}.v`,n.big?"an integer string":"a number",n.v),n.base!==void 0&&typeof n.base!="string"&&g(`${e}.base`,"a base name",n.base);return;case 2:ue(n.v)||g(`${e}.v`,"an integer string",n.v);return;case 3:typeof n.v!="string"&&g(`${e}.v`,"a string",n.v);return;case 4:j(n.v)||g(`${e}.v`,"a number",n.v),n.g!==void 0&&n.g!=="date"&&n.g!=="datetime"&&n.g!=="instant"&&g(`${e}.g`,'one of "date", "datetime" or "instant"',n.g),n.z!==void 0&&typeof n.z!="string"&&g(`${e}.z`,"a zone reference",n.z);return;case 5:j(n.v)||g(`${e}.v`,"a number",n.v);return;case 6:j(n.v)||g(`${e}.v`,"a number",n.v),typeof n.unit!="string"&&g(`${e}.unit`,"a unit name",n.unit),n.exact!==void 0&&rn(n.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:r,data:i}=n;(!Number.isInteger(t)||t<0)&&g(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(r)||r<0)&&g(`${e}.cols`,"a non-negative integer",r),(!Array.isArray(i)||i.length!==t*r)&&g(`${e}.data`,`an array of ${t} \xD7 ${r} cells`,i),i.every(s=>typeof s=="boolean"||j(s))||g(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!j(n.min)||!j(n.max))&&g(e,"a range with numeric min and max",n);return;case 10:typeof n.v!="boolean"&&g(`${e}.v`,"a boolean",n.v);return;case 13:(typeof n.code!="string"||typeof n.message!="string")&&g(e,"an error with a string code and message",n);return;default:return}}function xe(n,e,t){if(t>nn&&g(e,`function bodies nested at most ${nn} deep`,"deeper nesting"),H(n)||g(e,"a serialised program object",n),(!Array.isArray(n.opcodes)||!n.opcodes.every(r=>Number.isInteger(r)&&r>=0&&r<=255))&&g(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",n.opcodes),(!Array.isArray(n.numbers)||!n.numbers.every(j))&&g(`${e}.numbers`,"an array of numbers",n.numbers),Ee(n.strings,`${e}.strings`),typeof n.hasAsync!="boolean"&&g(`${e}.hasAsync`,"a boolean",n.hasAsync),n.constants!==void 0){let r=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(n.constants)||!n.constants.every(r))&&g(`${e}.constants`,"an array of [number, number] pairs",n.constants);}n.userFunctionBodies!==void 0&&(Array.isArray(n.userFunctionBodies)||g(`${e}.userFunctionBodies`,"an array of functions",n.userFunctionBodies),n.userFunctionBodies.forEach((r,i)=>an(r,`${e}.userFunctionBodies[${i}]`,t+1))),n.anonymousBodies!==void 0&&(Array.isArray(n.anonymousBodies)||g(`${e}.anonymousBodies`,"an array of bodies",n.anonymousBodies),n.anonymousBodies.forEach((r,i)=>{let s=`${e}.anonymousBodies[${i}]`;H(r)||g(s,"a body object",r),Ee(r.params,`${s}.params`),xe(r.program,`${s}.program`,t+1);}));}function an(n,e,t){H(n)||g(e,"a function object",n),typeof n.name!="string"&&g(`${e}.name`,"a function name",n.name),Ee(n.params,`${e}.params`),xe(n.program,`${e}.program`,t);}function Un(n){n.locale!==void 0&&typeof n.locale!="string"&&g("locale","a locale code",n.locale),H(n.variables)||g("variables","an object of values by name",n.variables);for(let[e,t]of Object.entries(n.variables))sn(t,`variables.${e}`);Array.isArray(n.userFunctions)||g("userFunctions","an array of functions",n.userFunctions),n.userFunctions.forEach((e,t)=>an(e,`userFunctions[${t}]`,1)),Array.isArray(n.lineCache)||g("lineCache","an array of cached lines",n.lineCache),n.lineCache.forEach((e,t)=>{let r=`lineCache[${t}]`;H(e)||g(r,"a cached line",e),Number.isInteger(e.line)||g(`${r}.line`,"a line number",e.line),typeof e.expression!="string"&&g(`${r}.expression`,"the line's expression text",e.expression),sn(e.result,`${r}.result`),xe(e.bytecode,`${r}.bytecode`,1),Ee(e.reads,`${r}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&g(`${r}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(n.bytecodeCache)||g("bytecodeCache","an array of compiled expressions",n.bytecodeCache),n.bytecodeCache.forEach((e,t)=>{let r=`bytecodeCache[${t}]`;(!H(e)||typeof e.expression!="string")&&g(r,"an { expression, program } pair",e),xe(e.program,`${r}.program`,1);});}var ln=null;function pr(n){ln=n;}function ze(){return ln}var cn=3e4,un=50,Se=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=ze();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let l=t.get(a);if(!l||l.bytecode.opcodes.length===0)continue;let u=l.bytecode.opcodes,p=l.bytecode.numbers,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),y=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);r.push({lineNumber:a,opcodesBuffer:h,numbersBuffer:y,opcodesLength:u.length,numbersLength:p.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.nextWorkerIndex(),c=this.workers[o];return new Promise(a=>{let l=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${cn/1e3} seconds; the worker was replaced`);},cn);this.pendingBatches.set(s,{id:s,lineNumbers:r.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(l),a(u);}}),c.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++)this.spawnWorker(e);}spawnWorker(e){let t=ze();if(t===null)return;let r=t();r.onmessage=i=>{this.handleWorkerMessage(i.data);},r.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=r;}failWorker(e,t,r){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(zn(s.lineNumbers,t,r)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function zn(n,e,t){return n.map(r=>({lineNumber:r,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function pn(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r$1(n$1.value);case 2:return s$1(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return M(n$1.value);case 5:return N$1(n$1.value);case 6:return u(n$1.value,n$1.unit??"");case 7:return n(n$1.value);case 10:return L$1(n$1.value!==0);case 12:return O(n$1.queryKey??"");case 13:return P(n$1.errorCode??"WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var te=class te{constructor(e,t,r,i=te.DEFAULT_HIGH_WATER_MARK){this.pending=new Map;this.collapsed=0;this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.checkpointer=null;this.warnedAboutMissingHook=false;this.flushesWithoutYielding=0;this.yieldProbeArmed=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;let t=`${e.packageId}:${e.queryKey}`;if(this.pending.has(t)){this.collapsed++;return}if(this.pending.set(t,e),!this.scheduled){this.scheduled=true;let r=this.flushesWithoutYielding>=te.MAX_CHAINED_FLUSHES,i=()=>{try{this.flush();}catch(s){let o=d(s);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${o.format()}`);}};r?setTimeout(i,0):queueMicrotask(i);}}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.size}get dedupCount(){return this.collapsed}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=new Map,this.collapsed=0,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.size===0)return;this.flushesWithoutYielding++,this.yieldProbeArmed||(this.yieldProbeArmed=true,setTimeout(()=>{this.flushesWithoutYielding=0,this.yieldProbeArmed=false;},0));let e=this.pending;this.pending=new Map,this.collapsed=0;let t=[],r=[];for(let a of e.values())a.isError?t.push(a):r.push(a);for(let a of t)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let i=new Set,s=[],o=[...r,...t];for(let a of o){if(a.signal.aborted)continue;s.push(a.queryKey);let l=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let u of l)i.add(u);}{let a=[...i],l=u=>{i.has(u)||(i.add(u),a.push(u));};for(let u=0;u<a.length;u++){let p=a[u];for(let h of this.dag.getWrites(p))for(let y of this.dag.getAffectedLines(h))l(y);for(let h of this.dag.getAffectedLinesByPosition(p))l(h);}}if(i.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:s});return}let c=this.topologicalSort(Array.from(i));if(c.length>un){let a=new Map;for(let l of c)a.set(l,this.lineCache.getEntryForLine(l));this.reExecuteViaWorkerPool(c,a,s).catch(l=>{let u=d(l);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${u.format()}`);});return}this.reExecuteMainThread(c,s);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let c of e)t.set(c,0),r.set(c,[]);for(let c of e){let a=this.dag.getWrites(c);for(let l of a)i.set(l,c);}for(let c of e){let a=this.dag.getReads(c);for(let l of a){let u=i.get(l);u!==void 0&&u!==c&&(r.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,a]of t)a===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,a)=>c-a);let o=[];for(let c=0;c<s.length;c++){let a=s[c];o.push(a);for(let l of r.get(a)??[]){let u=(t.get(l)??1)-1;t.set(l,u),u===0&&s.push(l);}}if(o.length<e.length){let c=new Set(o),a=e.filter(l=>!c.has(l)).sort((l,u)=>l-u);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new Se);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 c of s){let a=t.get(c.lineNumber);if(!a||c.isPending)continue;let l=pn(c);a.result=l,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,l),o.push(c.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}prepareSweep(e){if(e.length===0)return null;let t=e[0];for(let r=1;r<e.length;r++)e[r]<t&&(t=e[r]);return this.checkpointer.restoreTo(t-1),{at:t-1}}sweepTo(e,t){for(let r=e.at+1;r<t;r++)this.checkpointer.applyCheckpointAt(r);t>e.at&&(e.at=t);}reExecuteMainThread(e,t,r){let i=[],s=this.checkpointer!==null?this.prepareSweep(e):null;for(let o of e){s!==null&&this.sweepTo(s,o);let c=r?r.get(o):this.lineCache.getEntryForLine(o);if(!c||c.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let l=c$1(c.bytecode,this.vm,void 0,void 0,{lineIndex:o,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>a;)this.vm.pop();if(l.type==="value")s!==null&&c.writeVariable!==null&&this.checkpointer.updateCheckpointAt(o,[c.writeVariable]),c.result=l.value,this.warnIfUnwired(),this.onLineResult?.(o,l.value),i.push(o);else if(l.type==="error"){let u=P(l.error.code,l.error.message);c.result=u,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(o,u),i.push(o);}}catch(l){for(;this.vm.getStack().length>a;)this.vm.pop();let u=d(l),p=P(u.code,u.message);c.result=p,this.warnIfUnwired(),this.onLineResult?.(o,p),i.push(o);}}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{}}};te.DEFAULT_HIGH_WATER_MARK=64,te.MAX_CHAINED_FLUSHES=4;var ke=te;function $e(n$1,e){if(n$1.length>e.maxExpressionLength){let t=c.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 je(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.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 fe(n){return n.type==="IDENT"||n.type==="UNIT"}function $n(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function dn(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 jn(n){let e=new Set;for(let t=0;t<n.length;t++){if(!fe(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=dn(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)fe(n[i])&&e.add(n[i].value);}return e}function Ce(n){let e=[],t=[],r=jn(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"&&fe(n[i+2])){let o=N(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&&fe(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(fe(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&$n(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let c=dn(n,i+1);if(c!==null&&n[c+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 Rr(n){return c$2.classifyLine(n).skip}function wr(n,e){return c$2.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}var q=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},Te=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 We(n,e){let t=e.fields(n),r=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${r}-${i}`}function Wn(n,e){if(n instanceof Date)return We(n.getTime(),e);if(typeof n=="number")return Number.isFinite(n)?We(n,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function fn(n,e){if(n===void 0)return;if(typeof n=="function")return r=>n(new Date(r));let t=new Set;for(let r of n){let i=Wn(r,e);i!==null&&t.add(i);}return r=>t.has(We(r,e))}function Hn(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var Re=class n{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&Hn(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var _=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(),c=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,a=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,l=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&a?a.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:l,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
2
- `);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let a of i)r.push(`| ${a.stage} | ${a.count} | ${(a.meanWallTimeNs/1e3).toFixed(2)} | ${a.meanAllocBytes.toFixed(0)} | ${(a.minWallTimeNs/1e3).toFixed(2)} | ${(a.maxWallTimeNs/1e3).toFixed(2)} | ${(a.p50WallTimeNs/1e3).toFixed(2)} | ${(a.p95WallTimeNs/1e3).toFixed(2)} | ${(a.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((a,l)=>a+l.totalAllocBytes,0),o=e.reduce((a,l)=>a+l.totalWallTimeNs,0),c=e.filter(a=>a.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:** ${c}/${e.length} (${(c/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.join(`
3
- `)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let r=[];for(let[i,s]of t){let o=s.map(l=>l.wallTimeNs).sort((l,u)=>l-u),c=s.map(l=>l.allocBytes),a=s.length;r.push({stage:i,count:a,meanAllocBytes:c.reduce((l,u)=>l+u,0)/a,meanWallTimeNs:o.reduce((l,u)=>l+u,0)/a,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:He(o,50),p95WallTimeNs:He(o,95),p99WallTimeNs:He(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,c)=>o+c.allocBytes,0),s=t.reduce((o,c)=>o+c.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};_.enabled=false;function He(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 gn(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 we=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,r){let i=gn(e),s=this.byKey.get(i),o=s===void 0||s.ratioText!==t||s.baseUnit!==r;return this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length),o}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(gn(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function hn(n,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let d=r+1;d<t.length&&s.length<o&&t[d].type==="IDENT";d++)s.push(t[d].value);if(s.length===0)return null;let c=n.match(s);if(c===null||t[r+1+c.wordCount]?.type==="EQUALS")return null;let{ratioText:l,baseUnit:u}=c.definition,p=new a$9("STAR",c$9("STAR"),"*","*",i.offset,0,i.line,i.col),h=new a$9("NUMBER",c$9("NUMBER"),l,l,i.offset,0,i.line,i.col),y=new a$9("UNIT",c$9("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+c.wordCount,replacement:[i,p,h,y],ruleName:"uom:user-unit"}}}}var mn="engine:call-fusion";function yn(n,e=80){return {name:mn,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,r){let i=t[r];if(!i||i.type!=="IDENT"||t[r+1]?.type!=="LPAREN"||t[r-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=n.get(s);return o===void 0?null:{consumed:1,replacement:[new a$9(o,c$9(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:mn}}}}var Kn={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function vn(n){return n===void 0||n.type!=="IDENT"&&n.type!=="UNIT"?0:Kn[(n.text??n.value??"").toLowerCase()]??0}var ge=/^\d+$/;function Ne(n){return n.length===4}function ne(n,e,t,r,i,s){let o="datetime:month-name-date",c=t$1(n,e,t,r,o,i);return c!==null?c:s==="arithmetic"||e<1||e>12||n<1||n>31?null:v(j$1.DATE_NOT_A_CALENDAR_DAY,`"${u$1(r)}" is not a real date: ${m$1(n,e,t)}.`,r,`${o}:unreadable`)}function bn(n){return n.fields(n.now()).year}function En(n=64,e=()=>b$5,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:n,startTokenTypes:["NUMBER","IDENT","UNIT"],match(r,i){let s=e(),o=t(),c=r[i];if(c?.type==="NUMBER"&&ge.test(c.text??"")){let y=vn(r[i+1]);if(y===0)return null;let d=Number(c.text);if(d<1||d>31)return null;let S=r[i+2];return S?.type==="NUMBER"&&ge.test(S.text??"")&&Ne(S.text??"")?ne(d,y,Number(S.text),r.slice(i,i+3),s,o):ne(d,y,bn(s),r.slice(i,i+2),s,o)}let a=vn(c);if(a===0)return null;let l=r[i+1];if(l?.type!=="NUMBER"||!ge.test(l.text??""))return null;if(Ne(l.text??""))return ne(1,a,Number(l.text),r.slice(i,i+2),s,o);let u=Number(l.text),p=r[i+2],h=r[i+3];return p?.type==="COMMA"&&h?.type==="NUMBER"&&ge.test(h.text??"")&&Ne(h.text??"")?ne(u,a,Number(h.text),r.slice(i,i+4),s,o):p?.type==="NUMBER"&&ge.test(p.text??"")&&Ne(p.text??"")?ne(u,a,Number(p.text),r.slice(i,i+3),s,o):ne(u,a,bn(s),r.slice(i,i+2),s,o)}}}var Gn=30,qn=40,Yn=50,Qn=24;function Xn(n){switch(n){case a.PLUS:case a.MINUS:return Gn;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return qn;case a.CARET:return Yn;case a.PCT_ON:case a.PCT_OFF:return Qn;default:return 0}}function Jn(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 xn(n){return n.sourceEnd??n.offset+n.value.length}var Zn=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 er(n){return !Zn.has(n)}var Ke=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=Xn(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()&&!er(this.peek().type);)i=xn(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:xn(r)}}},Ge=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$a(r).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=Jn(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$a(e,a$b);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function qe(n){let{expression:e,tokens:t,evaluate:r,locale:i,readings:s=[]}=n,o=l=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:l})),c=()=>{let l=r(e);return {expression:e,steps:o(l),result:l}},a;try{a=new Ke(t).parseAll();}catch{return c()}try{let{steps:l,result:u}=new Ge(e,r,i).build(a);return {expression:e,steps:[...o(u),...l],result:u}}catch{return c()}}var U=class U{constructor(e={}){this.dag=new b;this.asyncFailures=new Map;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new a$2;this.resolverRegistry=new a$3;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new be;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.batchTagIndex=null;this.lineContext=null;this.lineContextDoc=null;this.lineContextScan=null;this.lineContextParsed=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.inertSignal=new AbortController().signal;this.userUnits=new we;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$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,calendar:o}=e;this.localeCode=t,this.config=c$3(b$1,i??{}),this.dateReading=k(this.config.date),this.lexer=new b$2(t),this.registry=new b$3,this.context=A({networkEnabled:this.config.network.enabled,calendar:o}),r?(this.diagnosticPipeline=new a$4,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$4,this.normalizer=new c$4;for(let[a,l]of Object.entries(c$5))this.normalizer.addPhrase(a,l);this.normalizer.register(d$2(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(hn(this.userUnits)),this.normalizer.register(yn(this.callFusions));let c=s??[];for(let a of c)try{this.registerPackage(a);}catch(l){let u=d(l);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let a=()=>this.context.calendar;this.normalizer.register(w(()=>this.dateReading.order,a,()=>this.config.date.onAmbiguous)),this.normalizer.register(En(void 0,a,()=>this.config.date.onAmbiguous));}this.parser=new a$5(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName,this.context.calendar),this.vm=b$6(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,fn(this.config.date.holidays,this.context.calendar)),this.queryClient=c$6(),this.batcher=new ke(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Re(this.dag,(a,l)=>this.batcher.add({queryKey:l,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new d$1(this.pluginFunctionIndexByName);for(let t of U.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let r=[];for(let o of this.lexer)o.type!=="COMMENT"&&r.push(o);let i=this.normalizer.normalize(r);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),c$1(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines,s=this.lineContext;return (s===null||this.lineContextDoc!==t||this.lineContextScan!==r||this.lineContextParsed!==i)&&(s=this.buildLineContext(t,r,i,e),this.lineContext=s,this.lineContextDoc=t,this.lineContextScan=r,this.lineContextParsed=i),s.lineIndex=e,s}buildLineContext(e,t,r,i){let s=this.dag,o;return o={lineIndex:i,getLineResult:e?a=>(s.registerLinePositionDependency(o.lineIndex,a),e.getLineAt(a)?.result??void 0):r?a=>r[a-1]?.result??void 0:void 0,isLineBoundary:e?a=>{let l=e.getLineAt(a);return l?l.isEmpty||/^\s*#/.test(l.text):true}:t?a=>{let l=t[a-1];return l?l.classification.skip||/^\s*#/.test(l.text):true}:void 0,getLineReads:e?a=>{let l=e.getLineAt(a);if(!(!l||l.bytecodes.length===0))return l.reads}:void 0,evaluateLineWithBinding:e?(a,l,u,p)=>this.evaluateLineWithBinding(a,l,u,p):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:e?a=>e.getLineAt(a)?.text:t?a=>t[a-1]?.text:void 0,getTaggedLines:e?a=>e.linesCarryingTag(a):t?a=>this.batchLinesCarryingTag(t,a):void 0},o}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=U.GOAL_SEEK_MAX_NESTING_DEPTH)return P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let c=o.bytecodes[0];this.goalSeekDepth++;try{let a=new Map([[t,r]]),l=this.vm.getStack().length;this.vm.pushCallFrame(a);try{let u=c$1(c,this.vm,void 0,void 0,this.buildLineContext(s,null,null,e),i);return u.type==="pending"?P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>l;)this.vm.pop();}}catch(a){return P("GOAL_SEEK_TARGET_ERROR",d(a).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,r){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,r);}touchCompiled(e,t){this.bytecodeCache.size<this.config.performance.defaultCacheSize||(this.bytecodeCache.delete(e),this.bytecodeCache.set(e,t));}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let r=this.failedParses.keys().next().value;r!==void 0&&this.failedParses.delete(r);}this.failedParses.set(e,t);}touchFailedParse(e,t){this.failedParses.size<this.config.performance.defaultCacheSize||(this.failedParses.delete(e),this.failedParses.set(e,t));}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Jt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let r={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=I(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),r.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase(),c=this.callFusionOwners.get(o);c?c.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$7(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))K(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let 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$7(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)L(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames){let i=(this.callFusionOwners.get(r)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(r),this.callFusions.delete(r)):(this.callFusionOwners.set(r,i),this.callFusions.set(r,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r$1=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s$1 of r$1){let o=s$1.type===s;if(!o&&s$1.type!==r)continue;let c=s$1.offset,a=s$1.sourceEnd??s$1.offset+s$1.text.length;i.push(this.describeDateLiteral(e.slice(c,a),c,a,s$1,o));}return i}describeDateLiteral(e,t,r,i,s){let o$1=q$1(e);if(o$1!==null){let l$1=o(o$1,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=l(o$1.groups[0],o$1.groups[1],o$1.groups[2],o$1.separator)==="iso",p$1=this.dateReading.order==="auto"?o$1.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,h=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p$1,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return l$1.kind==="date"?p({text:e,start:t,end:r,iso:n$1(l$1.day,l$1.month,l$1.year),...h,contested:l$1.alternative!==void 0,shortYear:l$1.shortYear,alternative:l$1.alternative},o$1.separator):p({text:e,start:t,end:r,iso:null,...h,contested:false,shortYear:false,problem:l$1.kind==="refuse"?l$1.code:void 0},o$1.separator,l$1.kind==="refuse"?l$1.message:void 0)}if(s){let l=i.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i.value}" is not a date this engine can read.`};return p({text:e,start:t,end:r,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:l.code},"slash",l.message)}let c=this.context.calendar.fields(Number(i.value)),a=/^\d{4}-/.test(e)?"iso":"spelled";return p({text:e,start:t,end:r,iso:n$1(c.day,c.month0+1,c.year),order:a==="iso"?"ISO":"spelled",orderSource:a,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new q(t,r,i,s.length>0?s[0]:null),o);}mayResolve(e){return e.hasAsync||this.resolverRegistry.mayIntercept(e)}armCancellation(e,t){if(!this.mayResolve(e))return this.vm.activeSignal=this.inertSignal,this.vm.abortCurrent=void 0,null;let r=new AbortController,i=()=>r.abort(),s=this.keystrokeSignal;s?.addEventListener("abort",i,{once:true}),a$6.localControllerCreated(t),s&&a$6.signalLinked(t);let o=()=>s?.removeEventListener("abort",i);return this.vm.activeSignal=r.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked(t),o(),r.abort();},o}registerLineWithTags(e,t,r,i){let s=a$7(t,r,i);this.dag.registerLine(e,s.reads,s.writes);}executeAndStore(e,t,r,i,s,o,c,a){let l=this.vm.getStack().length,u=this.armCancellation(e,"executeAndStore");a$8(this.queryClient);let p=c$1(e,this.vm,c,a,this.makeLineContext(t));for(;this.vm.getStack().length>l;)this.vm.pop();if(p.type==="pending"){let h=`${p.packageId||o}:${p.queryKey}`,y=this.asyncFailures.get(h)??0;if(y>=U.MAX_ASYNC_FAILURES){u?.();let S=P("ASYNC_RESOLVER_FAILED",`This value could not be fetched after ${y} attempts, so it is reported rather than retried. Edit the line to try again.`);return this.storeLineResult(t,S,e,i,s,r),S}this.resolveAsync(p),this.dag.registerLineDataSourceDependency(t,p.packageId||o,[p.queryKey]);let d=O(p.queryKey);return this.storeLineResult(t,d,e,i,s,r),d}if(p.type==="error")throw u?.(),p.error;return u?.(),this.registerLineWithTags(t,r,i,s),this.storeLineResult(t,p.value,e,i,s,r),p.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=this.armCancellation(e,"executeRaw");a$8(this.queryClient);let s=c$1(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return s.type!=="pending"&&i?.(),s}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine",c=`${o}:${t}`;try{if(await r,this.asyncFailures.delete(c),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)),u=(this.asyncFailures.get(c)??0)+1;if(this.asyncFailures.set(c,u),u>U.MAX_ASYNC_FAILURES)return;this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(b$8(e,r)>r)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let a of s){a.error&&o.errors.push(`Line ${a.lineNumber}: ${a.error}`);for(let l of a.inlineSolves)l.error&&o.errors.push(`Line ${a.lineNumber}: ${l.error}`);}if(t.includeDiagnostics??false){let a=this.diagnosticPipeline.collectReports();a.length>0&&(o.diagnostics=a[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}batchLinesCarryingTag(e,t){let r=this.batchTagIndex;if(r===null){r=new Map;for(let i=0;i<e.length;i++){let s=e[i].text;if(!(s.indexOf("#")<0))for(let o of b$9(s)){let c=r.get(o);c===void 0?r.set(o,[i+1]):c.push(i+1);}}this.batchTagIndex=r;}return r.get(t.toLowerCase())??[]}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;let s=this.batchTagIndex;this.batchTagIndex=null;try{for(let o of e){let c=o.text,a=o.lineNumber,l=o.startOffset,u=o.endOffset,p=o.classification.skip,h=o.inlineSolves.map(S=>({start:S.start,end:S.end,expression:S.expression,lineNumber:a,columnNumber:S.columnNumber})),y=h.length>0,d={lineNumber:a,text:c,startPosition:l,endPosition:u,isEmpty:p,hasInlineSolves:y,inlineSolves:h,expression:null,result:null,error:null};if(o.error)d.error=o.error.message;else if(!p){let S=c.trim().startsWith(":");if(y&&!S)for(let b of h)try{b.result=this.evaluateLine(a,b.expression);}catch(A){let L=A instanceof Error?A.message:String(A);b.error=L;}else {let b=o.classification.contentOffset,L=(b===void 0?c:c.slice(b-l)).trim();if(L)try{let D=this.evaluateLineWithPreTokenized(a,L,o.tokens);d.expression=L,d.result=D[0];}catch(D){let Ae=D instanceof Error?D.message:String(D);d.error=Ae;}}}t.push(d);}}finally{this.batchScanResults=r,this.batchParsedLines=i,this.batchTagIndex=s,this.lineContext=null;}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 c$1=true;for(let a=0;a<o;a++){let l=t[a].type;if(l!=="NUMBER"&&l!=="COLON"){c$1=false;break}}if(c$1){let a=t.slice(0,o+2).map(l=>l.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${a}" is not a valid time`,{tokenType:t[o].type,tokenValue:a})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=c$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let c of e.factorNames){let a=this.vm.getVar(c);if(a===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(a.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);r.push(a);}let i=r[0].value;for(let c=1;c<r.length;c++){let a=_$1(i,r[c].value);if(a.type===13)return a;i=a.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_$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.clearCompiledCache(),this.documentModel?.invalidateAll()),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 c$2=e.slice(2);if(c$2.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let a=r.value;this.accumulatorNames.add(a),this.vm.getVar(a)===void 0&&this.vm.setVar(a,n(0));let l=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$a("IDENT",a,[r]),b$a(l.type,l.text,[i]),b$a("LPAREN","(",[i]),...c$2,b$a("RPAREN",")",[i])],p=c$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(a,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e$1,t$1=-1){if(e$1.length===0)return null;if(e$1[e$1.length-1].type==="THEREFORE"){let l=e$1.slice(0,-1);if(l.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(l.length===1&&(l[0].type==="IDENT"||l[0].type==="UNIT")){let u=l[0].value,p=this.vm.getEquation(u),h=this.vm.getScalarEquation(u);if(p){let y=this.solveEquation(p,t$1);if(!(y.type===13&&y.value==="EQUATION_FACTOR_NOT_MATRIX")||!h)return y}if(h)return this.solveScalarEquation(h,t$1)}return this.simplifySymbolically(l,t$1)}if(e(e$1))return this.simplifySymbolically(e$1,t$1);if(e$1[0].type==="COLON"||e$1[0].type==="GLOBAL"||e$1[0].type==="GOAL_SEEK")return null;let i=e$1.findIndex(l=>l.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e$1.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e$1,i);let o=e$1.slice(i+1);if(s.length===1){let l=this.simplifySymbolically(o,t$1);return this.vm.setVar(s[0],l),l}let c$1=s[s.length-1],a=s.slice(0,-1);return this.vm.defineEquation(c$1,a,this.compileAdHoc(o)),this.vm.defineScalarEquation(c$1,this.compileAdHoc(e$1.slice(0,i)),this.compileAdHoc(o)),t(`${c$1} stored as an equation \u2014 solve with "${c$1} =>"`)}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(c=>c.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=this.executeSymbolicTolerant(e.rhsProgram,t);return k$1(r,i,e.variable)}lexToTokens(e,t,r=true){let i=[],s=false;if(r&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,r,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return this.touchCompiled(e,o),{kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),a;if(c)this.touchFailedParse(e,c),a=c.normalizedTokens;else {let b=$e(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let A=t.filter(D=>D.type!=="COMMENT");if(A.length===0)return {kind:"empty"};a=this.normalizer.normalize(A,i);let L=je(a,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:a}}let l,u=null;try{if(l=this.tryDefineUserUnit(a),l===null){let b=this.tryCompoundAssignment(a,s);b!==null&&(l=b,u=Ce(a));}l===null&&(l=this.trySymbolicGrammar(a,s));}catch(b){let{reads:A,writes:L}=Ce(a);return {kind:"error",stage:"parse",error:d(b),reads:A,writes:L,normalizedTokens:a}}if(l!==null)return {kind:"symbolic-solve",normalizedTokens:a,value:l,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:a};let{reads:p,writes:h}=Ce(a);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:a,reads:p,writes:h}),this.touchCompiled(e,o),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:o,cached:true};let y=this.builderPool[this.builderPoolIndex++%this.builderPool.length];y.reset();let d$1,S=null;try{let b=_.track("parser",()=>(this.parseExpression(y,a,r),y.build()));d$1=b.result,S=b.alloc;}catch(b){let A=d(b);return this.rememberFailedParse(e,{error:A,normalizedTokens:a,reads:p,writes:h}),{kind:"error",stage:"parse",error:A,reads:p,writes:h,normalizedTokens:a}}return this.cacheBytecode(e,d$1,{normalizedTokens:a,reads:p,writes:h}),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:d$1,cached:false,parserAlloc:S}}preflightAsync(e,t,r,i,s,o){if(!this.mayResolve(t))return {kind:"proceed"};let c=new AbortController,a=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let l=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",l,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",a),{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 q(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:c,writes:a,program:l}=s,u=this.preflightAsync(o,l,e,t,c,a);return u.kind==="pending"?u.value:this.executeAndStore(l,e,t,c,a,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return l$1(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,c,a,l){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:a,output:l});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c$1=_.isEnabled(),a=[],l=[],u=0,p=$e(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(l,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$8.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(l,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(l,"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 h=s?m=>{i.fireTokenEmitted({type:c$8.TokenEmitted,elapsedNs:0,expression:e,token:{type:m.type,value:m.value,offset:m.offset||0,line:m.line||t,col:m.col||0}});}:void 0,y=_.track("lexer",()=>this.lexToTokens(e,h)),d$1=y.result.tokens,S=y.result.hasParens,b=y.result.compiled;if(c$1&&y.alloc&&a.push(y.alloc),s){let m={};for(let P of d$1)m[P.type]=(m[P.type]||0)+1;this.addDiagnosticStage(l,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d$1.length,tokenTypes:m,hasParens:S,locale:this.localeCode,tokens:[...d$1]});let N=[];for(let P=0;P<d$1.length;P++){let oe=d$1[P];if(oe.type==="INLINE_SOLVE_START"){let B=-1;for(let K=P+1;K<d$1.length;K++)if(d$1[K].type==="BACKTICK_OPEN"){B=K;break}if(B>P){let Tn=d$1.slice(P+1,B).map(Rn=>Rn.value).join("");N.push({startTokenIndex:P,endTokenIndex:B,expression:Tn,columnNumber:oe.col||1}),P=B;}}}this.addDiagnosticStage(l,"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(!b&&d$1.length===0){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:m,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let A=0,L=[],D=new Map,Ae=s?m=>{A++,L.push(m),D.set(m.rule,(D.get(m.rule)||0)+1),i.fireTokenFused({type:c$8.TokenFused,elapsedNs:0,expression:e,ruleName:m.rule,sourceTokenCount:m.sourceTokens.length,fusedTokenType:m.fusedToken.type,fusedTokenValue:m.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$8.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d$1.length});let M=this.bytecodeCache.get(e);s&&!M&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d$1,S,Ae,t);b&&v.kind==="ready"&&(d$1=v.normalizedTokens),c$1&&v.kind==="ready"&&v.parserAlloc&&a.push(v.parserAlloc),s&&!M&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d$1:v.normalizedTokens??d$1;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$8.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:A}),this.addDiagnosticStage(l,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...D.entries()].map(([m,N])=>({rule:m,count:N})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(l,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:d$1.length,fusions:[],rulesApplied:[],tokens:[...d$1],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d$1)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d$1.length,totalOpcodes:0}),v.kind==="empty"){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:m,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let re=je(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(l,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:re.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:re.errorMessage}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:re.errorMessage,engineError:re.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(l,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:re.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:0});let m={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,m,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:m,debug:void 0,diagnostic:void 0}}let he=v.reads??[],ie=v.writes??[];if(s&&(this.addDiagnosticStage(l,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:he,writes:ie,isAssignment:ie.length>0}),this.addDiagnosticStage(l,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!M,cacheSize:this.bytecodeCache.size,cacheKey:e}),M?i.fireCacheHit({type:c$8.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$8.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0}),{value:n(0),tokens:k,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(l,"parser","Parser","\u{1F333}","parser",8,u,!!M,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(l,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!M,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!M}),i.fireBytecodeBuilt({type:c$8.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!M}));let kn=this.mayResolve(x),se=this.preflightAsync(k,x,t,e,he,ie);if(s&&(se.kind==="pending"?this.addDiagnosticStage(l,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:se.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):kn?this.addDiagnosticStage(l,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(l,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:true})),se.kind==="pending")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:se.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(l,se.value,k,x,null):void 0};let Cn=s&&this.config.diagnostic.vmTraceEnabled===true,w;try{let m=_.track("vm",()=>this.executeAndStore(x,t,e,he,ie,"_engine",Cn?i:void 0,e),{cacheHit:!!M});w=m.result,c$1&&m.alloc&&a.push(m.alloc);}catch(m){let N=d(m);return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:n(0),tokens:k,program:x,error:N.message,engineError:N,debug:void 0,diagnostic:void 0}}let me=w.type===12;if(s){let m=me?"pending":String(w.value??""),N=me?"Pending":w.unit?"Uom":"Number";this.addDiagnosticStage(l,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:N,resultValue:m,isPending:me});}if(me)return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:w,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(l,w,k,x,null):void 0};if(c$1&&a.length>0&&(this.lastTelemetry=_.createTelemetry(e,a,!!M)),s&&(this.addDiagnosticStage(l,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:he,writesRegistered:ie,dataSourcesRegistered:[]}),this.addDiagnosticStage(l,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(l,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(w.value),formattedValue:String(w.value),valueType:w.type===0?"Number":"Value",unit:w.unit}),i.fireVmHalt({type:c$8.VmHalt,elapsedNs:0,expression:e,result:w?{type:w.type,value:w.value,unit:w.unit}:void 0}),this.addDiagnosticStage(l,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length,cacheHit:!!M}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length})),s){let N=i.collectReports()[0]?.toJSON(),P=N;if(N){let oe=N.parselets.slice(o),B={};for(let K of oe)B[K.parseletCategory]=(B[K.parseletCategory]??0)+1;P={...N,parselets:oe,summary:{...N.summary,totalParselets:Object.keys(B).length,parseCategories:B}};}return {value:w,tokens:k,program:x,debug:P,diagnostic:this.buildDiagnosticResult(l,w,k,x,null)}}return {value:w,tokens:k,program:x}}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(this.touchCompiled(t,i),this.mayResolve(r.bytecode)){let c=new AbortController,a=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let l=c.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",l,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",a);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return 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,c]of this.bytecodeCache)e.push({expression:o,opcodesLength:c.opcodes.length,numbersLength:c.numbers.length,stringsLength:c.strings.length,hasAsync:c.hasAsync});let t=[];for(let o of this.lineCache.keys()){let c=o.indexOf(":"),a=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,l=c>0?o.slice(c+1):void 0,u=l!==void 0?this.lineCache.get(a,l):this.lineCache.getEntryForLine(a);u&&t.push({key:o,lineNumber:a,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let c=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:c}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return qe({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}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.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:r}=t,i=this.prepareExpression(e,t.tokens,r),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,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),O(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.asyncFailures.clear(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$c()===this.queryClient&&a$8(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null,this.lineContext=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let l of Object.keys(e.dataSourceDeps)){let u=Number(l);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:l,entry:u}of r){let p=t.has(l)||u.bytecode.hasAsync;p&&t.add(l);let h=u.writeVariable;if(h){let y=i.get(h);(!y||l>=y.line)&&i.set(h,{line:l,async:p});}}let s={};for(let[l,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(l)?.async)try{s[l]=Be(u,`variable "${l}"`);}catch(p){if(p instanceof b$b&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(_e),c=[];for(let{line:l,expression:u,entry:p}of r){if(t.has(l)||p.result.type===12)continue;let h;try{h=Be(p.result,`line ${l}`);}catch(y){if(y instanceof b$b&&y.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw y}c.push({line:l,expression:u,result:h,bytecode:pe(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let a=Array.from(this.bytecodeCache.entries()).map(([l,u])=>({expression:l,program:pe(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:a}}static fromJSON(e,t={}){on(e);let r=t.locale??e.locale??"en",i=new U({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Fe(r));for(let t of e.userFunctions){let r=Ue(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new q(Fe(t.result),de(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.registerLineWithTags(t.line,t.expression,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,de(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 c=this.executeRaw(o.bytecode,s);if(c.type==="pending"){this.resolveAsync(c);continue}if(c.type==="error"){let l=P(c.error.code,c.error.message);i.set(s,l),o.result=l;continue}let a=c.value;i.set(s,a),o.result=a;}return i}};U.MAX_ASYNC_FAILURES=3,U.GOAL_SEEK_MAX_NESTING_DEPTH=1,U.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var Sn=U;export{tr as a,Dn as b,Jt as c,ee as d,Q as e,V as f,pr as g,ze as h,ke as i,$e as j,je as k,Ce as l,Rr as m,wr as n,Sn as o};//# sourceMappingURL=chunk-NGHH4QKV.js.map
5
- //# sourceMappingURL=chunk-NGHH4QKV.js.map