solve-engine 2.38.20 → 2.38.22

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 (89) hide show
  1. package/dist/{PackageCompatibility-ZCZVGHws.d.ts → PackageCompatibility-C7ILySsH.d.ts} +1 -1
  2. package/dist/{PackageCompatibility-Bv42nEm2.d.cts → PackageCompatibility-CzDzOIg9.d.cts} +1 -1
  3. package/dist/{PackageRegistry-7dFbaAZp.d.cts → PackageRegistry-Bd8ErpwZ.d.cts} +78 -1
  4. package/dist/{PackageRegistry-B6s8LGCu.d.ts → PackageRegistry-D7_B0mxv.d.ts} +78 -1
  5. package/dist/{VMBuiltins-0C4z3yDS.d.cts → VMBuiltins-Baa90D2v.d.cts} +232 -1
  6. package/dist/{VMBuiltins-Bu6qaKi0.d.ts → VMBuiltins-BqkoJtHt.d.ts} +232 -1
  7. package/dist/chunk-54QMY2VL.cjs +2 -0
  8. package/dist/chunk-54QMY2VL.cjs.map +1 -0
  9. package/dist/{chunk-UOLCBH37.cjs → chunk-5GJUECKG.cjs} +5 -5
  10. package/dist/chunk-5GJUECKG.cjs.map +1 -0
  11. package/dist/chunk-CR7IHPA2.cjs +2 -0
  12. package/dist/chunk-CR7IHPA2.cjs.map +1 -0
  13. package/dist/{chunk-I4PKEUMZ.cjs → chunk-FJBWZW45.cjs} +2 -2
  14. package/dist/{chunk-I4PKEUMZ.cjs.map → chunk-FJBWZW45.cjs.map} +1 -1
  15. package/dist/chunk-NYJTBXSI.js +3 -0
  16. package/dist/chunk-NYJTBXSI.js.map +1 -0
  17. package/dist/{chunk-H4G3UXJV.js → chunk-NZUFFOB3.js} +3 -3
  18. package/dist/chunk-NZUFFOB3.js.map +1 -0
  19. package/dist/chunk-OBQC7KDY.cjs +2 -0
  20. package/dist/chunk-OBQC7KDY.cjs.map +1 -0
  21. package/dist/{chunk-3JSXJSMT.js → chunk-OC65AGRR.js} +2 -2
  22. package/dist/{chunk-3JSXJSMT.js.map → chunk-OC65AGRR.js.map} +1 -1
  23. package/dist/{chunk-EPLOL7WC.cjs → chunk-OQHRKHP7.cjs} +2 -2
  24. package/dist/{chunk-EPLOL7WC.cjs.map → chunk-OQHRKHP7.cjs.map} +1 -1
  25. package/dist/chunk-QP4VIEXZ.js +2 -0
  26. package/dist/chunk-QP4VIEXZ.js.map +1 -0
  27. package/dist/chunk-RAZ6IYUQ.js +5 -0
  28. package/dist/chunk-RAZ6IYUQ.js.map +1 -0
  29. package/dist/chunk-RMBUP4XA.js +2 -0
  30. package/dist/chunk-RMBUP4XA.js.map +1 -0
  31. package/dist/{chunk-BHHTXIUL.js → chunk-TVM5VYCM.js} +2 -2
  32. package/dist/{chunk-BHHTXIUL.js.map → chunk-TVM5VYCM.js.map} +1 -1
  33. package/dist/chunk-VNNRAHDE.cjs +3 -0
  34. package/dist/chunk-VNNRAHDE.cjs.map +1 -0
  35. package/dist/chunk-X2QJE3SV.js +2 -0
  36. package/dist/chunk-X2QJE3SV.js.map +1 -0
  37. package/dist/{chunk-7PUNL5CJ.cjs → chunk-ZJJ54J4L.cjs} +3 -3
  38. package/dist/{chunk-H4G3UXJV.js.map → chunk-ZJJ54J4L.cjs.map} +1 -1
  39. package/dist/constants.cjs +1 -1
  40. package/dist/constants.js +1 -1
  41. package/dist/engine.cjs +1 -1
  42. package/dist/engine.d.cts +128 -5
  43. package/dist/engine.d.ts +128 -5
  44. package/dist/engine.js +1 -1
  45. package/dist/engine.worker.cjs +1 -1
  46. package/dist/engine.worker.js +1 -1
  47. package/dist/index.cjs +1 -1
  48. package/dist/index.d.cts +4 -4
  49. package/dist/index.d.ts +4 -4
  50. package/dist/index.js +1 -1
  51. package/dist/language.d.cts +3 -3
  52. package/dist/language.d.ts +3 -3
  53. package/dist/packages.cjs +1 -1
  54. package/dist/packages.d.cts +2 -2
  55. package/dist/packages.d.ts +2 -2
  56. package/dist/packages.js +1 -1
  57. package/dist/testing.cjs +2 -2
  58. package/dist/testing.d.cts +3 -3
  59. package/dist/testing.d.ts +3 -3
  60. package/dist/testing.js +1 -1
  61. package/dist/vm.cjs +1 -1
  62. package/dist/vm.d.cts +1 -1
  63. package/dist/vm.d.ts +1 -1
  64. package/dist/vm.js +1 -1
  65. package/dist/worker.cjs +2 -2
  66. package/dist/worker.d.cts +2 -2
  67. package/dist/worker.d.ts +2 -2
  68. package/dist/worker.js +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-2YHOWQ43.js +0 -2
  71. package/dist/chunk-2YHOWQ43.js.map +0 -1
  72. package/dist/chunk-6W3JFXPQ.cjs +0 -2
  73. package/dist/chunk-6W3JFXPQ.cjs.map +0 -1
  74. package/dist/chunk-7PUNL5CJ.cjs.map +0 -1
  75. package/dist/chunk-HNXV35Q2.cjs +0 -2
  76. package/dist/chunk-HNXV35Q2.cjs.map +0 -1
  77. package/dist/chunk-JZQRUOO6.js +0 -2
  78. package/dist/chunk-JZQRUOO6.js.map +0 -1
  79. package/dist/chunk-K2OUNZZG.cjs +0 -2
  80. package/dist/chunk-K2OUNZZG.cjs.map +0 -1
  81. package/dist/chunk-KZPA4DUF.cjs +0 -3
  82. package/dist/chunk-KZPA4DUF.cjs.map +0 -1
  83. package/dist/chunk-MXMMDSX4.js +0 -3
  84. package/dist/chunk-MXMMDSX4.js.map +0 -1
  85. package/dist/chunk-RTEWTZ6I.js +0 -5
  86. package/dist/chunk-RTEWTZ6I.js.map +0 -1
  87. package/dist/chunk-SIUHB77U.js +0 -2
  88. package/dist/chunk-SIUHB77U.js.map +0 -1
  89. package/dist/chunk-UOLCBH37.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ 'use strict';var f=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,e,n,i){if(n.length===0)return null;let o=this.indexOfCheckpointAt(t),s=o>=0?o:this.insertionIndexFor(t),d=s>0?this.checkpoints[s-1]:null,h=Object.create(null),u=Object.create(null);for(let r of n){if(i!==void 0?i.has(r):this.vm.hasUserFunction(r)){let a=this.vm.getUserFunction(r);a&&(u[r]=a);continue}let l=this.vm.getVar(r);l!==void 0&&(h[r]=l);}let c={lineNumber:t,lineId:e,variables:h,functions:u,parent:d};o>=0?this.checkpoints[o]=c:this.checkpoints.splice(s,0,c);let p=this.checkpoints[s+1];return p!==void 0&&(p.parent=c),c}restoreTo(t){let e=this.nearestCheckpointIndex(t);this.vm.reset();for(let n=0;n<=e;n++){let i=this.checkpoints[n];for(let o of Object.keys(i.variables))this.vm.setVar(o,i.variables[o]);for(let o of Object.keys(i.functions)){let s=i.functions[o];this.vm.defineUserFunction(s.name,s.params,s.program);}}}indexOfCheckpointAt(t){let e=this.nearestCheckpointIndex(t);return e>=0&&this.checkpoints[e].lineNumber===t?e:-1}insertionIndexFor(t){return this.nearestCheckpointIndex(t)+1}nearestCheckpointIndex(t){let e=0,n=this.checkpoints.length-1,i=-1;for(;e<=n;){let o=e+n>>1;this.checkpoints[o].lineNumber<=t?(i=o,e=o+1):n=o-1;}return i}updateCheckpointAt(t,e){let n=this.getCheckpointAt(t);if(!n)return false;for(let i of e){if(this.vm.hasUserFunction(i)){let s=this.vm.getUserFunction(i);s&&(n.functions[i]=s);continue}let o=this.vm.getVar(i);o!==void 0&&(n.variables[i]=o);}return true}applyCheckpointAt(t){let e=this.getCheckpointAt(t);if(!e)return false;for(let n of Object.keys(e.variables))this.vm.setVar(n,e.variables[n]);for(let n of Object.keys(e.functions)){let i=e.functions[n];this.vm.defineUserFunction(i.name,i.params,i.program);}return true}dropCheckpointAt(t){let e=this.indexOfCheckpointAt(t);if(e<0)return;this.checkpoints.splice(e,1);let n=this.checkpoints[e];n!==void 0&&(n.parent=e>0?this.checkpoints[e-1]:null);}renumber(t){let e=[];for(let n of this.checkpoints){let i=t(n.lineId);i<1||(n.lineNumber=i,e.push(n));}e.sort((n,i)=>n.lineNumber-i.lineNumber);for(let n=0;n<e.length;n++)e[n].parent=n>0?e[n-1]:null;this.checkpoints=e;}forget(t){if(t.length!==0)for(let e of this.checkpoints)for(let n of t)delete e.variables[n],delete e.functions[n];}getNearestCheckpoint(t){let e=this.nearestCheckpointIndex(t);return e<0?null:this.checkpoints[e]}getCheckpointAt(t){let e=this.nearestCheckpointIndex(t);if(e<0)return;let n=this.checkpoints[e];return n.lineNumber===t?n:void 0}getAllCheckpoints(){return this.checkpoints}lookupFunctionBefore(t,e){let n=this.nearestCheckpointIndex(e-1),i=n<0?null:this.checkpoints[n];for(;i;){if(Object.prototype.hasOwnProperty.call(i.functions,t))return i.functions[t];i=i.parent;}}lookupVariableBefore(t,e){let n=this.nearestCheckpointIndex(e-1),i=n<0?null:this.checkpoints[n];for(;i;){if(Object.prototype.hasOwnProperty.call(i.variables,t))return i.variables[t];i=i.parent;}}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1];for(;e;){if(Object.prototype.hasOwnProperty.call(e.variables,t))return e.variables[t];e=e.parent;}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};exports.a=f;//# sourceMappingURL=chunk-CR7IHPA2.cjs.map
2
+ //# sourceMappingURL=chunk-CR7IHPA2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","functionNames","existing","insertAt","parent","variables","functions","name","fn","val","checkpoint","next","targetIndex","i","cp","key","index","low","high","result","mid","value","positionOf","kept","position","a","b","names","candidate"],"mappings":"aAuFO,IAAMA,EAAN,KAAqB,CAM3B,YAAYC,CAAAA,CAAQ,CAJpB,KAAQ,WAAA,CAA8B,EAAC,CAKtC,IAAA,CAAK,GAAKA,EACX,CAyBA,SACCC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACsB,CACtB,GAAID,CAAAA,CAAc,SAAW,CAAA,CAAG,OAAO,KAqBvC,IAAME,CAAAA,CAAW,KAAK,mBAAA,CAAoBJ,CAAU,EAC9CK,CAAAA,CAAWD,C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AA,CAAW,OACzB,CAED,CAEA,eAAeH,CAAAA,CAAiC,CAC/C,GAAI,IAAA,CAAK,YAAY,MAAA,GAAW,CAAA,CAAG,OAEnC,IAAIG,CAAAA,CAAkC,KAAK,WAAA,CAAY,IAAA,CAAK,YAAY,MAAA,CAAS,CAAC,EAClF,KAAOA,CAAAA,EAAY,CAClB,GAAI,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAKA,CAAAA,CAAW,SAAA,CAAWH,CAAI,CAAA,CAClE,OAAOG,EAAW,SAAA,CAAUH,CAAI,EAEjCG,CAAAA,CAAaA,CAAAA,CAAW,OACzB,CAED,CAQA,OAAc,CACb,IAAA,CAAK,YAAc,GACpB,CAGA,IAAI,KAAA,EAAgB,CACnB,OAAO,KAAK,WAAA,CAAY,MACzB,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,IAAA,CAAK,YAAY,MAAA,GAAW,CACpC,CAGA,IAAI,UAAA,EAAiB,CACpB,OAAO,IAAA,CAAK,EACb,CACD","file":"chunk-CR7IHPA2.cjs","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 * @param functionNames Which of those names the line defined as functions,\n\t * from the bytecode it ran. Without it the VM is asked, which cannot tell\n\t * a line that defined `f` from one that set the variable `f` under a\n\t * function of that name defined above.\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\tfunctionNames?: ReadonlySet<string>\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// This line's own entry is replaced, and nothing else is touched.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so a re-run must not append after entries that come later in\n\t\t// the document: editing line 2 of a document whose lines 1, 2 and 3 each\n\t\t// define something left the list as [1, 2, 3, 2], and a restore to line\n\t\t// 2 then found the stale entry.\n\t\t//\n\t\t// Replacing rather than truncating is the part that took a second go.\n\t\t// Dropping every entry at or after the line is sound only for a pass\n\t\t// running from line 1, which re-takes them as it continues. A pass\n\t\t// limited to a viewport does not: it re-snapshots the top of the\n\t\t// document and never reaches the definitions below its end line, so the\n\t\t// chain lost them, and `restoreTo` then RESET the VM and replayed a\n\t\t// prefix that no longer mentioned them. A line further down reading one\n\t\t// answered `Undefined variable` where it had answered a number. Absent\n\t\t// is worse than stale here: a stale entry is what the document is\n\t\t// currently showing anyway, and the pass corrects it when it reaches\n\t\t// that line.\n\t\tconst existing = this.indexOfCheckpointAt(lineNumber);\n\t\tconst insertAt = existing >= 0 ? existing : this.insertionIndexFor(lineNumber);\n\t\tconst parent = insertAt > 0 ? this.checkpoints[insertAt - 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 bag its line wrote (see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional). A name can be bound\n\t\t// in both bags at once, `f(x) = x + 1` above `:f = 4`, so the caller\n\t\t// says which names it defined as functions; only without that is the\n\t\t// VM asked, and it answers for the function whichever line ran.\n\t\tfor (const name of variableNames) {\n\t\t\tconst isFunction = functionNames !== undefined ? functionNames.has(name) : this.vm.hasUserFunction(name);\n\t\t\tif (isFunction) {\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\tif (existing >= 0) this.checkpoints[existing] = checkpoint;\n\t\telse this.checkpoints.splice(insertAt, 0, checkpoint);\n\t\t// The entry after this one now follows a different object.\n\t\tconst next = this.checkpoints[insertAt + 1];\n\t\tif (next !== undefined) next.parent = 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\t// The chain from the root to the target IS the array up to that index.\n\t\t//\n\t\t// Every checkpoint is created with the one before it in the array as its\n\t\t// parent (see {@link snapshot}), and the array is kept in document\n\t\t// order, so walking parent links would visit exactly these entries in\n\t\t// exactly this order. Reading the array instead of the links costs no\n\t\t// allocation, and it was the links that made this quadratic: the walk\n\t\t// runs target-to-root, so the chain was assembled by `unshift`ing each\n\t\t// entry onto the front, which shifts every entry already there. A\n\t\t// document with two thousand definitions did four million shifts per\n\t\t// restore, and a scroll restores.\n\t\t//\n\t\t// `CheckpointsStayInDocumentOrder.spec.ts` asserts the invariant this\n\t\t// relies on, so a change that broke it would fail there rather than\n\t\t// quietly restoring the wrong state here.\n\t\tconst targetIndex = this.nearestCheckpointIndex(lineNumber);\n\n\t\tthis.vm.reset();\n\t\tfor (let i = 0; i <= targetIndex; i++) {\n\t\t\tconst cp = this.checkpoints[i];\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 entries 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 walk runs root-to-target.\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/** The index of the checkpoint recorded exactly at `lineNumber`, or -1. */\n\tprivate indexOfCheckpointAt(lineNumber: number): number {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index >= 0 && this.checkpoints[index].lineNumber === lineNumber ? index : -1;\n\t}\n\n\t/** Where a checkpoint for `lineNumber` belongs, keeping the list in order. */\n\tprivate insertionIndexFor(lineNumber: number): number {\n\t\treturn this.nearestCheckpointIndex(lineNumber) + 1;\n\t}\n\n\t/**\n\t * The index of the last checkpoint at or before `lineNumber`, or -1.\n\t *\n\t * A binary search rather than a scan. The array is in document order, and\n\t * this is asked once per scroll and once per async batch, on a document\n\t * that can hold a checkpoint per definition.\n\t */\n\tprivate nearestCheckpointIndex(lineNumber: number): number {\n\t\tlet low = 0;\n\t\tlet high = this.checkpoints.length - 1;\n\t\tlet result = -1;\n\t\twhile (low <= high) {\n\t\t\tconst mid = (low + high) >> 1;\n\t\t\tif (this.checkpoints[mid].lineNumber <= lineNumber) {\n\t\t\t\tresult = mid;\n\t\t\t\tlow = mid + 1;\n\t\t\t} else {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t}\n\t\treturn result;\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/**\n\t * Drop `names` from every checkpoint, as though no line had ever set them.\n\t *\n\t * A checkpoint records what its line wrote, so a name whose defining line\n\t * has been deleted or edited into something else is still in the chain, and\n\t * the next restore would put it back into the VM after the VM had been told\n\t * to forget it. The two have to agree.\n\t *\n\t * @param names - The names no line defines any more.\n\t */\n\t/**\n\t * Drop the entry a line holds, because the line no longer writes anything.\n\t *\n\t * A line's entry is replaced when the line writes again and left alone\n\t * otherwise, so a definition edited into an expression with no definition in\n\t * it (`:v3 = 44` edited to `7 + 7`) kept saying `v3 = 44` in the chain. The\n\t * lines below it that asked what the prefix holds were told 44, where a pass\n\t * from scratch has nothing there. The entry after it is re-parented to the\n\t * one before, the same way {@link snapshot} keeps the links straight.\n\t *\n\t * @param lineNumber - 1-based line whose entry, if any, goes.\n\t */\n\tdropCheckpointAt(lineNumber: number): void {\n\t\tconst index = this.indexOfCheckpointAt(lineNumber);\n\t\tif (index < 0) return;\n\t\tthis.checkpoints.splice(index, 1);\n\t\tconst next = this.checkpoints[index];\n\t\tif (next !== undefined) next.parent = index > 0 ? this.checkpoints[index - 1] : null;\n\t}\n\n\t/**\n\t * Follow every line to its new position after a structural edit.\n\t *\n\t * An insert or a delete moves every line below it, and the chain is read\n\t * by position. It used to be cleared instead and rebuilt as lines ran, but\n\t * a clean line above the viewport never runs, so its entry was gone for\n\t * good and a line below asking what the prefix held was told nothing:\n\t * `:a = 5` above the viewport was reported as undefined by `:b = a + c`\n\t * under it. Each entry follows its line by id, the entry of a deleted\n\t * line goes, and the parents are linked again in the new order.\n\t *\n\t * @param positionOf - The 1-based position a line id has now, or -1 for a line that is gone.\n\t */\n\trenumber(positionOf: (lineId: number) => number): void {\n\t\tconst kept: VMCheckpoint[] = [];\n\t\tfor (const checkpoint of this.checkpoints) {\n\t\t\tconst position = positionOf(checkpoint.lineId);\n\t\t\tif (position < 1) continue;\n\t\t\tcheckpoint.lineNumber = position;\n\t\t\tkept.push(checkpoint);\n\t\t}\n\t\tkept.sort((a, b) => a.lineNumber - b.lineNumber);\n\t\tfor (let i = 0; i < kept.length; i++) kept[i].parent = i > 0 ? kept[i - 1] : null;\n\t\tthis.checkpoints = kept;\n\t}\n\n\tforget(names: readonly string[]): void {\n\t\tif (names.length === 0) return;\n\t\tfor (const checkpoint of this.checkpoints) {\n\t\t\tfor (const name of names) {\n\t\t\t\tdelete checkpoint.variables[name];\n\t\t\t\tdelete checkpoint.functions[name];\n\t\t\t}\n\t\t}\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\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index < 0 ? null : this.checkpoints[index];\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\t// Searched, not scanned: the async sweep asks this once for every line\n\t\t// it walks past, and a scan would make that walk quadratic.\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\tif (index < 0) return undefined;\n\t\tconst candidate = this.checkpoints[index];\n\t\treturn candidate.lineNumber === lineNumber ? candidate : undefined;\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\t/**\n\t * The value a name held at the end of the line before `lineNumber`, or\n\t * undefined if no line above it had set one.\n\t *\n\t * What a definition that failed leaves behind. A pass from scratch skips\n\t * the store when the right-hand side errors, so the name keeps whatever the\n\t * lines above it had put there: `:x = 1` then `:x = zz` leaves `x` at 1,\n\t * and `:x = zz` on its own leaves it undefined. The incremental path holds\n\t * the value from the previous pass instead, which for the line that failed\n\t * is its own old answer, so the evaluator asks here what the prefix holds\n\t * and puts that back. The chain records what each line wrote, in document\n\t * order, so the entry nearest before the line, followed through its\n\t * parents, is exactly the prefix.\n\t *\n\t * @param name - The variable.\n\t * @param lineNumber - The 1-based line whose own entry is to be excluded.\n\t * @returns The value the lines above set, or undefined.\n\t */\n\t/**\n\t * The function a name was bound to at the end of the line before\n\t * `lineNumber`, or undefined if no line above it had defined one.\n\t *\n\t * {@link lookupVariableBefore}, for the functions bag: a function\n\t * definition is a definition, and one edited away or failed leaves the name\n\t * as the lines above left it just as a variable does.\n\t *\n\t * @param name - The function name.\n\t * @param lineNumber - The 1-based line whose own entry is to be excluded.\n\t * @returns The definition the lines above made, or undefined.\n\t */\n\tlookupFunctionBefore(name: string, lineNumber: number): UserFunctionDef | undefined {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber - 1);\n\t\tlet checkpoint: VMCheckpoint | null = index < 0 ? null : this.checkpoints[index];\n\t\twhile (checkpoint) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(checkpoint.functions, name)) {\n\t\t\t\treturn checkpoint.functions[name];\n\t\t\t}\n\t\t\tcheckpoint = checkpoint.parent;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tlookupVariableBefore(name: string, lineNumber: number): Value | undefined {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber - 1);\n\t\tlet checkpoint: VMCheckpoint | null = index < 0 ? null : this.checkpoints[index];\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\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,2 +1,2 @@
1
- 'use strict';var chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');var d="2.38.20";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto",onAmbiguous:"refuse"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false},network:{enabled:true}};function n(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh},network:{...s.network,...e.network}}}var c=class{constructor(e={}){this.config=n(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw chunk6SYU4MH7_cjs.c.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw chunk6SYU4MH7_cjs.c.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw chunk6SYU4MH7_cjs.c.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw chunk6SYU4MH7_cjs.c.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return n(this.config,{})}update(e){this.config=n(this.config,e);}reset(){this.config=n(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};exports.a=m;exports.b=l;exports.c=n;exports.d=c;//# sourceMappingURL=chunk-I4PKEUMZ.cjs.map
2
- //# sourceMappingURL=chunk-I4PKEUMZ.cjs.map
1
+ 'use strict';var chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');var d="2.38.22";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto",onAmbiguous:"refuse"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false},network:{enabled:true}};function n(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh},network:{...s.network,...e.network}}}var c=class{constructor(e={}){this.config=n(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw chunk6SYU4MH7_cjs.c.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw chunk6SYU4MH7_cjs.c.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw chunk6SYU4MH7_cjs.c.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw chunk6SYU4MH7_cjs.c.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return n(this.config,{})}update(e){this.config=n(this.config,e);}reset(){this.config=n(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};exports.a=m;exports.b=l;exports.c=n;exports.d=c;//# sourceMappingURL=chunk-FJBWZW45.cjs.map
2
+ //# sourceMappingURL=chunk-FJBWZW45.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"mEAEE,IAAAA,EAAW,SAAA,CCcN,IAAMC,EAAyBD,ECgb/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,GAAA,CAChB,eAAgB,IAAA,CAChB,aAAA,CAAe,aACf,UAAA,CAAY,MAAA,CAIZ,YAAa,QACf,CAAA,CACA,YAAa,CAIX,gBAAA,CAAkB,IAalB,gBAAA,CAAkB,GACpB,EACC,UAAA,CAAY,CACV,oBAAqB,GAAA,CACrB,aAAA,CAAe,IACf,eAAA,CAAiB,EAAA,CACjB,kBAAmB,KACrB,CAAA,CACA,GAAI,CACF,aAAA,CAAe,IACf,eAAA,CAAiB,GAAA,CAKjB,iBAAA,CAAmB,GAAA,CAInB,qBAAsB,GAAA,CAMtB,gBAAA,CAAkB,IAMlB,qBAAA,CAAuB,GACzB,EACA,MAAA,CAAQ,CACN,qBAAsB,CAAA,CACtB,aAAA,CAAe,IACf,UAAA,CAAY,CAAA,CACZ,cAAe,GACjB,CAAA,CACA,WAAY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B,IAAMe,CAAAA,CAAmB,GAGzB,OAAI,IAAA,CAAK,OAAO,WAAA,CAAY,gBAAA,CAAmB,KAC7CA,CAAAA,CAAO,IAAA,CAAK,wCAAwC,CAAA,CAIlD,IAAA,CAAK,OAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-I4PKEUMZ.cjs","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.38.20\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./engine-worker\": {\n \"import\": {\n \"types\": \"./dist/engine.worker.d.ts\",\n \"default\": \"./dist/engine.worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.worker.d.cts\",\n \"default\": \"./dist/engine.worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n },\n \"./temporal\": {\n \"import\": {\n \"types\": \"./dist/temporal.d.ts\",\n \"default\": \"./dist/temporal.js\"\n },\n \"require\": {\n \"types\": \"./dist/temporal.d.cts\",\n \"default\": \"./dist/temporal.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.102.8\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.5.1\",\n \"@types/node\": \"^26.4.1\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.5.1\",\n \"temporal-polyfill\": \"1.0.4\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n * - `'locale'`: the order the reader's own machine writes dates in, asked of\n * `Intl` once per engine (see `calendar/HostLocale.ts`). Where that cannot\n * be answered, the engine reads dates exactly as `'auto'` does and reports\n * the fact through `ExpressionEngine.getDateReading()`, rather than guessing.\n * A host that is not the reader (a server rendering someone else's document)\n * names the reader instead, through {@link DateConfig.inputLocale}.\n *\n * Only ambiguous literals are affected. A spelled-out month (`March 9, 2024`)\n * is never ambiguous; nor is a hyphen literal with a four-digit leading group\n * (`2024-03-09`), which has no reading but year-month-day and is read as ISO\n * under every order, timestamp or not.\n */\nexport type DateInputOrder = 'auto' | 'locale' | 'DMY' | 'MDY' | 'YMD';\n\n/**\n * What a date-shaped numeric run the configured order cannot read does: report\n * the problem, or fall through to the arithmetic it is spelled like. See\n * {@link DateConfig.onAmbiguous}.\n */\nexport type DateAmbiguity = 'refuse' | 'arithmetic';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * The BCP-47 tag `'locale'` reads the order from, `\"en-US\"` or `\"de-DE\"`.\n * Unset, the host machine is asked.\n *\n * Read ONLY when {@link inputOrder} is `'locale'`. Setting it beside any\n * other order changes no result: a field that quietly switched inference on\n * would make the predictable mistake a wrong reading rather than no change.\n * Its shape is checked wherever it is set, though, and a tag `Intl` refuses\n * (`\"en_US\"`, with an underscore) raises `DATE_INPUT_LOCALE_INVALID` at\n * construction, because a locale silently ignored is a date order silently\n * wrong.\n *\n * Deliberately separate from the engine's `locale` option, which is a\n * language (`'en' | 'de' | 'fr'`) and carries no region. Day/month order is a\n * region question: a bare `en` probes as month-first while a UK machine\n * resolves to `en-GB` and probes as day-first, so wiring the two together\n * would flip every existing British engine to month-first.\n */\n readonly inputLocale?: string;\n /**\n * What a date-shaped numeric run the resolved order cannot read does.\n * Defaults to `'refuse'`.\n *\n * - `'refuse'`: the line reports a structured Error value naming the\n * problem, DATE_ORDER_MISMATCH when another order would have read it and\n * DATE_NOT_A_CALENDAR_DAY when no order names a real day. `12/25/2026` on\n * a day-first engine says there is no month 25, rather than answering\n * 0.00.\n * - `'arithmetic'`: the run falls through to the division or subtraction it\n * is spelled like, which is what every version before this one did.\n * `12/25/2026` is 0.00 again, and `2026-02-29` is 1,995.\n *\n * The refusal is scoped to runs nobody writes as arithmetic: a two-step\n * chain ending in a four-digit denominator (`03/04/2026` as division is\n * 0.0004), and an ISO-shaped hyphen run. A four-digit LEADING group is\n * ordinary arithmetic (`1000/10/5` is 20, `1024/8/2` is 64) and is never\n * refused, and neither is a run whose groups are all one or two digits\n * (`12/13/14` stays 0.07), because a two-digit year is too weak a signal to\n * hang a refusal on.\n *\n * The one refusal this setting does not restore is the dot form\n * (`25.12.2026` under a month-first order): its only other outcome is a\n * parse error, and an error is not an answer.\n */\n readonly onAmbiguous: DateAmbiguity;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Whether the engine may reach the network at all.\n *\n * On by default, which is the historic behaviour: a city name or a currency\n * pair in a line fetches live data from a public endpoint as soon as the\n * line evaluates. A host embedding the engine somewhere that must not make\n * outbound requests (an offline document, a sandboxed evaluation, a tenant\n * with egress rules) switches it off here and gets the same engine with no\n * egress: every live-data form answers with a `NETWORK_DISABLED` error\n * naming the setting, instead of a request.\n *\n * The gate closes before any request is made. It stops every async\n * resolver a package registers (weather, currency, stocks, crypto,\n * knowledge, and any host-supplied one) unless the resolver declares\n * itself `local` (it reads engine state, never a network; the engine's own\n * global-variable resolver is the one built-in case). It also refuses the\n * result of a plugin function that returns a promise. That last case is a\n * boundary rather than a guarantee: such a function has already run by the\n * time the engine sees the promise, so a package that fetches inside a\n * plugin function rather than through an async resolver may still have\n * started its request. The documented shape for live data is the resolver\n * (`createQueryResolver`), which this gate stops cold.\n *\n * Rates a host primes by hand (`currencyExchangeService.primeRates`) keep\n * working with the network off, which is what an offline host with its own\n * rate table wants.\n */\n export interface NetworkConfig {\n /** Master switch. When false, no async resolver runs and no live value is fetched. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n /** Whether live data may be fetched at all. See {@link NetworkConfig}. */\n readonly network: NetworkConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n // A date-shaped run no order can read reports the problem rather than\n // answering the fraction it is spelled like. See DateConfig.onAmbiguous\n // for the shapes this covers and the ones it deliberately does not.\n onAmbiguous: 'refuse',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n network: {\n // On, because it is what every existing consumer gets today. A host that\n // must not make outbound requests turns it off; see NetworkConfig.\n enabled: true,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 8\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n network: { ...base.network, ...override.network },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
1
+ {"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"mEAEE,IAAAA,EAAW,SAAA,CCcN,IAAMC,EAAyBD,ECgb/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,GAAA,CAChB,eAAgB,IAAA,CAChB,aAAA,CAAe,aACf,UAAA,CAAY,MAAA,CAIZ,YAAa,QACf,CAAA,CACA,YAAa,CAIX,gBAAA,CAAkB,IAalB,gBAAA,CAAkB,GACpB,EACC,UAAA,CAAY,CACV,oBAAqB,GAAA,CACrB,aAAA,CAAe,IACf,eAAA,CAAiB,EAAA,CACjB,kBAAmB,KACrB,CAAA,CACA,GAAI,CACF,aAAA,CAAe,IACf,eAAA,CAAiB,GAAA,CAKjB,iBAA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I,CAAAA,CAAqC,CAC1C,IAAA,CAAK,MAAA,CAASJ,EAAkB,IAAA,CAAK,MAAA,CAAQI,CAAM,EACrD,CAcA,OAAc,CACZ,IAAA,CAAK,OAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,QAAA,EAA6B,CAC3B,IAAMe,CAAAA,CAAmB,GAGzB,OAAI,IAAA,CAAK,OAAO,WAAA,CAAY,gBAAA,CAAmB,KAC7CA,CAAAA,CAAO,IAAA,CAAK,wCAAwC,CAAA,CAIlD,IAAA,CAAK,OAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-FJBWZW45.cjs","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.38.22\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./engine-worker\": {\n \"import\": {\n \"types\": \"./dist/engine.worker.d.ts\",\n \"default\": \"./dist/engine.worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.worker.d.cts\",\n \"default\": \"./dist/engine.worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n },\n \"./temporal\": {\n \"import\": {\n \"types\": \"./dist/temporal.d.ts\",\n \"default\": \"./dist/temporal.js\"\n },\n \"require\": {\n \"types\": \"./dist/temporal.d.cts\",\n \"default\": \"./dist/temporal.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.102.8\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.5.1\",\n \"@types/node\": \"^26.4.1\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.5.1\",\n \"temporal-polyfill\": \"1.0.4\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n * - `'locale'`: the order the reader's own machine writes dates in, asked of\n * `Intl` once per engine (see `calendar/HostLocale.ts`). Where that cannot\n * be answered, the engine reads dates exactly as `'auto'` does and reports\n * the fact through `ExpressionEngine.getDateReading()`, rather than guessing.\n * A host that is not the reader (a server rendering someone else's document)\n * names the reader instead, through {@link DateConfig.inputLocale}.\n *\n * Only ambiguous literals are affected. A spelled-out month (`March 9, 2024`)\n * is never ambiguous; nor is a hyphen literal with a four-digit leading group\n * (`2024-03-09`), which has no reading but year-month-day and is read as ISO\n * under every order, timestamp or not.\n */\nexport type DateInputOrder = 'auto' | 'locale' | 'DMY' | 'MDY' | 'YMD';\n\n/**\n * What a date-shaped numeric run the configured order cannot read does: report\n * the problem, or fall through to the arithmetic it is spelled like. See\n * {@link DateConfig.onAmbiguous}.\n */\nexport type DateAmbiguity = 'refuse' | 'arithmetic';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * The BCP-47 tag `'locale'` reads the order from, `\"en-US\"` or `\"de-DE\"`.\n * Unset, the host machine is asked.\n *\n * Read ONLY when {@link inputOrder} is `'locale'`. Setting it beside any\n * other order changes no result: a field that quietly switched inference on\n * would make the predictable mistake a wrong reading rather than no change.\n * Its shape is checked wherever it is set, though, and a tag `Intl` refuses\n * (`\"en_US\"`, with an underscore) raises `DATE_INPUT_LOCALE_INVALID` at\n * construction, because a locale silently ignored is a date order silently\n * wrong.\n *\n * Deliberately separate from the engine's `locale` option, which is a\n * language (`'en' | 'de' | 'fr'`) and carries no region. Day/month order is a\n * region question: a bare `en` probes as month-first while a UK machine\n * resolves to `en-GB` and probes as day-first, so wiring the two together\n * would flip every existing British engine to month-first.\n */\n readonly inputLocale?: string;\n /**\n * What a date-shaped numeric run the resolved order cannot read does.\n * Defaults to `'refuse'`.\n *\n * - `'refuse'`: the line reports a structured Error value naming the\n * problem, DATE_ORDER_MISMATCH when another order would have read it and\n * DATE_NOT_A_CALENDAR_DAY when no order names a real day. `12/25/2026` on\n * a day-first engine says there is no month 25, rather than answering\n * 0.00.\n * - `'arithmetic'`: the run falls through to the division or subtraction it\n * is spelled like, which is what every version before this one did.\n * `12/25/2026` is 0.00 again, and `2026-02-29` is 1,995.\n *\n * The refusal is scoped to runs nobody writes as arithmetic: a two-step\n * chain ending in a four-digit denominator (`03/04/2026` as division is\n * 0.0004), and an ISO-shaped hyphen run. A four-digit LEADING group is\n * ordinary arithmetic (`1000/10/5` is 20, `1024/8/2` is 64) and is never\n * refused, and neither is a run whose groups are all one or two digits\n * (`12/13/14` stays 0.07), because a two-digit year is too weak a signal to\n * hang a refusal on.\n *\n * The one refusal this setting does not restore is the dot form\n * (`25.12.2026` under a month-first order): its only other outcome is a\n * parse error, and an error is not an answer.\n */\n readonly onAmbiguous: DateAmbiguity;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Whether the engine may reach the network at all.\n *\n * On by default, which is the historic behaviour: a city name or a currency\n * pair in a line fetches live data from a public endpoint as soon as the\n * line evaluates. A host embedding the engine somewhere that must not make\n * outbound requests (an offline document, a sandboxed evaluation, a tenant\n * with egress rules) switches it off here and gets the same engine with no\n * egress: every live-data form answers with a `NETWORK_DISABLED` error\n * naming the setting, instead of a request.\n *\n * The gate closes before any request is made. It stops every async\n * resolver a package registers (weather, currency, stocks, crypto,\n * knowledge, and any host-supplied one) unless the resolver declares\n * itself `local` (it reads engine state, never a network; the engine's own\n * global-variable resolver is the one built-in case). It also refuses the\n * result of a plugin function that returns a promise. That last case is a\n * boundary rather than a guarantee: such a function has already run by the\n * time the engine sees the promise, so a package that fetches inside a\n * plugin function rather than through an async resolver may still have\n * started its request. The documented shape for live data is the resolver\n * (`createQueryResolver`), which this gate stops cold.\n *\n * Rates a host primes by hand (`currencyExchangeService.primeRates`) keep\n * working with the network off, which is what an offline host with its own\n * rate table wants.\n */\n export interface NetworkConfig {\n /** Master switch. When false, no async resolver runs and no live value is fetched. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n /** Whether live data may be fetched at all. See {@link NetworkConfig}. */\n readonly network: NetworkConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n // A date-shaped run no order can read reports the problem rather than\n // answering the fraction it is spelled like. See DateConfig.onAmbiguous\n // for the shapes this covers and the ones it deliberately does not.\n onAmbiguous: 'refuse',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n network: {\n // On, because it is what every existing consumer gets today. A host that\n // must not make outbound requests turns it off; see NetworkConfig.\n enabled: true,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 8\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n network: { ...base.network, ...override.network },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
@@ -0,0 +1,3 @@
1
+ import {a}from'./chunk-RAF57WYO.js';import {m,n,h as h$1}from'./chunk-RAZ6IYUQ.js';import {a as a$1}from'./chunk-X2QJE3SV.js';import {b as b$2,a as a$2}from'./chunk-OC65AGRR.js';import {b as b$1}from'./chunk-76F3LCIL.js';import {N,O,b as b$3}from'./chunk-QP4VIEXZ.js';import {h,i,P as P$1,j,k}from'./chunk-A34R65WT.js';import {b}from'./chunk-TVM5VYCM.js';import {c as c$1}from'./chunk-6NL7RBAG.js';import {c,b as b$4}from'./chunk-6G2NES2I.js';var F=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,i]=A(this.root,e);this.root=R(R(n,fe(t)),i);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=A(this.root,e),[i,s]=A(n,1),r=i?i.lineId:void 0;return this.root=R(t,s),r}spliceAt(e,t,n){let i=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-i),[r,o]=A(this.root,i),[d,a]=A(o,s),l=ge(d),c=z(n,0,n.length);return this.root=R(R(r,c),a),l}replaceAll(e){this.root=z(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),i=Math.min((this.root?.size??0)-1,t);if(n>i)return [];let s=[];return this.collectRange(this.root,n,i,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,i,s){if(!e)return;let r=e.left?e.left.size:0,o=i+r;o>t&&e.left&&this.collectRange(e.left,t,n,i,s),o>=t&&o<=n&&s.push(e.lineId),o<n&&e.right&&this.collectRange(e.right,t,n,o+1,s);}};function fe(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function U(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function R(u,e){return u?e?u.priority>e.priority?(u.right=R(u.right,e),U(u),u):(e.left=R(u,e.left),U(e),e):u:e}function A(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,i]=A(u.left,e);return u.left=i,U(u),[n,u]}else {let[n,i]=A(u.right,e-t-1);return u.right=n,U(u),[u,i]}}function ge(u){let e=[];return J(u,e),e}function J(u,e){u&&(J(u.left,e),e.push(u.lineId),J(u.right,e));}function z(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),i=pe(u[n]);return {lineId:u[n],size:t-e,priority:i,left:z(u,e,n),right:z(u,n+1,t)}}function pe(u){let e=u+2654435769|0;return e=Math.imul(e>>>16^e,73244475),e=Math.imul(e>>>16^e,73244475),e=(e>>>16^e)>>>0,e/4294967296}var T=class{constructor(e=b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new F;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.tagIndex=null;this.maxLines=e;}setDocument(e){if(b$1(e,this.maxLines)>this.maxLines)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1,this.tagIndex=null;let n=e.split(`
2
+ `),i=new Array(n.length);for(let s=0;s<n.length;s++){let r=this.nextLineId++;i[s]=r,this.lines.set(r,{lineId:r,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(i);for(let s of i)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],i=[...e].sort((s,r)=>r.startLine-s.startLine);for(let s of i){let r=s.startLine-1,o=[];for(let a$1 of s.insertLines){let l=this.nextLineId++;o.push(l),t.push(l),this.lines.set(l,{lineId:l,textHash:a(a$1),text:a$1,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:a$1.trim().length===0,inlineSolveCount:0});}for(let a of o)this.dirtyLineIds.add(a);if(this.tagIndex!==null)for(let a of o)this.indexTags(a,this.lines.get(a).text);let d=this.orderTree.spliceAt(r,s.deleteCount,o);for(let a of d)n.push(a),this.tagIndex!==null&&this.unindexTags(a,this.lines.get(a)?.text??""),this.lines.delete(a),this.dirtyLineIds.delete(a);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let i=a(t);return i===n.textHash?false:(this.tagIndex!==null&&(this.unindexTags(n.lineId,n.text),this.indexTags(n.lineId,t)),n.text=t,n.textHash=i,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}linesCarryingTag(e){let t=this.ensureTagIndex().get(e.toLowerCase());if(t===void 0||t.size===0)return [];let n=[];for(let i of t){let s=this.getLinePosition(i);s>0&&n.push(s);}return n.sort((i,s)=>i-s),n}ensureTagIndex(){if(this.tagIndex!==null)return this.tagIndex;this.tagIndex=new Map;for(let e of this.lines.values())this.indexTags(e.lineId,e.text);return this.tagIndex}indexTags(e,t){if(!(t.indexOf("#")<0))for(let n of b$2(t)){let i=this.tagIndex.get(n);i===void 0?this.tagIndex.set(n,new Set([e])):i.add(e);}}unindexTags(e,t){if(!(t.indexOf("#")<0))for(let n of b$2(t)){let i=this.tagIndex.get(n);i!==void 0&&(i.delete(e),i.size===0&&this.tagIndex.delete(n));}}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),i=[];for(let s of n){let r=this.lines.get(s);r&&i.push(r);}return i}getLineStatesInRange(e,t){let n=this.orderTree.getRange(e-1,t-1),i=new Array(n.length);for(let s=0;s<n.length;s++)i[s]=this.lines.get(n[s]);return i}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let i=this.getLinePosition(t);if(i>=1&&i<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}forgetResult(e){let t=this.lines.get(e);t&&(t.result=null,t.results=[]);}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,i,s,r,o,d=0){let a=this.lines.get(e);a&&(a.results=t,a.result=t[0]?.[0]??null,a.bytecodes=n,a.expressions=i,a.reads=s,a.writes=r,a.isVariableDef=o,a.inlineSolveCount=d,a.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,i,s,r,o=0){let d=this.lines.get(e);d&&(d.expressions=t,d.bytecodes=n,d.reads=i,d.writes=s,d.isVariableDef=r,d.inlineSolveCount=o);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1,this.tagIndex=null;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var M=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){if(this.worker)return this.worker;let e=h$1();if(e===null)throw new Error("no engine worker factory registered, so compilation stays on the main thread");return this.worker=e(),this.worker.onmessage=t=>{let n=t.data;if(!n||n.type!=="COMPILE_RESULT")return;let i=this.pending.get(n.id);if(!i)return;this.pending.delete(n.id);let s=[];for(let r of n.results)s.push(this.reconstructResult(r));i.resolve(s);},this.worker.onerror=t=>{for(let[n,i]of this.pending)i.reject(new Error(`Compilation worker error: ${t.message}`)),this.pending.delete(n);},this.worker}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let r of e){if(r.error)continue;let o=t.getLineById(r.lineId);if(!o||o.textHash!==r.compiledAgainstHash)continue;let d=n.get(r.lineId);d||(d={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:o.expressions.length>0?[...o.expressions]:[],textHash:r.compiledAgainstHash},n.set(r.lineId,d)),d.bytecodes.push(r.program);for(let a of r.reads)d.reads.add(a);for(let a of r.writes)d.writes.add(a);r.isVariableDef&&(d.isVariableDef=true);}let s=0;for(let[r,o]of n){if(o.bytecodes.length===0)continue;let a=t.getLineById(r)?.inlineSolveCount??0;t.updateLineCompiled(r,o.expressions,o.bytecodes,[...o.reads],[...o.writes],o.isVariableDef,a),s+=o.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),i={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:i,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var X=128,P=3,ae=6,ue=2,de=P,_=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/X)}static pageRange(e,t){return {startLine:e*X+1,endLine:Math.min((e+1)*X,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,i=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),r=u.pageForLine(n),o=Math.max(0,i-P),d=Math.min(r,s+P),a=Math.max(0,i-ae),l=Math.min(r,s+ae);for(let f=o;f<=d;f++)this.touchPage(f);for(let f=a;f<=l;f++)f>=o&&f<=d||this.evictPageResults(f,t,n);let c=a-1,h=Math.max(0,c-de+1);for(let f=h;f<=c;f++)this.evictPageBytecode(f,t,n);let m=l+1,g=Math.min(r,m+de-1);for(let f=m;f<=g;f++)this.evictPageBytecode(f,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let i=[],s=u.pageForLine(e.endLine),r=u.pageForLine(e.startLine),o=u.pageForLine(t.lineCount),d=[];if(n==="down"){let a=s+P+1,l=Math.min(a+ue-1,o);for(let c=a;c<=l&&c<=o;c++)d.push(c);}else {let a=r-P-1;for(let l=a;l>a-ue&&l>=0;l--)d.push(l);}for(let a of d){let l=u.pageRange(a,t.lineCount);for(let c=l.startLine;c<=l.endLine;c++){let h=t.getLineAt(c);if(h&&h.dirty&&!(h.bytecodes.length>0&&!h.isVariableDef)&&!h.isEmpty)if(h.expressions.length>0)for(let m of h.expressions)m.trim()&&i.push({lineId:h.lineId,expression:m,textHash:h.textHash});else {let m=c$1.findInlineSolves(h.text);if(m.length>0)for(let g of m)g.expression.trim()&&i.push({lineId:h.lineId,expression:g.expression,textHash:h.textHash});else {let g=h.text.trim();g&&i.push({lineId:h.lineId,expression:g,textHash:h.textHash});}}}}return i}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let i=u.pageRange(e,n);for(let s=i.startLine;s<=i.endLine;s++){let r=t.getLineAt(s);r&&!r.isVariableDef&&r.results.length>0&&(r.results=[],r.result=null);}}evictPageBytecode(e,t,n){let i=u.pageRange(e,n);for(let s=i.startLine;s<=i.endLine;s++){let r=t.getLineAt(s);!r||r.isVariableDef||(r.bytecodes.length>0||r.results.length>0)&&(r.bytecodes=[],r.results=[],r.result=null,t.markDirty(r.lineId));}}};var ce=(i=>(i[i.Tier1=1]="Tier1",i[i.Tier2=2]="Tier2",i[i.Tier3=3]="Tier3",i[i.Skipped=0]="Skipped",i))(ce||{});function Q(u){let e=new Set;for(let t of u)if(t.userFunctionBodies!==void 0)for(let n of t.userFunctionBodies)e.add(n.name);return e}function Y(u,e){let t=0;for(let n of u)if(n===e&&++t===2)return true;return false}var V=class{constructor(e,t,n){this.compilationWorker=null;this.textHashOfRecordedEdges=new Map;this.selfReadingWrites=new Map;this.cycleMemberIds=new Set;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??new a$1(t.getVM()),this.pageManager=new _,this.engine.getBatcher().checkpointer=this.checkpointer,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=N.subscribe(i=>{for(let s of this.dag.getAffectedLines(O(i)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=this.engine.userUnitNames(),i=[],s=new Map,r={tier1:0,tier2:0,tier3:0,skipped:0},o=this.doc.lineCount,d=Math.min(e.endLine,o),a=this.doc.getLineStatesInRange(1,d);for(let c=1;c<=d;c++){let h=a[c-1];if(!h){r.skipped++;continue}let m=c>=e.startLine&&c<=e.endLine,g=this.evaluateSingleLine(h,c,m);i.push(g),g.tier===1?r.tier1++:g.tier===2?r.tier2++:g.tier===3?r.tier3++:r.skipped++,g.results&&m&&s.set(c,g.results.flat());}this.settleCycles(),this.pageManager.maintainAfterEval(e,this.doc),this.engine.settleOrphanedNames();let l=new Set(this.engine.userUnitNames());return n.some(c=>!l.has(c))&&this.engine.invalidateForRemovedUserUnits(),{lines:i,resultMap:s,tierCounts:r}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,i=e.endLine+1;for(let s=i;s<=n;s++){let r=this.doc.getLineAt(s);if(!r||!r.dirty||r.bytecodes.length>0&&!r.isVariableDef)continue;let o=this.evaluateSingleLine(r,s,false);t.push(o);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new M),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.evaluate(e,t);this.reseedAccumulators(),this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let r of e)for(let o=0;o<r.deleteCount;o++){let d=r.startLine+o,a=this.dag.getWrites(d);for(let l of a)t.add(l);this.undefineOrphans(this.dag.removeLine(d)),this.engine.undefineUserUnitsFrom(this.doc.getLineAt(d)?.lineId??-1)&&this.engine.invalidateForRemovedUserUnits(),this.engine.getLineCache().removeAllForLine(d);}let n=new Set,i=new Set;for(let r of this.dag.linesReadingAPosition()){let o=this.doc.getLineAt(r);o&&(n.add(o.lineId),i.add(o.lineId));}for(let r of t){let o=this.dag.getAffectedLines(r);for(let d of o){let a=this.doc.getLineAt(d);a&&n.add(a.lineId);}}let s=this.doc.applyChanges(e);this.checkpointer?.renumber(r=>this.doc.getLinePosition(r));for(let r of t)this.engine.restoreToPrefix(r,Number.MAX_SAFE_INTEGER);for(let r of n)this.doc.markDirty(r);for(let r of i)this.doc.forgetResult(r);this.dag.clear();for(let r of s.removed)this.textHashOfRecordedEdges.delete(r),this.selfReadingWrites.delete(r),this.cycleMemberIds.delete(r);return {inserted:s.inserted,removed:s.removed}}forgetPositionsOfEditedText(e,t){let n=this.textHashOfRecordedEdges.get(e.lineId);n!==e.textHash&&(n!==void 0&&this.dag.forgetPositionReads(t),this.textHashOfRecordedEdges.set(e.lineId,e.textHash));}settleCycles(){let e=this.dag.takeReadersThatGainedAPosition(),t=this.dag.takeEdgeChanges(),n=new Set(e);for(let i of t.lines)n.add(i);for(let i of t.keys)if(!b$3(i))for(let s of this.dag.directConsumersOf(i))n.add(s);if(n.size!==0){if(this.cycleMemberIds.size>0){let i=this.doc.lineCount;for(let s=1;s<=i;s++){let r=this.doc.getLineAt(s);r!==void 0&&this.cycleMemberIds.has(r.lineId)&&n.add(s);}}this.recomputeCycleMembership(n);}}recomputeCycleMembership(e){let t=new Map,n=new Map,i=new Set,s=[],r=[],o=0,d=l=>{t.set(l,o),n.set(l,o),o++,s.push(l),i.add(l),r.push({line:l,targets:this.dependantsOf(l),next:0});},a=(l,c)=>{let h=this.doc.getLineAt(l);h!==void 0&&c!==this.cycleMemberIds.has(h.lineId)&&(c?this.cycleMemberIds.add(h.lineId):this.cycleMemberIds.delete(h.lineId),this.doc.markDirty(h.lineId));};for(let l of e)if(!t.has(l))for(d(l);r.length>0;){let c=r[r.length-1];if(c.next<c.targets.length){let g=c.targets[c.next++];t.has(g)?i.has(g)&&n.set(c.line,Math.min(n.get(c.line),t.get(g))):d(g);continue}if(r.pop(),r.length>0){let g=r[r.length-1].line;n.set(g,Math.min(n.get(g),n.get(c.line)));}if(n.get(c.line)!==t.get(c.line))continue;let h=[],m;do m=s.pop(),i.delete(m),h.push(m);while(m!==c.line);for(let g of h)a(g,h.length>1);}}dependantsOf(e){let t=[...this.dag.getAffectedLinesByPosition(e)];for(let n of this.dag.getWrites(e))if(!b$3(n)){for(let i of this.dag.directConsumersOf(n))t.push(i);if(this.engine.isAccumulatorName(n))for(let i of this.dag.getProducers(n))i>e&&t.push(i);}return t}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let i=this.doc.getLineAt(n);if(!(i===void 0||i.writes.length===0)){for(let s of i.writes)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],i=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},r=this.doc.lineCount,o=Math.min(t,r);for(let d=e;d<=o;d++){let a=this.doc.getLineAt(d);if(!a)continue;let l=this.evaluateSingleLine(a,d,true);n.push(l),l.tier===1?s.tier1++:l.tier===2?s.tier2++:l.tier===3?s.tier3++:s.skipped++,l.results&&i.set(d,l.results.flat());}return this.settleCycles(),{lines:n,resultMap:i,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){e.dirty&&this.forgetPositionsOfEditedText(e,t);let i=this.cycleMemberIds.has(e.lineId);if(this.engine.setLineOnCycle(i),i)for(let r of e.reads)b$3(r)||this.engine.restoreToPrefix(r,t);let s=this.dispatchLine(e,t,n);return (s.tier===1||s.tier===2)&&this.dag.reconcilePositionReads(t),s}dispatchLine(e,t,n){let i={lineId:e.lineId,lineNumber:t};if(!e.dirty&&!n)return {...i,tier:0,result:null,error:null};if(e.isEmpty||m(e.text))return this.deregisterIfDirty(e,t),e.isEmpty=true,this.doc.markClean(e.lineId),{...i,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:r}=this.extractExpressions(e);return s.length===0?(this.deregisterIfDirty(e,t),e.isEmpty=true,this.doc.markClean(e.lineId),{...i,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,r,i):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...i,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,r,i):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,i):{...i,tier:0,result:null,error:null}}deregisterIfDirty(e,t){if(e.dirty){for(let n of e.writes)this.engine.restoreToPrefix(n,t);e.reads=[],e.writes=[],this.registerWithTags(t,[],[]),this.engine.undefineUserUnitsFrom(e.lineId),this.checkpointer?.dropCheckpointAt(t);}}registerWithTags(e,t,n){let i=this.doc.getLineAt(e)?.text??"",s=a$2(i,t,n);this.undefineOrphans(this.dag.registerLine(e,s.reads,s.writes));}undefineOrphans(e){this.engine.forgetOrphanedNames(e);}evaluateTier1(e,t,n,i,s){this.engine.undefineUserUnitsFrom(e.lineId);let r=[],o=[],d=new Set,a=new Set,l=false,c=null,h=null,m=false,g=false;for(let C of e.writes)this.engine.restoreToPrefix(C,t);let f=new Set,x=[];for(let C of n){if(!C.trim())continue;let I=null,b;try{let p=this.engine.evaluateLine(t,C);I=[p],c=p,b=this.engine.getLineCache().get(t,C);}catch(p){let w=p instanceof Error?p.message:String(p);h||(h=w),m=true,I=null;}I&&I.some(p=>p.type===12)&&(g=true),I?r.push(I):r.push([P$1("eval_failed",h??"unknown error")]);let v=I===null;if(b){o.push(b.bytecode);for(let p of b.readVariables)d.add(p);b.writeVariable&&(a.add(b.writeVariable),l=true,Y(b.readVariables,b.writeVariable)&&x.push(b.writeVariable),v&&!f.has(b.writeVariable)?this.engine.restoreToPrefix(b.writeVariable,t):v||f.add(b.writeVariable));}else try{let{program:p,reads:w,writes:E}=this.engine.compileExpression(C);o.push(p);for(let y of w)d.add(y);for(let y of E)a.add(y);E.length>0&&(l=!0);for(let y of E)Y(w,y)&&x.push(y);for(let y of E)v&&!f.has(y)?this.engine.restoreToPrefix(y,t):v||f.add(y);}catch(p){if(o.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),p instanceof b$4&&p.context){let w=p.context.reads,E=p.context.writes;if(Array.isArray(w))for(let y of w)d.add(y);if(Array.isArray(E))for(let y of E)a.add(y),f.has(y)||this.engine.restoreToPrefix(y,t);}}}let S=[...d],L=[...a];return m||g?(this.doc.updateLineCompiled(e.lineId,n,o,S,L,l,i),e.results=r,e.result=r[0]?.[0]??null,e.inlineSolveCount=i,e.expressions=n):this.doc.updateLineResult(e.lineId,r,o,n,S,L,l,i),x.length>0?this.selfReadingWrites.set(e.lineId,x):this.selfReadingWrites.delete(e.lineId),this.registerWithTags(t,S,L),this.checkpointer&&L.length>0&&!g?this.checkpointer.snapshot(t,e.lineId,L,Q(o)):this.checkpointer&&L.length===0&&this.checkpointer.dropCheckpointAt(t),{...s,tier:1,result:c,results:r,error:h}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let i=[],s=null,r=null,o=false;for(let l of this.selfReadingWrites.get(e.lineId)??[])this.engine.restoreToPrefix(l,t);let d=this.engine.getLineCache(),a=new Set;for(let l=0;l<e.bytecodes.length;l++){let c=e.bytecodes[l];if(c.opcodes.length===0)continue;let h=d.get(t,e.expressions[l]??""),m=h!==void 0?h.writeVariable===null?[]:[h.writeVariable]:e.writes,g=false;try{let f=this.engine.executeCached(c,t);s=f,i.push([f]);}catch(f){let x=f instanceof Error?f.message:String(f);r||(r=x),o=true,g=true,i.push([P$1("exec_failed",x)]);}for(let f of m)g&&!a.has(f)?this.engine.restoreToPrefix(f,t):g||a.add(f);}return this.registerWithTags(t,e.reads,e.writes),i.length>0?(e.results=i,e.result=i[0][0]??null):e.result!==null&&j()&&(e.results=e.results.map(l=>l.map(k)),e.result=e.results[0]?.[0]??k(e.result)),o&&this.doc.markDirty(e.lineId),this.checkpointer&&e.writes.length>0&&!o&&this.checkpointer.snapshot(t,e.lineId,e.writes,Q(e.bytecodes)),{...n,tier:2,result:i.length>0?s:e.result,results:i.length>0?i:e.results,error:r}}evaluateTier3(e,t,n,i,s){let r=[],o=new Set,d=new Set,a=false,l=null,c=null,h=false,m=false;for(let L of e.writes)this.engine.restoreToPrefix(L,t);let g=new Set,f=[];for(let L of n){if(!L.trim())continue;let C;try{C=this.engine.compileExpression(L);}catch(p){let w=p instanceof Error?p.message:String(p);if(c||(c=w),h=true,r.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),p instanceof b$4&&p.context){let E=p.context.reads,y=p.context.writes;if(Array.isArray(E))for(let k of E)o.add(k);if(Array.isArray(y))for(let k of y)d.add(k),g.has(k)||this.engine.restoreToPrefix(k,t);}continue}let{program:I,reads:b,writes:v}=C;r.push(I);for(let p of b)o.add(p);for(let p of v)d.add(p);v.length>0&&(a=true);for(let p of v)Y(b,p)&&f.push(p);if(v.length>0&&I.opcodes.length>0)try{l=this.engine.executeCached(I,t),l&&l.type===12&&(m=!0);for(let p of v)g.add(p);}catch(p){let w=p instanceof Error?p.message:String(p);c||(c=w),h=true;for(let E of v)g.has(E)||this.engine.restoreToPrefix(E,t);}}let x=[...o],S=[...d];return this.doc.updateLineCompiled(e.lineId,n,r,x,S,a,i),this.registerWithTags(t,x,S),f.length>0?this.selfReadingWrites.set(e.lineId,f):this.selfReadingWrites.delete(e.lineId),a&&l&&!h&&!m&&(e.results=[[l]],e.result=l,this.doc.markClean(e.lineId)),this.checkpointer&&S.length>0&&!m?this.checkpointer.snapshot(t,e.lineId,S,Q(r)):this.checkpointer&&S.length===0&&this.checkpointer.dropCheckpointAt(t),{...s,tier:3,result:l,results:a&&l&&!h&&!m?[[l]]:void 0,error:c}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new M),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,i=e.endLine+1;for(let s=i;s<=n;s++){let r=this.doc.getLineAt(s);if(!r||!r.dirty||r.bytecodes.length>0&&!r.isVariableDef||r.isEmpty||m(r.text))continue;let{expressions:o}=this.extractExpressions(r);if(o.length!==0)for(let d of o)d.trim()&&t.push({lineId:r.lineId,expression:d,textHash:r.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(i=>i.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};function he(u){return typeof u.unit=="string"?u.unit:String(u.value)}function me(u,e,t={inputType:"markdown"}){let n$1=u.getDocumentModel(),i=new T;i.setDocument(e);let s=new V(i,u,new a$1(u.getVM()));try{let r=i.lineCount;s.evaluate({startLine:1,endLine:r});let o=[],d=[],a=0;for(let l=1;l<=r;l++){let c=i.getLineAt(l),h=c.text,m=a,g=a+h.length;a=g+1;let f=c.inlineSolveCount>0,x=[],S=null,L=null;c.isEmpty||(f?x=n(h,l).map((C,I)=>{let b=c.results[I]?.[0]??null;if(b&&b.type===13){let v=he(b);return d.push(`Line ${l}: ${v}`),{...C,result:null,error:v}}return {...C,result:b,error:null}}):(S=c.expressions[0]??null,L=c.result??null,L&&L.type===13&&d.push(`Line ${l}: ${he(L)}`))),o.push({lineNumber:l,text:h,startPosition:m,endPosition:g,isEmpty:c.isEmpty,hasInlineSolves:f,inlineSolves:x,expression:S,error:null,result:L});}return {lines:o,totalLines:r,errors:d}}finally{s.terminateWorker(),u.setDocumentModel(n$1);}}export{T as a,ce as b,V as c,me as d};//# sourceMappingURL=chunk-NYJTBXSI.js.map
3
+ //# sourceMappingURL=chunk-NYJTBXSI.js.map