solve-engine 2.14.0 → 2.15.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/{BytecodeBuilder-BGq9ZiO3.d.cts → BytecodeBuilder-CRYfrFfq.d.cts} +2 -1
- package/dist/{BytecodeBuilder-BGq9ZiO3.d.ts → BytecodeBuilder-CRYfrFfq.d.ts} +2 -1
- package/dist/{EngineError-Ce1lPkjZ.d.cts → EngineError-Cv5q4Rbv.d.cts} +3 -1
- package/dist/{EngineError-Ce1lPkjZ.d.ts → EngineError-Cv5q4Rbv.d.ts} +3 -1
- package/dist/{Lexer-B4C1qHXu.d.cts → Lexer-CCHFDcgP.d.cts} +1 -1
- package/dist/{Lexer-DKMlj7Sy.d.ts → Lexer-CqagTewQ.d.ts} +1 -1
- package/dist/{PackageCompatibility-BG0iur4I.d.cts → PackageCompatibility-C2IQZ_w3.d.cts} +1 -1
- package/dist/{PackageCompatibility-BlIcQg5v.d.ts → PackageCompatibility-Cl7GF_Iu.d.ts} +1 -1
- package/dist/{PackageRegistry-BJ0QQd3k.d.ts → PackageRegistry-CK_JoX50.d.ts} +14 -7
- package/dist/{PackageRegistry-DeGDZkNt.d.cts → PackageRegistry-CZO1IbS-.d.cts} +14 -7
- package/dist/{Parselet-Blq8B0Gj.d.ts → Parselet-CK0bNO1l.d.ts} +2 -2
- package/dist/{Parselet-BSndkWEY.d.cts → Parselet-DOGmj6N6.d.cts} +2 -2
- package/dist/{ScopeManager-D8nLv--u.d.cts → ScopeManager-BtqiTVjG.d.cts} +3 -3
- package/dist/{ScopeManager-CF3cZUqW.d.ts → ScopeManager-C6c1WmJD.d.ts} +3 -3
- package/dist/{TokenNormalizer-DnlL7_8c.d.cts → TokenNormalizer-BfTHg1qt.d.cts} +35 -0
- package/dist/{TokenNormalizer-DCWdZjGz.d.ts → TokenNormalizer-d7F1KQFs.d.ts} +35 -0
- package/dist/{VMCheckpoints-Dy39SVHa.d.cts → VMCheckpoints-BFDlaGse.d.cts} +2 -2
- package/dist/{VMCheckpoints-BsR5_auF.d.ts → VMCheckpoints-DJdvpliw.d.ts} +2 -2
- package/dist/{WorkerError-B4p6PNfx.d.cts → WorkerError-FH7KXX4_.d.cts} +1 -1
- package/dist/{WorkerError-Dhj9BQ_A.d.ts → WorkerError-J3v3ix_z.d.ts} +1 -1
- package/dist/{chunk-75XDS65A.cjs → chunk-2XZCLDHJ.cjs} +2 -2
- package/dist/chunk-2XZCLDHJ.cjs.map +1 -0
- package/dist/{chunk-BW6FR7DA.js → chunk-3PDDKWTJ.js} +3 -3
- package/dist/{chunk-BW6FR7DA.js.map → chunk-3PDDKWTJ.js.map} +1 -1
- package/dist/{chunk-3MBENI4Q.cjs → chunk-3Y56PSQD.cjs} +3 -3
- package/dist/{chunk-3MBENI4Q.cjs.map → chunk-3Y56PSQD.cjs.map} +1 -1
- package/dist/{chunk-YOHM2WQT.js → chunk-4IIFFJTJ.js} +4 -4
- package/dist/chunk-4IIFFJTJ.js.map +1 -0
- package/dist/chunk-5SDSIRPL.js +2 -0
- package/dist/chunk-5SDSIRPL.js.map +1 -0
- package/dist/{chunk-PNDQRCRQ.cjs → chunk-6U66HQKQ.cjs} +2 -2
- package/dist/chunk-6U66HQKQ.cjs.map +1 -0
- package/dist/{chunk-VBSMA7WJ.cjs → chunk-ABVDKMNF.cjs} +2 -2
- package/dist/chunk-ABVDKMNF.cjs.map +1 -0
- package/dist/chunk-AYTEPHRO.js +3 -0
- package/dist/chunk-AYTEPHRO.js.map +1 -0
- package/dist/chunk-C5MP74ER.js +2 -0
- package/dist/chunk-C5MP74ER.js.map +1 -0
- package/dist/{chunk-JQBG3LX4.js → chunk-CUDPOWXA.js} +2 -2
- package/dist/{chunk-JQBG3LX4.js.map → chunk-CUDPOWXA.js.map} +1 -1
- package/dist/{chunk-LUMVKVFQ.cjs → chunk-EEUA3OJ6.cjs} +2 -2
- package/dist/{chunk-LUMVKVFQ.cjs.map → chunk-EEUA3OJ6.cjs.map} +1 -1
- package/dist/chunk-EEVUKZ5B.cjs +2 -0
- package/dist/{chunk-EURCQMZK.cjs.map → chunk-EEVUKZ5B.cjs.map} +1 -1
- package/dist/{chunk-3HYO3QYW.cjs → chunk-EXCFCHAT.cjs} +2 -2
- package/dist/{chunk-3HYO3QYW.cjs.map → chunk-EXCFCHAT.cjs.map} +1 -1
- package/dist/chunk-FAGFPVYK.cjs +2 -0
- package/dist/chunk-FAGFPVYK.cjs.map +1 -0
- package/dist/chunk-FPGYRFJY.cjs +5 -0
- package/dist/chunk-FPGYRFJY.cjs.map +1 -0
- package/dist/chunk-FVQWN5HZ.cjs +2 -0
- package/dist/chunk-FVQWN5HZ.cjs.map +1 -0
- package/dist/{chunk-4BZIYU7S.cjs → chunk-GWCBPITD.cjs} +3 -3
- package/dist/{chunk-4BZIYU7S.cjs.map → chunk-GWCBPITD.cjs.map} +1 -1
- package/dist/{chunk-YAYBVVG2.js → chunk-GWJJRH32.js} +3 -3
- package/dist/{chunk-YAYBVVG2.js.map → chunk-GWJJRH32.js.map} +1 -1
- package/dist/chunk-HDGARCI2.cjs +2 -0
- package/dist/chunk-HDGARCI2.cjs.map +1 -0
- package/dist/{chunk-MVP2YD4X.cjs → chunk-HG4NPDN5.cjs} +2 -2
- package/dist/{chunk-MVP2YD4X.cjs.map → chunk-HG4NPDN5.cjs.map} +1 -1
- package/dist/{chunk-FNNIAJNY.cjs → chunk-IMXSVHQK.cjs} +2 -2
- package/dist/{chunk-FNNIAJNY.cjs.map → chunk-IMXSVHQK.cjs.map} +1 -1
- package/dist/{chunk-LH7URJZT.js → chunk-IPOU3JTA.js} +3 -3
- package/dist/{chunk-LH7URJZT.js.map → chunk-IPOU3JTA.js.map} +1 -1
- package/dist/{chunk-WTEXBPBR.js → chunk-JOIQFDZQ.js} +2 -2
- package/dist/chunk-JOIQFDZQ.js.map +1 -0
- package/dist/{chunk-KHCNMNZZ.js → chunk-JP4JMQOG.js} +2 -2
- package/dist/{chunk-KHCNMNZZ.js.map → chunk-JP4JMQOG.js.map} +1 -1
- package/dist/chunk-KKMLFYVW.cjs +3 -0
- package/dist/chunk-KKMLFYVW.cjs.map +1 -0
- package/dist/{chunk-62LMTO4F.js → chunk-LHLW7JLS.js} +2 -2
- package/dist/{chunk-62LMTO4F.js.map → chunk-LHLW7JLS.js.map} +1 -1
- package/dist/{chunk-SOMGSIO4.cjs → chunk-NAZ6PGLS.cjs} +2 -2
- package/dist/chunk-NAZ6PGLS.cjs.map +1 -0
- package/dist/{chunk-A33K7NY4.js → chunk-O3ALJLYC.js} +2 -2
- package/dist/chunk-O3ALJLYC.js.map +1 -0
- package/dist/chunk-P4ETODMP.js +2 -0
- package/dist/chunk-P4ETODMP.js.map +1 -0
- package/dist/{chunk-P6WPEUAJ.cjs → chunk-PREIL3IB.cjs} +2 -2
- package/dist/{chunk-P6WPEUAJ.cjs.map → chunk-PREIL3IB.cjs.map} +1 -1
- package/dist/chunk-Q3PSTNSY.js +2 -0
- package/dist/chunk-Q3PSTNSY.js.map +1 -0
- package/dist/{chunk-NQSWT3UO.js → chunk-Q7HPPLMG.js} +2 -2
- package/dist/{chunk-NQSWT3UO.js.map → chunk-Q7HPPLMG.js.map} +1 -1
- package/dist/chunk-RC4M6HBX.cjs +2 -0
- package/dist/chunk-RC4M6HBX.cjs.map +1 -0
- package/dist/{chunk-MSYX32PF.cjs → chunk-S3DFU33X.cjs} +2 -2
- package/dist/{chunk-MSYX32PF.cjs.map → chunk-S3DFU33X.cjs.map} +1 -1
- package/dist/chunk-TVE2DNPU.js +2 -0
- package/dist/chunk-TVE2DNPU.js.map +1 -0
- package/dist/{chunk-YNMMRH44.js → chunk-TZYMXNIB.js} +2 -2
- package/dist/chunk-TZYMXNIB.js.map +1 -0
- package/dist/{chunk-6TPXH6Y5.cjs → chunk-UUAFDZK6.cjs} +3 -3
- package/dist/{chunk-6TPXH6Y5.cjs.map → chunk-UUAFDZK6.cjs.map} +1 -1
- package/dist/{chunk-QYO7IEPR.js → chunk-UZSPBFZN.js} +2 -2
- package/dist/{chunk-QYO7IEPR.js.map → chunk-UZSPBFZN.js.map} +1 -1
- package/dist/chunk-VJP4GGCW.cjs +2 -0
- package/dist/chunk-VJP4GGCW.cjs.map +1 -0
- package/dist/chunk-W5ELYJ4Z.cjs +2 -0
- package/dist/chunk-W5ELYJ4Z.cjs.map +1 -0
- package/dist/{chunk-YTCTUBR2.js → chunk-WOIJPV7Z.js} +2 -2
- package/dist/{chunk-YTCTUBR2.js.map → chunk-WOIJPV7Z.js.map} +1 -1
- package/dist/{chunk-MVZUTETT.js → chunk-XK23K3EJ.js} +2 -2
- package/dist/{chunk-MVZUTETT.js.map → chunk-XK23K3EJ.js.map} +1 -1
- package/dist/{chunk-MPB7KUN5.js → chunk-YAZ4DUJJ.js} +2 -2
- package/dist/chunk-YAZ4DUJJ.js.map +1 -0
- package/dist/chunk-YFX53MZF.js +2 -0
- package/dist/chunk-YFX53MZF.js.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +10 -10
- package/dist/engine.d.ts +10 -10
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/language.d.cts +9 -9
- package/dist/language.d.ts +9 -9
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +2 -2
- package/dist/lexer.d.ts +2 -2
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +2 -2
- package/dist/normalizer.d.ts +2 -2
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +8 -8
- package/dist/packages.d.ts +8 -8
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-BM8xc0CZ.d.cts → pipeline-B4wf3M1h.d.cts} +5 -24
- package/dist/{pipeline-J2ehIm7t.d.ts → pipeline-QIT4iD8f.d.ts} +5 -24
- package/dist/resolvers.d.cts +1 -1
- package/dist/resolvers.d.ts +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +1 -1
- package/dist/uom.d.ts +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +8 -7
- package/dist/vm.d.ts +8 -7
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +9 -9
- package/dist/worker.d.ts +9 -9
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2VK3NH5S.cjs +0 -3
- package/dist/chunk-2VK3NH5S.cjs.map +0 -1
- package/dist/chunk-3GAWAMT4.js +0 -2
- package/dist/chunk-3GAWAMT4.js.map +0 -1
- package/dist/chunk-4FCHZYAH.js +0 -3
- package/dist/chunk-4FCHZYAH.js.map +0 -1
- package/dist/chunk-4QVBSG6B.cjs +0 -2
- package/dist/chunk-4QVBSG6B.cjs.map +0 -1
- package/dist/chunk-556Q7VZC.cjs +0 -2
- package/dist/chunk-556Q7VZC.cjs.map +0 -1
- package/dist/chunk-75XDS65A.cjs.map +0 -1
- package/dist/chunk-A33K7NY4.js.map +0 -1
- package/dist/chunk-C65UDMWH.cjs +0 -2
- package/dist/chunk-C65UDMWH.cjs.map +0 -1
- package/dist/chunk-EURCQMZK.cjs +0 -2
- package/dist/chunk-FUDVKPB7.cjs +0 -2
- package/dist/chunk-FUDVKPB7.cjs.map +0 -1
- package/dist/chunk-GMSBBLUQ.js +0 -2
- package/dist/chunk-GMSBBLUQ.js.map +0 -1
- package/dist/chunk-JEFMG6CV.js +0 -2
- package/dist/chunk-JEFMG6CV.js.map +0 -1
- package/dist/chunk-K4MME6ZT.js +0 -2
- package/dist/chunk-K4MME6ZT.js.map +0 -1
- package/dist/chunk-MPB7KUN5.js.map +0 -1
- package/dist/chunk-PL7AH5EU.cjs +0 -5
- package/dist/chunk-PL7AH5EU.cjs.map +0 -1
- package/dist/chunk-PNDQRCRQ.cjs.map +0 -1
- package/dist/chunk-SNVPM27Q.cjs +0 -2
- package/dist/chunk-SNVPM27Q.cjs.map +0 -1
- package/dist/chunk-SOMGSIO4.cjs.map +0 -1
- package/dist/chunk-T3FBAFRR.js +0 -2
- package/dist/chunk-T3FBAFRR.js.map +0 -1
- package/dist/chunk-VBSMA7WJ.cjs.map +0 -1
- package/dist/chunk-WTEXBPBR.js.map +0 -1
- package/dist/chunk-WYIOXAFW.cjs +0 -2
- package/dist/chunk-WYIOXAFW.cjs.map +0 -1
- package/dist/chunk-YNMMRH44.js.map +0 -1
- package/dist/chunk-YOHM2WQT.js.map +0 -1
- package/dist/chunk-YVKHEAFT.js +0 -2
- package/dist/chunk-YVKHEAFT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory","EngineError","_EngineError","category","init","chain","current","lines","ErrorFactory","_ErrorFactory","defaultRecoverable","codeOrInit","message","context","normalizeUnknownError","error","ok","value","err","isOk","r","isErr","map","fn","mapErr","andThen","unwrapOr","fallback","match","arms","combine","results","values","throwIfErr","tryCatch","normalize","e","tryCatchAsync","CoreErrorCodes"],"mappings":"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","file":"chunk-MPB7KUN5.js","sourcesContent":["/**\n * The engine's structured error type, the \"Rust/Go-style, verbose, easy to\n * tell the issue\" half of the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n super(init.message);\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = init.recoverable ?? true;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n /** New with the 2.0 descriptor redesign: a parselet emits a plugin call by NAME (`BytecodeBuilder.emitPluginCall(name, argCount)`) and the engine resolves that name to the index it assigned at registration. This fires when the name is absent from the builder's name->index map: the package used a `pluginFunctions` name it never declared, or the expression was parsed before that package registered. Not a user-input error; a package-authoring/registration fault. See `parser/BytecodeBuilder.ts`'s `emitPluginCall()`. */\n UNKNOWN_PLUGIN_FUNCTION: \"UNKNOWN_PLUGIN_FUNCTION\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */\n EXPLAIN_ASYNC_UNSUPPORTED: \"EXPLAIN_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */\n WORKDAY_OFFSET_EXPECTED_DATE: \"WORKDAY_OFFSET_EXPECTED_DATE\",\n /** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_EXPECTED_DATES: \"WORKDAYS_BETWEEN_EXPECTED_DATES\",\n /** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_RANGE_TOO_LARGE: \"WORKDAYS_BETWEEN_RANGE_TOO_LARGE\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** A compound assignment (`name += expr` / `name -= expr`) with nothing on the right, a line half-typed on the way to `total += 5`. */\n COMPOUND_ASSIGN_REQUIRES_EXPRESSION: \"COMPOUND_ASSIGN_REQUIRES_EXPRESSION\",\n /** A running total (`+= / -=`) whose right-hand side calls an async plugin (weather/stocks/currency). The same v1 scope restriction as the `\"=>\"` and user-function bodies. */\n COMPOUND_ASSIGN_ASYNC_UNSUPPORTED: \"COMPOUND_ASSIGN_ASYNC_UNSUPPORTED\",\n /** A savings-goal contribution period that is not one of daily/weekly/monthly/yearly (`how long to save $X at $Y <period>`). Names the accepted set. */\n UNKNOWN_SAVINGS_PERIOD: \"UNKNOWN_SAVINGS_PERIOD\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n\n // ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──\n /** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */\n SNAPSHOT_VERSION_MISMATCH: \"SNAPSHOT_VERSION_MISMATCH\",\n /** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */\n SNAPSHOT_MALFORMED: \"SNAPSHOT_MALFORMED\",\n /** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */\n SNAPSHOT_UNSUPPORTED_VALUE: \"SNAPSHOT_UNSUPPORTED_VALUE\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s 0-255 index pool (a single opcode-stream byte) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * The aggregated catalog type. Currently just `CoreErrorCode`, union in\n * each package's own code-object type here as Phase 5 converts it, e.g.\n * `CoreErrorCode | WeatherErrorCode | StocksErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode;\n"]}
|
package/dist/chunk-PL7AH5EU.cjs
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkFNNIAJNY_cjs=require('./chunk-FNNIAJNY.cjs'),chunkLNZNJSRW_cjs=require('./chunk-LNZNJSRW.cjs'),chunkTTFO4YDP_cjs=require('./chunk-TTFO4YDP.cjs'),chunk556Q7VZC_cjs=require('./chunk-556Q7VZC.cjs'),chunkMVP2YD4X_cjs=require('./chunk-MVP2YD4X.cjs'),chunk6TPXH6Y5_cjs=require('./chunk-6TPXH6Y5.cjs'),chunkWYIOXAFW_cjs=require('./chunk-WYIOXAFW.cjs'),chunk4QVBSG6B_cjs=require('./chunk-4QVBSG6B.cjs'),chunkC65UDMWH_cjs=require('./chunk-C65UDMWH.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkZLRJ7TDP_cjs=require('./chunk-ZLRJ7TDP.cjs'),chunkEURCQMZK_cjs=require('./chunk-EURCQMZK.cjs'),chunk75XDS65A_cjs=require('./chunk-75XDS65A.cjs'),chunkPNDQRCRQ_cjs=require('./chunk-PNDQRCRQ.cjs'),chunkLUMVKVFQ_cjs=require('./chunk-LUMVKVFQ.cjs'),chunk3HYO3QYW_cjs=require('./chunk-3HYO3QYW.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkSNVPM27Q_cjs=require('./chunk-SNVPM27Q.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=chunkLUMVKVFQ_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=chunkLUMVKVFQ_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 chunkPNDQRCRQ_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 chunkPNDQRCRQ_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 chunkPNDQRCRQ_cjs.m(1,e,n.base)}case 2:return new chunkPNDQRCRQ_cjs.m(2,BigInt(n.v));case 3:return new chunkPNDQRCRQ_cjs.m(3,n.v);case 4:return new chunkPNDQRCRQ_cjs.m(4,_(n.v));case 5:return new chunkPNDQRCRQ_cjs.m(5,_(n.v));case 6:{let e=new chunkPNDQRCRQ_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 chunkPNDQRCRQ_cjs.m(7,t)}case 8:return new chunkPNDQRCRQ_cjs.m(8,{min:_(n.min),max:_(n.max)});case 10:return new chunkPNDQRCRQ_cjs.m(10,n.v);case 13:return new chunkPNDQRCRQ_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:chunkPNDQRCRQ_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=chunkEURCQMZK_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 chunk3HYO3QYW_cjs.c.classifyLine(n).skip}function Gn(n,e){return chunk3HYO3QYW_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 chunkSNVPM27Q_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col),f=new chunkSNVPM27Q_cjs.a("NUMBER",chunk5IJD5L3O_cjs.c("NUMBER"),c,c,i.offset,0,i.line,i.col),m=new chunkSNVPM27Q_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=chunk6TPXH6Y5_cjs.c(e,chunk6TPXH6Y5_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 chunk556Q7VZC_cjs.a;this.lineCache=new he;this.accumulatorNames=new Set;this.scopeManager=new chunk556Q7VZC_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=chunkLUMVKVFQ_cjs.c(chunkLUMVKVFQ_cjs.b,i??{}),this.lexer=new chunk3HYO3QYW_cjs.b(t,chunk3HYO3QYW_cjs.d(t)),this.registry=new chunkFNNIAJNY_cjs.b,this.context=chunkEURCQMZK_cjs.x(),r?(this.diagnosticPipeline=new chunkMVP2YD4X_cjs.a,this.timelineCollector=new chunkMVP2YD4X_cjs.b,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new chunkMVP2YD4X_cjs.a,this.normalizer=new chunkC65UDMWH_cjs.c;for(let[a,l]of Object.entries(chunkC65UDMWH_cjs.g))this.normalizer.addPhrase(a,l);this.normalizer.register(chunkC65UDMWH_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(chunkWYIOXAFW_cjs.h(()=>this.config.date.inputOrder)),this.parser=new chunkFNNIAJNY_cjs.a(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName),this.vm=chunk556Q7VZC_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 chunkPNDQRCRQ_cjs.P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=oe.GOAL_SEEK_MAX_NESTING_DEPTH)return chunkPNDQRCRQ_cjs.P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return chunkPNDQRCRQ_cjs.P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return chunkPNDQRCRQ_cjs.P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let 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=chunk556Q7VZC_cjs.d(a,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?chunkPNDQRCRQ_cjs.P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?chunkPNDQRCRQ_cjs.P(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 chunkPNDQRCRQ_cjs.P("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=chunkEURCQMZK_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))chunkEURCQMZK_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)chunkEURCQMZK_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=chunk556Q7VZC_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=chunkPNDQRCRQ_cjs.O(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=chunk556Q7VZC_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=chunk556Q7VZC_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 chunkPNDQRCRQ_cjs.P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return chunkPNDQRCRQ_cjs.P("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=chunk75XDS65A_cjs._(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=chunk75XDS65A_cjs.da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?chunkPNDQRCRQ_cjs.P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):chunk75XDS65A_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(),chunkPNDQRCRQ_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,chunkPNDQRCRQ_cjs.n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[chunkC65UDMWH_cjs.b("IDENT",l,[r]),chunkC65UDMWH_cjs.b(c.type,c.text,[i]),chunkC65UDMWH_cjs.b("LPAREN","(",[i]),...a,chunkC65UDMWH_cjs.b("RPAREN",")",[i])],p=chunk556Q7VZC_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(chunkWYIOXAFW_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)),chunkPNDQRCRQ_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)),chunkPNDQRCRQ_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 chunkEURCQMZK_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=chunkPNDQRCRQ_cjs.O(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=chunkPNDQRCRQ_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 chunkPNDQRCRQ_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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=chunkPNDQRCRQ_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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:chunkMVP2YD4X_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=chunkPNDQRCRQ_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:chunkPNDQRCRQ_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:chunkMVP2YD4X_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:chunkPNDQRCRQ_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:chunkMVP2YD4X_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:chunkMVP2YD4X_cjs.c.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:chunkMVP2YD4X_cjs.c.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:chunkMVP2YD4X_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value:chunkPNDQRCRQ_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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:chunkMVP2YD4X_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:chunkPNDQRCRQ_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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:chunkMVP2YD4X_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),chunkPNDQRCRQ_cjs.O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),chunkPNDQRCRQ_cjs.O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?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 chunkPNDQRCRQ_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 chunkPNDQRCRQ_cjs.n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),chunkPNDQRCRQ_cjs.O(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.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:chunkLUMVKVFQ_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,chunkPNDQRCRQ_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=chunkPNDQRCRQ_cjs.P(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=chunk556Q7VZC_cjs.c(chunkEURCQMZK_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=chunk556Q7VZC_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 chunkPNDQRCRQ_cjs.n(n.value);case 1:return chunkPNDQRCRQ_cjs.r(n.value);case 2:return chunkPNDQRCRQ_cjs.s(BigInt(n.value));case 3:return chunkPNDQRCRQ_cjs.t(String(n.value));case 4:return chunkPNDQRCRQ_cjs.M(n.value);case 5:return chunkPNDQRCRQ_cjs.N(n.value);case 6:return chunkPNDQRCRQ_cjs.u(n.value,n.unit??"");case 7:return chunkPNDQRCRQ_cjs.n(n.value);case 10:return chunkPNDQRCRQ_cjs.L(n.value!==0);case 12:return chunkPNDQRCRQ_cjs.O(n.queryKey??"");case 13:return chunkPNDQRCRQ_cjs.P("WORKER_EXECUTION_ERROR",n.unit??"Unknown worker error");default:return chunkPNDQRCRQ_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=chunk556Q7VZC_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=chunkPNDQRCRQ_cjs.P(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=chunkPNDQRCRQ_cjs.P(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-PL7AH5EU.cjs.map
|
|
5
|
-
//# sourceMappingURL=chunk-PL7AH5EU.cjs.map
|