solve-engine 2.2.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Configuration-B6W0-T67.d.cts → Configuration-BGQn-cJ8.d.cts} +38 -0
- package/dist/{Configuration-B6W0-T67.d.ts → Configuration-BGQn-cJ8.d.ts} +38 -0
- package/dist/FormattingSettings-bRKjU7wI.d.cts +47 -0
- package/dist/FormattingSettings-bRKjU7wI.d.ts +47 -0
- package/dist/{PackageCompatibility-DBsZ0l2a.d.ts → PackageCompatibility-UsSZIfHs.d.ts} +1 -1
- package/dist/{PackageCompatibility-Cv7zjqSV.d.cts → PackageCompatibility-cEClSSkz.d.cts} +1 -1
- package/dist/{PackageRegistry-DRbqNJfI.d.ts → PackageRegistry-B3yJHSxX.d.ts} +24 -1
- package/dist/{PackageRegistry-BSGQ6saH.d.cts → PackageRegistry-BsLmAVZJ.d.cts} +24 -1
- package/dist/{chunk-7NXAZJDB.js → chunk-5R7S5KJJ.js} +3 -3
- package/dist/{chunk-7NXAZJDB.js.map → chunk-5R7S5KJJ.js.map} +1 -1
- package/dist/chunk-6ZNNPXXE.cjs +3 -0
- package/dist/chunk-6ZNNPXXE.cjs.map +1 -0
- package/dist/{chunk-7GK3XEZF.js → chunk-7E7NXKQ5.js} +2 -2
- package/dist/chunk-7E7NXKQ5.js.map +1 -0
- package/dist/chunk-AR7L5OJ2.js +2 -0
- package/dist/chunk-AR7L5OJ2.js.map +1 -0
- package/dist/chunk-B5NBFGNP.js +3 -0
- package/dist/chunk-B5NBFGNP.js.map +1 -0
- package/dist/{chunk-6C6IPUBH.cjs → chunk-E2ZSMJEL.cjs} +3 -3
- package/dist/{chunk-6C6IPUBH.cjs.map → chunk-E2ZSMJEL.cjs.map} +1 -1
- package/dist/chunk-GALZNKW7.js +3 -0
- package/dist/chunk-GALZNKW7.js.map +1 -0
- package/dist/{chunk-ZCNBT44X.cjs → chunk-LNZNJSRW.cjs} +2 -2
- package/dist/chunk-LNZNJSRW.cjs.map +1 -0
- package/dist/chunk-MMT2LS5I.cjs +2 -0
- package/dist/chunk-MMT2LS5I.cjs.map +1 -0
- package/dist/chunk-NAMMTJBE.cjs +3 -0
- package/dist/chunk-NAMMTJBE.cjs.map +1 -0
- package/dist/chunk-NXIMGB4S.cjs +2 -0
- package/dist/chunk-NXIMGB4S.cjs.map +1 -0
- package/dist/chunk-UA3BGOYT.js +5 -0
- package/dist/chunk-UA3BGOYT.js.map +1 -0
- package/dist/chunk-UGQM6ZXU.js +2 -0
- package/dist/chunk-UGQM6ZXU.js.map +1 -0
- package/dist/chunk-WYAY6WPQ.cjs +5 -0
- package/dist/chunk-WYAY6WPQ.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +5 -5
- package/dist/engine.d.ts +5 -5
- package/dist/engine.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +2 -2
- package/dist/format.d.ts +2 -2
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/language.d.cts +3 -3
- package/dist/language.d.ts +3 -3
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +11 -2
- package/dist/packages.d.ts +11 -2
- package/dist/packages.js +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +14 -0
- package/dist/resolvers.d.ts +14 -0
- package/dist/resolvers.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +3 -3
- package/dist/worker.d.ts +3 -3
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/FormattingSettings-CJHyxcYu.d.cts +0 -27
- package/dist/FormattingSettings-CJHyxcYu.d.ts +0 -27
- package/dist/chunk-7BXPCWKM.cjs +0 -2
- package/dist/chunk-7BXPCWKM.cjs.map +0 -1
- package/dist/chunk-7GK3XEZF.js.map +0 -1
- package/dist/chunk-E2Q3PQ2G.js +0 -3
- package/dist/chunk-E2Q3PQ2G.js.map +0 -1
- package/dist/chunk-HLBYHXQD.cjs +0 -3
- package/dist/chunk-HLBYHXQD.cjs.map +0 -1
- package/dist/chunk-J4LZD4ZY.js +0 -3
- package/dist/chunk-J4LZD4ZY.js.map +0 -1
- package/dist/chunk-KVTOV3TZ.js +0 -2
- package/dist/chunk-KVTOV3TZ.js.map +0 -1
- package/dist/chunk-OVKDDTXO.cjs +0 -3
- package/dist/chunk-OVKDDTXO.cjs.map +0 -1
- package/dist/chunk-TN5E6JU6.js +0 -2
- package/dist/chunk-TN5E6JU6.js.map +0 -1
- package/dist/chunk-U2UZJX5W.cjs +0 -5
- package/dist/chunk-U2UZJX5W.cjs.map +0 -1
- package/dist/chunk-X3R7B7XM.cjs +0 -2
- package/dist/chunk-X3R7B7XM.cjs.map +0 -1
- package/dist/chunk-YU3PACLE.js +0 -5
- package/dist/chunk-YU3PACLE.js.map +0 -1
- package/dist/chunk-ZCNBT44X.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$1}from'./chunk-MPB7KUN5.js';var d="2.4.0";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto"},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}};function r(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}}}var c=class{constructor(e={}){this.config=r(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 r(this.config,{})}update(e){this.config=r(this.config,e);}reset(){this.config=r(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,r as c,c as d};//# sourceMappingURL=chunk-UGQM6ZXU.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-UGQM6ZXU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"2CAEE,IAAAA,EAAW,OAAA,CCcN,IAAMC,EAAyBD,ECkV/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,IAChB,cAAA,CAAgB,IAAA,CAChB,cAAe,YAAA,CACf,UAAA,CAAY,MACd,CAAA,CACA,WAAA,CAAa,CAIX,gBAAA,CAAkB,IAalB,gBAAA,CAAkB,GACpB,EACC,UAAA,CAAY,CACV,oBAAqB,GAAA,CACrB,aAAA,CAAe,IACf,eAAA,CAAiB,EAAA,CACjB,kBAAmB,KACrB,CAAA,CACA,GAAI,CACF,aAAA,CAAe,IACf,eAAA,CAAiB,GAAA,CAKjB,iBAAA,CAAmB,GAAA,CAInB,qBAAsB,GAAA,CAMtB,gBAAA,CAAkB,IAMlB,qBAAA,CAAuB,GACzB,EACA,MAAA,CAAQ,CACN,oBAAA,CAAsB,CAAA,CACtB,cAAe,GAAA,CACf,UAAA,CAAY,EACZ,aAAA,CAAe,GACjB,EACA,UAAA,CAAY,CACV,OAAA,CAAS,KAAA,CACT,eAAgB,KAClB,CAAA,CACA,kBAAmB,CACjB,OAAA,CAAS,KACX,CACF,EAiBK,SAASC,CAAAA,CACdC,CAAAA,CACAC,EACc,CACd,OAAO,CACL,IAAA,CAAM,CAAE,GAAGD,CAAAA,CAAK,IAAA,CAAM,GAAGC,CAAAA,CAAS,IAAK,CAAA,CACvC,WAAA,CAAa,CAAE,GAAGD,CAAAA,CAAK,YAAa,GAAGC,CAAAA,CAAS,WAAY,CAAA,CAC5D,WAAY,CAAE,GAAGD,EAAK,UAAA,CAAY,GAAGC,EAAS,UAAW,CAAA,CACzD,EAAA,CAAI,CAAE,GAAGD,CAAAA,CAAK,EAAA,CAAI,GAAGC,CAAAA,CAAS,EAAG,EACjC,MAAA,CAAQ,CAAE,GAAGD,CAAAA,CAAK,MAAA,CAAQ,GAAGC,CAAAA,CAAS,MAAO,EAC7C,UAAA,CAAY,CAAE,GAAGD,CAAAA,CAAK,UAAA,CAAY,GAAGC,CAAAA,CAAS,UAAW,CAAA,CACzD,iBAAA,CAAmB,CAAE,GAAGD,CAAAA,CAAK,kBAAmB,GAAGC,CAAAA,CAAS,iBAAkB,CAChF,CACF,CAYO,IAAMC,EAAN,KAAoB,CAGzB,YAAYC,CAAAA,CAAgC,EAAC,CAAG,CAC9C,KAAK,MAAA,CAASJ,CAAAA,CAAkBD,EAAgBK,CAAM,EACxD,CAQA,GAAA,CAAOC,CAAAA,CAAiB,CACtB,IAAMC,CAAAA,CAAOD,EAAK,KAAA,CAAM,GAAG,EACvBE,CAAAA,CAAmB,IAAA,CAAK,OAE5B,IAAA,IAAWC,CAAAA,IAAOF,CAAAA,CAChB,GAAIC,GAAW,OAAOA,CAAAA,EAAY,UAAYC,CAAAA,IAAOD,CAAAA,CACnDA,EAAWA,CAAAA,CAAoCC,CAAG,CAAA,CAAA,KAElD,MAAMC,IAAa,MAAA,CACjB,uBAAA,CACA,iCAAiCJ,CAAI,CAAA,CAAA,CACrC,CAAE,IAAA,CAAAA,CAAK,CACT,CAAA,CAIJ,OAAOE,CACT,CAQA,IAAOF,CAAAA,CAAcK,CAAAA,CAAgB,CACnC,IAAMJ,CAAAA,CAAOD,EAAK,KAAA,CAAM,GAAG,EAC3B,GAAIC,CAAAA,CAAK,OAAS,CAAA,CAChB,MAAMG,IAAa,MAAA,CACjB,qBAAA,CACA,CAAA,cAAA,EAAiBJ,CAAI,yCACrB,CAAE,IAAA,CAAAA,CAAK,CACT,CAAA,CAGF,IAAMM,CAAAA,CAAUL,CAAAA,CAAK,CAAC,CAAA,CAChBM,EAAWN,CAAAA,CAAK,CAAC,EAEvB,GAAI,EAAEK,KAAW,IAAA,CAAK,MAAA,CAAA,CACpB,MAAMF,GAAAA,CAAa,OACjB,0BAAA,CACA,CAAA,iCAAA,EAAoCE,CAAO,CAAA,CAAA,CAC3C,CAAE,QAAAA,CAAAA,CAAS,IAAA,CAAAN,CAAK,CAClB,CAAA,CAGF,IAAMQ,CAAAA,CAAgB,IAAA,CAAK,OAAOF,CAA6B,CAAA,CAC/D,GAAIE,CAAAA,EAAiB,OAAOA,CAAAA,EAAkB,QAAA,CAC3CA,EAAqDD,CAAQ,CAAA,CAAIF,OAElE,MAAMD,GAAAA,CAAa,OACjB,2BAAA,CACA,CAAA,kCAAA,EAAqCJ,CAAI,CAAA,CAAA,CACzC,CAAE,IAAA,CAAAA,CAAK,CACT,CAEJ,CAUA,WAA0B,CACxB,OAAOL,CAAAA,CAAkB,IAAA,CAAK,OAAQ,EAAE,CAC1C,CAKA,MAAA,CAAOI,EAAqC,CAC1C,IAAA,CAAK,OAASJ,CAAAA,CAAkB,IAAA,CAAK,OAAQI,CAAM,EACrD,CAcA,KAAA,EAAc,CACZ,KAAK,MAAA,CAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,UAA6B,CAC3B,IAAMe,EAAmB,EAAC,CAG1B,OAAI,IAAA,CAAK,MAAA,CAAO,YAAY,gBAAA,CAAmB,GAAA,EAC7CA,EAAO,IAAA,CAAK,wCAAwC,EAIlD,IAAA,CAAK,MAAA,CAAO,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-UGQM6ZXU.js","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.4.0\",\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 \"./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 },\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.100.10\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.4.1\",\n \"@types/node\": \"^26.2.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.4.2\",\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 *\n * Only the all-numeric literals are affected. A spelled-out month (`March 9,\n * 2024`) is never ambiguous, and an ISO timestamp is always read as ISO.\n */\nexport type DateInputOrder = 'auto' | 'DMY' | 'MDY' | 'YMD';\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 * 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 * 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 }\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 },\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 };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 7\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 };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';var chunkFDE5HWDI_cjs=require('./chunk-FDE5HWDI.cjs'),chunkLNZNJSRW_cjs=require('./chunk-LNZNJSRW.cjs'),chunkTTFO4YDP_cjs=require('./chunk-TTFO4YDP.cjs'),chunkSYYE3QAX_cjs=require('./chunk-SYYE3QAX.cjs'),chunkAXMQG5TS_cjs=require('./chunk-AXMQG5TS.cjs'),chunk6ZNNPXXE_cjs=require('./chunk-6ZNNPXXE.cjs'),chunkNXIMGB4S_cjs=require('./chunk-NXIMGB4S.cjs'),chunk4QVBSG6B_cjs=require('./chunk-4QVBSG6B.cjs'),chunkVAGS5JS7_cjs=require('./chunk-VAGS5JS7.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkZLRJ7TDP_cjs=require('./chunk-ZLRJ7TDP.cjs'),chunkJAK3RAFA_cjs=require('./chunk-JAK3RAFA.cjs'),chunkN7N7MPMK_cjs=require('./chunk-N7N7MPMK.cjs'),chunkPS272DZJ_cjs=require('./chunk-PS272DZJ.cjs'),chunkMMT2LS5I_cjs=require('./chunk-MMT2LS5I.cjs'),chunk32GC2FHC_cjs=require('./chunk-32GC2FHC.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunk2LFLR3VZ_cjs=require('./chunk-2LFLR3VZ.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkMSYX32PF_cjs=require('./chunk-MSYX32PF.cjs'),chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');function Ct(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let a=new Set(Object.keys(s));for(let l of Object.keys(o))a.has(l)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function jt(n,e){let t=[];if(Ct("prefixParseletTokenType","prefixParselets",n,e,t),Ct("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let a=n.phrases[s];a!==void 0&&a!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[n.name,e.name]});}if(n.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(n.asConverters).some(a=>a.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[n.name,e.name]});}if(n.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(n.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[n.name,e.name]});}if(n.normalizerRules&&e.normalizerRules){let s=new Set(n.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[n.name,e.name]});}let r=n.lexerVocabulary,i=e.lexerVocabulary;if(r?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let a=r.keywords[s];a!==void 0&&a!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let a=r.operators[s];a!==void 0&&a!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[n.name,e.name]});}if(n.asyncResolvers&&e.asyncResolvers){let s=new Set(n.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${n.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[n.name,e.name]});}if(n.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let a=n.tokenCategories[s];a!==void 0&&a!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[n.name,e.name]});}return t}function Tt(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...jt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var Gt=/(\d+)\.(\d+)\.(\d+)/,qt=/^\d+$/;function Nt(n){let e=Gt.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Qt(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Ne(n){let e=n.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let r=0;r<e.length;r++){if(!qt.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Xt([n,e,t]){let r=n>0?[n+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[n,e,t]},{op:"<",v:r}]}function Jt([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Yt(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Ne(n.slice(1));return i&&Xt(i)}if(n[0]==="~"){let i=Ne(n.slice(1));return i&&Jt(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Ne(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function wt(n){let e=[];for(let t of n.split("||")){let r=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of r){let o=Yt(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Rt(n){return wt(n.trim())!==null}function Zt(n,e){let t=Qt(n,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function At(n,e){let t=wt(e.trim());return t===null?false:t.some(r=>r.every(i=>Zt(n,i)))}function en(n,e=chunkMMT2LS5I_cjs.a){if(!n.engineVersion)return {compatible:true};if(!Rt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Nt(e);return t===null||!At(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function Pt(n,e=chunkMMT2LS5I_cjs.a){let t=en(n,e);if(!t.compatible)throw t.reason==="invalid-range"?chunkSOMGSIO4_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):chunkSOMGSIO4_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var G="solve-engine/snapshot",W=1;function F(n){return Number.isFinite(n)?n:Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity"}function _(n){if(typeof n=="number")return n;if(n==="NaN")return NaN;if(n==="Infinity")return 1/0;if(n==="-Infinity")return -1/0;throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(n)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(n)})}var D={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Lt(n){return {coef:n.coef.toString(),scale:n.scale}}function It(n){return {coef:BigInt(n.coef),scale:n.scale}}function tn(n){return {n:n.n.toString(),d:n.d.toString()}}function nn(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Ot(n){return chunkPS272DZJ_cjs.g[n]??String(n)}function we(n,e){throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Ot(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Ot(n)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:n,location:e}})}function Re(n,e){switch(n.type){case 0:{let t={t:0,v:F(n.value)};return n.exact!==void 0&&(t.exact=Lt(n.exact)),n.rational!==void 0&&(t.rational=tn(n.rational)),t}case 1:{let t=n.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:n.unit}:{t:1,v:F(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:return {t:4,v:F(n.value)};case 5:return {t:5,v:F(n.value)};case 6:{let t={t:6,v:F(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=Lt(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&we(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>rn(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:F(t.min),max:F(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return we(n.type,e)}}function rn(n,e){return typeof n=="boolean"?n:typeof n=="number"?F(n):we(9,`${e} (symbolic matrix cell)`)}function Ae(n){switch(n.t){case 0:{let e=new chunkPS272DZJ_cjs.m(0,_(n.v));return n.exact!==void 0&&(e.exact=It(n.exact)),n.rational!==void 0&&(e.rational=nn(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):_(n.v);return new chunkPS272DZJ_cjs.m(1,e,n.base)}case 2:return new chunkPS272DZJ_cjs.m(2,BigInt(n.v));case 3:return new chunkPS272DZJ_cjs.m(3,n.v);case 4:return new chunkPS272DZJ_cjs.m(4,_(n.v));case 5:return new chunkPS272DZJ_cjs.m(5,_(n.v));case 6:{let e=new chunkPS272DZJ_cjs.m(6,_(n.v),n.unit);return n.exact!==void 0&&(e.exact=It(n.exact)),e}case 7:{let e=n.data.map(r=>typeof r=="boolean"?r:_(r)),t={rows:n.rows,cols:n.cols,data:e,hasSymbolic:false};return new chunkPS272DZJ_cjs.m(7,t)}case 8:return new chunkPS272DZJ_cjs.m(8,{min:_(n.min),max:_(n.max)});case 10:return new chunkPS272DZJ_cjs.m(10,n.v);case 13:return new chunkPS272DZJ_cjs.m(13,n.code,n.message);default:throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(n.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(n.t)})}}function re(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,F),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Pe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:re(t.program)}))),e}function ie(n){let e={opcodes:Uint8Array.from(n.opcodes),numbers:Float64Array.from(n.numbers,_),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=new Map(n.constants)),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Le)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ie(t.program)}))),e}function Pe(n){return {name:n.name,params:n.params.slice(),program:re(n.program)}}function Le(n){return {name:n.name,params:n.params.slice(),program:ie(n.program)}}function Vt(n){if(typeof n!="object"||n===null)throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${G}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==G)throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${G}"`,found:JSON.stringify(e.format)});if(e.version!==W)throw chunkSOMGSIO4_cjs.c.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${W}.`,expected:`snapshot version ${W}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:W,engineVersion:e.engineVersion}})}var K=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},he=class n{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(n.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let r of t.values())return r}set(e,t,r){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=n.exprKey(r);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(n.exprKey(t))??false}remove(e,t){let r=this.byLine.get(e);r&&r.delete(n.exprKey(t))&&(this.count--,r.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,r]of this.byLine)for(let[i,s]of r)e(n.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,r]of this.byLine)for(let[i,s]of r)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,r]of this.byLine)for(let i of r.keys())e.push(n.displayKey(t,i));return e}};function Ie(n){let e=new Date(n),t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return `${e.getFullYear()}-${t}-${r}`}function sn(n){if(n instanceof Date)return Ie(n.getTime());if(typeof n=="number")return Number.isFinite(n)?Ie(n):null;let e=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return e?`${e[1]}-${e[2]}-${e[3]}`:null}function Bt(n){if(n===void 0)return;if(typeof n=="function")return t=>n(new Date(t));let e=new Set;for(let t of n){let r=sn(t);r!==null&&e.add(r);}return t=>e.has(Ie(t))}function on(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var fe=class n{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&on(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,r){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),a=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=a?a[0]*1e9+a[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
|
|
2
|
+
`);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)r.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,c)=>l+c.totalAllocBytes,0),o=e.reduce((l,c)=>l+c.totalWallTimeNs,0),a=e.filter(l=>l.fastPath).length;return r.push(""),r.push("### Totals"),r.push(""),r.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),r.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),r.push(`- **Fast-path runs:** ${a}/${e.length} (${(a/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.join(`
|
|
3
|
+
`)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let r=[];for(let[i,s]of t){let o=s.map(c=>c.wallTimeNs).sort((c,u)=>c-u),a=s.map(c=>c.allocBytes),l=s.length;r.push({stage:i,count:l,meanAllocBytes:a.reduce((c,u)=>c+u,0)/l,meanWallTimeNs:o.reduce((c,u)=>c+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:Oe(o,50),p95WallTimeNs:Oe(o,95),p99WallTimeNs:Oe(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,a)=>o+a.allocBytes,0),s=t.reduce((o,a)=>o+a.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};U.enabled=false;function Oe(n,e){if(n.length===0)return 0;if(n.length===1)return n[0];let t=e/100*(n.length-1),r=Math.floor(t),i=Math.ceil(t);if(r===i)return n[r];let s=t-r;return n[r]*(1-s)+n[i]*s}function Ve(n,e){if(n.length>e.maxExpressionLength){let t=chunkSOMGSIO4_cjs.c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n.length})`,{expressionLength:n.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:chunkPS272DZJ_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function Be(n,e){let t=0,r=0,i=0;for(let o of n)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(r++,i=Math.max(i,r)),(o.value===")"||o.type==="RPAREN")&&r--;let s=n.length+t*5+i*10;if(s>e.maxComplexity){let o=chunkSOMGSIO4_cjs.c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function se(n){return n.type==="IDENT"||n.type==="UNIT"}function an(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function Mt(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r].type==="LPAREN")t++;else if(n[r].type==="RPAREN"&&(t--,t===0))return r;return null}function ln(n){let e=new Set;for(let t=0;t<n.length;t++){if(!se(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=Mt(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)se(n[i])&&e.add(n[i].value);}return e}function me(n){let e=[],t=[],r=ln(n);for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="GLOBAL"){if(i+2<n.length&&n[i+1].type==="COLON"&&se(n[i+2])){let o=chunkJAK3RAFA_cjs.K(n[i+2].value);e.push(o),i+3<n.length&&n[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&n[i-1].type==="GLOBAL")continue;if(i+1<n.length&&se(n[i+1])){let o=n[i+1].value;e.push(o),i+2<n.length&&n[i+2].type==="EQUALS"&&t.push(o);}}if(se(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&an(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let a=Mt(n,i+1);if(a!==null&&n[a+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=n[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function jn(n){return chunk32GC2FHC_cjs.c.classifyLine(n).skip}function Gn(n,e){return chunk32GC2FHC_cjs.c.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}function Dt(n){let e=n[n.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...n.slice(0,-1),t].join(" ")}var ye=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,r){let i=Dt(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(Dt(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function Ut(n,e=82){return {name:"uom:user-unit",priority:e,match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let g=r+1;g<t.length&&s.length<o&&t[g].type==="IDENT";g++)s.push(t[g].value);if(s.length===0)return null;let a=n.match(s);if(a===null||t[r+1+a.wordCount]?.type==="EQUALS")return null;let{ratioText:c,baseUnit:u}=a.definition,p=new chunk2LFLR3VZ_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col),f=new chunk2LFLR3VZ_cjs.a("NUMBER",chunk5IJD5L3O_cjs.c("NUMBER"),c,c,i.offset,0,i.line,i.col),m=new chunk2LFLR3VZ_cjs.a("UNIT",chunk5IJD5L3O_cjs.c("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+a.wordCount,replacement:[i,p,f,m],ruleName:"uom:user-unit"}}}}var cn=30,un=40,pn=50,gn=24;function dn(n){switch(n){case chunk5IJD5L3O_cjs.a.PLUS:case chunk5IJD5L3O_cjs.a.MINUS:return cn;case chunk5IJD5L3O_cjs.a.STAR:case chunk5IJD5L3O_cjs.a.SLASH:case chunk5IJD5L3O_cjs.a.MOD:case chunk5IJD5L3O_cjs.a.OF:return un;case chunk5IJD5L3O_cjs.a.CARET:return pn;case chunk5IJD5L3O_cjs.a.PCT_ON:case chunk5IJD5L3O_cjs.a.PCT_OFF:return gn;default:return 0}}function hn(n){switch(n){case chunk5IJD5L3O_cjs.a.PLUS:return "plus";case chunk5IJD5L3O_cjs.a.MINUS:return "minus";case chunk5IJD5L3O_cjs.a.STAR:return "times";case chunk5IJD5L3O_cjs.a.SLASH:return "divided by";case chunk5IJD5L3O_cjs.a.MOD:return "mod";case chunk5IJD5L3O_cjs.a.CARET:return "to the power of";case chunk5IJD5L3O_cjs.a.OF:return "of";case chunk5IJD5L3O_cjs.a.PCT_ON:return "plus";case chunk5IJD5L3O_cjs.a.PCT_OFF:return "less";default:return n.toLowerCase()}}function _t(n){return n.sourceEnd??n.offset+n.value.length}var fn=new Set([chunk5IJD5L3O_cjs.a.NUMBER,chunk5IJD5L3O_cjs.a.BIGINT,chunk5IJD5L3O_cjs.a.IDENT,chunk5IJD5L3O_cjs.a.UNIT,chunk5IJD5L3O_cjs.a.PERCENT,chunk5IJD5L3O_cjs.a.PI,chunk5IJD5L3O_cjs.a.E,chunk5IJD5L3O_cjs.a.TRUE,chunk5IJD5L3O_cjs.a.FALSE,chunk5IJD5L3O_cjs.a.DOLLAR,chunk5IJD5L3O_cjs.a.POUND,chunk5IJD5L3O_cjs.a.EURO,chunk5IJD5L3O_cjs.a.YEN,chunk5IJD5L3O_cjs.a.RUBLE,chunk5IJD5L3O_cjs.a.WON,chunk5IJD5L3O_cjs.a.CURRENCY_SYMBOL]);function mn(n){return !fn.has(n)}var Me=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let r=this.peek();if(!r)break;let i=dn(r.type);if(i===0||i<=e)break;this.next();let s=r.type===chunk5IJD5L3O_cjs.a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:r.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===chunk5IJD5L3O_cjs.a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===chunk5IJD5L3O_cjs.a.PLUS||this.peek().type===chunk5IJD5L3O_cjs.a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===chunk5IJD5L3O_cjs.a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!mn(this.peek().type);)i=_t(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),r=this.peek();if(!r||r.type!==chunk5IJD5L3O_cjs.a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:_t(r)}}},De=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=chunkMSYX32PF_cjs.a(r).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=hn(e.op);return e.op===chunk5IJD5L3O_cjs.a.PCT_ON||e.op===chunk5IJD5L3O_cjs.a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=chunk6ZNNPXXE_cjs.c(e,chunk6ZNNPXXE_cjs.a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function Ue(n){let{expression:e,tokens:t,evaluate:r,locale:i}=n,s=()=>({expression:e,steps:[],result:r(e)}),o;try{o=new Me(t).parseAll();}catch{return s()}try{let{steps:a,result:l}=new De(e,r,i).build(o);return {expression:e,steps:a,result:l}}catch{return s()}}var oe=class oe{constructor(e={}){this.dag=new chunkSYYE3QAX_cjs.a;this.lineCache=new he;this.accumulatorNames=new Set;this.scopeManager=new chunkSYYE3QAX_cjs.b;this.resolverRegistry=new chunkLNZNJSRW_cjs.a;this.packageContributions=new Map;this.registeredPackages=new Map;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new ye;this.bytecodeCache=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new chunk4QVBSG6B_cjs.d(this.pluginFunctionIndexByName),new chunk4QVBSG6B_cjs.d(this.pluginFunctionIndexByName),new chunk4QVBSG6B_cjs.d(this.pluginFunctionIndexByName),new chunk4QVBSG6B_cjs.d(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t="en",diagnostics:r=false,config:i,packages:s}=e;this.localeCode=t,this.config=chunkMMT2LS5I_cjs.c(chunkMMT2LS5I_cjs.b,i??{}),this.lexer=new chunk32GC2FHC_cjs.b(t,chunk32GC2FHC_cjs.d(t)),this.registry=new chunkFDE5HWDI_cjs.b,this.context=chunkJAK3RAFA_cjs.x(),r?(this.diagnosticPipeline=new chunkAXMQG5TS_cjs.a,this.timelineCollector=new chunkAXMQG5TS_cjs.b,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new chunkAXMQG5TS_cjs.a,this.normalizer=new chunkVAGS5JS7_cjs.c;for(let[a,l]of Object.entries(chunkVAGS5JS7_cjs.g))this.normalizer.addPhrase(a,l);this.normalizer.register(chunkVAGS5JS7_cjs.d(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(Ut(this.userUnits));let o=s??[];for(let a of o)try{this.registerPackage(a);}catch(l){let c=chunkSOMGSIO4_cjs.d(l);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${c.format()}`);}this.registry.hasPrefix("DATETIME_LITERAL")&&this.normalizer.register(chunkNXIMGB4S_cjs.h(()=>this.config.date.inputOrder)),this.parser=new chunkFDE5HWDI_cjs.a(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName),this.vm=chunkSYYE3QAX_cjs.c(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,Bt(this.config.date.holidays)),this.queryClient=chunkZLRJ7TDP_cjs.c(),this.batcher=new be(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new fe(this.dag,(a,l)=>this.batcher.add({queryKey:l,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null;}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:r?s=>{let o=r[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,a,l)=>this.evaluateLineWithBinding(s,o,a,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,getLineText:t?s=>t.getLineAt(s)?.text:r?s=>r[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return chunkPS272DZJ_cjs.N("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=oe.GOAL_SEEK_MAX_NESTING_DEPTH)return chunkPS272DZJ_cjs.N("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return chunkPS272DZJ_cjs.N("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return chunkPS272DZJ_cjs.N("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let a=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,r]]),c=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=chunkSYYE3QAX_cjs.d(a,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?chunkPS272DZJ_cjs.N("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?chunkPS272DZJ_cjs.N(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>c;)this.vm.pop();}}catch(l){return chunkPS272DZJ_cjs.N("GOAL_SEEK_TARGET_ERROR",chunkSOMGSIO4_cjs.d(l).message)}finally{this.goalSeekDepth--;}}cacheBytecode(e,t){let r=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=r){let i=this.bytecodeCache.keys().next().value;i!==void 0&&this.bytecodeCache.delete(i);}this.bytecodeCache.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Pt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=Tt(e,[...this.registeredPackages.values()]);for(let i of t.conflicts)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let r={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=chunkJAK3RAFA_cjs.F(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),r.normalizerRuleNames.push(i.name);if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))chunkY7O4D3BJ_cjs.b(i,s),r.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))chunkJAK3RAFA_cjs.H(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e);}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let r of t.pluginFunctionIndices)delete this.context.pluginFunctions[r],delete this.context.pluginFunctionOwners[r];for(let r of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(r);for(let r of t.resolverNamespaces)this.resolverRegistry.unregister(r);for(let r of t.tokenCategories)chunkY7O4D3BJ_cjs.c(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)chunkJAK3RAFA_cjs.I(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.bytecodeCache.clear(),true}getConfig(){return {...this.config}}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new K(t,r,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,r,i,s,o,a,l){let c=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("executeAndStore"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},chunkZLRJ7TDP_cjs.a(this.queryClient);let f=chunkSYYE3QAX_cjs.d(e,this.vm,a,l,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(f.type==="pending"){this.resolveAsync(f),this.dag.registerLineDataSourceDependency(t,f.packageId||o,[f.queryKey]);let m=chunkPS272DZJ_cjs.M(f.queryKey);return this.storeLineResult(t,m,e,i,s,r),m}if(f.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),f.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,f.value,e,i,s,r),f.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("executeRaw"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},chunkZLRJ7TDP_cjs.a(this.queryClient);let o=chunkSYYE3QAX_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine";try{if(await r,s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(a){if(s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after error");return}let l=a instanceof Error?a:new Error(String(a));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(chunkUURM7P3P_cjs.b(e,r)>r)throw chunkSOMGSIO4_cjs.c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let c of l.inlineSolves)c.error&&o.errors.push(`Line ${l.lineNumber}: ${c.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
|
|
4
|
+
`),r=this.lexer.scanDocument(t);return this.processScanResults(r)}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,a=s.lineNumber,l=s.startOffset,c=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(g=>({start:g.start,end:g.end,expression:g.expression,lineNumber:a,columnNumber:g.columnNumber})),f=p.length>0,m={lineNumber:a,text:o,startPosition:l,endPosition:c,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(!u){let g=o.trim().startsWith(":");if(f&&!g)for(let A of p)try{A.result=this.evaluateLine(a,A.expression);}catch(I){let O=I instanceof Error?I.message:String(I);A.error=O;}else {let A=s.classification.contentOffset,O=(A===void 0?o:o.slice(A-l)).trim();if(O)try{let E=this.evaluateLineWithPreTokenized(a,O,s.tokens);m.expression=O,m.result=E[0];}catch(E){let X=E instanceof Error?E.message:String(E);m.error=X;}}}t.push(m);}}finally{this.batchScanResults=r,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,r){let i=[],s=false;for(let o of r)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,r,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?r:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let a=true;for(let l=0;l<o;l++){let c=t[l].type;if(c!=="NUMBER"&&c!=="COLON"){a=false;break}}if(a){let l=t.slice(0,o+2).map(c=>c.value).join("");throw chunkSOMGSIO4_cjs.c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw chunkSOMGSIO4_cjs.c.parsing("UNEXPECTED_TRAILING_TOKEN",`Unexpected token after expression: "${s.value}"`,{tokenType:s.type,tokenValue:s.value})}}compileAdHoc(e){let t=new chunk4QVBSG6B_cjs.d(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=chunkSYYE3QAX_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw chunkSOMGSIO4_cjs.c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let a of e.factorNames){let l=this.vm.getVar(a);if(l===void 0)return chunkPS272DZJ_cjs.N("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return chunkPS272DZJ_cjs.N("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${a}" must be a Matrix (got a different value type).`);r.push(l);}let i=r[0].value;for(let a=1;a<r.length;a++){let l=chunkN7N7MPMK_cjs._(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=chunkN7N7MPMK_cjs.da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?chunkPS272DZJ_cjs.N("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):chunkN7N7MPMK_cjs._(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let r=[];for(;t<e.length&&e[t].type==="IDENT";)r.push(e[t].value),t++;if(r.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.bytecodeCache.clear(),chunkPS272DZJ_cjs.t(`${r.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let r=e[0],i=e[1],s=r.type==="IDENT"||r.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let a=e.slice(2);if(a.length===0)throw chunkSOMGSIO4_cjs.c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let l=r.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,chunkPS272DZJ_cjs.n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[chunkVAGS5JS7_cjs.b("IDENT",l,[r]),chunkVAGS5JS7_cjs.b(c.type,c.text,[i]),chunkVAGS5JS7_cjs.b("LPAREN","(",[i]),...a,chunkVAGS5JS7_cjs.b("RPAREN",")",[i])],p=chunkSYYE3QAX_cjs.d(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw chunkSOMGSIO4_cjs.c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let c=e.slice(0,-1);if(c.length===0)throw chunkSOMGSIO4_cjs.c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c.length===1&&(c[0].type==="IDENT"||c[0].type==="UNIT")){let u=c[0].value,p=this.vm.getEquation(u),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t)}return this.simplifySymbolically(c,t)}if(chunkNXIMGB4S_cjs.b(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],c),c}let a=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(a,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(a,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),chunkPS272DZJ_cjs.t(`${a} stored as an equation \u2014 solve with "${a} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(a=>a.type==="EQUALS"))return null;let s=this.equationUnknowns(r,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(r),this.compileAdHoc(i)),chunkPS272DZJ_cjs.t(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let r=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||r.includes(i.value)||r.push(i.value));return r}solveScalarEquation(e,t=-1){let r=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return chunkJAK3RAFA_cjs.i(r,i,e.variable)}lexToTokens(e,t){let r=[],i=false;this.lexer.resetExpression(e);for(let s of this.lexer)s.type!=="COMMENT"&&((s.type==="LPAREN"||s.type==="RPAREN")&&(i=true),r.push(s),t?.(s));return {tokens:r,hasParens:i}}prepareExpression(e,t,r,i,s=-1){let o=Ve(e,this.config.validation);if(!o.passed)return {kind:"error",stage:"length",error:o.error.engineError};let a=t.filter(E=>E.type!=="COMMENT");if(a.length===0)return {kind:"empty"};let l=this.normalizer.normalize(a,i),c=Be(l,this.config.validation);if(!c.passed)return {kind:"error",stage:"complexity",error:c.engineError,normalizedTokens:l};let u,p=null;try{if(u=this.tryDefineUserUnit(l),u===null){let E=this.tryCompoundAssignment(l,s);E!==null&&(u=E,p=me(l));}u===null&&(u=this.trySymbolicGrammar(l,s));}catch(E){let{reads:X,writes:P}=me(l);return {kind:"error",stage:"parse",error:chunkSOMGSIO4_cjs.d(E),reads:X,writes:P,normalizedTokens:l}}if(u!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:u,reads:p?.reads,writes:p?.writes};let{reads:f,writes:m}=me(l),g=this.bytecodeCache.get(e);if(g)return {kind:"ready",normalizedTokens:l,reads:f,writes:m,program:g,cached:true};let A=this.builderPool[this.builderPoolIndex++%this.builderPool.length];A.reset();let I,O=null;try{let E=U.track("parser",()=>(this.parseExpression(A,l,r),A.build()));I=E.result,O=E.alloc;}catch(E){return {kind:"error",stage:"parse",error:chunkSOMGSIO4_cjs.d(E),reads:f,writes:m,normalizedTokens:l}}return this.cacheBytecode(e,I),{kind:"ready",normalizedTokens:l,reads:f,writes:m,program:I,cached:false,parserAlloc:O}}preflightAsync(e,t,r,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("preflightAsync"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("preflightAsync");let c=a.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=chunkPS272DZJ_cjs.M(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let p=chunkPS272DZJ_cjs.n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:a,writes:l,program:c}=s,u=this.preflightAsync(o,c,e,t,a,l);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,a,l,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:chunkSOMGSIO4_cjs.c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return chunkPS272DZJ_cjs.l(r.value)}evaluateLineWithDebug(e,t,r="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,r),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,r)}addDiagnosticStage(e,t,r,i,s,o,a,l,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:a,skipped:l,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,a=U.isEnabled(),l=[],c=[],u=0,p=Ve(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:chunkAXMQG5TS_cjs.c.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let f=s?h=>{i.fireTokenEmitted({type:chunkAXMQG5TS_cjs.c.TokenEmitted,elapsedNs:0,expression:e,token:{type:h.type,value:h.value,offset:h.offset||0,line:h.line||t,col:h.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,f)),g=m.result.tokens,A=m.result.hasParens;if(a&&m.alloc&&l.push(m.alloc),s){let h={};for(let R of g)h[R.type]=(h[R.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:g.length,tokenTypes:h,hasParens:A,locale:this.localeCode,tokens:[...g]});let N=[];for(let R=0;R<g.length;R++){let ee=g[R];if(ee.type==="INLINE_SOLVE_START"){let V=-1;for(let z=R+1;z<g.length;z++)if(g[z].type==="BACKTICK_OPEN"){V=z;break}if(V>R){let Wt=g.slice(R+1,V).map(Ht=>Ht.value).join("");N.push({startTokenIndex:R,endTokenIndex:V,expression:Wt,columnNumber:ee.col||1}),R=V;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:N.length>0,inlineSolveSpans:N});}if(g.length===0){let h=chunkPS272DZJ_cjs.n(0);return this.lineCache.set(t,new K(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let I=0,O=[],E=new Map,X=s?h=>{I++,O.push(h),E.set(h.rule,(E.get(h.rule)||0)+1),i.fireTokenFused({type:chunkAXMQG5TS_cjs.c.TokenFused,elapsedNs:0,expression:e,ruleName:h.rule,sourceTokenCount:h.sourceTokens.length,fusedTokenType:h.fusedToken.type,fusedTokenValue:h.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:chunkAXMQG5TS_cjs.c.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:g.length});let P=this.bytecodeCache.get(e);s&&!P&&this.parser.setDiagnosticPipeline(i,e);let y=this.prepareExpression(e,g,A,X,t);a&&y.kind==="ready"&&y.parserAlloc&&l.push(y.parserAlloc),s&&!P&&this.parser.setDiagnosticPipeline(void 0,"");let x=y.kind==="empty"?g:y.normalizedTokens??g;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:chunkAXMQG5TS_cjs.c.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:x.length,fusionsCount:I}),this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:x.length,fusions:O,rulesApplied:[...E.entries()].map(([h,N])=>({rule:h,count:N})),tokens:[...x],phrases:this.normalizer.getPhrases()})):this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:g.length,fusions:[],rulesApplied:[],tokens:[...g],phrases:this.normalizer.getPhrases()})),y.kind==="empty"||y.kind==="error"&&y.stage==="length"){if(s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=chunkPS272DZJ_cjs.n(0);return this.lineCache.set(t,new K(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:chunkPS272DZJ_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0}}let J=Be(x,this.config.validation);if(y.kind==="error"&&y.stage==="complexity")return s&&(this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:J.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0},errorMessage:J.errorMessage}),i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:chunkPS272DZJ_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:J.errorMessage,engineError:J.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:J.complexityScore??x.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0}}),y.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:0});let h={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,y.value,h,y.reads??[],y.writes??[],e),{value:y.value,tokens:x,program:h,debug:void 0,diagnostic:void 0}}let ae=y.reads??[],Y=y.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ae,writes:Y,isAssignment:Y.length>0}),this.addDiagnosticStage(c,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!P,cacheSize:this.bytecodeCache.size,cacheKey:e}),P?i.fireCacheHit({type:chunkAXMQG5TS_cjs.c.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:chunkAXMQG5TS_cjs.c.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value:chunkPS272DZJ_cjs.n(0),tokens:x,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0};if(y.kind!=="ready")throw chunkSOMGSIO4_cjs.c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let v=y.program;s&&(this.addDiagnosticStage(c,"parser","Parser","\u{1F333}","parser",8,u,!!P,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!P,{type:"compiler",opcodeCount:v.opcodes.length,numberConstants:v.numbers.length,stringConstants:v.strings.length,hasAsync:v.hasAsync,cached:!!P}),i.fireBytecodeBuilt({type:chunkAXMQG5TS_cjs.c.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:v.opcodes.length,numbersLength:v.numbers.length,stringsLength:v.strings.length,isCached:!!P}));let $t=v.hasAsync||this.resolverRegistry.size>0,Z=this.preflightAsync(x,v,t,e,ae,Y);if(s&&(Z.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:Z.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):$t?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),Z.kind==="pending")return s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:Z.value,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,Z.value,x,v,null):void 0};let Kt=s&&this.config.diagnostic.vmTraceEnabled===true,C;try{let h=U.track("vm",()=>this.executeAndStore(v,t,e,ae,Y,"_engine",Kt?i:void 0,e),{cacheHit:!!P});C=h.result,a&&h.alloc&&l.push(h.alloc);}catch(h){let N=chunkSOMGSIO4_cjs.d(h);return s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:chunkPS272DZJ_cjs.n(0),tokens:x,program:v,error:N.message,engineError:N,debug:void 0,diagnostic:void 0}}let le=C.type===12;if(s){let h=le?"pending":String(C.value??""),N=le?"Pending":C.unit?"Uom":"Number";this.addDiagnosticStage(c,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:v.opcodes.length,stackDepth:this.vm.getStack().length,resultType:N,resultValue:h,isPending:le});}if(le)return s&&i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:C,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,C,x,v,null):void 0};if(a&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!P)),s&&(this.addDiagnosticStage(c,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ae,writesRegistered:Y,dataSourcesRegistered:[]}),this.addDiagnosticStage(c,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(C.value),formattedValue:String(C.value),valueType:C.type===0?"Number":"Value",unit:C.unit}),i.fireVmHalt({type:chunkAXMQG5TS_cjs.c.VmHalt,elapsedNs:0,expression:e,result:C?{type:C.type,value:C.value,unit:C.unit}:void 0}),this.addDiagnosticStage(c,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length,cacheHit:!!P}),i.firePipelineEnd({type:chunkAXMQG5TS_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length})),s){let N=i.collectReports()[0]?.toJSON(),R=N;if(N){let ee=N.parselets.slice(o),V={};for(let z of ee)V[z.parseletCategory]=(V[z.parseletCategory]??0)+1;R={...N,parselets:ee,summary:{...N.summary,totalParselets:Object.keys(V).length,parseCategories:V}};}return {value:C,tokens:x,program:v,debug:R,diagnostic:this.buildDiagnosticResult(c,C,x,v,null)}}return {value:C,tokens:x,program:v}}buildDiagnosticResult(e,t,r,i,s){return {stages:e,value:t,tokens:r,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let r=this.lineCache.get(e,t);if(!r)return;let i=this.bytecodeCache.get(t);if(!i)return;if(r.bytecode.hasAsync||this.resolverRegistry.size>0){let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("reEvaluateLine preflight");let c=a.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),chunkPS272DZJ_cjs.M(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),chunkPS272DZJ_cjs.M(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?chunkTTFO4YDP_cjs.a.keystrokeSignalSet(e.aborted):chunkTTFO4YDP_cjs.a.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,a]of this.bytecodeCache)e.push({expression:o,opcodesLength:a.opcodes.length,numbersLength:a.numbers.length,stringsLength:a.strings.length,hasAsync:a.hasAsync});let t=[];for(let o of this.lineCache.keys()){let a=o.indexOf(":"),l=a>0?parseInt(o.slice(0,a),10)||0:parseInt(o,10)||0,c=a>0?o.slice(a+1):void 0,u=c!==void 0?this.lineCache.get(l,c):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let a=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:a}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return Ue({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode})}evaluateIsolated(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r,void 0,-1);if(i.kind==="empty")return chunkPS272DZJ_cjs.n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw chunkSOMGSIO4_cjs.c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r);if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new chunkSOMGSIO4_cjs.b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:t,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:r}=this.lexToTokens(e);return this.prepareExpression(e,t,r).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return chunkPS272DZJ_cjs.n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),chunkPS272DZJ_cjs.M(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),chunkZLRJ7TDP_cjs.b()===this.queryClient&&chunkZLRJ7TDP_cjs.a(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.bytecodeCache.clear(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let c of Object.keys(e.dataSourceDeps)){let u=Number(c);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:c,entry:u}of r){let p=t.has(c)||u.bytecode.hasAsync;p&&t.add(c);let f=u.writeVariable;if(f){let m=i.get(f);(!m||c>=m.line)&&i.set(f,{line:c,async:p});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Re(u,`variable "${c}"`);}catch(p){if(p instanceof chunkSOMGSIO4_cjs.b&&p.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Pe),a=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let f;try{f=Re(p.result,`line ${c}`);}catch(m){if(m instanceof chunkSOMGSIO4_cjs.b&&m.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}a.push({line:c,expression:u,result:f,bytecode:re(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:re(u)}));return {format:G,version:W,engineVersion:chunkMMT2LS5I_cjs.a,locale:this.localeCode,variables:s,userFunctions:o,lineCache:a,bytecodeCache:l}}static fromJSON(e,t={}){Vt(e);let r=t.locale??e.locale??"en",i=new oe({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Ae(r));for(let t of e.userFunctions){let r=Le(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new K(Ae(t.result),ie(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,ie(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,chunkPS272DZJ_cjs.n(t));let i=new Map;for(let s of r){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.executeRaw(o.bytecode,s);if(a.type==="pending"){this.resolveAsync(a);continue}if(a.type==="error"){let c=chunkPS272DZJ_cjs.N(a.error.code,a.error.message);i.set(s,c),o.result=c;continue}let l=a.value;i.set(s,l),o.result=l;}return i}};oe.GOAL_SEEK_MAX_NESTING_DEPTH=1;var ve=oe;var _e=(()=>{throw new Error("engine.worker.ts was not processed by esbuild-plugin-inline-worker, so worker offload is unavailable")}),q=null;function yn(){return q||(q=new ve),q}var Q=null;function vn(){return Q||(Q=chunkSYYE3QAX_cjs.c(chunkJAK3RAFA_cjs.w,200,5e4)),Q}function bn(n){let e={lineId:n.lineId,expression:n.expression,compiledAgainstHash:n.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let t=yn(),{program:r,reads:i,writes:s}=t.compileExpression(n.expression),o=s.length>0,a=r.opcodes,l=r.numbers,c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),u=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);return {...e,opcodesBuffer:c,numbersBuffer:u,opcodesLength:a.length,numbersLength:l.length,strings:[...r.strings],reads:i,writes:s,isVariableDef:o}}catch(t){return {...e,opcodesBuffer:new ArrayBuffer(0),numbersBuffer:new ArrayBuffer(0),opcodesLength:0,numbersLength:0,error:t instanceof Error?t.message:String(t)}}}function En(n){let e=[],t=[];for(let r of n.items){let i=bn(r);e.push(i),i.opcodesBuffer.byteLength>0&&t.push(i.opcodesBuffer),i.numbersBuffer.byteLength>0&&t.push(i.numbersBuffer);}self.postMessage({id:n.id,type:"COMPILE_RESULT",results:e},t);}function Sn(n){let e=vn();e.reset();let t=new Uint8Array(n.opcodesBuffer,0,n.opcodesLength),r=new Float64Array(n.numbersBuffer,0,n.numbersLength),i={opcodes:t,numbers:r,strings:n.strings};try{let s=chunkSYYE3QAX_cjs.d(i,e);if(s.type==="pending")return {lineNumber:n.lineNumber,valueType:12,value:0,isPending:!0,queryKey:s.queryKey};if(s.type==="error")return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:!1,unit:s.error.message};let o=s.value;return {lineNumber:n.lineNumber,valueType:o.type,value:typeof o.value=="number"?o.value:typeof o.value=="bigint"?Number(o.value):0,unit:o.unit,isPending:!1}}catch{return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:false,unit:"Worker execution failed"}}}function xn(n){let e=[];for(let t of n.items)e.push(Sn(t));self.postMessage({id:n.id,type:"EXECUTE_RESULT",results:e});}var kn=typeof self<"u"&&typeof window>"u",Cn=n=>{if(n.origin&&self.location&&n.origin!==self.location.origin)return;let e=n.data;switch(e.type){case "COMPILE_BATCH":En(e);break;case "EXECUTE_BATCH":xn(e);break;case "TERMINATE":{q&&(q.clear(),q=null),Q&&(Q.reset(),Q=null),self.postMessage({id:e.id,type:"COMPILE_RESULT",results:[]});break}default:self.postMessage({id:-1,type:"COMPILE_RESULT",results:[],error:`Unknown message type: ${e.type}`});}};kn&&(self.onmessage=Cn);var Tn=3e4,Ft=50,Ee=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{return _e().terminate(),this._available=!0,!0}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let l=t.get(a);if(!l||l.bytecode.opcodes.length===0)continue;let c=l.bytecode.opcodes,u=l.bytecode.numbers,p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);r.push({lineNumber:a,opcodesBuffer:p,numbersBuffer:f,opcodesLength:c.length,numbersLength:u.length,strings:[...l.bytecode.strings]});}if(r.length===0)return Promise.resolve([]);let i=[];for(let a of r)a.opcodesBuffer.byteLength>0&&i.push(a.opcodesBuffer),a.numbersBuffer.byteLength>0&&i.push(a.numbersBuffer);let s=this.nextId++,o=this.getNextWorker();return new Promise(a=>{let l=setTimeout(()=>{this.pendingBatches.delete(s),a([]);},Tn);this.pendingBatches.set(s,{id:s,lineNumbers:e,resolve:c=>{clearTimeout(l),a(c);}}),o.postMessage({type:"EXECUTE_BATCH",id:s,items:r},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++){let t=_e();t.onmessage=r=>{this.handleWorkerMessage(r.data);},t.onerror=r=>{console.error(`[ExecutionPool] Worker ${e} error:`,r.message);for(let[i,s]of this.pendingBatches)s.resolve([]),this.pendingBatches.delete(i);},this.workers.push(t);}}getNextWorker(){let e=this.workers[this.nextWorker];return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function zt(n){switch(n.valueType){case 0:return chunkPS272DZJ_cjs.n(n.value);case 1:return chunkPS272DZJ_cjs.r(n.value);case 2:return chunkPS272DZJ_cjs.s(BigInt(n.value));case 3:return chunkPS272DZJ_cjs.t(String(n.value));case 4:return chunkPS272DZJ_cjs.K(n.value);case 5:return chunkPS272DZJ_cjs.L(n.value);case 6:return chunkPS272DZJ_cjs.u(n.value,n.unit??"");case 7:return chunkPS272DZJ_cjs.n(n.value);case 10:return chunkPS272DZJ_cjs.J(n.value!==0);case 12:return chunkPS272DZJ_cjs.M(n.queryKey??"");case 13:return chunkPS272DZJ_cjs.N("WORKER_EXECUTION_ERROR",n.unit??"Unknown worker error");default:return chunkPS272DZJ_cjs.n(n.value)}}var Se=class Se{constructor(e,t,r,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved but AsyncResolutionBatcher.onLineResult is not set, so the value cannot reach your document and the line will keep showing as pending. Set it to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let r=chunkSOMGSIO4_cjs.d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${r.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let c of e){let u=`${c.packageId}:${c.queryKey}`;t.set(u,c);}let r=[],i=[];for(let c of t.values())c.isError?r.push(c):i.push(c);for(let c of r)c.signal.aborted||this.notifyListeners({type:"error",queryKey:c.queryKey,packageId:c.packageId,error:c.error??new Error("Unknown async resolution error")});let s=new Set,o=[],a=[...i,...r];for(let c of a){if(c.signal.aborted)continue;o.push(c.queryKey);let u=this.dag.getAffectedLinesByDataSource(c.packageId,[c.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>Ft){let c=new Map;for(let u of l)c.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,c,o).catch(u=>{let p=chunkSOMGSIO4_cjs.d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let a of e)t.set(a,0),r.set(a,[]);for(let a of e){let l=this.dag.getWrites(a);for(let c of l)i.set(c,a);}for(let a of e){let l=this.dag.getDependencies(a);for(let c of l){let u=i.get(c);u!==void 0&&u!==a&&(r.get(u).push(a),t.set(a,(t.get(a)??0)+1));}}let s=[];for(let[a,l]of t)l===0&&s.push(a);if(s.length===0&&e.length>0)return [...e].sort((a,l)=>a-l);let o=[];for(;s.length>0;){let a=s.shift();o.push(a);for(let l of r.get(a)??[]){let c=(t.get(l)??1)-1;t.set(l,c),c===0&&s.push(l);}}if(o.length<e.length){let a=e.filter(l=>!o.includes(l)).sort((l,c)=>l-c);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new Ee);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,r,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let a of s){let l=t.get(a.lineNumber);if(!l||a.isPending)continue;let c=zt(a);l.result=c,this.warnIfUnwired(),this.onLineResult?.(a.lineNumber,c),o.push(a.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}reExecuteMainThread(e,t,r){let i=[];for(let s of e){let o=r?r.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let l=chunkSYYE3QAX_cjs.d(o.bytecode,this.vm);for(;this.vm.getStack().length>a;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let c=chunkPS272DZJ_cjs.N(l.error.code,l.error.message);o.result=c,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,c),i.push(s);}}catch(l){for(;this.vm.getStack().length>a;)this.vm.pop();let c=chunkSOMGSIO4_cjs.d(l),u=chunkPS272DZJ_cjs.N(c.code,c.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var be=Se;exports.a=Tt;exports.b=en;exports.c=Pt;exports.d=G;exports.e=W;exports.f=D;exports.g=_e;exports.h=be;exports.i=Ve;exports.j=Be;exports.k=me;exports.l=jn;exports.m=Gn;exports.n=ve;//# sourceMappingURL=chunk-WYAY6WPQ.cjs.map
|
|
5
|
+
//# sourceMappingURL=chunk-WYAY6WPQ.cjs.map
|