solve-engine 2.38.9 → 2.38.11

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 (83) hide show
  1. package/dist/{PackageCompatibility-DMvoenB_.d.cts → PackageCompatibility-BrCgFgXc.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-Xu04H_z-.d.ts → PackageCompatibility-CfREcBQl.d.ts} +1 -1
  3. package/dist/{PackageRegistry-BgXiVaR8.d.cts → PackageRegistry-BZnmnyrd.d.cts} +1 -1
  4. package/dist/{PackageRegistry-D2ysmOVL.d.ts → PackageRegistry-BwjDDm71.d.ts} +1 -1
  5. package/dist/{VMBuiltins-DR0PyI_g.d.cts → VMBuiltins-BAZsNYQ-.d.cts} +17 -0
  6. package/dist/{VMBuiltins-CjuRXAOD.d.ts → VMBuiltins-CorEIEMd.d.ts} +17 -0
  7. package/dist/{VMCheckpoints-Ch3ElC4X.d.cts → VMCheckpoints-BcuUNpLy.d.cts} +6 -1
  8. package/dist/{VMCheckpoints-C2REEAxr.d.ts → VMCheckpoints-CAONfMZS.d.ts} +6 -1
  9. package/dist/chunk-4CECSCRX.cjs +2 -0
  10. package/dist/chunk-4CECSCRX.cjs.map +1 -0
  11. package/dist/chunk-7TMPBP5P.cjs +5 -0
  12. package/dist/chunk-7TMPBP5P.cjs.map +1 -0
  13. package/dist/{chunk-SU7LRT6J.js → chunk-BQTIQI5Q.js} +3 -3
  14. package/dist/{chunk-SU7LRT6J.js.map → chunk-BQTIQI5Q.js.map} +1 -1
  15. package/dist/chunk-EDKYFXEZ.cjs +2 -0
  16. package/dist/chunk-EDKYFXEZ.cjs.map +1 -0
  17. package/dist/{chunk-NTSH57MK.js → chunk-ERFHCXV4.js} +2 -2
  18. package/dist/{chunk-NTSH57MK.js.map → chunk-ERFHCXV4.js.map} +1 -1
  19. package/dist/chunk-ODKM4MVB.js +5 -0
  20. package/dist/chunk-ODKM4MVB.js.map +1 -0
  21. package/dist/{chunk-KKIGQ7GW.js → chunk-QS7UXI44.js} +2 -2
  22. package/dist/{chunk-KKIGQ7GW.js.map → chunk-QS7UXI44.js.map} +1 -1
  23. package/dist/{chunk-LYGVLHAW.cjs → chunk-R35GD4DP.cjs} +2 -2
  24. package/dist/{chunk-LYGVLHAW.cjs.map → chunk-R35GD4DP.cjs.map} +1 -1
  25. package/dist/{chunk-Y7UPP5QQ.cjs → chunk-TOZHWK7O.cjs} +3 -3
  26. package/dist/{chunk-Y7UPP5QQ.cjs.map → chunk-TOZHWK7O.cjs.map} +1 -1
  27. package/dist/{chunk-64P4KHHU.js → chunk-U7DOO2OE.js} +3 -3
  28. package/dist/chunk-U7DOO2OE.js.map +1 -0
  29. package/dist/chunk-VRQUCWT2.js +2 -0
  30. package/dist/chunk-VRQUCWT2.js.map +1 -0
  31. package/dist/{chunk-PLYETVYZ.cjs → chunk-WHR3SUWC.cjs} +2 -2
  32. package/dist/{chunk-PLYETVYZ.cjs.map → chunk-WHR3SUWC.cjs.map} +1 -1
  33. package/dist/{chunk-PBDZLX5E.cjs → chunk-WSMGTKCC.cjs} +3 -3
  34. package/dist/chunk-WSMGTKCC.cjs.map +1 -0
  35. package/dist/chunk-WZUFPG3F.js +2 -0
  36. package/dist/chunk-WZUFPG3F.js.map +1 -0
  37. package/dist/constants.cjs +1 -1
  38. package/dist/constants.js +1 -1
  39. package/dist/engine.cjs +1 -1
  40. package/dist/engine.d.cts +4 -4
  41. package/dist/engine.d.ts +4 -4
  42. package/dist/engine.js +1 -1
  43. package/dist/engine.worker.cjs +1 -1
  44. package/dist/engine.worker.js +1 -1
  45. package/dist/index.cjs +1 -1
  46. package/dist/index.d.cts +4 -4
  47. package/dist/index.d.ts +4 -4
  48. package/dist/index.js +1 -1
  49. package/dist/language.d.cts +3 -3
  50. package/dist/language.d.ts +3 -3
  51. package/dist/packages.cjs +1 -1
  52. package/dist/packages.d.cts +2 -2
  53. package/dist/packages.d.ts +2 -2
  54. package/dist/packages.js +1 -1
  55. package/dist/testing.cjs +2 -2
  56. package/dist/testing.d.cts +3 -3
  57. package/dist/testing.d.ts +3 -3
  58. package/dist/testing.js +1 -1
  59. package/dist/vm.cjs +1 -1
  60. package/dist/vm.cjs.map +1 -1
  61. package/dist/vm.d.cts +2 -2
  62. package/dist/vm.d.ts +2 -2
  63. package/dist/vm.js +1 -1
  64. package/dist/vm.js.map +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 +4 -4
  70. package/dist/chunk-2JR7PALQ.js +0 -2
  71. package/dist/chunk-2JR7PALQ.js.map +0 -1
  72. package/dist/chunk-64P4KHHU.js.map +0 -1
  73. package/dist/chunk-H3IASAE2.cjs +0 -5
  74. package/dist/chunk-H3IASAE2.cjs.map +0 -1
  75. package/dist/chunk-NCUOMY3E.js +0 -2
  76. package/dist/chunk-NCUOMY3E.js.map +0 -1
  77. package/dist/chunk-PBDZLX5E.cjs.map +0 -1
  78. package/dist/chunk-Q57LJFCT.cjs +0 -2
  79. package/dist/chunk-Q57LJFCT.cjs.map +0 -1
  80. package/dist/chunk-U6H5A6PT.cjs +0 -2
  81. package/dist/chunk-U6H5A6PT.cjs.map +0 -1
  82. package/dist/chunk-Z4ZNKE5U.js +0 -5
  83. package/dist/chunk-Z4ZNKE5U.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import {c as c$1}from'./chunk-6G2NES2I.js';var d="2.38.9";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 c$1.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 c$1.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 c$1.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 c$1.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:[]}}};export{m as a,l as b,n as c,c as d};//# sourceMappingURL=chunk-NCUOMY3E.js.map
2
- //# sourceMappingURL=chunk-NCUOMY3E.js.map
@@ -1 +0,0 @@
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":"2CAEE,IAAAA,EAAW,QAAA,CCcN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,CAAS,KAAAN,CAAK,CAClB,EAGF,IAAMQ,CAAAA,CAAgB,KAAK,MAAA,CAAOF,CAA6B,CAAA,CAC/D,GAAIE,GAAiB,OAAOA,CAAAA,EAAkB,SAC3CA,CAAAA,CAAqDD,CAAQ,EAAIF,CAAAA,CAAAA,KAElE,MAAMD,IAAa,MAAA,CACjB,2BAAA,CACA,qCAAqCJ,CAAI,CAAA,CAAA,CACzC,CAAE,IAAA,CAAAA,CAAK,CACT,CAEJ,CAUA,WAA0B,CACxB,OAAOL,EAAkB,IAAA,CAAK,MAAA,CAAQ,EAAE,CAC1C,CAKA,MAAA,CAAOI,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-NCUOMY3E.js","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.38.9\",\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.0\",\n \"@types/node\": \"^26.4.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.5.0\",\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 +0,0 @@
1
- {"version":3,"sources":["../src/engine/SegmentTree.ts","../src/engine/DocumentModel.ts","../src/engine/CompilationWorkerManager.ts","../src/engine/PageManager.ts","../src/engine/ThreeTierEvaluator.ts","../src/engine/evaluateDocument.ts"],"names":["SegmentTree","index","lineId","left","right","split","merge","createNode","midRight","mid","removed","startIndex","deleteCount","newIds","clampedStart","clampedCount","collectInOrder","newTree","buildTreap","lineIds","endIndex","clampedEnd","result","node","leftSize","targetStart","targetEnd","offset","nodeIndex","updateSize","collect","start","end","priority","pseudoRandom","seed","x","DocumentModel","maxLines","DEFAULT_CONFIG","text","countLines","ErrorFactory","rawLines","djb2Hash","id","changes","inserted","sorted","a","b","change","startIdx","removedIds","atLine","texts","startLine","endLine","lineNumber","newText","state","newHash","tag","ids","positions","position","memberTagsOf","idx","pos","compiledAgainstHash","results","bytecodes","expressions","reads","writes","isVariableDef","inlineSolveCount","s","CompilationWorkerManager","factory","engineWorkerFactory","event","data","pending","raw","err","items","worker","resolve","reject","doc","byLineId","batch","r","w","stored","opcodes","numbers","program","PAGE_SIZE","HOT_PAGE_RADIUS","WARM_PAGE_RADIUS","PRELOAD_PAGE_COUNT","COLD_EVICT_BUFFER","PageManager","_PageManager","pageNum","docLineCount","newViewport","viewport","viewportStartPage","viewportEndPage","lastPage","hotStart","hotEnd","warmStart","warmEnd","coldLeftEnd","coldLeftStart","coldRightStart","coldRightEnd","direction","pages","startPage","endPage","p","firstPreloadPage","range","expression","inlineSpans","sharedLexer","span","EvalTier","ThreeTierEvaluator","engine","checkpointer","sharedGlobalVariableStore","name","globalDagKey","signal","enableValueArena","lines","resultMap","tierCounts","docEnd","evalEnd","states","inViewport","lineResult","disableValueArena","startPos","_err","allWrites","i","lineNum","downstreamLineIds","writeVar","affected","names","baseResult","isEmptyLine","edges","withTagEdges","allResults","allBytecodes","allReads","hasVariableDef","lastValue","firstError","anyFailed","anyPending","value","entry","evaluated","e","errorMessage","v","errorValue","compileErr","EngineError","errReads","errWrites","bytecode","isArenaActive","group","persistentValue","lastResult","targets","trimmed","errorMessageOf","evaluateDocument","input","_options","previousDocumentModel","evaluator","lineCount","errors","n","startPosition","endPosition","hasInlineSolves","inlineSolves","findInlineSolvesInLine","message"],"mappings":"mdA6CO,IAAMA,EAAN,KAAkB,CAAlB,cACN,IAAA,CAAQ,IAAA,CAAoB,MAK5B,IAAI,MAAA,EAAiB,CACpB,OAAO,KAAK,IAAA,CAAO,IAAA,CAAK,KAAK,IAAA,CAAO,CACrC,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,KAAK,IAAA,GAAS,IACtB,CAOA,KAAA,CAAMC,CAAAA,CAAmC,CACxC,GAAI,EAAAA,EAAQ,CAAA,EAAKA,CAAAA,GAAU,KAAK,IAAA,EAAM,IAAA,EAAQ,IAC9C,OAAO,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA,CAAMA,CAAK,CAAA,CAAE,MACtC,CAMA,QAAA,CAASA,EAAeC,CAAAA,CAAsB,CAC7C,GAAM,CAACC,CAAAA,CAAMC,CAAK,CAAA,CAAIC,CAAAA,CAAM,KAAK,IAAA,CAAMJ,CAAK,EAC5C,IAAA,CAAK,IAAA,CAAOK,EAAMA,CAAAA,CAAMH,CAAAA,CAAMI,EAAAA,CAAWL,CAAM,CAAC,CAAA,CAAGE,CAAK,EACzD,CAOA,QAAA,CAASH,EAAmC,CAC3C,GAAIA,EAAQ,CAAA,EAAKA,CAAAA,GAAU,KAAK,IAAA,EAAM,IAAA,EAAQ,GAAI,OAElD,GAAM,CAACE,CAAAA,CAAMK,CAAQ,CAAA,CAAIH,CAAAA,CAAM,KAAK,IAAA,CAAMJ,CAAK,EACzC,CAACQ,CAAAA,CAAKL,CAAK,CAAA,CAAIC,CAAAA,CAAMG,CAAAA,CAAU,CAAC,EAEhCE,CAAAA,CAAUD,CAAAA,CAAMA,EAAI,MAAA,CAAS,MAAA,CACnC,YAAK,IAAA,CAAOH,CAAAA,CAAMH,CAAAA,CAAMC,CAAK,EACtBM,CACR,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,CAAC,CAAA,EAAK,IAAA,CAMrCtC,CAAAA,CAASsC,CAAAA,CAAM,MAAA,EAAU,IAAA,CACrBtC,CAAAA,EAAUA,CAAAA,CAAO,IAAA,GAAS,EAAA,EAC7B8K,CAAAA,CAAO,IAAA,CAAK,CAAA,KAAA,EAAQC,CAAC,CAAA,EAAA,EAAKR,EAAAA,CAAevK,CAAM,CAAC,CAAA,CAAE,CAAA,CAAA,CAAA,CAIpDuH,CAAAA,CAAM,IAAA,CAAK,CACV,UAAA,CAAYwD,CAAAA,CACZ,IAAA,CAAA7J,CAAAA,CACA,aAAA,CAAA8J,CAAAA,CACA,WAAA,CAAAC,EACA,OAAA,CAAS3I,CAAAA,CAAM,OAAA,CACf,eAAA,CAAA4I,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAzE,CAAAA,CAIA,KAAA,CAAO,IAAA,CACP,MAAA,CAAA1G,CACD,CAAC,EACF,CAEA,OAAO,CAAE,KAAA,CAAAuH,CAAAA,CAAO,UAAA,CAAYsD,CAAAA,CAAW,MAAA,CAAAC,CAAO,CAC/C,CAAA,OAAE,CAIDF,CAAAA,CAAU,eAAA,EAAgB,CAC1B5D,CAAAA,CAAO,gBAAA,CAAiB2D,CAAqB,EAC9C,CACD","file":"chunk-PBDZLX5E.cjs","sourcesContent":["/**\n * SegmentTree, an order-statistic Treap (randomized BST).\n *\n * Replaces the flat `lineOrder: number[]` array in DocumentModel with a\n * balanced tree that supports O(log N) insert, delete, and get-at-index\n * operations. Each node stores a `lineId` and its subtree size, enabling\n * order-statistic queries (find the k-th element by position).\n *\n * Key operations:\n * getAt(index), O(log N) expected\n * insertAt(index), O(log N) expected\n * deleteAt(index), O(log N) expected\n * spliceAt(index, deleteCount, newIds), O(log N + deleteCount + insertCount)\n * indexOf(lineId), O(N) without reverse map; cached lazily in DocumentModel\n *\n * Implementation: Treap (Tree + Heap) with implicit keys.\n * Nodes are ordered by position (in-order traversal), not by lineId value.\n * The `size` field enables O(log N) order statistics.\n * Random priorities maintain balance with high probability (O(log N) depth).\n *\n * Memory: ~40 bytes per node (lineId + size + priority + left + right).\n * For 100K lines: ~4MB for tree structure (acceptable).\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\ninterface Node {\n\tlineId: number;\n\t/** Total number of nodes in this subtree (including self). */\n\tsize: number;\n\t/** Random priority for heap property (maintains balance). */\n\tpriority: number;\n\tleft: Node | null;\n\tright: Node | null;\n}\n\n// ── SegmentTree ────────────────────────────────────────────────────────────\n\n/**\n * Maps document offsets to line numbers in logarithmic time.\n *\n * A document is edited constantly, and every edit shifts the offsets of every\n * line after it. Recomputing them linearly on each keystroke is what this\n * avoids.\n */\nexport class SegmentTree {\n\tprivate root: Node | null = null;\n\n\t// ── Public API ───────────────────────────────────────────────────────\n\n\t/** Total number of elements in the tree. */\n\tget length(): number {\n\t\treturn this.root ? this.root.size : 0;\n\t}\n\n\t/** Whether the tree is empty. */\n\tget isEmpty(): boolean {\n\t\treturn this.root === null;\n\t}\n\n\t/**\n\t * Get the lineId at the given 0-based index.\n\t * Returns undefined if index is out of bounds.\n\t * O(log N) expected.\n\t */\n\tgetAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\t\treturn this.nodeAt(this.root, index).lineId;\n\t}\n\n\t/**\n\t * Insert a single lineId at the given 0-based index.\n\t * O(log N) expected.\n\t */\n\tinsertAt(index: number, lineId: number): void {\n\t\tconst [left, right] = split(this.root, index);\n\t\tthis.root = merge(merge(left, createNode(lineId)), right);\n\t}\n\n\t/**\n\t * Delete a single element at the given 0-based index.\n\t * Returns the removed lineId, or undefined if out of bounds.\n\t * O(log N) expected.\n\t */\n\tdeleteAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\n\t\tconst [left, midRight] = split(this.root, index);\n\t\tconst [mid, right] = split(midRight, 1);\n\n\t\tconst removed = mid ? mid.lineId : undefined;\n\t\tthis.root = merge(left, right);\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Bulk splice: delete `deleteCount` elements at `startIndex` (0-based),\n\t * then insert `newIds` in their place.\n\t *\n\t * Returns the removed lineId array.\n\t * O(log N + deleteCount + insertCount) expected.\n\t */\n\tspliceAt(\n\t\tstartIndex: number,\n\t\tdeleteCount: number,\n\t\tnewIds: number[]\n\t): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedCount = Math.min(\n\t\t\tMath.max(0, deleteCount),\n\t\t\t(this.root?.size ?? 0) - clampedStart\n\t\t);\n\n\t\t// Split into three parts: [0, start) [start, start+count) [start+count, end)\n\t\tconst [left, midRight] = split(this.root, clampedStart);\n\t\tconst [mid, right] = split(midRight, clampedCount);\n\n\t\t// Collect removed IDs\n\t\tconst removed = collectInOrder(mid);\n\n\t\t// Build a treap from the new IDs and merge\n\t\tconst newTree = buildTreap(newIds, 0, newIds.length);\n\t\tthis.root = merge(merge(left, newTree), right);\n\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Replace the entire tree with a new set of lineIds.\n\t * O(N), builds a balanced treap from a flat array.\n\t */\n\treplaceAll(lineIds: number[]): void {\n\t\tthis.root = buildTreap(lineIds, 0, lineIds.length);\n\t}\n\n\t/**\n\t * Get a contiguous range of lineIds by index.\n\t * O(rangeSize + log N), single in-order walk instead of N × O(log N).\n\t *\n\t * This is the hot path for viewport rendering in DocumentModel.getVisibleLines().\n\t */\n\tgetRange(startIndex: number, endIndex: number): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedEnd = Math.min((this.root?.size ?? 0) - 1, endIndex);\n\t\tif (clampedStart > clampedEnd) return [];\n\n\t\tconst result: number[] = [];\n\t\tthis.collectRange(this.root, clampedStart, clampedEnd, 0, result);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Clear the tree.\n\t */\n\tclear(): void {\n\t\tthis.root = null;\n\t}\n\n\t// ── Iteration ─────────────────────────────────────────────────────────\n\n\t/**\n\t * In-order iterator yielding all lineIds.\n\t */\n\t*[Symbol.iterator](): IterableIterator<number> {\n\t\tyield* this.inOrder(this.root);\n\t}\n\n\tprivate *inOrder(node: Node | null): IterableIterator<number> {\n\t\tif (!node) return;\n\t\tyield* this.inOrder(node.left);\n\t\tyield node.lineId;\n\t\tyield* this.inOrder(node.right);\n\t}\n\n\t// ── Private helpers ───────────────────────────────────────────────────\n\n\tprivate nodeAt(node: Node | null, index: number): Node {\n\t\t// This is only called with valid indices, so node is non-null\n\t\tconst leftSize = node!.left ? node!.left.size : 0;\n\n\t\tif (index < leftSize) {\n\t\t\treturn this.nodeAt(node!.left, index);\n\t\t} else if (index === leftSize) {\n\t\t\treturn node!;\n\t\t} else {\n\t\t\treturn this.nodeAt(node!.right, index - leftSize - 1);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all node values in the range [targetStart, targetEnd] into result.\n\t * `offset` is the 0-based start of the current subtree within the full tree.\n\t * O(rangeSize + log N), skips entire subtrees outside the target range.\n\t */\n\tprivate collectRange(\n\t\tnode: Node | null,\n\t\ttargetStart: number,\n\t\ttargetEnd: number,\n\t\toffset: number,\n\t\tresult: number[]\n\t): void {\n\t\tif (!node) return;\n\n\t\tconst leftSize = node.left ? node.left.size : 0;\n\t\tconst nodeIndex = offset + leftSize;\n\n\t\t// Traverse left subtree if it overlaps the target range\n\t\tif (nodeIndex > targetStart && node.left) {\n\t\t\tthis.collectRange(node.left, targetStart, targetEnd, offset, result);\n\t\t}\n\n\t\t// Include this node if within range\n\t\tif (nodeIndex >= targetStart && nodeIndex <= targetEnd) {\n\t\t\tresult.push(node.lineId);\n\t\t}\n\n\t\t// Traverse right subtree if it overlaps the target range\n\t\tif (nodeIndex < targetEnd && node.right) {\n\t\t\tthis.collectRange(node.right, targetStart, targetEnd, nodeIndex + 1, result);\n\t\t}\n\t}\n}\n\n// ── Free functions ──────────────────────────────────────────────────────────\n\n/** Create a new treap node. */\nfunction createNode(lineId: number): Node {\n\treturn {\n\t\tlineId,\n\t\tsize: 1,\n\t\tpriority: Math.random(),\n\t\tleft: null,\n\t\tright: null,\n\t};\n}\n\n/** Update a node's size from its children. */\nfunction updateSize(node: Node): void {\n\tnode.size = 1 + (node.left ? node.left.size : 0) + (node.right ? node.right.size : 0);\n}\n\n/**\n * Merge two treaps. All keys in `left` must be ≤ all keys in `right`.\n * O(log N) expected.\n */\nfunction merge(left: Node | null, right: Node | null): Node | null {\n\tif (!left) return right;\n\tif (!right) return left;\n\n\tif (left.priority > right.priority) {\n\t\tleft.right = merge(left.right, right);\n\t\tupdateSize(left);\n\t\treturn left;\n\t} else {\n\t\tright.left = merge(left, right.left);\n\t\tupdateSize(right);\n\t\treturn right;\n\t}\n}\n\n/**\n * Split a treap at `index` (0-based).\n * Returns [left, right] where `left` contains the first `index` elements\n * and `right` contains the rest.\n * O(log N) expected.\n */\nfunction split(\n\tnode: Node | null,\n\tindex: number\n): [Node | null, Node | null] {\n\tif (!node) return [null, null];\n\n\tconst leftSize = node.left ? node.left.size : 0;\n\n\tif (index <= leftSize) {\n\t\tconst [left, right] = split(node.left, index);\n\t\tnode.left = right;\n\t\tupdateSize(node);\n\t\treturn [left, node];\n\t} else {\n\t\tconst [left, right] = split(node.right, index - leftSize - 1);\n\t\tnode.right = left;\n\t\tupdateSize(node);\n\t\treturn [node, right];\n\t}\n}\n\n/**\n * Collect all lineIds from a treap in-order.\n * O(N).\n */\nfunction collectInOrder(node: Node | null): number[] {\n\tconst result: number[] = [];\n\tcollect(node, result);\n\treturn result;\n}\n\nfunction collect(node: Node | null, result: number[]): void {\n\tif (!node) return;\n\tcollect(node.left, result);\n\tresult.push(node.lineId);\n\tcollect(node.right, result);\n}\n\n/**\n * Build a balanced treap from a flat array of lineIds.\n * Uses divide-and-conquer with pre-sorted priorities to produce\n * a heap-ordered tree in O(N) time.\n * O(N).\n */\nfunction buildTreap(lineIds: number[], start: number, end: number): Node | null {\n\tif (start >= end) return null;\n\n\tconst mid = Math.floor((start + end) / 2);\n\n\t// The priority comes from the line's own id, not from its position in this\n\t// build. Position carries no entropy across separate builds: an insert of a\n\t// single line is always `buildTreap(ids, 0, 1)`, so `mid` is always 0, so\n\t// every singly-inserted node got the same priority and they chained into a\n\t// list instead of a tree. The id is unique and stable, so the same set of\n\t// lines still produces the same shape, which is what the determinism here\n\t// was for.\n\tconst priority = pseudoRandom(lineIds[mid]);\n\n\tconst node: Node = {\n\t\tlineId: lineIds[mid],\n\t\tsize: end - start,\n\t\tpriority,\n\t\tleft: buildTreap(lineIds, start, mid),\n\t\tright: buildTreap(lineIds, mid + 1, end),\n\t};\n\n\treturn node;\n}\n\n/**\n * Simple pseudo-random number generator for deterministic treap building.\n * Uses a multiplicative hash of the input.\n *\n * Zero used to be a fixed point: it survives the shift, the xor and the\n * multiply unchanged, so `pseudoRandom(0)` was exactly `0`, the lowest priority\n * a node can have. The seed is offset by a large odd constant first, so no input\n * maps to itself, and the result is read as unsigned so the range really is\n * `[0, 1)` rather than straddling zero.\n */\nfunction pseudoRandom(seed: number): number {\n\tlet x = (seed + 0x9e3779b9) | 0;\n\tx = Math.imul((x >>> 16) ^ x, 0x45d9f3b);\n\tx = Math.imul((x >>> 16) ^ x, 0x45d9f3b);\n\tx = ((x >>> 16) ^ x) >>> 0;\n\treturn x / 0x100000000; // normalize to [0, 1)\n}\n","import { Value } from \"@solve-js/vm/Value\";\nimport { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { djb2Hash } from \"@solve-js/utilities/Hash\";\nimport { SegmentTree } from \"@solve-js/engine/SegmentTree\";\nimport { DEFAULT_CONFIG } from \"@solve-js/constants/Configuration\";\nimport { countLines } from \"@solve-js/utilities/Strings\";\nimport { memberTagsOf } from \"@solve-js/packages/tags/TagScanner\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── LineState ──────────────────────────────────────────────────────────────\n\n/**\n * Persistent per-line state tracked by the DocumentModel.\n *\n * Each line receives an immutable `lineId` that survives structural edits\n * (insertions, deletions, line shifts). This allows caches, the dependency\n * graph, and VM checkpoints to reference lines by ID instead of by volatile\n * line numbers.\n *\n * ── Multi-expression support ─────────────────────────────────────────\n * A single document line may contain multiple inline solves (`s\\`...\\``).\n * To support this without breaking the 1:1 line-to-DAG-node contract:\n * - `expressions[]` holds all extracted expression strings (1 entry for\n * full-line expressions, N entries for N inline solves).\n * - `bytecodes[]` holds compiled bytecode in corresponding order.\n * - `results[]` holds evaluation **result groups** in corresponding order.\n * Each element is a `Value[]`, a group of Values produced by that expression.\n * For variable definitions, the group always has exactly 1 element.\n * For multi-output expressions (e.g., currency conversion), the group\n * may have multiple Values (one per target unit).\n * - `reads[]` and `writes[]` are aggregated across ALL expressions on\n * the line, the DAG treats the line as a single dependency node.\n * - `inlineSolveCount` is 0 for full-line expressions, >0 for inline solves.\n */\nexport interface LineState {\n\t/** Immutable unique identifier, survives all structural edits. */\n\treadonly lineId: number;\n\n\t/** djb2 hash of the line text, used for O(1) change detection. */\n\ttextHash: number;\n\n\t/** The full line text (may include markdown). */\n\ttext: string;\n\n\t/**\n\t * Extracted expression texts.\n\t * - Full-line expressions: one entry (the trimmed text).\n\t * - Inline solve lines: one entry per `s\\`...\\`` span, in left-to-right order.\n\t * - Markdown-only lines: empty array.\n\t */\n\texpressions: string[];\n\n\t/**\n\t * Compiled bytecode for each expression, in corresponding order.\n\t * Parallel to {@link expressions}.\n\t */\n\tbytecodes: BytecodeProgram[];\n\n\t/** Variables this line reads (for dependency tracking). Aggregated across all expressions. */\n\treads: string[];\n\n\t/** Variables this line writes (empty if not a variable definition). Aggregated across all expressions. */\n\twrites: string[];\n\n\t/**\n\t * Evaluation result groups for each expression, in corresponding order.\n\t * Each `Value[]` is a group of Values produced by one expression.\n\t * Variable definitions always produce exactly 1 Value per group.\n\t * Multi-output expressions (e.g. currency conversion) may produce N Values.\n\t */\n\tresults: Value[][];\n\n\t/**\n\t * Convenience accessor for the first expression's first result.\n\t * Equals `results[0]?.[0] ?? null`. For single-expression lines,\n\t * this is the primary result. For multi-expression (inline solve) lines,\n\t * prefer accessing `results[i][j]` directly.\n\t */\n\tresult: Value | null;\n\n\t/** True if this line needs re-evaluation. */\n\tdirty: boolean;\n\n\t/** True if any expression on this line defines a variable (never evict bytecode). */\n\tisVariableDef: boolean;\n\n\t/** True if this line contains only markdown (no evaluable expression). */\n\tisEmpty: boolean;\n\n\t/**\n\t * Number of inline solve expressions on this line.\n\t * 0 = full-line expression (or markdown-only).\n\t * >0 = N inline solves embedded in markdown text.\n\t */\n\tinlineSolveCount: number;\n}\n\n// ── ViewportRange ──────────────────────────────────────────────────────────\n\n/** The visible line range, used to decide which lines are evaluated eagerly. */\nexport interface ViewportRange {\n\tstartLine: number; // 1-based, inclusive\n\tendLine: number; // 1-based, inclusive\n}\n\n// ── LineChange ─────────────────────────────────────────────────────────────\n\n/** Describes a structural change to the document's line list. */\nexport interface LineChange {\n\t/** 1-based line number where the change starts. */\n\tstartLine: number;\n\t/** Number of lines deleted (0 for pure insertion). */\n\tdeleteCount: number;\n\t/** New line texts inserted in place of deleted lines. */\n\tinsertLines: string[];\n}\n\n// ── ApplyChangesResult ─────────────────────────────────────────────────────\n\n/** Result of applying changes to the document model. */\nexport interface ApplyChangesResult {\n\t/** Line IDs of newly inserted lines. */\n\tinserted: number[];\n\t/** Line IDs that were removed. */\n\tremoved: number[];\n}\n\n// ── DocumentModel ──────────────────────────────────────────────────────────\n\n/**\n * Persistent document model with O(log N) line lookups and structural edits.\n *\n * Design:\n * - Each line has an immutable `lineId` (monotonically increasing counter).\n * - `LineState` objects are stored in a `Map<lineId, LineState>` for O(1) access.\n * - Line ordering is maintained in a `SegmentTree` (order-statistic Treap) that\n * supports O(log N) insert, delete, and get-at-index operations.\n * - A lazy position cache (`Map<lineId, number>`) provides O(1) position lookups\n * after the first `getLinePosition()` call and is invalidated on structural edits.\n *\n * Key invariant: line IDs never change, only their positions in the order tree.\n * This means cached bytecode, dependency graph entries, and VM checkpoints\n * keyed by lineId remain valid across all structural edits.\n */\nexport class DocumentModel {\n\t/** Persistent line ID → LineState. */\n\tprivate lines: Map<number, LineState> = new Map();\n\n\t/** Order-statistic treap representing the current document line order. */\n\tprivate orderTree: SegmentTree = new SegmentTree();\n\n\t/** Monotonically increasing counter for new line IDs. */\n\tprivate nextLineId: number = 1;\n\n\t/**\n\t * Lazy position cache: lineId → 1-based position.\n\t * Built on first `getLinePosition()` call, invalidated on structural edits.\n\t */\n\tprivate _positionCache: Map<number, number> | null = null;\n\n\t/**\n\t * Line IDs currently marked dirty, maintained alongside every\n\t * `state.dirty` mutation (in this class and in every other module that\n\t * holds a direct `LineState` reference: ThreeTierEvaluator, PageManager).\n\t * Lets {@link hasAnyDirtyLineBefore} answer \"is anything before position\n\t * X dirty\" in O(d log N), d = current dirty count, typically tiny once\n\t * a document has settled after its initial evaluation, instead of\n\t * O(N log N), which used to mean every scroll event re-walked the WHOLE\n\t * document via `getLineAt()` regardless of how little of it was actually\n\t * dirty. Benchmarked: ~10.6ms per setViewport() call scrolled near the\n\t * bottom of a 20k-line document before this fix.\n\t */\n\tprivate dirtyLineIds: Set<number> = new Set();\n\n\t/**\n\t * Lower-cased category tag to the ids of the lines carrying it, or `null`\n\t * while nothing has asked.\n\t *\n\t * `total of #food` used to walk the whole document looking for `#food`, so a\n\t * document of members and totals cost one walk per total: D aggregates over\n\t * N lines is D x N, and a notepad of a few thousand tagged lines took\n\t * minutes. This turns an aggregate into a lookup of its own members.\n\t *\n\t * Built on the first query rather than with the document, so a document with\n\t * no tags in it, which is most of them, never scans for any. Once built it is\n\t * kept in step by the four places that change a line's text: {@link setDocument},\n\t * {@link applyChanges}, {@link editLine} and {@link clear}. Keyed by line id\n\t * rather than position, so inserting or deleting a line above a tagged one\n\t * does not touch it.\n\t */\n\tprivate tagIndex: Map<string, Set<number>> | null = null;\n\n\t/**\n\t * Most lines this model will hold. See `constants/Configuration.ts`'s\n\t * `performance.maxDocumentLines`, which is where the default comes from and\n\t * which a host raises through its engine config; a host that builds a\n\t * DocumentModel directly passes it here instead.\n\t */\n\tprivate readonly maxLines: number;\n\n\t/**\n\t * @param maxLines - Ceiling on the line count, defaulting to the engine's\n\t * configured one. Every line costs a LineState with six arrays in it\n\t * whatever the line says, so the cost of a document is its line count and\n\t * nothing else bounds it: two hundred thousand lines of `1 + 1` exhausted\n\t * the heap here, before a single expression had been looked at.\n\t */\n\tconstructor(maxLines: number = DEFAULT_CONFIG.performance.maxDocumentLines) {\n\t\tthis.maxLines = maxLines;\n\t}\n\n\t// ── Initialization ──────────────────────────────────────────────────\n\n\t/**\n\t * Initialize or replace the entire document from a text blob.\n\t * Clears all existing state and assigns new persistent line IDs.\n\t *\n\t * @throws `DOCUMENT_TOO_LARGE` for a document past {@link maxLines}, before\n\t * any of it is stored. Recoverable: nothing has been replaced yet, so the\n\t * model still holds whatever it held.\n\t */\n\tsetDocument(text: string): void {\n\t\t// Counted before anything is cleared, so a refused document leaves the\n\t\t// previous one intact rather than half-replaced.\n\t\tconst lineCount = countLines(text, this.maxLines);\n\t\tif (lineCount > this.maxLines) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"DOCUMENT_TOO_LARGE\",\n\t\t\t\t`This document has more than ${this.maxLines.toLocaleString(\"en-US\")} lines, which is the most the engine will hold at once`,\n\t\t\t\t{ maxLines: this.maxLines },\n\t\t\t);\n\t\t}\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.dirtyLineIds.clear();\n\t\tthis.nextLineId = 1;\n\t\tthis.tagIndex = null;\n\n\t\tconst rawLines = text.split(\"\\n\");\n\t\tconst lineIds = new Array<number>(rawLines.length);\n\n\t\tfor (let i = 0; i < rawLines.length; i++) {\n\t\t\tconst lineId = this.nextLineId++;\n\t\t\tlineIds[i] = lineId;\n\t\t\tthis.lines.set(lineId, {\n\t\t\t\tlineId,\n\t\t\t\ttextHash: djb2Hash(rawLines[i]),\n\t\t\t\ttext: rawLines[i],\n\t\t\t\texpressions: [],\n\t\t\t\tbytecodes: [],\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tresults: [],\n\t\t\t\tresult: null,\n\t\t\t\tdirty: true,\n\t\t\t\tisVariableDef: false,\n\t\t\t\tisEmpty: rawLines[i].trim().length === 0,\n\t\t\t\tinlineSolveCount: 0,\n\t\t\t});\n\t\t}\n\n\t\t// O(N) balanced treap build from flat array\n\t\tthis.orderTree.replaceAll(lineIds);\n\n\t\t// Every line starts dirty (see the object literal above), seed the\n\t\t// tracking set to match. This is the one place the set is legitimately\n\t\t// O(N): a fresh document needs full evaluation anyway.\n\t\tfor (const id of lineIds) this.dirtyLineIds.add(id);\n\t}\n\n\t// ── Structural edits ────────────────────────────────────────────────\n\n\t/**\n\t * Apply one or more line-level changes to the document.\n\t *\n\t * **Precondition:** Changes must be **non-overlapping** in their line ranges.\n\t * If two changes target the same or adjacent lines, the reverse-order\n\t * processing may produce incorrect results because the first-applied\n\t * change shifts the line numbers that the second change references.\n\t *\n\t * Changes are applied in **reverse order** (highest startLine first) so\n\t * that earlier changes in the document don't shift the indices of later\n\t * changes during processing.\n\t *\n\t * Returns both the newly inserted line IDs and the removed line IDs.\n\t * Callers should use `removed` to clean up the dependency graph and\n\t * other data structures keyed by lineId.\n\t */\n\tapplyChanges(changes: LineChange[]): ApplyChangesResult {\n\t\tconst inserted: number[] = [];\n\t\tconst removed: number[] = [];\n\n\t\t// Sort descending by startLine so earlier changes don't shift later indices\n\t\tconst sorted = [...changes].sort((a, b) => b.startLine - a.startLine);\n\n\t\tfor (const change of sorted) {\n\t\t\tconst startIdx = change.startLine - 1; // convert to 0-based\n\n\t\t\t// Create new LineState entries for inserted lines\n\t\t\tconst newIds: number[] = [];\n\t\t\tfor (const text of change.insertLines) {\n\t\t\t\tconst lineId = this.nextLineId++;\n\t\t\t\tnewIds.push(lineId);\n\t\t\t\tinserted.push(lineId);\n\t\t\t\tthis.lines.set(lineId, {\n\t\t\t\t\tlineId,\n\t\t\t\t\ttextHash: djb2Hash(text),\n\t\t\t\t\ttext,\n\t\t\t\t\texpressions: [],\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: [],\n\t\t\t\t\twrites: [],\n\t\t\t\t\tresults: [],\n\t\t\t\t\tresult: null,\n\t\t\t\t\tdirty: true,\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\tisEmpty: text.trim().length === 0,\n\t\t\t\t\tinlineSolveCount: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// New lines start dirty (see the object literal above), track them.\n\t\t\tfor (const id of newIds) this.dirtyLineIds.add(id);\n\n\n\t\t\t// Only when something has already asked for one: an index nothing has\n\t\t\t// built yet describes no lines, so it has none to learn about either.\n\t\t\tif (this.tagIndex !== null) {\n\t\t\t\tfor (const id of newIds) this.indexTags(id, this.lines.get(id)!.text);\n\t\t\t}\n\n\t\t\t// O(log N) splice: delete old IDs, insert new IDs\n\t\t\tconst removedIds = this.orderTree.spliceAt(\n\t\t\t\tstartIdx,\n\t\t\t\tchange.deleteCount,\n\t\t\t\tnewIds\n\t\t\t);\n\t\t\tfor (const id of removedIds) {\n\t\t\t\tremoved.push(id);\n\t\t\t\tif (this.tagIndex !== null) this.unindexTags(id, this.lines.get(id)?.text ?? \"\");\n\t\t\t\tthis.lines.delete(id);\n\t\t\t\tthis.dirtyLineIds.delete(id);\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate position cache, positions shifted for all lines\n\t\tthis._positionCache = null;\n\n\t\treturn { inserted, removed };\n\t}\n\n\t/**\n\t * Insert new lines at the given 1-based position.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tinsertLines(atLine: number, texts: string[]): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine: atLine,\n\t\t\tdeleteCount: 0,\n\t\t\tinsertLines: texts,\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.inserted;\n\t}\n\n\t/**\n\t * Delete lines in the given 1-based range [startLine, endLine] inclusive.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tdeleteLines(startLine: number, endLine: number): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine,\n\t\t\tdeleteCount: endLine - startLine + 1,\n\t\t\tinsertLines: [],\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.removed;\n\t}\n\n\t/**\n\t * Update the text of a single line in place.\n\t * If the text hash differs, marks the line dirty and clears its\n\t * bytecode/result so it gets re-evaluated.\n\t *\n\t * Returns true if the text actually changed (hash mismatch).\n\t */\n\teditLine(lineNumber: number, newText: string): boolean {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (!state) return false;\n\n\t\tconst newHash = djb2Hash(newText);\n\t\tif (newHash === state.textHash) return false;\n\n\t\tif (this.tagIndex !== null) {\n\t\t\tthis.unindexTags(state.lineId, state.text);\n\t\t\tthis.indexTags(state.lineId, newText);\n\t\t}\n\t\tstate.text = newText;\n\t\tstate.textHash = newHash;\n\t\tstate.expressions = [];\n\t\tstate.bytecodes = [];\n\t\tstate.results = [];\n\t\tstate.result = null;\n\t\tstate.inlineSolveCount = 0;\n\t\tstate.dirty = true;\n\t\tthis.dirtyLineIds.add(state.lineId);\n\t\tstate.isEmpty = newText.trim().length === 0;\n\t\treturn true;\n\t}\n\n\t// ── Queries ─────────────────────────────────────────────────────────\n\n\t/**\n\t * The 1-based positions of the lines carrying `#tag`, in document order.\n\t *\n\t * What `total of #tag` reads. Case-insensitive, matching how a tag is read\n\t * on a line, and it names membership only: a line that merely asks about the\n\t * group (`total of #tag`) is not in it, and neither is a `#heading`.\n\t *\n\t * Ascending, because an aggregate reports the first line it cannot read and\n\t * the line it names has to be the first one in the document, not whichever\n\t * happened to be indexed first.\n\t *\n\t * @param tag - The tag name without its `#`.\n\t * @returns Its lines' positions, ascending; empty when no line carries it.\n\t */\n\tlinesCarryingTag(tag: string): number[] {\n\t\tconst ids = this.ensureTagIndex().get(tag.toLowerCase());\n\t\tif (ids === undefined || ids.size === 0) return [];\n\t\tconst positions: number[] = [];\n\t\tfor (const id of ids) {\n\t\t\tconst position = this.getLinePosition(id);\n\t\t\t// A line still in the index but no longer in the document cannot\n\t\t\t// happen through the maintained paths; guarded rather than trusted,\n\t\t\t// since the alternative is aggregating over position -1.\n\t\t\tif (position > 0) positions.push(position);\n\t\t}\n\t\tpositions.sort((a, b) => a - b);\n\t\treturn positions;\n\t}\n\n\t/** The tag index, built over every line the first time one is asked for. */\n\tprivate ensureTagIndex(): Map<string, Set<number>> {\n\t\tif (this.tagIndex !== null) return this.tagIndex;\n\t\tthis.tagIndex = new Map();\n\t\tfor (const state of this.lines.values()) this.indexTags(state.lineId, state.text);\n\t\treturn this.tagIndex;\n\t}\n\n\t/** Records `lineId` as a member of every group its text joins. */\n\tprivate indexTags(lineId: number, text: string): void {\n\t\tif (text.indexOf(\"#\") < 0) return; // the overwhelmingly common line\n\t\tfor (const tag of memberTagsOf(text)) {\n\t\t\tconst ids = this.tagIndex!.get(tag);\n\t\t\tif (ids === undefined) this.tagIndex!.set(tag, new Set([lineId]));\n\t\t\telse ids.add(lineId);\n\t\t}\n\t}\n\n\t/** Drops `lineId` from every group the text it used to hold joined. */\n\tprivate unindexTags(lineId: number, text: string): void {\n\t\tif (text.indexOf(\"#\") < 0) return;\n\t\tfor (const tag of memberTagsOf(text)) {\n\t\t\tconst ids = this.tagIndex!.get(tag);\n\t\t\tif (ids === undefined) continue;\n\t\t\tids.delete(lineId);\n\t\t\tif (ids.size === 0) this.tagIndex!.delete(tag);\n\t\t}\n\t}\n\n\t/**\n\t * Get the LineState at the given 1-based line position. O(1).\n\t */\n\tgetLineAt(position: number): LineState | undefined {\n\t\tconst idx = position - 1;\n\t\tconst lineId = this.orderTree.getAt(idx);\n\t\tif (lineId === undefined) return undefined;\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get the 1-based position of a line by its persistent ID.\n\t * Returns -1 if the line ID is not in the document.\n\t *\n\t * Uses a lazy position cache: O(N) on first call after structural edit,\n\t * O(1) on subsequent calls. The cache is invalidated by any structural edit.\n\t */\n\tgetLinePosition(lineId: number): number {\n\t\tif (this._positionCache) {\n\t\t\treturn this._positionCache.get(lineId) ?? -1;\n\t\t}\n\n\t\t// Build position cache on first call after invalidation\n\t\tthis._positionCache = new Map();\n\t\tlet pos = 1;\n\t\tfor (const id of this.orderTree) {\n\t\t\tthis._positionCache.set(id, pos++);\n\t\t}\n\n\t\treturn this._positionCache.get(lineId) ?? -1;\n\t}\n\n\t/**\n\t * Get all LineState entries within the given viewport range (1-based, inclusive).\n\t * Uses SegmentTree.getRange() for O(viewport + log N) collection instead of\n\t * O(viewport × log N) per-line lookups.\n\t */\n\tgetVisibleLines(startLine: number, endLine: number): LineState[] {\n\t\tconst lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);\n\t\tconst result: LineState[] = [];\n\t\tfor (const lineId of lineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * The lines from `startLine` to `endLine`, one entry per position.\n\t *\n\t * The same lines {@link getVisibleLines} returns, except that a position\n\t * whose line is missing keeps its place as `undefined` rather than closing\n\t * the gap, so the caller can index by position.\n\t *\n\t * Resolving the ids here rather than handing them back is deliberate and\n\t * measured: the loop below is monomorphic over this class's own map, and\n\t * asking {@link getLineById} once per position instead was 20% slower on a\n\t * twenty-thousand-line document.\n\t *\n\t * One in-order walk of the order tree, O(span + log N), against the\n\t * O(log N) descent per position that asking {@link getLineAt} in a loop\n\t * costs. The evaluator walks from line 1 to the end of the viewport on\n\t * every pass, so that descent was a third of the cost of an edit on a long\n\t * document scrolled near the bottom.\n\t *\n\t * @param startLine - First position, 1-based, inclusive.\n\t * @param endLine - Last position, 1-based, inclusive.\n\t * @returns One entry per position in the span, in document order.\n\t */\n\tgetLineStatesInRange(startLine: number, endLine: number): (LineState | undefined)[] {\n\t\tconst lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);\n\t\tconst result = new Array<LineState | undefined>(lineIds.length);\n\t\tfor (let i = 0; i < lineIds.length; i++) result[i] = this.lines.get(lineIds[i]);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get all LineState entries in order. Useful for batch processing.\n\t */\n\tgetAllLines(): LineState[] {\n\t\treturn this.getVisibleLines(1, this.lineCount);\n\t}\n\n\t/**\n\t * Get a LineState by its persistent line ID. O(1).\n\t */\n\tgetLineById(lineId: number): LineState | undefined {\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get all lines that are marked dirty.\n\t */\n\tgetDirtyLines(): LineState[] {\n\t\tconst result: LineState[] = [];\n\t\tfor (const state of this.lines.values()) {\n\t\t\tif (state.dirty) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Whether any line before `position` (1-based, exclusive) is dirty.\n\t *\n\t * Used by ThreeTierEvaluator.setViewport() to decide whether cached\n\t * checkpoint state might be stale and a full evaluate() (from line 1) is\n\t * needed instead of the cheap viewport-only path.\n\t *\n\t * O(d log N) where d = current dirty line count via {@link dirtyLineIds},\n\t * not O(N log N), a document that's mostly clean (the steady state after\n\t * initial load) answers this in the cost of resolving a handful of\n\t * lineIds to positions, not walking every line up to `position`.\n\t */\n\thasAnyDirtyLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether any **variable-definition** line before `position` (1-based,\n\t * exclusive) is dirty.\n\t *\n\t * Narrower than {@link hasAnyDirtyLineBefore}: `VMCheckpointer.snapshot()`\n\t * only ever records state for lines with `writes.length > 0` (see\n\t * VMCheckpoints.ts), so a dirty plain-expression line before the viewport\n\t * cannot have invalidated any checkpoint, there's no checkpoint entry\n\t * for it to invalidate. Only a dirty variable-def line can mean the VM\n\t * state a checkpoint would restore is stale.\n\t *\n\t * This distinction matters because `PageManager.evictPageBytecode()`\n\t * marks evicted non-variable-def lines dirty (so they get Tier 1 if\n\t * scrolled back into view), and Tier 3's compile-only path never clears\n\t * `dirty` for non-variable-def lines by design. Using the broader\n\t * `hasAnyDirtyLineBefore` here meant scrolling far into a large,\n\t * variable-def-free document would trip `setViewport()`'s fallback to\n\t * `evaluate()` on every single call, evaluate() reprocesses the evicted\n\t * lines via Tier 3, which recompiles their bytecode without clearing\n\t * dirty, so the very next `maintainAfterEval()` re-evicts and re-dirties\n\t * the same lines, forever re-triggering the fallback on an otherwise\n\t * unchanged viewport.\n\t */\n\thasAnyDirtyVariableDefLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (!state || !state.isVariableDef) continue;\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Number of lines currently marked dirty. For diagnostics/tests. */\n\tget dirtyCount(): number {\n\t\treturn this.dirtyLineIds.size;\n\t}\n\n\t// ── Thread-safety validation ────────────────────────────────────────\n\n\t/**\n\t * Verify that bytecode compiled by a worker is still valid for this line.\n\t *\n\t * When Phase 5.2h sends compilation to a worker, the worker posts back\n\t * `{lineId, bytecode, reads, writes, compiledAgainstHash}`. Between dispatch\n\t * and response, the user may have edited the line. This method lets the\n\t * main thread check whether the bytecode is still applicable.\n\t *\n\t * @returns true if the line still exists and its text hash matches.\n\t */\n\tisBytecodeValid(lineId: number, compiledAgainstHash: number): boolean {\n\t\tconst state = this.lines.get(lineId);\n\t\treturn state !== undefined && state.textHash === compiledAgainstHash;\n\t}\n\n\t// ── State mutations ─────────────────────────────────────────────────\n\n\t/**\n\t * Mark a line as clean (re-evaluated successfully).\n\t */\n\tmarkClean(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = false;\n\t\t\tthis.dirtyLineIds.delete(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation) by its 1-based position.\n\t * Convenience for callers that have line numbers instead of line IDs.\n\t */\n\tmarkDirtyByLineNumber(lineNumber: number): void {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(state.lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation).\n\t */\n\tmarkDirty(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark all lines as dirty (e.g., after plugin register/unregister).\n\t */\n\tinvalidateAll(): void {\n\t\tfor (const state of this.lines.values()) {\n\t\t\tstate.dirty = true;\n\t\t}\n\t\tthis.dirtyLineIds = new Set(this.lines.keys());\n\t}\n\n\t/**\n\t * Update a line's evaluation state after successful execution (Tier 1 / Tier 2).\n\t *\n\t * Sets results, bytecodes, reads, writes, and marks the line clean.\n\t * Supports multi-expression lines (inline solves) via parallel arrays.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param results - Evaluation result groups for each expression (in order). Each element is a Value[].\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineResult(\n\t\tlineId: number,\n\t\tresults: Value[][],\n\t\tbytecodes: BytecodeProgram[],\n\t\texpressions: string[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.expressions = expressions;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\tstate.dirty = false;\n\t\tthis.dirtyLineIds.delete(lineId);\n\t}\n\n\t/**\n\t * Update a line's compile-only state (Tier 3: background compilation).\n\t *\n\t * Stores expressions, bytecodes, reads, and writes. Does NOT set results\n\t * and does NOT mark the line clean, it still needs execution (Tier 1 or\n\t * Tier 2) to produce results. This distinction allows the three-tier\n\t * evaluation strategy: compile invisible lines in the background without\n\t * executing them, then execute from cached bytecode when scrolled into view.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineCompiled(\n\t\tlineId: number,\n\t\texpressions: string[],\n\t\tbytecodes: BytecodeProgram[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.expressions = expressions;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t// NOTE: dirty remains unchanged, line still needs execution\n\t}\n\n\t// ── Properties ──────────────────────────────────────────────────────\n\n\tget lineCount(): number {\n\t\treturn this.orderTree.length;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.orderTree.isEmpty;\n\t}\n\n\t/**\n\t * Iterator over LineState in document order.\n\t */\n\t*[Symbol.iterator](): IterableIterator<LineState> {\n\t\tfor (const lineId of this.orderTree) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) yield state;\n\t\t}\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────\n\n\tclear(): void {\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.nextLineId = 1;\n\t\tthis.tagIndex = null;\n\t}\n\n\t/**\n\t * Serialize the document model to a plain object for debugging.\n\t */\n\ttoJSON(): object {\n\t\treturn {\n\t\t\tlineCount: this.lineCount,\n\t\t\tlines: this.getAllLines().map((s) => ({\n\t\t\t\tlineId: s.lineId,\n\t\t\t\ttext: s.text.substring(0, 80), // truncate for readability\n\t\t\t\ttextHash: s.textHash,\n\t\t\t\tdirty: s.dirty,\n\t\t\t\tisVariableDef: s.isVariableDef,\n\t\t\t\tisEmpty: s.isEmpty,\n\t\t\t\thasBytecode: s.bytecodes.length > 0,\n\t\t\t\thasResult: s.results.length > 0,\n\t\t\t\tinlineSolveCount: s.inlineSolveCount,\n\t\t\t\treads: s.reads,\n\t\t\t\twrites: s.writes,\n\t\t\t})),\n\t\t};\n\t}\n}\n","/**\n * CompilationWorkerManager, main-thread bridge to the compilation worker.\n *\n * Manages the worker lifecycle and provides a batch compilation API.\n * Receives transferred ArrayBuffers from the worker and reconstructs\n * BytecodeProgram objects with zero-copy TypedArray views.\n *\n * Usage:\n * const manager = new CompilationWorkerManager();\n * const bytecodeByLineId = await manager.compileBatch(items, docModel);\n *\n * Thread safety:\n * Each result includes `compiledAgainstHash`. Before storing bytecode\n * in the DocumentModel, we validate via `docModel.isBytecodeValid()`.\n * If the line was edited between dispatch and response, the bytecode\n * is discarded, the next evaluate() will recompile it synchronously.\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { engineWorkerFactory } from \"@solve-js/workers/WorkerFactory\";\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/** One line sent to a worker for compilation. */\nexport interface CompileRequestItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\n/** Compiled bytecode returned from a worker, or the error that stopped it. */\nexport interface CompileResponseItem {\n\tlineId: number;\n\t/** Hash of the expression text when the compile was dispatched (for safety validation). */\n\tcompiledAgainstHash: number;\n\tprogram: BytecodeProgram;\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// Raw result from worker (before BytecodeProgram reconstruction)\ninterface WorkerCompileResult {\n\tlineId: number;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── CompilationWorkerManager ──────────────────────────────────────────────\n\n/**\n * Compiles lines on a background worker.\n *\n * A response is discarded when the line changed between dispatch and return,\n * because bytecode compiled against stale text would produce a result for an\n * expression the user has already edited. The next evaluation recompiles it\n * synchronously.\n */\nexport class CompilationWorkerManager {\n\tprivate worker: Worker | null = null;\n\tprivate nextId = 1;\n\tprivate pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (results: CompileResponseItem[]) => void;\n\t\t\treject: (error: Error) => void;\n\t\t}\n\t>();\n\n\tconstructor() {}\n\n\t/**\n\t * Ensure the worker is started (lazy initialization).\n\t *\n\t * Starts it from the factory a host registered with\n\t * `setEngineWorkerFactory`. With no factory there is no worker, which is\n\t * the ordinary case: the throw travels as a rejected promise out of\n\t * `compileBatch` (it is `async`), and its callers already treat that as\n\t * \"compile this line on the main thread instead\". This is the same contract\n\t * the throwing worker stub had before the factory replaced it.\n\t */\n\tprivate ensureWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\n\t\tconst factory = engineWorkerFactory();\n\t\tif (factory === null) {\n\t\t\tthrow new Error(\"no engine worker factory registered, so compilation stays on the main thread\");\n\t\t}\n\t\tthis.worker = factory();\n\n\t\tthis.worker.onmessage = (event: MessageEvent) => {\n\t\t\tconst data = event.data;\n\t\t\tif (!data || data.type !== \"COMPILE_RESULT\") return;\n\n\t\t\tconst pending = this.pending.get(data.id);\n\t\t\tif (!pending) return;\n\n\t\t\tthis.pending.delete(data.id);\n\n\t\t\tconst results: CompileResponseItem[] = [];\n\t\t\tfor (const raw of data.results as WorkerCompileResult[]) {\n\t\t\t\tresults.push(this.reconstructResult(raw));\n\t\t\t}\n\t\t\tpending.resolve(results);\n\t\t};\n\n\t\tthis.worker.onerror = (err) => {\n\t\t\t// Reject all pending requests on worker error\n\t\t\tfor (const [id, pending] of this.pending) {\n\t\t\t\tpending.reject(\n\t\t\t\t\tnew Error(`Compilation worker error: ${err.message}`)\n\t\t\t\t);\n\t\t\t\tthis.pending.delete(id);\n\t\t\t}\n\t\t};\n\n\t\treturn this.worker;\n\t}\n\n\t/**\n\t * Batch-compile expressions in the worker.\n\t *\n\t * Sends a batch of { lineId, expression, textHash } to the worker,\n\t * which compiles each and transfers bytecode ArrayBuffers back.\n\t * Bytecode is reconstructed into BytecodeProgram objects.\n\t *\n\t * Results are returned in the same order as the input items.\n\t *\n\t * @param items Expressions to compile.\n\t * @returns Compiled bytecode for each item (or error).\n\t */\n\tasync compileBatch(items: CompileRequestItem[]): Promise<CompileResponseItem[]> {\n\t\tif (items.length === 0) return [];\n\n\t\tconst worker = this.ensureWorker();\n\t\tconst id = this.nextId++;\n\n\t\treturn new Promise<CompileResponseItem[]>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\n\t\t\tworker.postMessage({\n\t\t\t\ttype: \"COMPILE_BATCH\",\n\t\t\t\tid,\n\t\t\t\titems,\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Store worker-compiled bytecode into the DocumentModel, with safety\n\t * validation. Only stores bytecode for lines whose text has not changed\n\t * since the compilation request was dispatched.\n\t *\n\t * Results for the same lineId are batched, all bytecodes from\n\t * successful compilations are passed to updateLineCompiled in a single\n\t * call. This supports multi-expression lines (inline solves).\n\t *\n\t * @param results Compiled results from the worker.\n\t * @param doc The target document model.\n\t * @returns Number of results successfully stored (passed safety check).\n\t */\n\tstoreResults(\n\t\tresults: CompileResponseItem[],\n\t\tdoc: DocumentModel\n\t): number {\n\t\t// Batch results by lineId (multiple inline solves share the same lineId)\n\t\tconst byLineId = new Map<\n\t\t\tnumber,\n\t\t\t{\n\t\t\t\tbytecodes: BytecodeProgram[];\n\t\t\t\treads: Set<string>;\n\t\t\t\twrites: Set<string>;\n\t\t\t\tisVariableDef: boolean;\n\t\t\t\texpressions: string[];\n\t\t\t\ttextHash: number;\n\t\t\t}\n\t\t>();\n\t\tlet validCount = 0;\n\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\n\t\t\t// Safety check: has the line been edited since dispatch?\n\t\t\tconst state = doc.getLineById(result.lineId);\n\t\t\tif (!state) continue;\n\n\t\t\t// Validate that the line text hasn't changed since dispatch.\n\t\t\tif (state.textHash !== result.compiledAgainstHash) continue;\n\n\t\t\t// Batch by lineId\n\t\t\tlet batch = byLineId.get(result.lineId);\n\t\t\tif (!batch) {\n\t\t\t\tbatch = {\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: new Set(),\n\t\t\t\t\twrites: new Set(),\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\texpressions: state.expressions.length > 0 ? [...state.expressions] : [],\n\t\t\t\t\ttextHash: result.compiledAgainstHash,\n\t\t\t\t};\n\t\t\t\tbyLineId.set(result.lineId, batch);\n\t\t\t}\n\n\t\t\tbatch.bytecodes.push(result.program);\n\t\t\tfor (const r of result.reads) batch.reads.add(r);\n\t\t\tfor (const w of result.writes) batch.writes.add(w);\n\t\t\tif (result.isVariableDef) batch.isVariableDef = true;\n\t\t\tvalidCount++;\n\t\t}\n\n\t\t// Store batched results\n\t\tlet stored = 0;\n\t\tfor (const [lineId, batch] of byLineId) {\n\t\t\tif (batch.bytecodes.length === 0) continue;\n\t\t\t// Preserve inlineSolveCount from the LineState so the evaluator\n\t\t\t// knows this line has multiple expressions (avoids re-extraction).\n\t\t\tconst state = doc.getLineById(lineId);\n\t\t\tconst inlineSolveCount = state?.inlineSolveCount ?? 0;\n\t\t\tdoc.updateLineCompiled(\n\t\t\t\tlineId,\n\t\t\t\tbatch.expressions,\n\t\t\t\tbatch.bytecodes,\n\t\t\t\t[...batch.reads],\n\t\t\t\t[...batch.writes],\n\t\t\t\tbatch.isVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\tstored += batch.bytecodes.length;\n\t\t}\n\n\t\treturn stored;\n\t}\n\n\t/**\n\t * Terminate the worker and clean up.\n\t */\n\tterminate(): void {\n\t\tif (this.worker) {\n\t\t\tthis.worker.terminate();\n\t\t\tthis.worker = null;\n\t\t\tthis.pending.clear();\n\t\t}\n\t}\n\n\t/**\n\t * Whether the worker is currently active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this.worker !== null;\n\t}\n\n\t// ── Private helpers ────────────────────────────────────────────────\n\n\t/**\n\t * Reconstruct a BytecodeProgram from transferred ArrayBuffers.\n\t *\n\t * The transferred ArrayBuffers are zero-copy, we create TypedArray\n\t * views directly over them. No data is copied or serialized.\n\t */\n\tprivate reconstructResult(raw: WorkerCompileResult): CompileResponseItem {\n\t\tif (raw.error) {\n\t\t\treturn {\n\t\t\t\tlineId: raw.lineId,\n\t\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\t\tprogram: { opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false },\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tisVariableDef: false,\n\t\t\t\terror: raw.error,\n\t\t\t};\n\t\t}\n\n\t\t// Reconstruct TypedArrays from transferred ArrayBuffers.\n\t\t// These are views over the same memory, zero-copy from worker.\n\t\tconst opcodes =\n\t\t\traw.opcodesLength > 0\n\t\t\t\t? new Uint8Array(raw.opcodesBuffer, 0, raw.opcodesLength)\n\t\t\t\t: new Uint8Array(0);\n\t\tconst numbers =\n\t\t\traw.numbersLength > 0\n\t\t\t\t? new Float64Array(raw.numbersBuffer, 0, raw.numbersLength)\n\t\t\t\t: new Float64Array(0);\n\n\t\tconst program: BytecodeProgram = {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: raw.strings,\n\t\t\thasAsync: false,\n\t\t};\n\n\t\treturn {\n\t\t\tlineId: raw.lineId,\n\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\tprogram,\n\t\t\treads: raw.reads,\n\t\t\twrites: raw.writes,\n\t\t\tisVariableDef: raw.isVariableDef,\n\t\t\terror: null,\n\t\t};\n\t}\n}\n","/**\n * PageManager, page-based LRU eviction + directional preloading.\n *\n * Groups document lines into fixed-size pages (128 lines each) and manages\n * three temperature tiers:\n * • Hot (viewport ± 3 pages): Keep bytecode + results\n * • Warm (viewport ± 6 pages): Keep bytecode, evict results\n * • Cold (beyond ± 6 pages): Evict bytecode + results (except variable defs)\n *\n * Variable definition bytecode is **never evicted** because it forms the\n * backbone of the dependency graph and VM checkpoints.\n *\n * Preloading: When the user scrolls in a consistent direction, the next\n * 1–2 pages are pre-compiled via the background worker so bytecode is\n * cache-hot by the time those lines scroll into view.\n *\n * Usage:\n * const pm = new PageManager();\n * // After evaluation:\n * pm.maintainAfterEval(viewport, doc);\n * // After scroll (viewport-only change):\n * pm.maintainAfterEval(viewport, doc);\n * const targets = pm.getPreloadTargets(viewport, doc);\n * // dispatch targets to compilation worker\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\n/** Number of lines per page. Tunable, 128 balances granularity with overhead. */\nexport const PAGE_SIZE = 128;\n\n/** Number of pages on each side of the viewport considered \"hot.\" */\nconst HOT_PAGE_RADIUS = 3;\n\n/** Number of pages on each side of the viewport considered \"warm\" (includes hot). */\nconst WARM_PAGE_RADIUS = 6;\n\n/** Number of pages to preload ahead of the scroll direction. */\nconst PRELOAD_PAGE_COUNT = 2;\n\n/**\n * Pages just beyond the warm range that are \"newly cold\", they were warm\n * on the previous scroll and now need bytecode eviction. Once evicted, they\n * stay cold and don't need re-eviction on subsequent frames (the inner\n * `evictPageBytecode` checks for non-null bytecode and short-circuits).\n *\n * This buffer lets us skip iterating the vast majority of cold pages on\n * every scroll, reducing `maintainAfterEval` from O(total pages) to\n * O(hot + warm + buffer) ≈ O(1) for any document size.\n */\nconst COLD_EVICT_BUFFER = HOT_PAGE_RADIUS;\n\n// ── PageManager ──────────────────────────────────────────────────────────\n\n/**\n * Splits a long document into pages so only what is near the viewport is held\n * in full.\n *\n * A document is edited constantly and most of it is off screen. Paging keeps\n * the cost of a keystroke proportional to what is visible rather than to the\n * length of the document.\n */\nexport class PageManager {\n\t/** Previous viewport for scroll direction detection. null = no previous viewport. */\n\tprivate lastViewportStart: number | null = null;\n\n\t/** Saved scroll direction from the most recent maintainAfterEval call. */\n\tprivate savedDirection: \"down\" | \"up\" | null = null;\n\n\t/** Per-page access counter for LRU tracking. */\n\tprivate pageAccess: Map<number, number> = new Map();\n\n\t/** Monotonically increasing access sequence number. */\n\tprivate accessSeq = 0;\n\n\t// ── Static helpers ─────────────────────────────────────────────────\n\n\t/** Get the page number for a 1-based line number (0-based page index). */\n\tstatic pageForLine(lineNumber: number): number {\n\t\treturn Math.floor((lineNumber - 1) / PAGE_SIZE);\n\t}\n\n\t/** Get the 1-based inclusive line range for a page. */\n\tstatic pageRange(\n\t\tpageNum: number,\n\t\tdocLineCount: number\n\t): { startLine: number; endLine: number } {\n\t\treturn {\n\t\t\tstartLine: pageNum * PAGE_SIZE + 1,\n\t\t\tendLine: Math.min((pageNum + 1) * PAGE_SIZE, docLineCount),\n\t\t};\n\t}\n\n\t// ── Public API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Detect scroll direction from viewport movement.\n\t * Returns null on first call (no previous viewport) or no movement.\n\t */\n\tdetectDirection(newViewport: { startLine: number }): \"down\" | \"up\" | null {\n\t\tif (this.lastViewportStart === null) return null;\n\t\tif (newViewport.startLine > this.lastViewportStart) return \"down\";\n\t\tif (newViewport.startLine < this.lastViewportStart) return \"up\";\n\t\treturn null;\n\t}\n\n\t/**\n\t * Maintain page tiers after evaluation.\n\t *\n\t * 1. Records the new viewport position\n\t * 2. Touches hot pages (viewport ± HOT_PAGE_RADIUS) for LRU\n\t * 3. Evicts cold/warm pages based on distance from viewport\n\t *\n\t * Call this after every `evaluate()`, `setViewport()`, or `evaluateAll()`.\n\t */\n\tmaintainAfterEval(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): void {\n\t\t// ── Capture direction BEFORE updating lastViewportStart ───\n\t\tthis.savedDirection = this.detectDirection(viewport);\n\t\tthis.lastViewportStart = viewport.startLine;\n\n\t\tconst docLineCount = doc.lineCount;\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst lastPage = PageManager.pageForLine(docLineCount);\n\n\t\t// Compute hot/warm page ranges in O(1) using range math:\n\t\t// A page is within RADIUS of the viewport span iff it falls in\n\t\t// [viewportStartPage - RADIUS, viewportEndPage + RADIUS].\n\t\tconst hotStart = Math.max(0, viewportStartPage - HOT_PAGE_RADIUS);\n\t\tconst hotEnd = Math.min(lastPage, viewportEndPage + HOT_PAGE_RADIUS);\n\t\tconst warmStart = Math.max(0, viewportStartPage - WARM_PAGE_RADIUS);\n\t\tconst warmEnd = Math.min(lastPage, viewportEndPage + WARM_PAGE_RADIUS);\n\n\t\t// Touch hot pages to keep them fresh in LRU\n\t\tfor (let p = hotStart; p <= hotEnd; p++) {\n\t\t\tthis.touchPage(p);\n\t\t}\n\n\t\t// Evict warm-but-not-hot pages: keep bytecode, evict results only\n\t\tfor (let p = warmStart; p <= warmEnd; p++) {\n\t\t\tif (p >= hotStart && p <= hotEnd) continue;\n\t\t\tthis.evictPageResults(p, doc, docLineCount);\n\t\t}\n\n\t\t// Evict \"newly cold\" pages: a buffer zone just outside the warm\n\t\t// range. Pages beyond this buffer were already evicted on prior\n\t\t// scrolls and don't need re-eviction.\n\t\t// ── Left side (just above page 0, just below warm range) ──\n\t\tconst coldLeftEnd = warmStart - 1;\n\t\tconst coldLeftStart = Math.max(0, coldLeftEnd - COLD_EVICT_BUFFER + 1);\n\t\tfor (let p = coldLeftStart; p <= coldLeftEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t\t// ── Right side (just above warm range, just below lastPage) ──\n\t\tconst coldRightStart = warmEnd + 1;\n\t\tconst coldRightEnd = Math.min(lastPage, coldRightStart + COLD_EVICT_BUFFER - 1);\n\t\tfor (let p = coldRightStart; p <= coldRightEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t}\n\n\t/**\n\t * Get lines ahead of the viewport that should be pre-compiled.\n\t *\n\t * Looks PRELOAD_PAGE_COUNT pages ahead of the current scroll direction.\n\t * Only returns lines that are dirty, don't already have bytecode,\n\t * and are not empty/markdown-only.\n\t *\n\t * @param viewport The current viewport.\n\t * @param doc The document model.\n\t * @returns Items ready to send to the compilation worker.\n\t */\n\tgetPreloadTargets(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): Array<{ lineId: number; expression: string; textHash: number }> {\n\t\t// Use the direction saved by the last maintainAfterEval call.\n\t\t// We cannot re-detect because maintainAfterEval already updated\n\t\t// lastViewportStart to the current viewport position.\n\t\tconst direction = this.savedDirection;\n\t\tif (!direction) return [];\n\n\t\tconst items: Array<{ lineId: number; expression: string; textHash: number }> = [];\n\t\t// Use viewport end page for downward preload start, start page for upward.\n\t\t// This ensures we preload *beyond* the full viewport span, not just its start.\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst lastPage = PageManager.pageForLine(doc.lineCount);\n\n\t\tconst pages: number[] = [];\n\t\tif (direction === \"down\") {\n\t\t\t// Preload pages immediately after the viewport's hot radius beyond its end\n\t\t\tconst startPage = viewportEndPage + HOT_PAGE_RADIUS + 1;\n\t\t\tconst endPage = Math.min(startPage + PRELOAD_PAGE_COUNT - 1, lastPage);\n\t\t\tfor (let p = startPage; p <= endPage && p <= lastPage; p++) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t} else {\n\t\t\t// Preload pages immediately before the viewport's hot radius before its start\n\t\t\tconst firstPreloadPage = viewportStartPage - HOT_PAGE_RADIUS - 1;\n\t\t\tfor (let p = firstPreloadPage; p > firstPreloadPage - PRELOAD_PAGE_COUNT && p >= 0; p--) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t}\n\n\t\tfor (const pageNum of pages) {\n\t\t\tconst range = PageManager.pageRange(pageNum, doc.lineCount);\n\t\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\t\tconst state = doc.getLineAt(pos);\n\t\t\t\tif (!state) continue;\n\t\t\t\tif (!state.dirty) continue;\n\t\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\t\t\t\tif (state.isEmpty) continue;\n\n\t\t\t\t// Extract expressions using the shared lexer to handle inline\n\t\t\t\t// solves (s`...`). For full-line expressions, this returns [text].\n\t\t\t\t// For inline solve lines, this returns each extracted expression.\n\t\t\t\tif (state.expressions.length > 0) {\n\t\t\t\t\t// Use pre-extracted expressions (from prior evaluation)\n\t\t\t\t\tfor (const expression of state.expressions) {\n\t\t\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Expressions not yet extracted, use lexer to find inline solves\n\t\t\t\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\t\t\t\tif (inlineSpans.length > 0) {\n\t\t\t\t\t\tfor (const span of inlineSpans) {\n\t\t\t\t\t\t\tif (!span.expression.trim()) continue;\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression: span.expression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Full-line expression\n\t\t\t\t\t\tconst expression = state.text.trim();\n\t\t\t\t\t\tif (expression) {\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Reset internal state (e.g., after document switch).\n\t */\n\tclear(): void {\n\t\tthis.pageAccess.clear();\n\t\tthis.accessSeq = 0;\n\t\tthis.lastViewportStart = null;\n\t\tthis.savedDirection = null;\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/** Record a page access with a monotonic sequence number. */\n\tprivate touchPage(pageNum: number): void {\n\t\tthis.pageAccess.set(pageNum, ++this.accessSeq);\n\t}\n\n\t/**\n\t * Evict results from all non-variable-def lines in a page.\n\t * Bytecode is preserved so Tier 2 execution works on scroll-back.\n\t */\n\tprivate evictPageResults(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (state && !state.isVariableDef && state.results.length > 0) {\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evict bytecode + results from all non-variable-def lines in a page.\n\t * Variable definition bytecode is **never** evicted, it forms the\n\t * backbone of the DAG and VM checkpoints.\n\t *\n\t * Evicted lines are marked dirty so they get Tier 1 re-evaluation\n\t * when scrolled back into view.\n\t */\n\tprivate evictPageBytecode(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (!state || state.isVariableDef) continue;\n\n\t\t\tif (state.bytecodes.length > 0 || state.results.length > 0) {\n\t\t\t\tstate.bytecodes = [];\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t\tdoc.markDirty(state.lineId);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport {\n\tDocumentModel,\n\tLineChange,\n\tLineState,\n\tViewportRange,\n} from \"@solve-js/engine/DocumentModel\";\nimport { Value, ValueType, enableValueArena, disableValueArena, errorValue, persistentValue, isArenaActive } from \"@solve-js/vm/Value\";\nimport { DependencyGraph } from \"@solve-js/vm/DependencyGraph\";\nimport { VMCheckpointer } from \"@solve-js/vm/VMCheckpoints\";\nimport { isEmptyLine } from \"@solve-js/engine/ExpressionEngineSafety\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\nimport { CompilationWorkerManager, type CompileRequestItem } from \"@solve-js/engine/CompilationWorkerManager\";\nimport { PageManager } from \"@solve-js/engine/PageManager\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { withTagEdges } from \"@solve-js/packages/tags/TagScanner\";\nimport { sharedGlobalVariableStore, globalDagKey } from \"@solve-js/vm/GlobalVariableStore\";\n\n// ── EvalTier (diagnostic enum) ──────────────────────────────────────────\n\n/**\n * How much work a line's evaluation required.\n *\n * The tiers exist because most lines in a document have not changed. A line\n * that is clean and cached costs far less than one being compiled fresh, and\n * knowing which happened is how a slow document gets diagnosed.\n */\nexport enum EvalTier {\n\t/** Full pipeline: Lex → Parse → Compile → Execute (visible + dirty). */\n\tTier1 = 1,\n\t/** Execute-only from cached bytecode (visible + cached). */\n\tTier2 = 2,\n\t/** Compile-only for dependency tracking (invisible). Executes only variable assignments. */\n\tTier3 = 3,\n\t/** Skipped, already clean or non-evaluable. */\n\tSkipped = 0,\n}\n\n// ── EvalLineResult ──────────────────────────────────────────────────────\n\n/** Outcome for one line, including which tier handled it. */\nexport interface EvalLineResult {\n\t/** The line's persistent ID from DocumentModel. */\n\tlineId: number;\n\t/** 1-based line position. */\n\tlineNumber: number;\n\t/** Which tier was used. */\n\ttier: EvalTier;\n\t/** The first evaluation result, or null on error / non-evaluable. */\n\tresult: Value | null;\n\t/** All result groups (one per expression/inline-solve), or undefined if skipped. */\n\tresults?: Value[][];\n\t/** Error message, or null. */\n\terror: string | null;\n}\n\n// ── EvalResult ──────────────────────────────────────────────────────────\n\n/** Outcome for a whole evaluation pass, with per-tier counts. */\nexport interface EvalResult {\n\t/** Per-line evaluation results. */\n\tlines: EvalLineResult[];\n\t/** Map of line numbers → flattened results for quick lookup. */\n\tresultMap: Map<number, Value[]>;\n\t/** Number of lines processed at each tier. */\n\ttierCounts: { tier1: number; tier2: number; tier3: number; skipped: number };\n}\n\n// ── ThreeTierEvaluator ──────────────────────────────────────────────────\n\n/**\n * Orchestrates three-tier evaluation over a persistent DocumentModel.\n *\n * ── Tier assignment ─────────────────────────────────────────────────\n * | Tier | Condition | Action |\n * |───────|────────────────────────────────────|───────────────────────────────|\n * | **1** | Visible + Dirty (new/changed) | Full pipeline: lex→parse→compile→execute |\n * | **2** | Visible + Cached (scroll into view)| Execute from cached bytecode |\n * | **3** | Invisible + Dirty | Compile-only; execute only variable defs |\n * | Skip | Clean, empty, or non-evaluable | No action |\n *\n * ── Evaluation order ─────────────────────────────────────────────────\n * Lines are always processed in ascending document order (line 1 → end)\n * so that variable assignments flow correctly through the shared VM.\n * Tier 2 relies on this: by the time a clean cached line is reached,\n * the VM already contains all variables from preceding Tier-1 lines.\n *\n * ── Thread safety ────────────────────────────────────────────────────\n * Tier 1 (visible+dirty) compilation runs synchronously on the main thread\n * for immediate rendering. Tier 3 (invisible+dirty) compilation can be\n * dispatched to a Web Worker via `dispatchBackgroundCompiles()`. Worker-\n * compiled bytecode is stored in the DocumentModel and validated via\n * `isBytecodeValid()` to ensure the line text hasn't changed between\n * dispatch and response.\n */\nexport class ThreeTierEvaluator {\n\tprivate doc: DocumentModel;\n\tprivate engine: ExpressionEngine;\n\tprivate dag: DependencyGraph;\n\tprivate checkpointer: VMCheckpointer | null;\n\tprivate compilationWorker: CompilationWorkerManager | null = null;\n\tprivate pageManager: PageManager;\n\n\t/**\n\t * Unsubscribe from sharedGlobalVariableStore, set in the constructor\n\t * called from terminateWorker(). See the subscription itself below for\n\t * why this only marks lines dirty and never re-evaluates synchronously.\n\t */\n\tprivate globalUnsubscribe: (() => void) | null = null;\n\n\t/**\n\t * @param doc The persistent document model.\n\t * @param engine The expression engine (shared VM is accessed via engine.getVM()).\n\t * @param checkpointer Optional VM state checkpointer. If provided, the evaluator\n\t * will create checkpoints after variable-definition lines and support fast VM\n\t * restoration via `restoreTo()`. If omitted, checkpointing is disabled.\n\t */\n\tconstructor(\n\t\tdoc: DocumentModel,\n\t\tengine: ExpressionEngine,\n\t\tcheckpointer?: VMCheckpointer\n\t) {\n\t\tthis.doc = doc;\n\t\tthis.engine = engine;\n\t\tthis.dag = engine.getDag();\n\t\tthis.checkpointer = checkpointer ?? null;\n\t\tthis.pageManager = new PageManager();\n\n\t\t// Lets the engine answer \"what's line N's cached result\" for\n\t\t// cross-line features (prev/line<N>/aggregation) without owning\n\t\t// document lifecycle itself. See ExpressionEngine.makeLineContext().\n\t\tthis.engine.setDocumentModel(this.doc);\n\n\t\t// ── Cross-document global-variable propagation ──────────────────\n\t\t// GlobalVariableAsyncResolver (via preflight) handles a line's FIRST\n\t\t// resolution when a global it reads wasn't known yet. This handles\n\t\t// the ONGOING case: a line that already has a real (non-pending)\n\t\t// value for `global :x` needs to go dirty again when some OTHER\n\t\t// document writes a NEW value to x, so this document's next\n\t\t// evaluate() picks up the change, \"dealing with the DAG across\n\t\t// pages\", not just first-resolution.\n\t\tthis.globalUnsubscribe = sharedGlobalVariableStore.subscribe((name) => {\n\t\t\t// Mark-dirty ONLY, never synchronously re-evaluate here.\n\t\t\t// enableValueArena/disableValueArena (Value.ts) is a single\n\t\t\t// non-reentrant module-level flag; evaluate()/setViewport() both\n\t\t\t// wrap their body in it, so a re-entrant evaluate() call from\n\t\t\t// inside this callback (itself possibly firing from INSIDE\n\t\t\t// another evaluate() call, via a STORE_GLOBAL_VAR opcode in some\n\t\t\t// other document being evaluated concurrently) would disable the\n\t\t\t// arena out from under the still-running outer call. This\n\t\t\t// mirrors applyTransaction()'s existing contract exactly: mark\n\t\t\t// dirty, let the caller's own evaluate() cadence pick it up.\n\t\t\tfor (const lineNumber of this.dag.getAffectedLines(globalDagKey(name))) {\n\t\t\t\tthis.doc.markDirtyByLineNumber(lineNumber);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Evaluate all lines needed to render the given viewport.\n\t *\n\t * Processes lines from 1 to `viewport.endLine` in document order.\n\t * Dirty lines in the viewport get Tier-1 full pipeline; clean cached\n\t * lines get Tier-2 bytecode execution. Lines after the viewport\n\t * get Tier-3 compile-only (with variable-def execution).\n\t *\n\t * @returns Results for all processed lines, including tier metadata.\n\t */\n\tevaluate(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine so that\n\t\t// all per-evaluation AbortControllers created during this call\n\t\t// are canceled when the user types a new keystroke.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Value reuse ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// Re-seed running-total accumulators before the from-line-1 pass. A\n\t\t\t// `total += 5` line reads its own running value, so re-running it in\n\t\t\t// place would read the previous evaluation's total and double-count.\n\t\t\t// Reset each accumulator variable and mark every line that touches\n\t\t\t// it dirty, so the loop below recomputes the total from its seed,\n\t\t\t// top to bottom. (No-op when the document has no accumulators.)\n\t\t\tthis.reseedAccumulators();\n\n\t\t\tconst lines: EvalLineResult[] = [];\n\t\t\tconst resultMap = new Map<number, Value[]>();\n\t\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\t\t// Process from line 1 to the end of the viewport for correct VM state.\n\t\t\t// We go to viewport.endLine because Tier 3 for invisible lines can be\n\t\t\t// done separately via backgroundCompile().\n\t\t\tconst docEnd = this.doc.lineCount;\n\t\t\tconst evalEnd = Math.min(viewport.endLine, docEnd);\n\n\t\t\t// Walked once, rather than descended into per position. See\n\t\t\t// `DocumentModel.getLineStatesInRange`.\n\t\t\tconst states = this.doc.getLineStatesInRange(1, evalEnd);\n\n\t\t\tfor (let pos = 1; pos <= evalEnd; pos++) {\n\t\t\t\tconst state = states[pos - 1];\n\t\t\t\tif (!state) {\n\t\t\t\t\ttierCounts.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst inViewport = pos >= viewport.startLine && pos <= viewport.endLine;\n\n\t\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, inViewport);\n\t\t\t\tlines.push(lineResult);\n\n\t\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\t\telse tierCounts.skipped++;\n\n\t\t\t\tif (lineResult.results && inViewport) {\n\t\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Phase 5.2g: Page-based LRU eviction ──────────────────────\n\t\t\t// Evict bytecode/results from cold/warm pages to bound memory.\n\t\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t\treturn { lines, resultMap, tierCounts };\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references\n\t\t\t// from being used by subsequent evaluations from other code paths.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents arena Values from leaking into subsequent evaluations or tests.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).\n\t *\n\t * Compiles expressions to discover reads/writes for the dependency graph\n\t * without executing display-only expressions. Variable definitions are\n\t * executed to maintain VM state for future Tier-2 executions.\n\t *\n\t * This is intended to be called after evaluate() so visible lines are\n\t * rendered first, then background work fills in the dependency graph.\n\t *\n\t * **Phase 5.2h:** This synchronous method is retained for environments\n\t * without Worker support. Prefer `dispatchBackgroundCompiles()` which\n\t * offloads compilation to a Web Worker with Transferable bytecode.\n\t */\n\tbackgroundCompile(viewport: ViewportRange): EvalLineResult[] {\n\t\tconst results: EvalLineResult[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines, already compiled + executed\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled Tier 3 lines, they have bytecode\n\t\t\t// but were compiled without execution (non-variable-def).\n\t\t\t// Recompiling is wasteful since the text hasn't changed\n\t\t\t// (text change clears bytecodes via editLine).\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, false);\n\t\t\tresults.push(lineResult);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Dispatch background compilation to a Web Worker (Phase 5.2h).\n\t *\n\t * Collects invisible dirty lines beyond the viewport that need compilation,\n\t * sends them to the compilation worker, and asynchronously stores the\n\t * transferred bytecode in the DocumentModel when the worker responds.\n\t *\n\t * This is the non-blocking alternative to `backgroundCompile()`. The worker\n\t * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),\n\t * so bytecode appears on the main thread without serialization overhead.\n\t *\n\t * Lines that already have cached bytecode (from a previous worker pass or\n\t * synchronous compile) are skipped, only truly uncompiled dirty lines are\n\t * sent to the worker.\n\t *\n\t * **Usage:** Call after `evaluate()` so visible lines render first, then\n\t * this fills the bytecode cache for future Tier-2 scrolls.\n\t *\n\t * @param viewport The current visible range. Lines beyond viewport.endLine\n\t * that are dirty and don't have bytecode are dispatched.\n\t */\n\tdispatchBackgroundCompiles(viewport: ViewportRange): void {\n\t\t// Collect invisible dirty lines that need compilation\n\t\tconst items = this.collectInvisibleCompileTargets(viewport);\n\t\tif (items.length === 0) return;\n\n\t\t// Lazy-init the worker (only if there are items to compile)\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: send to worker, store results when they arrive\n\t\tthis.compilationWorker.compileBatch(items).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Worker failure is non-fatal, next evaluate() will compile\n\t\t\t// these expressions synchronously.\n\t\t});\n\t}\n\n\t/**\n\t * Terminate the compilation worker if active, and unsubscribe from\n\t * sharedGlobalVariableStore. Call this when the evaluator is no longer\n\t * needed to clean up resources, every call site that retires a\n\t * ThreeTierEvaluator (document switch, pane destroy()) already calls\n\t * this unconditionally, so folding the global-store unsubscribe in here\n\t * needs no new call sites anywhere.\n\t */\n\tterminateWorker(): void {\n\t\tif (this.compilationWorker) {\n\t\t\tthis.compilationWorker.terminate();\n\t\t\tthis.compilationWorker = null;\n\t\t}\n\t\tif (this.globalUnsubscribe) {\n\t\t\tthis.globalUnsubscribe();\n\t\t\tthis.globalUnsubscribe = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DocumentModel (read-only access for decoration building).\n\t */\n\tgetDoc(): DocumentModel {\n\t\treturn this.doc;\n\t}\n\n\t/**\n\t * Evaluate all dirty lines in the document, regardless of viewport.\n\t * Used for full re-evaluation after plugin register/unregister.\n\t */\n\tevaluateAll(signal?: AbortSignal): EvalResult {\n\t\tconst viewport = { startLine: 1, endLine: this.doc.lineCount };\n\t\tconst result = this.evaluate(viewport, signal);\n\t\t// evaluate() already calls maintainAfterEval internally\n\t\treturn result;\n\t}\n\n\t/**\n\t * Zero-allocation viewport evaluation, the Phase 5.2e \"holy grail.\"\n\t *\n\t * **Key insight:** When the user scrolls (viewport-only change, no edits),\n\t * we don't need to re-evaluate from line 1. Instead:\n\t *\n\t * 1. Restore the VM to just before the viewport via the nearest checkpoint.\n\t * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).\n\t * 3. Lines before the viewport are completely skipped, their state lives in\n\t * the VM checkpointer's prototypal chain.\n\t *\n\t * **Correctness guard:** If any variable-definition line before the viewport\n\t * is dirty (e.g., the user edited a variable def that hasn't been\n\t * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`\n\t * which processes from line 1 and rebuilds fresh checkpoints. This\n\t * guarantees that stale checkpoints are never used as restoration targets.\n\t * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only\n\t * records state for lines that write a variable, so a dirty plain-expression\n\t * line before the viewport has no checkpoint to invalidate (see\n\t * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).\n\t *\n\t * **Performance:** O(visible lines) instead of O(document length). Target:\n\t * < 1ms for a typical ~30-line viewport, independent of document size.\n\t *\n\t * @param viewport The visible line range.\n\t * @returns Results for visible lines only. Lines before the viewport are\n\t * not included in `lines[]` or `resultMap`.\n\t */\n\tsetViewport(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Correctness guard: dirty lines before viewport invalidate checkpoints ──\n\t\tif (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {\n\t\t\t// Clear stale checkpoints, evaluate() will rebuild them from line 1.\n\t\t\t// evaluate() handles its own arena enable/disable and signal cleanup.\n\t\t\tthis.checkpointer?.clear();\n\t\t\treturn this.evaluate(viewport, signal);\n\t\t}\n\n\t\t// ── Phase 5.2g: Page-based LRU eviction (MUST run before preload) ──\n\t\t// maintainAfterEval captures the scroll direction and updates lastViewportStart\n\t\t// BEFORE preloadNextPages reads the direction for preloading.\n\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t// ── Phase 5.2g: Detect scroll direction & preload ───────────\n\t\tthis.preloadNextPages(viewport);\n\n\t\t// ── Restore VM state from nearest checkpoint before the viewport ──\n\t\t// This sets all variables that were defined at or before startLine-1.\n\t\tthis.restoreTo(viewport.startLine - 1);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Tier 2 execution ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// ── Evaluate only visible lines ──\n\t\t\tconst result = this.collectEvalResults(viewport.startLine, viewport.endLine);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents cross-test contamination from arena leaks.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Apply incremental line-level changes to the document model.\n\t *\n\t * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation\n\t * with O(changed) incremental updates. Key benefits:\n\t *\n\t * 1. Unchanged lines retain their persistent lineIds → bytecode survives\n\t * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation\n\t * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)\n\t * 4. Clean lines outside viewport are skipped entirely\n\t *\n\t * The DAG is fully cleared after propagation: shifted lines would have\n\t * stale entries keyed by old line numbers, so the DAG is rebuilt from\n\t * scratch during the subsequent `evaluate()` call.\n\t *\n\t * **Caller should follow up with `evaluate(viewport)`** to re-evaluate\n\t * dirty lines from line 1 and rebuild the DAG + checkpoints.\n\t *\n\t * @param changes Line-level changes to apply. Must be non-overlapping.\n\t * @returns Metadata about the applied changes.\n\t */\n\tapplyTransaction(changes: LineChange[]): {\n\t\tinserted: number[];\n\t\tremoved: number[];\n\t} {\n\t\t// ── Phase 1: Collect DAG writes + downstream lineIds ───────────\n\t\t// Must happen BEFORE applyChanges() because line numbers are still\n\t\t// valid at this point. We collect writes from deleted lines and\n\t\t// resolve downstream consumers to lineIds (not line numbers) so\n\t\t// they survive the position shifts that applyChanges() causes.\n\t\tconst allWrites = new Set<string>();\n\n\t\tfor (const change of changes) {\n\t\t\tfor (let i = 0; i < change.deleteCount; i++) {\n\t\t\t\tconst lineNum = change.startLine + i;\n\t\t\t\tconst writes = this.dag.getWrites(lineNum);\n\t\t\t\tfor (const w of writes) {\n\t\t\t\t\tallWrites.add(w);\n\t\t\t\t}\n\t\t\t\t// Clean up DAG references for this line\n\t\t\t\tthis.dag.removeLine(lineNum);\n\t\t\t\t// And its cached bytecode. The dependency graph was already\n\t\t\t\t// pruned here; the LineCache was not, so a deleted line kept its\n\t\t\t\t// entry until the whole cache was dropped on a document switch.\n\t\t\t\t// Editing a long document over a session accumulated entries for\n\t\t\t\t// line numbers that no longer existed.\n\t\t\t\tthis.engine.getLineCache().removeAllForLine(lineNum);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve downstream consumers to persistent lineIds BEFORE the\n\t\t// structural change shifts line numbers. After applyChanges(),\n\t\t// we mark these lineIds dirty, their positions don't matter.\n\t\tconst downstreamLineIds = new Set<number>();\n\t\tfor (const writeVar of allWrites) {\n\t\t\tconst affected = this.dag.getAffectedLines(writeVar);\n\t\t\tfor (const lineNum of affected) {\n\t\t\t\tconst state = this.doc.getLineAt(lineNum);\n\t\t\t\tif (state) {\n\t\t\t\t\tdownstreamLineIds.add(state.lineId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// ── Phase 2: Apply structural changes to DocumentModel ─────────\n\t\tconst result = this.doc.applyChanges(changes);\n\n\t\t// ── Phase 3: Clear checkpointer (line numbers shifted) ─────────\n\t\tthis.checkpointer?.clear();\n\n\t\t// ── Phase 4: Mark DAG-downstream lines dirty by lineId ─────────\n\t\t// Using lineId instead of line number is position-agnostic:\n\t\t// lines that shifted due to insertions/deletions above them are\n\t\t// still correctly targeted. Lines that were deleted (lineId no\n\t\t// longer in the doc) are silently ignored by markDirty().\n\t\tfor (const lineId of downstreamLineIds) {\n\t\t\tthis.doc.markDirty(lineId);\n\t\t}\n\n\t\t// ── Phase 5: Clear DAG to avoid phantom entries ────────────────\n\t\t// Entries keyed by old line numbers are stale after structural\n\t\t// changes. Rather than updating shifted entries, we clear the DAG\n\t\t// and let the subsequent evaluate() call rebuild it from scratch.\n\t\tthis.dag.clear();\n\n\t\treturn {\n\t\t\tinserted: result.inserted,\n\t\t\tremoved: result.removed,\n\t\t};\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/**\n\t * Reset running-total accumulators and mark the lines that touch them\n\t * dirty, so the from-line-1 pass in {@link evaluate} recomputes each total\n\t * from its seed instead of reading its own previous evaluation's value.\n\t *\n\t * A `total += 5` line compiles to no bytecode (it rides the symbolic\n\t * channel), so a clean one would be skipped by the tier dispatch rather\n\t * than re-run. It must re-run to re-apply its delta over the freshly-reset\n\t * base, so every line that WRITES an accumulator name is forced dirty (the\n\t * DAG drops a self-writing line from its own variable's consumers, so\n\t * getAffectedLines can't surface them). Pure readers of the total keep\n\t * their real bytecode and re-run via Tier 2 once the total is correct, so\n\t * they need no special handling. Cheap: a no-op unless the document\n\t * actually uses `+=`/`-=`, and accumulators are rare.\n\t */\n\tprivate reseedAccumulators(): void {\n\t\tconst names = this.engine.resetAccumulators();\n\t\tif (names.size === 0) return;\n\t\tconst docEnd = this.doc.lineCount;\n\t\tfor (let pos = 1; pos <= docEnd; pos++) {\n\t\t\tconst writes = this.dag.getWrites(pos);\n\t\t\tif (writes.size === 0) continue;\n\t\t\tfor (const w of writes) {\n\t\t\t\tif (names.has(w)) {\n\t\t\t\t\tthis.doc.markDirtyByLineNumber(pos);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Collect evaluation results for a contiguous range of lines.\n\t *\n\t * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).\n\t * All lines in the range are treated as in-viewport (visible), callers that\n\t * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.\n\t *\n\t * @param startLine First line to evaluate (1-based, inclusive).\n\t * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.\n\t */\n\tprivate collectEvalResults(startLine: number, endLine: number): EvalResult {\n\t\tconst lines: EvalLineResult[] = [];\n\t\tconst resultMap = new Map<number, Value[]>();\n\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst evalEnd = Math.min(endLine, docEnd);\n\n\t\tfor (let pos = startLine; pos <= evalEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// All processed lines are in-viewport for setViewport, or conditionally\n\t\t\t// in-viewport for evaluate (handled by caller). We pass `true` here\n\t\t\t// because evaluateSingleLine's `inViewport` param controls Tier 1 vs\n\t\t\t// Tier 3 dispatch; callers must manage this distinction externally.\n\t\t\t//\n\t\t\t// evaluate() handles this by passing `inViewport` per-line; it loops\n\t\t\t// directly rather than using this helper for that reason.\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, true);\n\t\t\tlines.push(lineResult);\n\n\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\telse tierCounts.skipped++;\n\n\t\t\tif (lineResult.results) {\n\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t}\n\t\t}\n\n\t\treturn { lines, resultMap, tierCounts };\n\t}\n\n\t/**\n\t * Check whether any **variable-definition** line before `position`\n\t * (1-based, exclusive) is dirty.\n\t *\n\t * Used by `setViewport()` to decide whether to fall back to `evaluate()`:\n\t * if a variable-def before the viewport is dirty, the checkpoint state\n\t * `restoreTo()` would use may be stale and we need to reprocess from\n\t * line 1 to rebuild checkpoints correctly.\n\t *\n\t * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:\n\t * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a\n\t * dirty plain-expression line before the viewport can't have invalidated\n\t * one, there's nothing checkpointed for it to invalidate. Using the\n\t * broader check here previously caused a real perf bug: `PageManager`'s\n\t * cold-page eviction marks evicted non-variable-def lines dirty, so\n\t * scrolling far into a large, variable-def-free document would trip this\n\t * guard, fall back to `evaluate()`, which recompiles those lines via\n\t * Tier 3 (never clearing their dirty flag by design), causing the very\n\t * next `maintainAfterEval()` to re-evict and re-dirty them, a\n\t * self-sustaining loop that pinned every subsequent `setViewport()` call\n\t * to the cost of a full re-evaluation instead of O(visible lines).\n\t *\n\t * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which\n\t * tracks dirty lineIds incrementally instead of scanning every line up to\n\t * `position` on every call. This used to be a real per-scroll cost\n\t * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)\n\t * since it fired on every viewport change, not just edits.\n\t */\n\tprivate hasDirtyLinesBefore(position: number): boolean {\n\t\treturn this.doc.hasAnyDirtyVariableDefLineBefore(position);\n\t}\n\n\t/**\n\t * Evaluate a single line using the appropriate tier.\n\t *\n\t * Tier assignment logic:\n\t * - Empty/markdown-only lines → skipped\n\t * - Dirty + in-viewport → Tier 1 (full pipeline)\n\t * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)\n\t * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)\n\t * - Clean + no bytecode → skipped (non-evaluable)\n\t */\n\tprivate evaluateSingleLine(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tinViewport: boolean\n\t): EvalLineResult {\n\t\tconst baseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\"> = {\n\t\t\tlineId: state.lineId,\n\t\t\tlineNumber,\n\t\t};\n\n\t\t// A clean line outside the viewport has nothing to do, and nothing has\n\t\t// to be worked out in order to know that.\n\t\t//\n\t\t// It is the last case the dispatch below reaches, so it used to arrive\n\t\t// there having paid for an emptiness scan of its text and an expression\n\t\t// extraction, neither of which can change the answer: the line is not\n\t\t// dirty, so it is not compiled, and it is not visible, so it is not\n\t\t// executed. A pass runs from line 1 to the end of the viewport, so on a\n\t\t// long document scrolled to the bottom almost every line took that\n\t\t// route, and an edit cost the distance from line 1 rather than the size\n\t\t// of the viewport.\n\t\t//\n\t\t// The two paths below this also mark an empty line clean and record\n\t\t// that it is empty. Both are already true of a line that is clean: it\n\t\t// has been through here before, on the pass that cleaned it.\n\t\tif (!state.dirty && !inViewport) {\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Skip empty/markdown-only lines\n\t\tif (state.isEmpty || isEmptyLine(state.text)) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Extract all evaluable expressions (may be multiple inline solves)\n\t\tconst { expressions, inlineSolveCount } = this.extractExpressions(state);\n\t\tif (expressions.length === 0) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Determine the expression to evaluate (only needed for dirty lines)\n\t\tif (state.dirty) {\n\t\t\tif (inViewport) {\n\t\t\t\t// ── Tier 1: Visible + Dirty → Full Pipeline ──────────\n\t\t\t\treturn this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t} else {\n\t\t\t\t// ── Tier 3: Invisible + Dirty → Compile-only ─────────\n\t\t\t\t// Skip recompilation if already compiled by a previous Tier 3 pass.\n\t\t\t\t// Non-variable-def lines keep dirty=true after Tier 3 (so they get\n\t\t\t\t// Tier 1 when scrolled into view), but recompiling identical text\n\t\t\t\t// produces the same bytecode and DAG entries. Text changes clear\n\t\t\t\t// bytecodes via DocumentModel.editLine(), so a length check is safe.\n\t\t\t\tif (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {\n\t\t\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t\t\t}\n\t\t\t\treturn this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t}\n\t\t}\n\n\t\t// Line is clean\n\t\tif (inViewport && state.bytecodes.length > 0) {\n\t\t\t// ── Tier 2: Visible + Cached → Execute from bytecode ────\n\t\t\treturn this.evaluateTier2(state, lineNumber, baseResult);\n\t\t}\n\n\t\t// Clean, not in viewport, or no bytecode → skip\n\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t}\n\n\t/**\n\t * Register a line's edges, with the groups its text joins and asks about.\n\t *\n\t * The evaluator registers from three places and the engine from two, and a\n\t * line registered twice with different edge sets loses whichever went first.\n\t * They all route through the same helper so the sets cannot disagree.\n\t */\n\tprivate registerWithTags(lineNumber: number, reads: string[], writes: string[]): void {\n\t\tconst text = this.doc.getLineAt(lineNumber)?.text ?? \"\";\n\t\tconst edges = withTagEdges(text, reads, writes);\n\t\tthis.dag.registerLine(lineNumber, edges.reads, edges.writes);\n\t}\n\n\t/**\n\t * Tier 1: Full pipeline, lex, parse, compile, execute.\n\t * Uses the engine's existing evaluateLine() which handles all pipeline\n\t * stages including DAG updates and LineCache population.\n\t *\n\t * Supports multiple expressions per line (inline solves). Evaluates each\n\t * expression left-to-right through the engine so variable definitions in\n\t * earlier solves update the VM state before later solves are evaluated.\n\t * Reads/writes are aggregated across all expressions for the DAG.\n\t */\n\tprivate evaluateTier1(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allResults: Value[][] = [];\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when any expression returned a value still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Evaluate each expression independently, a failure in one expression\n\t\t// (e.g., parse error in s`bad syntax`) must not prevent other expressions\n\t\t// on the same line from being evaluated and having their results stored.\n\t\t// Without per-expression error handling, same-line cross-reference inline\n\t\t// solves (s`:a = 5` s`:b = a + 3` s`a + b`) would lose ALL results when\n\t\t// the third expression throws because 'b' references cross a VM state\n\t\t// boundary or the engine encounters a transient error.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\tlet value: Value[] | null = null;\n\t\t\tlet entry: { bytecode: BytecodeProgram; readVariables: string[]; writeVariable: string | null } | undefined;\n\n\t\t\ttry {\n\t\t\t\t// evaluateLine returns the single evaluated Value; this evaluator\n\t\t\t\t// keeps its results grouped as Value[] per expression (allResults\n\t\t\t\t// is Value[][]), so wrap the one value into its group here.\n\t\t\t\tconst evaluated = this.engine.evaluateLine(lineNumber, expression);\n\t\t\t\tvalue = [evaluated];\n\t\t\t\tlastValue = evaluated;\n\t\t\t\t// Sync the DocumentModel from the LineCache.\n\t\t\t\t// Use get(lineNumber, expression) instead of getEntryForLine(lineNumber)\n\t\t\t\t// because multiple expressions on the same line share the same lineNumber\n\t\t\t\t// and getEntryForLine always returns the FIRST entry (Map insertion order).\n\t\t\t\tentry = this.engine.getLineCache().get(lineNumber, expression) as typeof entry;\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\tvalue = null;\n\t\t\t}\n\n\t\t\t// An unresolved async value does not throw, so `anyFailed` alone would\n\t\t\t// let this line be marked clean while its data has not arrived. Once\n\t\t\t// clean, nothing re-runs the resolver preflight and the value stays\n\t\t\t// pending for good. Treat it as not-yet-complete instead.\n\t\t\tif (value && value.some((v) => v.type === ValueType.Pending)) {\n\t\t\t\tanyPending = true;\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tallResults.push(value);\n\t\t\t} else {\n\t\t\t\t// Expression failed, push an ErrorValue sentinel so results[] stays\n\t\t\t\t// aligned with expressions[] and bytecodes[] indices. Downstream code\n\t\t\t\t// checking result.type === Error will find it, vs a raw null that NPEs.\n\t\t\t\tallResults.push([errorValue(\"eval_failed\", firstError ?? \"unknown error\")]);\n\t\t\t}\n\n\t\t\tif (entry) {\n\t\t\t\tallBytecodes.push(entry.bytecode);\n\t\t\t\tfor (const r of entry.readVariables) allReads.add(r);\n\t\t\t\tif (entry.writeVariable) {\n\t\t\t\t\tallWrites.add(entry.writeVariable);\n\t\t\t\t\thasVariableDef = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: LineCache missed, compile expression ourselves\n\t\t\t\ttry {\n\t\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\t\tallBytecodes.push(program);\n\t\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\t\t\t\t} catch (compileErr) {\n\t\t\t\t\t// Push empty bytecode, expression will recompile on next pass.\n\t\t\t\t\t// The expression still failed to compile, but reads/writes were\n\t\t\t\t\t// already extracted from its tokens before the parse attempt\n\t\t\t\t\t// compileExpression() surfaces them via the thrown error's\n\t\t\t\t\t// context. Register them anyway so the DAG knows this line\n\t\t\t\t\t// depends on those variables and re-evaluates it once they\n\t\t\t\t\t// become defined, instead of losing the dependency entirely.\n\t\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t\t\tif (compileErr instanceof EngineError && compileErr.context) {\n\t\t\t\t\t\tconst errReads = compileErr.context.reads;\n\t\t\t\t\t\tconst errWrites = compileErr.context.writes;\n\t\t\t\t\t\tif (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);\n\t\t\t\t\t\tif (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Always store results, even partial ones. If any expression failed\n\t\t// the line stays dirty so the failed expression(s) get retried on the\n\t\t// next evaluation pass. But successfully-evaluated expressions' results\n\t\t// are preserved so the DAG, UI decorations, and downstream consumers\n\t\t// can use them immediately.\n\t\tif (anyFailed || anyPending) {\n\t\t\t// Store partial results via updateLineCompiled (doesn't clear dirty).\n\t\t\t// The successful expressions' bytecodes are cached so Tier 2 works\n\t\t\t// for them on the next scroll pass.\n\t\t\tthis.doc.updateLineCompiled(\n\t\t\t\tstate.lineId,\n\t\t\t\texpressions,\n\t\t\t\tallBytecodes,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\t// Also set results for the successful expressions\n\t\t\tstate.results = allResults;\n\t\t\tstate.result = allResults[0]?.[0] ?? null;\n\t\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t\tstate.expressions = expressions;\n\t\t} else {\n\t\t\t// All expressions succeeded, store full results and mark clean\n\t\t\tthis.doc.updateLineResult(\n\t\t\t\tstate.lineId,\n\t\t\t\tallResults,\n\t\t\t\tallBytecodes,\n\t\t\t\texpressions,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t}\n\n\t\t// Register reads/writes in DAG (aggregated across all expressions).\n\t\t// Always register, even lines with no reads/writes (pure expressions\n\t\t// like \"2+2\") need DAG entries so downstream queries for line presence work.\n\t\tthis.registerWithTags(lineNumber, reads, writes);\n\n\t\t// ── Checkpoint after variable definition ──\n\t\t// A pending value is not a value worth checkpointing: restoring it would\n\t\t// reinstate the unresolved placeholder rather than the eventual result.\n\t\tif (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {\n\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t}\n\n\t\treturn {\n\t\t\t...baseResult,\n\t\t\ttier: EvalTier.Tier1,\n\t\t\tresult: lastValue,\n\t\t\tresults: allResults,\n\t\t\terror: firstError,\n\t\t};\n\t}\n\n\t/**\n\t * Tier 2: Execute from cached bytecode only.\n\t * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode\n\t * against the engine's shared VM. Supports multiple bytecodes per line\n\t * (inline solves), each is executed left-to-right so variable definitions\n\t * in earlier bytecodes update the VM before later ones run.\n\t * Assumes the VM already has correct variable state from preceding\n\t * Tier-1 evaluations.\n\t */\n\tprivate evaluateTier2(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tif (state.bytecodes.length === 0) {\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\tconst results: Value[][] = [];\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\n\t\t// Execute each bytecode independently, a failure in one should not\n\t\t// prevent other bytecodes on the same line from executing. Same-line\n\t\t// inline solves with variable definitions (s`:a = 5` s`a + 3`) rely\n\t\t// on earlier bytecodes updating the VM before later ones execute.\n\t\tfor (const bytecode of state.bytecodes) {\n\t\t\tif (bytecode.opcodes.length === 0) continue;\n\t\t\ttry {\n\t\t\t\tconst value = this.engine.executeCached(bytecode, lineNumber);\n\t\t\t\tlastValue = value;\n\t\t\t\tresults.push([value]);\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push error sentinel to maintain results[i] ↔ bytecodes[i] alignment\n\t\t\t\tresults.push([errorValue(\"exec_failed\", errorMessage)]);\n\t\t\t}\n\t\t}\n\n\t\t// Update DAG: re-register reads/writes from the cached metadata.\n\t\t// Always register, even empty reads/writes so DAG line-presence queries work.\n\t\tthis.registerWithTags(lineNumber, state.reads, state.writes);\n\n\t\t// A line that ran nothing keeps the result it already had.\n\t\t//\n\t\t// Some expressions compile to a program with no opcodes: a unit\n\t\t// definition (`1 sprint = 2 weeks`) and an equation stored for later\n\t\t// (`y + 3 = 10`) both do their work while being compiled, and have\n\t\t// nothing left to execute. The loop above skips those programs, so\n\t\t// `results` comes back empty, and assigning it unconditionally replaced\n\t\t// the answer Tier 1 had computed with nothing. The line showed\n\t\t// `sprint defined` on the pass that compiled it and went blank on the\n\t\t// next one, with the document untouched, because a live document is\n\t\t// evaluated again and again rather than once.\n\t\t//\n\t\t// Executing nothing produces no new result, which is not the same as\n\t\t// producing an empty one.\n\t\tif (results.length > 0) {\n\t\t\tstate.results = results;\n\t\t\tstate.result = results[0][0] ?? null;\n\t\t} else if (state.result !== null && isArenaActive()) {\n\t\t\t// Kept by value, not by reference.\n\t\t\t//\n\t\t\t// A pass runs with the Value arena on, and a result that never came\n\t\t\t// back through the VM's HALT is arena-owned: nothing cloned it on\n\t\t\t// the way out, because the program had no opcodes to return from.\n\t\t\t// Holding that object means holding a slot the arena hands to a\n\t\t\t// later line, and the line's own answer is then overwritten in\n\t\t\t// place. `1 sprint = 2 weeks` read `sprint defined` and then, once\n\t\t\t// the line below it had run, read that line's number instead.\n\t\t\t// Every stored result, keeping the line's shape: a line can hold\n\t\t\t// several expressions, and all of them can be definitions.\n\t\t\tstate.results = state.results.map((group) => group.map(persistentValue));\n\t\t\tstate.result = state.results[0]?.[0] ?? persistentValue(state.result);\n\t\t}\n\t\tif (anyFailed) {\n\t\t\t// Mark dirty so failed bytecodes are re-compiled (Tier 1) next pass\n\t\t\tthis.doc.markDirty(state.lineId);\n\t\t}\n\n\t\treturn {\n\t\t\t...baseResult,\n\t\t\ttier: EvalTier.Tier2,\n\t\t\t// The stored result, for the same reason: a caller reading this pass's\n\t\t\t// answer for the line must see what the line says, not the nothing\n\t\t\t// that running no opcodes returned.\n\t\t\tresult: results.length > 0 ? lastValue : state.result,\n\t\t\tresults: results.length > 0 ? results : state.results,\n\t\t\terror: firstError,\n\t\t};\n\t}\n\n\t/**\n\t * Tier 3: Compile-only for invisible lines.\n\t * Lex → Parse → Compile to discover reads/writes for the dependency graph.\n\t * Executes the bytecode ONLY if the line defines a variable (isVariableDef\n\t * or writes.length > 0), because variable assignments affect VM state\n\t * that other lines depend on. Pure expression lines are compiled but NOT\n\t * executed, saving CPU for large documents.\n\t *\n\t * Supports multiple expressions per line (inline solves). Each is compiled\n\t * separately; variable-def expressions are also executed.\n\t */\n\tprivate evaluateTier3(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastResult: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when a result is still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Compile each expression independently, a parse error in one\n\t\t// should not prevent other expressions from being compiled and\n\t\t// having their reads/writes registered in the DAG.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\ttry {\n\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\tallBytecodes.push(program);\n\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\n\t\t\t\tif (writes.length > 0 && program.opcodes.length > 0) {\n\t\t\t\t\t// Variable definitions MUST execute to maintain VM state\n\t\t\t\t\tlastResult = this.engine.executeCached(program, lineNumber);\n\t\t\t\t\t// Same reasoning as Tier 1: a pending result does not throw,\n\t\t\t\t\t// and marking the line clean would strand it unresolved.\n\t\t\t\t\tif (lastResult && lastResult.type === ValueType.Pending) {\n\t\t\t\t\t\tanyPending = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push empty bytecode placeholder for alignment\n\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Store compile-only state in DocumentModel, even partial results\n\t\t// preserve successful expressions' bytecodes and DAG data.\n\t\tthis.doc.updateLineCompiled(\n\t\t\tstate.lineId,\n\t\t\texpressions,\n\t\t\tallBytecodes,\n\t\t\treads,\n\t\t\twrites,\n\t\t\thasVariableDef,\n\t\t\tinlineSolveCount,\n\t\t);\n\n\t\t// Register reads/writes in DAG regardless, partial data is valid.\n\t\t// Always register, even empty reads/writes for DAG line-presence queries.\n\t\tthis.registerWithTags(lineNumber, reads, writes);\n\n\t\tif (hasVariableDef && lastResult && !anyFailed && !anyPending) {\n\t\t\tstate.results = [[lastResult]];\n\t\t\tstate.result = lastResult;\n\t\t\tthis.doc.markClean(state.lineId);\n\n\t\t\t// ── Checkpoint after variable definition ────────────\n\t\t\tif (this.checkpointer) {\n\t\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t\t}\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier3, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : undefined, error: firstError };\n\t}\n\n\t// ── Public checkpoint API (used by Phase 5.2e setViewport) ──────\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 at or before `lineNumber` and replays\n\t * all variable definitions from the checkpoint chain into the VM.\n\t * After calling this, the VM is ready to evaluate lines starting at\n\t * `lineNumber + 1` without re-evaluating all preceding lines.\n\t *\n\t * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`\n\t * before evaluating only the newly visible lines. This is the key to\n\t * O(visible lines) scrolling.\n\t *\n\t * @param lineNumber The line number to restore to. Variables defined\n\t * at lines ≤ this number will be available in the VM.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tif (this.checkpointer) {\n\t\t\tthis.checkpointer.restoreTo(lineNumber);\n\t\t}\n\t}\n\n\t/**\n\t * Get the VM checkpointer, or null if checkpointing is disabled.\n\t */\n\tgetCheckpointer(): VMCheckpointer | null {\n\t\treturn this.checkpointer;\n\t}\n\n\t/**\n\t * Get the PageManager (Phase 5.2g).\n\t * Exposed for testing.\n\t */\n\tgetPageManager(): PageManager {\n\t\treturn this.pageManager;\n\t}\n\n\t// ── Phase 5.2g: Directional preloading ──────────────────────────\n\n\t/**\n\t * Preload the next 1–2 pages in the current scroll direction.\n\t *\n\t * Called during `setViewport()` (scroll-only path). Collects dirty\n\t * uncompiled lines in pages just beyond the viewport and dispatches\n\t * them to the background compilation worker so bytecode is ready\n\t * before the user scrolls those lines into view.\n\t */\n\tprivate preloadNextPages(viewport: ViewportRange): void {\n\t\tconst targets = this.pageManager.getPreloadTargets(viewport, this.doc);\n\t\tif (targets.length === 0) return;\n\n\t\t// Lazy-init worker if needed\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: worker compiles, stores bytecode on response\n\t\tthis.compilationWorker.compileBatch(targets).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Non-fatal, next evaluate() will compile synchronously\n\t\t});\n\t}\n\n\t/**\n\t * Collect invisible dirty lines that need background compilation.\n\t *\n\t * Iterates lines beyond `viewport.endLine`, filtering for:\n\t * - Dirty lines (need re-compilation)\n\t * - Non-empty, non-markdown lines\n\t * - No existing bytecode (skip already-compiled Tier 3 lines)\n\t *\n\t * Returns CompileRequestItem[] suitable for CompilationWorkerManager.\n\t */\n\tprivate collectInvisibleCompileTargets(viewport: ViewportRange): CompileRequestItem[] {\n\t\tconst items: CompileRequestItem[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled lines\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\t// Skip empty/markdown-only lines\n\t\t\tif (state.isEmpty || isEmptyLine(state.text)) continue;\n\n\t\t\tconst { expressions } = this.extractExpressions(state);\n\t\t\tif (expressions.length === 0) continue;\n\n\t\t\t// Create one CompileRequestItem per expression (inline solves\n\t\t\t// on the same line share the same lineId + textHash). The worker\n\t\t\t// compiles each independently; storeResults batches by lineId.\n\t\t\tfor (const expression of expressions) {\n\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\titems.push({\n\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\texpression,\n\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Extract all evaluable expressions from a LineState.\n\t *\n\t * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.\n\t * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.\n\t * For pre-extracted (cached) expressions: returns the cached array.\n\t *\n\t * Inline solves are extracted left-to-right via the sharedLexer, so variable\n\t * definitions in earlier solves (e.g., `s\\`x = 5\\` more text s\\`x + 1\\``)\n\t * correctly update the VM state before later solves are evaluated.\n\t */\n\tprivate extractExpressions(state: LineState): { expressions: string[]; inlineSolveCount: number } {\n\t\t// Use pre-extracted expressions if available (from cache / previous evaluation)\n\t\tif (state.expressions.length > 0) {\n\t\t\treturn { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };\n\t\t}\n\n\t\tconst trimmed = state.text.trim();\n\t\tif (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };\n\n\t\t// Check for inline solve syntax: s`expression`\n\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\tif (inlineSpans.length > 0) {\n\t\t\treturn {\n\t\t\t\texpressions: inlineSpans.map(s => s.expression),\n\t\t\t\tinlineSolveCount: inlineSpans.length,\n\t\t\t};\n\t\t}\n\n\t\t// Full-line expression\n\t\treturn { expressions: [trimmed], inlineSolveCount: 0 };\n\t}\n}\n","/**\n * Whole-document evaluation through the incremental engine.\n *\n * The engine has two ways to read a document, and they are not interchangeable.\n * {@link ExpressionEngine.parseDocument} is the light batch pass: it scans the\n * text, reads earlier lines' results, and skips markdown, which is everything\n * line references, category tags and table columns need. What it has no way to\n * do is re-run an earlier line with a variable bound to a trial value, which is\n * exactly what goal seek (`solve line N for x = target`) is, so goal seek comes\n * back as a `GOAL_SEEK_NO_DOCUMENT` error through `parseDocument`.\n *\n * The re-run primitive lives on the incremental `DocumentModel` +\n * `ThreeTierEvaluator` path (a live editor drives it on every keystroke). This\n * helper stands that path up for a single pass and hands back the familiar\n * {@link ParsingResult}, so a caller reads the answers exactly as it would from\n * `parseDocument`, goal seek included. A documentation notepad that wants goal\n * seek to resolve, and the tests that prove those examples, both go through\n * here.\n *\n * Two boundaries, each deliberate:\n *\n * - It builds a fresh model and evaluator per call and disposes the evaluator\n * before returning, which suits occasional evaluation, not the keystroke loop\n * a real editor runs against one long-lived `ThreeTierEvaluator`.\n * - Unlike `parseDocument`, it does not classify a markdown table's own rows as\n * skippable: they reach the evaluator as expressions and error. A document\n * that mixes a raw table with goal seek is the one case that wants both paths,\n * the table read through `parseDocument` and the goal seek through here.\n */\nimport type { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport { ThreeTierEvaluator } from \"@solve-js/engine/ThreeTierEvaluator\";\nimport { findInlineSolvesInLine } from \"@solve-js/engine/ExpressionEngineSafety\";\nimport { Value, ValueType } from \"@solve-js/vm/Value\";\nimport type {\n\tParsedLine,\n\tParsingResult,\n\tUnifiedParsingOptions,\n\tInlineSolvePosition,\n} from \"@solve-js/types/ParsingResult\";\n\n/** Read the human-readable message off an error Value (`unit` holds it, `value` holds the code). */\nfunction errorMessageOf(value: Value): string {\n\treturn typeof value.unit === \"string\" ? value.unit : String(value.value);\n}\n\n/**\n * Evaluate a whole document with full cross-line context, including the line\n * re-runs goal seek needs, and return per-line results in the same shape\n * {@link ExpressionEngine.parseDocument} produces.\n *\n * @param engine - The engine to borrow for the pass. Its current document model\n * (if any) is restored before returning.\n * @param input - The document text, newline-separated.\n * @param _options - Accepted so a call reads the same as `parseDocument`'s, but\n * not consulted: the incremental pass reads the document as markdown regardless.\n */\nexport function evaluateDocument(\n\tengine: ExpressionEngine,\n\tinput: string,\n\t_options: UnifiedParsingOptions = { inputType: \"markdown\" },\n): ParsingResult {\n\tconst previousDocumentModel = engine.getDocumentModel();\n\n\tconst doc = new DocumentModel();\n\tdoc.setDocument(input);\n\t// The constructor wires the model onto the engine (engine.setDocumentModel),\n\t// which is what makeLineContext reads to expose the re-run primitive.\n\tconst evaluator = new ThreeTierEvaluator(doc, engine);\n\n\ttry {\n\t\tconst lineCount = doc.lineCount;\n\t\tevaluator.evaluate({ startLine: 1, endLine: lineCount });\n\n\t\tconst lines: ParsedLine[] = [];\n\t\tconst errors: string[] = [];\n\t\t// Document character offsets are not carried on the line model, so they\n\t\t// are accumulated here to keep startPosition/endPosition faithful to\n\t\t// parseDocument's, one newline between lines.\n\t\tlet offset = 0;\n\n\t\tfor (let n = 1; n <= lineCount; n++) {\n\t\t\tconst state = doc.getLineAt(n)!;\n\t\t\tconst text = state.text;\n\t\t\tconst startPosition = offset;\n\t\t\tconst endPosition = offset + text.length;\n\t\t\toffset = endPosition + 1; // + the newline that separated this line from the next\n\n\t\t\tconst hasInlineSolves = state.inlineSolveCount > 0;\n\t\t\tlet inlineSolves: InlineSolvePosition[] = [];\n\t\t\tlet expression: string | null = null;\n\t\t\tlet result: Value | null = null;\n\n\t\t\tif (state.isEmpty) {\n\t\t\t\t// Prose, a heading, or a blank line: nothing to report.\n\t\t\t} else if (hasInlineSolves) {\n\t\t\t\t// Zip the located spans against the line's per-expression results,\n\t\t\t\t// which the model holds in the same left-to-right order.\n\t\t\t\tinlineSolves = findInlineSolvesInLine(text, n).map((span, i) => {\n\t\t\t\t\tconst value = state.results[i]?.[0] ?? null;\n\t\t\t\t\tif (value && value.type === ValueType.Error) {\n\t\t\t\t\t\tconst message = errorMessageOf(value);\n\t\t\t\t\t\terrors.push(`Line ${n}: ${message}`);\n\t\t\t\t\t\treturn { ...span, result: null, error: message };\n\t\t\t\t\t}\n\t\t\t\t\treturn { ...span, result: value, error: null };\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\texpression = state.expressions[0] ?? null;\n\t\t\t\t// A returned error (goal seek with no document, a faulted\n\t\t\t\t// conversion) stays in `result` as an error-typed Value, exactly\n\t\t\t\t// as parseDocument leaves it, so both document passes report a\n\t\t\t\t// line the same way and a caller can compare them value for\n\t\t\t\t// value. It is also gathered into `errors` for a flat list.\n\t\t\t\tresult = state.result ?? null;\n\t\t\t\tif (result && result.type === ValueType.Error) {\n\t\t\t\t\terrors.push(`Line ${n}: ${errorMessageOf(result)}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlines.push({\n\t\t\t\tlineNumber: n,\n\t\t\t\ttext,\n\t\t\t\tstartPosition,\n\t\t\t\tendPosition,\n\t\t\t\tisEmpty: state.isEmpty,\n\t\t\t\thasInlineSolves,\n\t\t\t\tinlineSolves,\n\t\t\t\texpression,\n\t\t\t\t// Always null: the incremental pass stores a line's failure as an\n\t\t\t\t// error-typed Value in `result` (above), never as a thrown error\n\t\t\t\t// the way parseDocument sets this field. Kept for shape parity.\n\t\t\t\terror: null,\n\t\t\t\tresult,\n\t\t\t});\n\t\t}\n\n\t\treturn { lines, totalLines: lineCount, errors };\n\t} finally {\n\t\t// Drop this pass's evaluator (unsubscribes it from the shared global\n\t\t// store) and put back whatever document the host had wired, so borrowing\n\t\t// the engine for one pass leaves nothing behind.\n\t\tevaluator.terminateWorker();\n\t\tengine.setDocumentModel(previousDocumentModel);\n\t}\n}\n"]}