solve-engine 2.38.10 → 2.38.12
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/{PackageCompatibility-Xu04H_z-.d.ts → PackageCompatibility-7daIo3Hc.d.ts} +1 -1
- package/dist/{PackageCompatibility-DMvoenB_.d.cts → PackageCompatibility-BQqAi18x.d.cts} +1 -1
- package/dist/{PackageRegistry-BgXiVaR8.d.cts → PackageRegistry-CgmkZ9-l.d.cts} +1 -1
- package/dist/{PackageRegistry-D2ysmOVL.d.ts → PackageRegistry-DcyhcuUP.d.ts} +1 -1
- package/dist/{VMBuiltins-DR0PyI_g.d.cts → VMBuiltins-CgXOvwMx.d.cts} +62 -0
- package/dist/{VMBuiltins-CjuRXAOD.d.ts → VMBuiltins-nHNiqOnT.d.ts} +62 -0
- package/dist/{VMCheckpoints-C2REEAxr.d.ts → VMCheckpoints-Cj1lxo1z.d.ts} +6 -1
- package/dist/{VMCheckpoints-Ch3ElC4X.d.cts → VMCheckpoints-ZCTfca_Z.d.cts} +6 -1
- package/dist/{chunk-24H6XWE3.cjs → chunk-25ZZB2W6.cjs} +2 -2
- package/dist/{chunk-24H6XWE3.cjs.map → chunk-25ZZB2W6.cjs.map} +1 -1
- package/dist/{chunk-DZIWDDU5.js → chunk-4RJUVBHL.js} +2 -2
- package/dist/{chunk-DZIWDDU5.js.map → chunk-4RJUVBHL.js.map} +1 -1
- package/dist/{chunk-SU7LRT6J.js → chunk-BKPNQTEU.js} +3 -3
- package/dist/{chunk-SU7LRT6J.js.map → chunk-BKPNQTEU.js.map} +1 -1
- package/dist/{chunk-PLYETVYZ.cjs → chunk-EIFT45H3.cjs} +2 -2
- package/dist/{chunk-PLYETVYZ.cjs.map → chunk-EIFT45H3.cjs.map} +1 -1
- package/dist/chunk-FTI34FPL.js +5 -0
- package/dist/chunk-FTI34FPL.js.map +1 -0
- package/dist/{chunk-WVMSZLMH.cjs → chunk-FU7TW5GB.cjs} +3 -3
- package/dist/chunk-FU7TW5GB.cjs.map +1 -0
- package/dist/chunk-JHHTGKHV.js +2 -0
- package/dist/chunk-JHHTGKHV.js.map +1 -0
- package/dist/chunk-JVIUA2PL.cjs +2 -0
- package/dist/chunk-JVIUA2PL.cjs.map +1 -0
- package/dist/{chunk-KKIGQ7GW.js → chunk-QQOYU665.js} +2 -2
- package/dist/{chunk-KKIGQ7GW.js.map → chunk-QQOYU665.js.map} +1 -1
- package/dist/{chunk-Y7UPP5QQ.cjs → chunk-QZ437BWD.cjs} +3 -3
- package/dist/{chunk-Y7UPP5QQ.cjs.map → chunk-QZ437BWD.cjs.map} +1 -1
- package/dist/{chunk-XTXPHCZR.cjs → chunk-TJR3EQB4.cjs} +5 -5
- package/dist/chunk-TJR3EQB4.cjs.map +1 -0
- package/dist/{chunk-NTSH57MK.js → chunk-WTIMAWOG.js} +2 -2
- package/dist/{chunk-NTSH57MK.js.map → chunk-WTIMAWOG.js.map} +1 -1
- package/dist/{chunk-LYGVLHAW.cjs → chunk-ZBXB3HDZ.cjs} +2 -2
- package/dist/{chunk-LYGVLHAW.cjs.map → chunk-ZBXB3HDZ.cjs.map} +1 -1
- package/dist/{chunk-3F2S43MU.js → chunk-ZGP35A6D.js} +3 -3
- package/dist/chunk-ZGP35A6D.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 +4 -4
- package/dist/engine.d.ts +4 -4
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/language.d.cts +3 -3
- package/dist/language.d.ts +3 -3
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +2 -2
- package/dist/packages.d.ts +2 -2
- package/dist/packages.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.cjs.map +1 -1
- package/dist/vm.d.cts +2 -2
- package/dist/vm.d.ts +2 -2
- package/dist/vm.js +1 -1
- package/dist/vm.js.map +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +2 -2
- package/dist/worker.d.ts +2 -2
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2JR7PALQ.js +0 -2
- package/dist/chunk-2JR7PALQ.js.map +0 -1
- package/dist/chunk-3F2S43MU.js.map +0 -1
- package/dist/chunk-CTC4ZR6K.js +0 -5
- package/dist/chunk-CTC4ZR6K.js.map +0 -1
- package/dist/chunk-Q57LJFCT.cjs +0 -2
- package/dist/chunk-Q57LJFCT.cjs.map +0 -1
- package/dist/chunk-WVMSZLMH.cjs.map +0 -1
- package/dist/chunk-XTXPHCZR.cjs.map +0 -1
package/dist/vm.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.cjs","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\tconst parent =\n\t\t\tthis.checkpoints.length > 0\n\t\t\t\t? this.checkpoints[this.checkpoints.length - 1]\n\t\t\t\t: null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","keep","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.cjs","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// Everything at or after this line goes before the new checkpoint is\n\t\t// taken.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so appending on a re-run broke both halves of that. Editing\n\t\t// line 2 of a document whose lines 1, 2 and 3 each define something\n\t\t// left the list as [1, 2, 3, 2]: `getNearestCheckpoint(2)` stops at the\n\t\t// first entry past its target, so it found the stale line 2 and\n\t\t// restored the old value, and the new line 2 inherited from line 3, a\n\t\t// chain running backwards through the document that would have defined\n\t\t// a variable from a line that had not run yet.\n\t\t//\n\t\t// Nothing is lost by dropping them. A pass runs in document order and\n\t\t// every line that writes takes a checkpoint, so the ones removed here\n\t\t// are re-taken by this same pass as it continues past this line.\n\t\tlet keep = this.checkpoints.length;\n\t\twhile (keep > 0 && this.checkpoints[keep - 1].lineNumber >= lineNumber) keep--;\n\t\tif (keep !== this.checkpoints.length) this.checkpoints.length = keep;\n\n\t\tconst parent = keep > 0 ? this.checkpoints[keep - 1] : null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
package/dist/vm.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as allocatePluginFunctionIndex, b as builtinFunctions, c as createVM, e as executeBytecode, p as pluginFunctionIndexFor, d as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-
|
|
1
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as allocatePluginFunctionIndex, b as builtinFunctions, c as createVM, e as executeBytecode, p as pluginFunctionIndexFor, d as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-CgXOvwMx.cjs';
|
|
2
2
|
import { V as Value } from './Value-B55Hvn3e.cjs';
|
|
3
3
|
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-B55Hvn3e.cjs';
|
|
4
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-
|
|
4
|
+
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-ZCTfca_Z.cjs';
|
|
5
5
|
import './BytecodeBuilder-DSWKZi4f.cjs';
|
|
6
6
|
import './CalendarBackend-MdS3Bb4P.cjs';
|
|
7
7
|
import './EngineError-Bm4OYmw8.cjs';
|
package/dist/vm.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as allocatePluginFunctionIndex, b as builtinFunctions, c as createVM, e as executeBytecode, p as pluginFunctionIndexFor, d as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-
|
|
1
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as allocatePluginFunctionIndex, b as builtinFunctions, c as createVM, e as executeBytecode, p as pluginFunctionIndexFor, d as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-nHNiqOnT.js';
|
|
2
2
|
import { V as Value } from './Value-B55Hvn3e.js';
|
|
3
3
|
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-B55Hvn3e.js';
|
|
4
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-
|
|
4
|
+
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-Cj1lxo1z.js';
|
|
5
5
|
import './BytecodeBuilder-DSWKZi4f.js';
|
|
6
6
|
import './CalendarBackend-MdS3Bb4P.js';
|
|
7
7
|
import './EngineError-Bm4OYmw8.js';
|
package/dist/vm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as ScopeManager,b as createVM,c as executeBytecode}from'./chunk-
|
|
1
|
+
export{a as ScopeManager,b as createVM,c as executeBytecode}from'./chunk-QQOYU665.js';import'./chunk-JP4JMQOG.js';export{b as DependencyGraph,y as OpRegistry,H as allocatePluginFunctionIndex,x as binaryOp,F as builtinFunctions,I as pluginFunctionIndexFor,G as pluginFunctionRegistry,z as sharedOpRegistry,l as unifyUom}from'./chunk-JHHTGKHV.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';export{m as Value,g as ValueType,s as bigIntValue,c as chargeAllocation,d as checkAllocation,e as checkedArray,E as colVectorValue,r as hexValue,C as matrixValue,n as numberValue,F as rangeValue,D as rowVectorValue,t as stringValue,u as uomValue}from'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import'./chunk-PRSXXDTA.js';import'./chunk-6G2NES2I.js';var l=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,r,e){if(e.length===0)return null;let n=this.checkpoints.length;for(;n>0&&this.checkpoints[n-1].lineNumber>=t;)n--;n!==this.checkpoints.length&&(this.checkpoints.length=n);let o=n>0?this.checkpoints[n-1]:null,i=Object.create(o?.variables??null),c=Object.create(o?.functions??null);for(let s of e){if(this.vm.hasUserFunction(s)){let a=this.vm.getUserFunction(s);a&&(c[s]=a);continue}let u=this.vm.getVar(s);u!==void 0&&(i[s]=u);}let p={lineNumber:t,lineId:r,variables:i,functions:c,parent:o};return this.checkpoints.push(p),p}restoreTo(t){let r=this.getNearestCheckpoint(t);if(!r){this.vm.reset();return}let e=[],n=r;for(;n;)e.unshift(n),n=n.parent;this.vm.reset();for(let o of e){for(let i of Object.keys(o.variables))this.vm.setVar(i,o.variables[i]);for(let i of Object.keys(o.functions)){let c=o.functions[i];this.vm.defineUserFunction(c.name,c.params,c.program);}}}getNearestCheckpoint(t){let r=null;for(let e of this.checkpoints)if(e.lineNumber<=t)r=e;else break;return r}getCheckpointAt(t){return this.checkpoints.find(r=>r.lineNumber===t)}getAllCheckpoints(){return this.checkpoints}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1].variables;for(;e;){if(Object.prototype.hasOwnProperty.call(e,t))return e[t];e=Object.getPrototypeOf(e);}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};export{l as VMCheckpointer};//# sourceMappingURL=vm.js.map
|
|
2
2
|
//# sourceMappingURL=vm.js.map
|
package/dist/vm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.js","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\tconst parent =\n\t\t\tthis.checkpoints.length > 0\n\t\t\t\t? this.checkpoints[this.checkpoints.length - 1]\n\t\t\t\t: null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","keep","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.js","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// Everything at or after this line goes before the new checkpoint is\n\t\t// taken.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so appending on a re-run broke both halves of that. Editing\n\t\t// line 2 of a document whose lines 1, 2 and 3 each define something\n\t\t// left the list as [1, 2, 3, 2]: `getNearestCheckpoint(2)` stops at the\n\t\t// first entry past its target, so it found the stale line 2 and\n\t\t// restored the old value, and the new line 2 inherited from line 3, a\n\t\t// chain running backwards through the document that would have defined\n\t\t// a variable from a line that had not run yet.\n\t\t//\n\t\t// Nothing is lost by dropping them. A pass runs in document order and\n\t\t// every line that writes takes a checkpoint, so the ones removed here\n\t\t// are re-taken by this same pass as it continues past this line.\n\t\tlet keep = this.checkpoints.length;\n\t\twhile (keep > 0 && this.checkpoints[keep - 1].lineNumber >= lineNumber) keep--;\n\t\tif (keep !== this.checkpoints.length) this.checkpoints.length = keep;\n\n\t\tconst parent = keep > 0 ? this.checkpoints[keep - 1] : null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
package/dist/worker.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkHSTGWWU2_cjs=require('./chunk-HSTGWWU2.cjs'),
|
|
2
|
-
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o=>{try{let a=$(n,o.packages);t=new
|
|
1
|
+
'use strict';var chunkHSTGWWU2_cjs=require('./chunk-HSTGWWU2.cjs'),chunkTJR3EQB4_cjs=require('./chunk-TJR3EQB4.cjs');require('./chunk-P5YWBIIU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-R3W53ZMP.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-EIFT45H3.cjs'),require('./chunk-HG4NPDN5.cjs');var chunkJUIHUG4M_cjs=require('./chunk-JUIHUG4M.cjs');require('./chunk-W4XLVZ6R.cjs');var chunkQZ437BWD_cjs=require('./chunk-QZ437BWD.cjs');require('./chunk-NMZRAJLJ.cjs');var chunkZBXB3HDZ_cjs=require('./chunk-ZBXB3HDZ.cjs');require('./chunk-K3PZ66XR.cjs'),require('./chunk-YV4GDW5A.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-GDLYXRMA.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-JVIUA2PL.cjs'),require('./chunk-OBZJKZ2F.cjs'),require('./chunk-SF5QVUEI.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs');var chunk5TVI2UPZ_cjs=require('./chunk-5TVI2UPZ.cjs'),chunk5N4XDULO_cjs=require('./chunk-5N4XDULO.cjs');require('./chunk-EQNKDTMX.cjs'),require('./chunk-E4HAKNBQ.cjs'),require('./chunk-NH74IT7B.cjs'),require('./chunk-PHWIO4P3.cjs');var chunk25ZZB2W6_cjs=require('./chunk-25ZZB2W6.cjs');require('./chunk-3MG7VIPL.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-72J5V7SN.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs');var chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');function B(e){if(e?.date?.inputOrder!=="locale")return e;let r={...e.date,inputOrder:chunkZBXB3HDZ_cjs.k({...chunk25ZZB2W6_cjs.b.date,...e.date}).order};return delete r.inputLocale,{...e,date:r}}var x=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:B(r.config),packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=chunkHSTGWWU2_cjs.e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(chunkHSTGWWU2_cjs.e());if(t?.aborted)return Promise.reject(chunkHSTGWWU2_cjs.d(r));let s=this.nextId++;return new Promise((i,l)=>{let c={resolve:i,reject:l};if(t){let p=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(chunkHSTGWWU2_cjs.d(r)));};c.signal=t,c.onAbort=p,t.addEventListener("abort",p,{once:true});}this.pending.set(s,c),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(chunkHSTGWWU2_cjs.c(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:chunkHSTGWWU2_cjs.c(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function G(e){let r=new x(e.transport);return await r.init(e),r}function F(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function H(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?chunk5N4XDULO_cjs.R(n):typeof n=="number"&&!Number.isFinite(n)?F(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:chunkJUIHUG4M_cjs.c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=F(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut),e.grain!==void 0&&(t.grain=e.grain),e.zone!==void 0&&(t.zone=e.zone);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=H(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:chunk5TVI2UPZ_cjs.f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:chunk5TVI2UPZ_cjs.g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:chunkJUIHUG4M_cjs.c(e).replace(/^=\s*/,"")};}return t}function q(e,r){return e?m(e,r):null}function J(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:q(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>J(n,r)),expression:e.expression,result:q(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function $(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw chunk6SYU4MH7_cjs.c.config(chunkHSTGWWU2_cjs.a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function Q(e,r={}){let n=r.packages??chunkQZ437BWD_cjs.z,t=null,s,i=new Map,l=new Map,c=null,p=null,g=o=>e.postMessage(o),E=(o,a)=>{g({kind:"error",id:o,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a))});},D=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
|
|
2
|
+
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o=>{try{let a=$(n,o.packages);t=new chunkTJR3EQB4_cjs.o({locale:o.localeCode??"en",diagnostics:o.diagnostics??!1,config:o.config,packages:a,calendar:r.calendar}),s=r.calendar?{...o.formatting??chunkJUIHUG4M_cjs.a,calendar:r.calendar}:o.formatting,U(t),g({kind:"ready",id:o.id});}catch(a){E(o.id,a);}},K=(o,a)=>{let{method:u,args:d}=a;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw chunk6SYU4MH7_cjs.c.execution(chunkHSTGWWU2_cjs.a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},_=o=>{let a=t;if(!a){E(o.id,chunk6SYU4MH7_cjs.c.execution(chunkHSTGWWU2_cjs.a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}c?.abort();let u=new AbortController;c=u,l=D(o),i.set(o.id,u),a.setKeystrokeSignal(u.signal);try{let d=K(a,o);g({kind:"result",id:o.id,value:d});}catch(d){E(o.id,d);}finally{i.delete(o.id),a.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":j(a);break;case "request":_(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{p?.(),p=null,c?.abort(),c=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function X(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function Y(){let e=null,r=null,n=true,t=(l,c)=>{let p=X(c);queueMicrotask(()=>{n&&l()?.(p);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function Z(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function ee(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}exports.createLinkedTransports=Y;exports.createWorkerEngine=G;exports.eventTargetTransport=Z;exports.messagePortTransport=ee;exports.serializeParsedLine=y;exports.serializeParsingResult=R;exports.serializeValue=m;exports.startWorkerRuntime=Q;//# sourceMappingURL=worker.cjs.map
|
|
3
3
|
//# sourceMappingURL=worker.cjs.map
|
package/dist/worker.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EngineConfigOverride } from './Configuration-BxriK9Kw.cjs';
|
|
2
|
-
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-
|
|
2
|
+
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-CgmkZ9-l.cjs';
|
|
3
3
|
import { F as FormattingSettings } from './FormattingSettings-ByO-4wiM.cjs';
|
|
4
4
|
import { E as EngineError } from './EngineError-Bm4OYmw8.cjs';
|
|
5
5
|
import { b as ValueType, i as ColourFormat, D as DatetimeGrain, V as Value } from './Value-B55Hvn3e.cjs';
|
|
@@ -13,7 +13,7 @@ import './Lexer-DaWkCu84.cjs';
|
|
|
13
13
|
import './resolvers.cjs';
|
|
14
14
|
import '@tanstack/query-core';
|
|
15
15
|
import './TokenNormalizer-D382VSYh.cjs';
|
|
16
|
-
import './VMBuiltins-
|
|
16
|
+
import './VMBuiltins-CgXOvwMx.cjs';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* The seam between the harness and whatever actually carries messages.
|
package/dist/worker.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EngineConfigOverride } from './Configuration-BxriK9Kw.js';
|
|
2
|
-
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-
|
|
2
|
+
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-DcyhcuUP.js';
|
|
3
3
|
import { F as FormattingSettings } from './FormattingSettings-CvCzAfsz.js';
|
|
4
4
|
import { E as EngineError } from './EngineError-Bm4OYmw8.js';
|
|
5
5
|
import { b as ValueType, i as ColourFormat, D as DatetimeGrain, V as Value } from './Value-B55Hvn3e.js';
|
|
@@ -13,7 +13,7 @@ import './Lexer-DPn5dfCH.js';
|
|
|
13
13
|
import './resolvers.js';
|
|
14
14
|
import '@tanstack/query-core';
|
|
15
15
|
import './TokenNormalizer-DAzPp-j1.js';
|
|
16
|
-
import './VMBuiltins-
|
|
16
|
+
import './VMBuiltins-nHNiqOnT.js';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* The seam between the harness and whatever actually carries messages.
|
package/dist/worker.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$1,e,d,c as c$2,b}from'./chunk-YID47OPR.js';import {o}from'./chunk-
|
|
1
|
+
import {a as a$1,e,d,c as c$2,b}from'./chunk-YID47OPR.js';import {o}from'./chunk-FTI34FPL.js';import'./chunk-RU3KGJRA.js';import'./chunk-2RWAXT6O.js';import'./chunk-RMDCGYZM.js';import'./chunk-MIQBJGGR.js';import'./chunk-QQOYU665.js';import'./chunk-JP4JMQOG.js';import {c,a}from'./chunk-SSS3ZMKX.js';import'./chunk-HLZRNZEU.js';import {z}from'./chunk-BKPNQTEU.js';import'./chunk-AWGSR2GZ.js';import {k}from'./chunk-WTIMAWOG.js';import'./chunk-U5MESNRT.js';import'./chunk-DB5ISONG.js';import'./chunk-76F3LCIL.js';import'./chunk-EOKHRS2T.js';import'./chunk-TCZSPH4A.js';import'./chunk-JHHTGKHV.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-5TCSFTZD.js';import {R as R$1}from'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';import'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import {b as b$1}from'./chunk-4RJUVBHL.js';import'./chunk-6NL7RBAG.js';import'./chunk-JPFCXLJV.js';import'./chunk-APYRNAU2.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c as c$1,d as d$1}from'./chunk-6G2NES2I.js';function B(e){if(e?.date?.inputOrder!=="locale")return e;let r={...e.date,inputOrder:k({...b$1.date,...e.date}).order};return delete r.inputLocale,{...e,date:r}}var x=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:B(r.config),packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((i,l)=>{let c={resolve:i,reject:l};if(t){let p=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};c.signal=t,c.onAbort=p,t.addEventListener("abort",p,{once:true});}this.pending.set(s,c),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function G(e){let r=new x(e.transport);return await r.init(e),r}function F(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function H(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R$1(n):typeof n=="number"&&!Number.isFinite(n)?F(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=F(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut),e.grain!==void 0&&(t.grain=e.grain),e.zone!==void 0&&(t.zone=e.zone);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=H(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:c(e).replace(/^=\s*/,"")};}return t}function q(e,r){return e?m(e,r):null}function J(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:q(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>J(n,r)),expression:e.expression,result:q(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function $(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw c$1.config(a$1.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function Q(e,r={}){let n=r.packages??z,t=null,s,i=new Map,l=new Map,c=null,p=null,g=o=>e.postMessage(o),E=(o,a)=>{g({kind:"error",id:o,error:b(d$1(a))});},D=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
|
|
2
2
|
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:b(d$1(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o$1=>{try{let a$1=$(n,o$1.packages);t=new o({locale:o$1.localeCode??"en",diagnostics:o$1.diagnostics??!1,config:o$1.config,packages:a$1,calendar:r.calendar}),s=r.calendar?{...o$1.formatting??a,calendar:r.calendar}:o$1.formatting,U(t),g({kind:"ready",id:o$1.id});}catch(a){E(o$1.id,a);}},K=(o,a)=>{let{method:u,args:d}=a;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw c$1.execution(a$1.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},_=o=>{let a=t;if(!a){E(o.id,c$1.execution(a$1.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}c?.abort();let u=new AbortController;c=u,l=D(o),i.set(o.id,u),a.setKeystrokeSignal(u.signal);try{let d=K(a,o);g({kind:"result",id:o.id,value:d});}catch(d){E(o.id,d);}finally{i.delete(o.id),a.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":j(a);break;case "request":_(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{p?.(),p=null,c?.abort(),c=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function X(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function Y(){let e=null,r=null,n=true,t=(l,c)=>{let p=X(c);queueMicrotask(()=>{n&&l()?.(p);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function Z(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function ee(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}export{Y as createLinkedTransports,G as createWorkerEngine,Z as eventTargetTransport,ee as messagePortTransport,y as serializeParsedLine,R as serializeParsingResult,m as serializeValue,Q as startWorkerRuntime};//# sourceMappingURL=worker.js.map
|
|
3
3
|
//# sourceMappingURL=worker.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "solve-engine",
|
|
3
|
-
"version": "2.38.
|
|
3
|
+
"version": "2.38.12",
|
|
4
4
|
"description": "An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"expression-evaluator",
|
package/dist/chunk-2JR7PALQ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-X2GQAKL2.js';import {c as c$2}from'./chunk-PICFFFJV.js';import {ga as ga$1,C as C$1,z as z$1,B,E,p,i,j,r,s,qa,l,h,g,f,e as e$1,k,Q as Q$2,V as V$1,ha as ha$1,la,ra as ra$1,ja,ma,J as J$1,w,o,a as a$1,d,u as u$1,W,Y,F as F$1,_,da,ca,ba,$,L,O as O$1,c as c$3,na as na$1,pa,ka,ia as ia$1,oa as oa$1,v as v$1,q as q$1,m as m$1,b as b$2,A,n as n$1,K as K$1,fa,I,H as H$1,G as G$1,N as N$1,t as t$1,D,P as P$1,y,x,M}from'./chunk-IHPYXJIY.js';import {b}from'./chunk-EOO6M65F.js';import {Q as Q$1,P,p as p$1,q,K,n,s as s$1,u,C as C$2,v,m,H,N,t,r as r$1}from'./chunk-A34R65WT.js';import {c as c$1,e,i as i$1,j as j$1}from'./chunk-BWTVJD5L.js';import {a}from'./chunk-PRSXXDTA.js';import {c}from'./chunk-6G2NES2I.js';var Rr={variable:"",global:"global:",tag:"#",datasource:"ds:"};function hn(e,t){return Rr[e]+t}function pn(e,t){return hn("datasource",`${e}:${JSON.stringify(t)}`)}var yt=new Set,bn=new Set,yn=class{constructor(){this.consumers=new Map;this.producers=new Map;this.dependencies=new Map;this.writes=new Map;this.lineReads=new Map;this.pinnedReads=new Map;}hasSameEdges(t,n,r,o,i){if(t===void 0||t.size!==r.length+(i?.size??0))return false;if(o.length===0){if(n!==void 0)return false}else if(n===void 0||n.size!==o.length)return false;for(let a of r)if(!t.has(a))return false;if(n!==void 0){for(let a of o)if(!n.has(a))return false}return true}registerLine(t,n,r){let o=this.pinnedReads.size!==0?this.pinnedReads.get(t):void 0,i=this.lineReads.get(t),a=this.writes.get(t);if(this.hasSameEdges(i,a,n,r,o))return;if(i)for(let s of i){if(o?.has(s))continue;let l=this.consumers.get(s);l&&l.delete(t);}if(a)for(let s of a){let l=this.producers.get(s);l&&l.delete(t);}let u=new Set(n);if(o)for(let s of o)u.add(s);this.lineReads.set(t,u);for(let s of n){let l=this.consumers.get(s);l!==void 0?l.add(t):this.consumers.set(s,new Set([t]));}for(let s of r){let l=this.producers.get(s);l!==void 0?l.add(t):this.producers.set(s,new Set([t]));}if(r.length>0){this.dependencies.set(t,o===void 0?u:new Set(n)),this.writes.set(t,new Set(r));for(let s of r){let l=this.consumers.get(s);l&&l.delete(t);}}else this.writes.delete(t),this.dependencies.delete(t);}registerLineDataSourceDependency(t,n,r){let o=pn(n,r),i=this.pinnedReads.get(t);i!==void 0?i.add(o):this.pinnedReads.set(t,new Set([o]));let a=this.lineReads.get(t);a===void 0?this.lineReads.set(t,new Set([o])):(a===this.dependencies.get(t)&&this.dependencies.set(t,new Set(a)),a.add(o));let u=this.consumers.get(o);u!==void 0?u.add(t):this.consumers.set(o,new Set([t]));}getAffectedLines(t){let n=new Set,r=this.consumers.get(t);if(r===void 0)return n;let o=new Set([t]),i=[r];for(let a=0;a<i.length;a++)for(let u of i[a]){if(n.has(u))continue;n.add(u);let s=this.writes.get(u);if(s!==void 0)for(let l of s){if(o.has(l))continue;o.add(l);let d=this.consumers.get(l);d!==void 0&&i.push(d);}}return n}getAffectedLinesInOrder(t){let n=this.getAffectedLines(t);if(n.size===0)return [];let r=n.size,o=new Array(r),i=new Array(r),a=new Array(r);{let b=0;for(let A of n)o[b]=A,i[b]=this.writes.get(A),a[b]=this.lineReads.get(A),b++;}let u=new Set;for(let b=0;b<r;b++){let A=i[b];if(A!==void 0)for(let j of A)u.add(j);}let s=new Map,l=[],d=[];for(let b=0;b<r;b++){let A=a[b];if(A===void 0)continue;let j=i[b];for(let Y of A){if(!u.has(Y)||j!==void 0&&j.has(Y))continue;let ee=s.get(Y);ee===void 0&&(ee=r+s.size,s.set(Y,ee)),l.push(ee),d.push(b);}}let h=r+s.size;if(s.size===0)return o;let g=[],I=[];for(let b=0;b<r;b++){let A=i[b];if(A!==void 0)for(let j of A){let Y=s.get(j);Y!==void 0&&(g.push(b),I.push(Y));}}let q=g.length,at=l.length,Pe=new Int32Array(h),Le=new Int32Array(h);for(let b=0;b<q;b++)Pe[g[b]]++,Le[I[b]]++;for(let b=0;b<at;b++)Pe[l[b]]++,Le[d[b]]++;let se=new Int32Array(h+1);for(let b=0;b<h;b++)se[b+1]=se[b]+Pe[b];let ut=new Int32Array(se[h]),st=Pe;st.set(se.subarray(0,h));for(let b=0;b<q;b++)ut[st[g[b]]++]=I[b];for(let b=0;b<at;b++)ut[st[l[b]]++]=d[b];let Fe=new Int32Array(h),ge=new Uint8Array(h),Ne=0;for(let b=0;b<h;b++)Le[b]===0&&(Fe[Ne++]=b,ge[b]=1);if(Ne===0){let b=0;for(let A=1;A<r;A++)o[A]<o[b]&&(b=A);Fe[Ne++]=b,ge[b]=1;}let Ue=[];for(let b=0;b<Ne;b++){let A=Fe[b];A<r&&Ue.push(o[A]);let j=se[A+1];for(let Y=se[A];Y<j;Y++){let ee=ut[Y];--Le[ee]===0&&ge[ee]===0&&(Fe[Ne++]=ee,ge[ee]=1);}}if(Ue.length<r){let b=[];for(let A=0;A<r;A++)ge[A]===0&&b.push(o[A]);b.sort((A,j)=>A-j);for(let A=0;A<b.length;A++)Ue.push(b[A]);}return Ue}getAffectedLinesByDataSource(t,n){return this.consumers.get(pn(t,n))??yt}removeLine(t){let n=this.lineReads.get(t);if(n){for(let o of n){let i=this.consumers.get(o);i&&i.delete(t);}this.lineReads.delete(t);}let r=this.writes.get(t);if(r)for(let o of r)this.producers.get(o)?.delete(t);r!==void 0&&(this.dependencies.delete(t),this.writes.delete(t)),this.pinnedReads.size!==0&&this.pinnedReads.delete(t);}getConsumers(t){return this.consumers.get(t)??yt}getProducers(t){return this.producers.get(t)??yt}getDependencies(t){return this.dependencies.get(t)??bn}getWrites(t){return this.writes.get(t)??bn}getSnapshot(){let t={};for(let[s,l]of this.consumers)t[s]=Array.from(l);let n={};for(let[s,l]of this.writes)n[s]=Array.from(l);let r={};for(let[s,l]of this.lineReads)r[s]=Array.from(l);let o={};for(let[s,l]of this.producers)o[s]=Array.from(l);let i=hn("datasource",""),a={};for(let[s,l]of this.lineReads){let d=Array.from(l).filter(h=>h.startsWith(i));d.length>0&&(a[s]=d.map(h=>h.slice(i.length)));}let u={};for(let[s,l]of this.consumers)s.startsWith(i)&&(u[s.slice(i.length)]=Array.from(l));return {consumers:t,producers:o,writes:n,reads:r,dataSourceDeps:a,dataSourceConsumers:u}}clear(){this.consumers.clear(),this.producers.clear(),this.dependencies.clear(),this.writes.clear(),this.lineReads.clear(),this.pinnedReads.clear();}};function gn(e,t){let n=t===2?L:M,r=n(e.n),o=n(e.d);return r===null||o===null?null:{n:r,d:o}}function Nn(e,t){let n=y(e),r=new Map;for(let[o,i]of n){if(i%t!==0)return null;r.set(o,i/t);}return x(r)}function Ar(e,t){let n=y(e);for(let[r,o]of y(t))n.set(r,(n.get(r)??0)+o);return x(n)}function Rn(e,t){let n=y(e);for(let[r,o]of y(t)){let i=(n.get(r)??0)-o;i<=0?n.delete(r):n.set(r,i);}return x(n)}function xr(e,t){let n=y(e),r=new Map;for(let[o,i]of y(t)){let a=n.get(o);a!==void 0&&r.set(o,Math.min(a,i));}return x(r)}function Sr(e){let t=new Set;for(let n of e)for(let r of y(n).keys())t.add(r);return [...t].sort()}function oe(e){let t=new Map;for(let n of e)t.set(n.key,n.coefficient);return E({terms:t,vars:Sr(e.map(n=>n.key))})}function ht(e){let t=e[0];for(let n=1;n<e.length;n++)t={kind:"mul",left:t,right:e[n]};return t}function vr(e){return [...e.terms].map(([n,r])=>({key:n,coefficient:r})).sort((n,r)=>D(n.key,r.key,e.vars))}function Sn(e){if(e.vars.length<2)return null;let t=vr(e);return t.length===2?Mr(t[0],t[1]):t.length===3?Ir(t):t.length===4?Er(t):null}function Mr(e,t){let n=e.coefficient.n>0n,r=t.coefficient.n>0n;if(!n)return null;let o=gt(e,t,2);if(o!==null&&!r)return ht([oe([o.a,Xe(o.b)]),oe([o.a,o.b])]);let i=gt(e,t,3);if(i===null)return null;let a=oe(r?[i.a,i.b]:[i.a,Xe(i.b)]),u=r?Xe(Ze(i.a,i.b)):Ze(i.a,i.b);return ht([a,oe([An(i.a),u,An(i.b)])])}function gt(e,t,n){let r=t.coefficient.n<0n?j(t.coefficient):t.coefficient,o=gn(e.coefficient,n),i=gn(r,n);if(o===null||i===null)return null;let a=Nn(e.key,n),u=Nn(t.key,n);return a===null||u===null?null:{a:{key:a,coefficient:o},b:{key:u,coefficient:i}}}function Xe(e){return {key:e.key,coefficient:j(e.coefficient)}}function Ze(e,t){return {key:Ar(e.key,t.key),coefficient:h(e.coefficient,t.coefficient)}}function An(e){return Ze(e,e)}function Ir(e){let[t,n,r]=e;if(t.coefficient.n<0n||r.coefficient.n<0n)return null;let o=gt(t,r,2);if(o===null)return null;let i$1=Ze(o.a,o.b);if(i$1.key!==n.key)return null;let a=h(i$1.coefficient,{n:2n,d:1n}),u=n.coefficient.n<0n,s=u?j(n.coefficient):n.coefficient;return m$1(i(s,a))?{kind:"pow",base:oe([o.a,u?Xe(o.b):o.b]),exponent:p(2)}:null}function Er(e){let t=[[[0,1],[2,3]],[[0,2],[1,3]],[[0,3],[1,2]]];for(let n of t){let r=xn(e[n[0][0]],e[n[0][1]]),o=xn(e[n[1][0]],e[n[1][1]]);if(!(r===null||o===null)&&kr(r.cofactor,o.cofactor))return ht([oe([r.common,o.common]),oe(r.cofactor)])}return null}function xn(e,t){let n=xr(e.key,t.key),r={key:n,coefficient:e.coefficient},o=[{key:Rn(e.key,n),coefficient:{n:1n,d:1n}},{key:Rn(t.key,n),coefficient:i(t.coefficient,e.coefficient)}];return o[0].key===o[1].key?null:{common:r,cofactor:o}}function kr(e,t){return e.length!==t.length?false:e.every((n,r)=>n.key===t[r].key&&n.coefficient.n===t[r].coefficient.n&&n.coefficient.d===t[r].coefficient.d)}var wr=12,He=4096,_r=100000n;function We(e,t){let n=e<0n?-e:e,r=t<0n?-t:t;for(;r!==0n;){let o=n%r;n=r,r=o;}return n}function Mn(e,t){return e===0n||t===0n?0n:e/We(e,t)*t}function vn(e){let t=e<0n?-e:e;if(t===0n)return null;let n=[];for(let r=1n;r*r<=t;r++){if(r>_r)return null;if(t%r!==0n)continue;n.push(r);let o=t/r;if(o!==r&&n.push(o),n.length>He)return null}return n}function In(e,t){let n=a$1;for(let r of e)n=f(h(n,t),r);return n}function Tr(e,t){let n=[e[0]];for(let r=1;r<e.length-1;r++)n.push(f(e[r],h(n[r-1],t)));return n}function be(e){if(e.length<2)return [];if(e.length===2){let[l$1,d]=e;return l(l$1)?[]:[i(g(a$1,d),l$1)]}let t=1n;for(let l of e)t=Mn(t,l.d);let n=e.map(l=>l.n*t/l.d),r=n[0],o=n[n.length-1];if(o===0n)return [];let i$1=vn(o),a=vn(r);if(i$1===null||a===null)throw c.execution("SYMBOLIC_FACTOR_LIMIT_EXCEEDED","This polynomial's coefficients have too many divisors to search for rational roots.",{limit:He});if(i$1.length*a.length>He)throw c.execution("SYMBOLIC_FACTOR_LIMIT_EXCEEDED","This polynomial has too many candidate rational roots to test.",{limit:He});let u=[],s=new Set;for(let l$1 of i$1)for(let d of a)for(let h of [1n,-1n]){let g={n:h*l$1/We(l$1,d),d:d/We(l$1,d)},I=`${g.n}/${g.d}`;s.has(I)||(s.add(I),l(In(e,g))&&u.push(g));}return u}function Vr(e,t){return l(t)?q$1(e):t.n>0n?{kind:"sub",left:q$1(e),right:p(t)}:{kind:"add",left:q$1(e),right:p(j(t))}}function Or(e,t){let n=e.length-1,r=new Map;return e.forEach((o,i)=>{if(l(o))return;let a=n-i;r.set(a===0?"":a===1?t:`${t}^${a}`,o);}),E({terms:r,vars:r.size>0?[t]:[]})}function Rt(e,t){let n=[],r=[...e],o=be(r);for(;o.length>0&&r.length>2;){for(let a of o){let u=0;for(;r.length>1&&l(In(r,a));)r=Tr(r,a),u++;u>0&&n.push({base:Vr(t,a),power:u});}o=r.length>2?be(r):[];}return r.length-1>=1?(n.push({base:Or(r,t),power:1}),{content:b$2,factors:n}):{content:r.length===1?r[0]:b$2,factors:n}}function Cr(e){let t=[];m$1(e.content)||t.push(p(e.content));for(let r$1 of e.factors)t.push(r$1.power===1?r$1.base:r(r$1.base,p({n:BigInt(r$1.power),d:1n})));if(t.length===0)return p(b$2);let n=t[0];for(let r=1;r<t.length;r++)n={kind:"mul",left:n,right:t[r]};return n}function Dr(e){let t=0n,n=1n;for(let r of e.terms.values())t=We(t,r.n),n=Mn(n,r.d);return t===0n?b$2:{n:t,d:n}}function Pr(e){let t=new Map;for(let o of e.vars){let i=1/0;for(let a of e.terms.keys()){let u=Lr(a,o);u<i&&(i=u);}i>0&&i!==1/0&&t.set(o,i);}if(t.size===0)return {monomial:t,reduced:e};let n=new Map;for(let[o,i]of e.terms){let a=Nt(o);for(let[u,s]of t)a.set(u,(a.get(u)??0)-s);n.set(Fr(a),i);}let r=new Set;for(let o of n.keys())for(let i of Nt(o).keys())r.add(i);return {monomial:t,reduced:{terms:n,vars:[...r].sort()}}}function Lr(e,t){return Nt(e).get(t)??0}function Nt(e){let t=new Map;if(e==="")return t;for(let n of e.split("*")){let r=n.indexOf("^");r===-1?t.set(n,1):t.set(n.slice(0,r),Number(n.slice(r+1)));}return t}function Fr(e){return [...e.keys()].filter(n=>(e.get(n)??0)>0).sort().map(n=>e.get(n)===1?n:`${n}^${e.get(n)}`).join("*")}function Ur(e){let t=[...e.keys()].sort(),n=null;for(let r$1 of t){let o=e.get(r$1),i=o===1?q$1(r$1):r(q$1(r$1),p({n:BigInt(o),d:1n}));n=n===null?i:{kind:"mul",left:n,right:i};}return n}function En(e){let t=C$1(e);if(t===null||t.terms.size===0||z$1(t)>wr||t.vars.length===0)return e;let n=Dr(t),r=m$1(n)?t:$r(t,i(b$2,n)),{monomial:o,reduced:i$1}=Pr(r),a=Ur(o),u=A(i$1);if(u===null){let q=Sn(i$1);return q!==null?Br(n,a,q):qr(n,a,i$1)??e}let s=[...B(i$1,u)].reverse(),l=Rt(s,u),d=h(n,l.content);if(l.factors.length<=1&&(l.factors[0]?.power??1)===1&&a===null&&m$1(d))return e;let g=[];m$1(d)||g.push(p(d)),a!==null&&g.push(a),g.push(Cr({content:b$2,factors:l.factors}));let I=g[0];for(let q=1;q<g.length;q++)I={kind:"mul",left:I,right:g[q]};return I}function $r(e,t){let n=new Map;for(let[r,o]of e.terms)n.set(r,h(o,t));return {terms:n,vars:e.vars}}function Br(e,t,n){let r=[];m$1(e)||r.push(p(e)),t!==null&&r.push(t),r.push(n);let o=r[0];for(let i=1;i<r.length;i++)o={kind:"mul",left:o,right:r[i]};return o}function qr(e,t,n){if(t===null&&m$1(e))return null;let r=[];m$1(e)||r.push(p(e)),t!==null&&r.push(t),r.push(E(n));let o=r[0];for(let i=1;i<r.length;i++)o={kind:"mul",left:o,right:r[i]};return o}var V={n:2n,d:1n},G={n:3n,d:1n},Ee={n:4n,d:1n};function Yr(e,t,n,r){let o=j(i(t,h(G,e))),i$1=i(g(h(G,h(e,n)),h(t,t)),h(G,h(e,e))),a=h(V,h(t,h(t,t))),u=h({n:9n,d:1n},h(e,h(t,n))),s=h({n:27n,d:1n},h(h(e,e),r)),l=i(f(g(a,u),s),h({n:27n,d:1n},h(e,h(e,e))));return {p:i$1,q:l,shift:o}}function wn(e,t,n,r){let{p:o,q:i,shift:a}=Yr(e,t,n,r),u=j(f(h(Ee,h(o,h(o,o))),h({n:27n,d:1n},h(i,i))));return k(u,a$1)>0?{exact:[],approximate:jr(o,i,a)}:l(u)?{exact:Kr(o,i,a),approximate:[]}:{exact:Gr(o,i,a),approximate:[]}}function Kr(e,t,n){if(l(e))return [p(n)];let r=f(i(h(G,t),e),n),o=f(j(i(h(G,t),h(V,e))),n);return [r,o].sort(k).map(p)}function Gr(e,t,n){let r=j(i(t,V)),o=f(h(i(t,V),i(t,V)),h(i(e,G),h(i(e,G),i(e,G)))),i$1=O$1(o),a={kind:"call",name:"cbrt",args:[{kind:"add",left:p(r),right:i$1}]},u={kind:"call",name:"cbrt",args:[{kind:"sub",left:p(r),right:i$1}]},s={kind:"add",left:a,right:u},l={kind:"sub",left:a,right:u},d={kind:"add",left:p(n),right:{kind:"div",left:{kind:"neg",operand:s},right:p(V)}},h$1={kind:"mul",left:{kind:"div",left:{kind:"mul",left:l,right:O$1(G)},right:p(V)},right:w(n$1)};return [{kind:"add",left:p(n),right:s},{kind:"sub",left:d,right:h$1},{kind:"add",left:d,right:h$1}]}function jr(e,t,n){let r=e$1(e),o=e$1(t),i=e$1(n),a=2*Math.sqrt(-r/3),u=3*o/(2*r)*Math.sqrt(-3/r),s=Math.acos(Math.min(1,Math.max(-1,u)))/3;return [0,1,2].map(l=>a*Math.cos(s-2*Math.PI*l/3)+i).sort((l,d)=>l-d)}function Xr(e,t,n,r){let o=j(i(e,Ee)),i$1=h(e,e),a=g(t,i(h(G,i$1),{n:8n,d:1n})),u=f(g(n,i(h(e,t),V)),i(h(i$1,e),{n:8n,d:1n})),s=g(f(g(r,i(h(e,n),Ee)),i(h(i$1,t),{n:16n,d:1n})),i(h(G,h(i$1,i$1)),{n:256n,d:1n}));return {p:a,q:u,r:s,shift:o}}function _n(e,t,n,r,o,i$1){let a=I=>i(I,e),{p:u,q:s,r:l$1,shift:d}=Xr(a(t),a(n),a(r),a(o)),h=l(s)?Hr(u,l$1):Jr(u,s,l$1,i$1);if(h===null)return null;let g=l(d)?h:h.map(I=>({kind:"add",left:p(d),right:I}));return {exact:Zr(g),approximate:[]}}function Zr(e){let t=new Set,n=[];for(let r of e){let o=t$1(Q$2(r));t.has(o)||(t.add(o),n.push(r));}return n}function Hr(e,t){let n=g(h(e,e),h(Ee,t));if(k(n,a$1)<0)return Qr(e,t);let r=N$1(n);return r!==null?Wr(j(e),r,l(n)):zr(e,t,n)}function Wr(e,t,n){let r=n?[i(e,V)]:[i(f(e,t),V),i(g(e,t),V)],o=[];for(let i of r){if(l(i)){o.push(p(a$1));continue}let a=P$1(i);o.push({kind:"neg",operand:a},a);}return o}function zr(e,t,n){let r=p(j(e)),o=O$1(n),i=k(e,a$1)<=0,a=[{node:At({kind:"add",left:r,right:o}),positive:i||k(t,a$1)<=0},{node:At({kind:"sub",left:r,right:o}),positive:i&&k(t,a$1)>=0}],u=[];for(let{node:s,positive:l}of a){let h={kind:"call",name:"sqrt",args:[l?s:{kind:"neg",operand:s}]},g=l?h:{kind:"mul",left:h,right:w(n$1)};u.push({kind:"neg",operand:g},g);}return u}function At(e){return {kind:"div",left:e,right:p(V)}}function Qr(e,t){let n=i(j(e),V),r=N$1(t),o=r===null?kn(O$1(t),n):O$1(i(f(r,n),V)),a={kind:"mul",left:r===null?kn(O$1(t),j(n)):O$1(i(g(r,n),V)),right:w(n$1)},u={kind:"add",left:o,right:a},s={kind:"sub",left:o,right:a};return [{kind:"neg",operand:u},{kind:"neg",operand:s},s,u]}function kn(e,t){let n=t.n>=0n?{kind:"add",left:e,right:p(t)}:{kind:"sub",left:e,right:p(j(t))};return {kind:"call",name:"sqrt",args:[At(n)]}}function Jr(e,t,n,r){let o=[{n:1n,d:1n},h(V,e),g(h(e,e),h(Ee,n)),j(h(t,t))];for(let i$1 of be(o)){if(k(i$1,a$1)<=0)continue;let a=N$1(i$1);if(a===null)continue;let u=f(e,i$1),s=i(t,a),l=i(g(u,s),V),d=i(f(u,s),V),h={n:1n,d:1n};return [...r(h,a,l),...r(h,j(a),d)]}return null}var eo=200,to=1e-14,no=1e-10,ro=1e-10,Tn=1e-9,oo=1e-8,io=4;function ke(e,t){return {re:e.re-t.re,im:e.im-t.im}}function ao(e,t){return {re:e.re*t.re-e.im*t.im,im:e.re*t.im+e.im*t.re}}function On(e,t){if(Math.abs(t.re)>=Math.abs(t.im)){let o=t.im/t.re,i=t.re+t.im*o;return {re:(e.re+e.im*o)/i,im:(e.im-e.re*o)/i}}let n=t.re/t.im,r=t.re*n+t.im;return {re:(e.re*n+e.im)/r,im:(e.im*n-e.re)/r}}function z(e){return Math.hypot(e.re,e.im)}function ze(e,t){let n=0,r=0;for(let o of e){let i=n*t.re-r*t.im+o;r=n*t.im+r*t.re,n=i;}return {re:n,im:r}}function uo(e,t){let n=z(t),r=0;for(let o of e)r=r*n+Math.abs(o);return r}function so(e){let t=e.length-1,n=[];for(let r=0;r<t;r++)n.push(e[r]*(t-r));return n}function lo(e){let t=[...e].reverse(),r=[...K$1(t)].reverse().map(e$1);return r.some(o=>!Number.isFinite(o))?null:r}function co(e){let t=e.length-1,n=0;for(let a=1;a<e.length;a++)n=Math.max(n,Math.abs(e[a]));let r=1+n,o=-e[1]/t,i=[];for(let a=0;a<t;a++){let u=2*Math.PI*a/t+Math.PI/(2*t);i.push({re:o+r*Math.cos(u),im:r*Math.sin(u)});}return i}function mo(e){let t=e.length-1,n=co(e);for(let r=0;r<eo;r++){let o=0,i=1;for(let a=0;a<t;a++){let u={re:1,im:0};for(let l=0;l<t;l++)a!==l&&(u=ao(u,ke(n[a],n[l])));if(u.re===0&&u.im===0){n[a]={re:n[a].re+1e-6*(a+1),im:n[a].im+1e-6};continue}let s=On(ze(e,n[a]),u);if(!Number.isFinite(s.re)||!Number.isFinite(s.im))return null;n[a]=ke(n[a],s),o=Math.max(o,z(s)),i=Math.max(i,z(n[a]));}if(o<=to*i)return n}return null}function Vn(e,t,n){let r=n;for(let o=0;o<io;o++){let i=ze(t,r);if(i.re===0&&i.im===0)break;let a=ke(r,On(ze(e,r),i));if(!Number.isFinite(a.re)||!Number.isFinite(a.im))break;r=a;}return r}function fo(e,t,n){let r=Math.max(1,z(n));if(n.im!==0&&Math.abs(n.im)<=Tn*r){let o=Vn(e,t,{re:n.re,im:0});if(xt(e,o))return {re:o.re,im:0}}if(n.re!==0&&Math.abs(n.re)<=Tn*r){let o=Vn(e,t,{re:0,im:n.im});if(xt(e,o))return {re:0,im:o.im}}return n}function xt(e,t){return !Number.isFinite(t.re)||!Number.isFinite(t.im)?false:z(ze(e,t))<=no*uo(e,t)}function po(e){let t=[...e],n=t.map(r=>r.im===0);for(let r=0;r<t.length;r++){if(n[r])continue;let o={re:t[r].re,im:-t[r].im},i=-1,a=Number.POSITIVE_INFINITY;for(let d=r+1;d<t.length;d++){if(n[d])continue;let h=z(ke(t[d],o));h<a&&(a=h,i=d);}if(i===-1||a>oo*Math.max(1,z(t[r])))continue;let u=(t[r].re+t[i].re)/2,s=(Math.abs(t[r].im)+Math.abs(t[i].im))/2,l=t[r].im<0?-1:1;t[r]={re:u,im:l*s},t[i]={re:u,im:-l*s},n[r]=true,n[i]=true;}return t}function bo(e){for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let r=Math.max(1,z(e[t]),z(e[n]));if(z(ke(e[t],e[n]))<=ro*r)return false}return true}function Cn(e){let t=lo(e);if(t===null)return null;if(t.length<2)return [];let n=mo(t);if(n===null)return null;let r=so(t),o=po(n).map(i=>fo(t,r,i));for(let i of o)if(!xt(t,i))return null;return bo(o)?[...o].sort((i,a)=>i.re-a.re||i.im-a.im):null}var Dn=8;function yo(e,t){let n=a$1;for(let r of e)n=f(h(n,t),r);return n}function ho(e,t){let n=[e[0]];for(let r=1;r<e.length-1;r++)n.push(f(e[r],h(n[r-1],t)));return n}function Pn(e,t,n){let r=g(h(t,t),h(Ro(),h(e,n))),o=h(No(),e);if(k(r,a$1)<0)return go(j(t),r,o);if(l(r))return [p(i(j(t),o))];let i$1=L(r.n),a=L(r.d);if(i$1!==null&&a!==null){let h={n:i$1,d:a},g$1=i(f(j(t),h),o),I=i(g(j(t),h),o);return k(I,g$1)<=0?[p(I),p(g$1)]:[p(g$1),p(I)]}let u=O$1(r),s=k(o,a$1)>0,l$1={kind:"div",left:{kind:"sub",left:p(j(t)),right:u},right:p(o)},d={kind:"div",left:{kind:"add",left:p(j(t)),right:u},right:p(o)};return s?[l$1,d]:[d,l$1]}function go(e,t,n){let r=j(t),o$1=L(r.n),i$1=L(r.d);if(o$1!==null&&i$1!==null){let l=i({n:o$1,d:i$1},n),d=i(e,n);return [w(o(d,j(l))),w(o(d,l))]}let a=i(e,n),u=i(r,h(n,n)),s={kind:"mul",left:O$1(u),right:w(n$1)};return l(a)?[{kind:"neg",operand:s},s]:[{kind:"sub",left:p(a),right:s},{kind:"add",left:p(a),right:s}]}function No(){return {n:2n,d:1n}}function Ro(){return {n:4n,d:1n}}function Ao(e){return {re:e,im:0}}function Ln(e,t,n){let r=C$1({kind:"sub",left:e,right:t});if(r===null)return {kind:"unsupported",reason:"this is not a polynomial equation (it divides by an unknown, or calls a function of one)"};let o=r.vars.filter(u=>u!==n),i=z$1(r,n);if(o.length>0)return i!==1?{kind:"unsupported",reason:`solving for "${n}" needs the equation to be linear in it when other unknowns (${o.join(", ")}) are present`}:xo(r,n);if(i===0)return r.terms.size===0?{kind:"identity"}:{kind:"contradiction"};if(i>Dn)return {kind:"unsupported",reason:`degree ${i} is above the supported maximum of ${Dn}`};let a=[...B(r,n)].reverse();return Mo(a)}function xo(e,t){let n=new Map,r=new Map;for(let[u,s]of e.terms){let l=u.split("*").filter(h=>h.length>0),d=l.indexOf(t);d===-1?r.set(u,s):(l.splice(d,1),n.set(l.join("*"),s));}let o=u=>{let s=new Set;for(let l of u.keys())for(let d of l.split("*"))d.length>0&&s.add(d.split("^")[0]);return [...s].sort()},i=E({terms:n,vars:o(n)});return {kind:"roots",exact:[{kind:"div",left:{kind:"neg",operand:E({terms:r,vars:o(r)})},right:i}],approximate:[]}}function So(e){return e.length===4?wn(e[0],e[1],e[2],e[3]):e.length===5?_n(e[0],e[1],e[2],e[3],e[4],Pn):null}function vo(e){let t=[],n=[...e],r=0;for(;n.length>1&&l(n[n.length-1]);)n=n.slice(0,-1),r++;for(r>0&&t.push(a$1);n.length>1;){let o=be(n);if(o.length===0)break;for(let i of o){let a=0;for(;n.length>1&&l(yo(n,i));)n=ho(n,i),a++;a>0&&t.push(i);}}return {roots:t.sort(k),remaining:n}}function Mo(e){let{roots:t,remaining:n}=vo(e),r=t.map(p),o=[],i$1=n.length-1,a=e.length-n.length;if(i$1<=0)return ye(r,o,a,0,"");if(i$1===1)return r.push(p(i(j(n[1]),n[0]))),ye(r,o,a+1,0,"");if(i$1===2)return r.push(...Pn(n[0],n[1],n[2])),ye(r,o,a+2,0,"");let u=So(n);if(u!==null)return r.push(...u.exact),o.push(...u.approximate.map(Ao)),ye(r,o,a+i$1,0,"");let s=Cn(n);return s!==null?(o.push(...s),ye(r,o,a+i$1,0,"")):ye(r,o,a,i$1,`a degree-${i$1} factor of it has no exact solution here and the numerical method did not converge on that factor`)}function ye(e,t,n,r,o){let i=e.length+t.length,a=n>=1&&(i<1||i>n);return r>0||a?{kind:"incomplete",exact:e,approximate:t,missing:a?Math.max(1,n+r-i):r,reason:a?`${i} root${i===1?"":"s"} were produced for a degree-${n+r} equation, which does not add up`:o}:{kind:"roots",exact:e,approximate:t}}var Fn={0:"sqrt",1:"abs",2:"sin",3:"cos",4:"tan",5:"log",6:"ceil",7:"floor",8:"round",11:"asin",12:"acos",13:"atan",14:"atan2",15:"sinh",16:"cosh",17:"tanh",18:"asinh",19:"acosh",20:"atanh",21:"cbrt",23:"expm1",24:"exp",26:"hypot",28:"log10",29:"log1p",30:"log2",33:"sign",34:"trunc",35:"degtorad",36:"radtodeg",61:"root",62:"fact"},Io=31,na=new Set([67,68,69,70,71,72,73,74,75,76,77,78,79]);function O(e){if(e.type===9)return e.value;if(e.type===13||e.type===12)return null;let t=e.toNumber();return Number.isFinite(t)?p(d(t)):null}function C(e){let t=Q$2(e);return t.kind==="const"?n(e$1(t.value)):K(t)}function Qe(e){return P("SYMBOLIC_UNSUPPORTED_FUNCTION",`"${e}" cannot be applied to an expression that still contains an unknown.`)}function ra(e,t){let n=O(e),r$1=O(t);return n===null||r$1===null?Qe("^"):C(r(n,r$1))}function oa(e){let t=O(e);return t===null?Qe("-"):C({kind:"neg",operand:t})}function ia(e,t){let n=[];for(let o of t){let i=Q$1(o);if(i)return i;let a=O(o);if(a===null)return Qe(Fn[e]??`builtin ${e}`);n.push(a);}if(e===Io&&n.length===2)return C(r(n[0],n[1]));let r$1=Fn[e];return r$1===void 0?Qe(`builtin ${e}`):C(s(r$1,n))}function Eo(e){let t=C(e);return t.type===0&&!Number.isInteger(t.toNumber())?K(e):t}function ko(e){return e.im===0?n(e.re):K(w(o(d(e.re),d(e.im))))}function wo(e){switch(e.kind){case "identity":return t("true for every value");case "contradiction":return t("no solution");case "unsupported":return P("SYMBOLIC_SOLVE_UNSUPPORTED",`Cannot solve this equation: ${e.reason}.`);case "incomplete":{let t=e.exact.length+e.approximate.length;return P("SYMBOLIC_SOLVE_INCOMPLETE",`Only ${t} of this equation's ${t+e.missing} roots could be found: ${e.reason}.`)}case "roots":{let t$1=e.exact.map(Eo);for(let n of e.approximate)t$1.push(ko(n));return t$1.length===0?t("no solution"):t$1.length===1?t$1[0]:C$2(1,t$1.length,t$1.map(n=>n.type===9?n.value:n.toNumber()))}}}function $n(e,t,n){let r=O(e),o=O(t);return r===null||o===null?P("SYMBOLIC_NONFINITE_OPERAND","An equation side has no exact value to solve with."):wo(Ln(r,o,n))}function he(e$1,t){if(e$1.type===6&&t.type===6){if(e$1.unit===t.unit)return {lv:e$1.toNumber(),rv:t.toNumber(),unit:e$1.unit,sameMeasure:true};let n=c$1(e$1.unit),r=c$1(t.unit),o=c$2.isCurrency(e$1.unit)&&c$2.isCurrency(t.unit);if(n&&n===r){let i=e(t.toNumber(),t.unit,e$1.unit);return {lv:e$1.toNumber(),rv:i,unit:e$1.unit,sameMeasure:true}}if(o){let i=c$2.convertSync(t.toNumber(),t.unit,e$1.unit);if(i!==null)return {lv:e$1.toNumber(),rv:i,unit:e$1.unit,sameMeasure:true}}return {lv:e$1.toNumber(),rv:t.toNumber(),unit:void 0,sameMeasure:false}}return e$1.type===6?{lv:e$1.toNumber(),rv:t.toNumber(),unit:e$1.unit,sameMeasure:true}:t.type===6?{lv:e$1.toNumber(),rv:t.toNumber(),unit:t.unit,sameMeasure:true}:{lv:e$1.toNumber(),rv:t.toNumber(),unit:void 0,sameMeasure:true}}function we(e,t){let n=new Array(e.length),r;for(let o=0;o<e.length;o++){let i=e[o];if(i.type!==6||i.unit===void 0){n[o]=i.toNumber();continue}if(r===void 0){r=i,n[o]=i.toNumber();continue}let{rv:a,sameMeasure:u}=he(r,i);if(!u){let s=_e(r.unit,i.unit,t);return P("INCOMPATIBLE_UNITS",s??`Cannot combine incompatible units: ${r.unit??"?"} and ${i.unit??"?"}`)}n[o]=a;}return {magnitudes:n,unit:r?.unit}}var _o=1e-12;function To(e,t,n){let r=0;return Number.isFinite(e)&&Math.abs(e)>r&&(r=Math.abs(e)),Number.isFinite(t)&&Math.abs(t)>r&&(r=Math.abs(t)),Number.isFinite(n)&&Math.abs(n)>r&&(r=Math.abs(n)),r}function ya(e,t){let{lv:n,rv:r,sameMeasure:o}=he(e,t);if(!o)return {lv:n,rv:r,equal:false,sameMeasure:false};if(e.type===6&&t.type===6&&e.unit!==void 0&&e.unit===t.unit&&e.exact!==void 0&&t.exact!==void 0&&c$2.isCurrency(e.unit))return {lv:n,rv:r,equal:qa(e.exact,t.exact)===0,sameMeasure:true};if(n===r)return {lv:n,rv:r,equal:true,sameMeasure:true};if(!Number.isFinite(n)||!Number.isFinite(r))return {lv:n,rv:r,equal:false,sameMeasure:true};let i=To(n,r,t.toNumber());return {lv:n,rv:r,equal:Math.abs(n-r)<=i*_o,sameMeasure:true}}var Vo={time:"duration",luminousIntensity:"luminous intensity"},Oo=new Set(["money","data"]),Co={add:"added",sub:"subtracted",mul:"multiplied",div:"divided"};function Je(e){if(c$2.isCurrency(e))return "money";let t=c$1(e);if(t!==void 0)return Vo[t]??t}function Bn(e){return Oo.has(e)?e:/^[aeiou]/.test(e)?`an ${e}`:`a ${e}`}function _e(e,t,n){let r=e===void 0?void 0:Je(e),o=t===void 0?void 0:Je(t);if(r!==void 0&&o!==void 0&&r!==o)return `${r} and ${o} cannot be ${n}`}function Do(e){return e!==void 0?Co[e]??"combined":"combined"}function ha(e,t){let n=Je(e),r=Je(t);if(n!==void 0&&r!==void 0&&n!==r)return `${Bn(n)} cannot be converted to ${Bn(r)}`}function ga(e,t){let n=e.type===6?e.unit:void 0,r=t.type===6?t.unit:void 0,o=_e(n,r,"compared");return P("INCOMPATIBLE_UNITS",o??`Cannot compare incompatible units: ${n??"?"} and ${r??"?"}`)}function qn(e){if(e.type===2)return e.value;let t=e.toNumber();if(!Number.isInteger(t)){let n=Number.isNaN(t)?"NaN":String(t);throw c.execution("BIGINT_INEXACT_OPERAND",`A whole-number (n) value can only be combined with another whole number, and ${n} is not one`,{operand:n})}return BigInt(t)}function Na(){return c.execution("BIGINT_DIVISION_BY_ZERO","Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity")}function Ra(e,t){let n=Yn(e),r=Yn(t);return n===null||r===null?null:n<r?-1:n>r?1:0}function Yn(e){if(e.type===2)return e.value;let t=e.toNumber();return Number.isInteger(t)?BigInt(t):null}function St(e,t){return Number.isFinite(t)?Math.pow(e,t):e===1||e===-1&&!Number.isNaN(t)?1:Math.pow(e,t)}function Kn(e){return e.exact!==void 0?e.exact:ha$1(e.toNumber())}function Po(e,t,n){let r=e.type===6&&e.unit!==void 0&&e.exact!==void 0&&c$2.isCurrency(e.unit),o=t.type===6&&t.unit!==void 0&&t.exact!==void 0&&c$2.isCurrency(t.unit);if(!r&&!o)return null;let i,a,u;if(r&&o){if(e.unit!==t.unit||n==="div")return null;i=e.exact,a=t.exact,u=e.unit;}else if(r&&t.type!==6)i=e.exact,u=e.unit,a=Kn(t);else if(o&&e.type!==6)a=t.exact,u=t.unit,i=Kn(e);else return null;if(i===null||a===null)return null;let s;switch(n){case "add":s=ja(i,a);break;case "sub":s=ka(i,a);break;case "mul":s=la(i,a);break;case "div":if(na$1(a))return null;s=pa(i,a);break}return v(ra$1(s),u,s)}function et(e){return e.rational!==void 0?e.rational:(e.type===0||e.type===1)&&typeof e.value=="number"&&Number.isInteger(e.value)?c$3(BigInt(e.value)):null}function Aa(e,t,n){let r=et(e);if(r===null)return null;let o=et(t);if(o===null||n==="div"&&l(o))return null;let i$1;try{switch(n){case "add":i$1=f(r,o);break;case "sub":i$1=g(r,o);break;case "mul":i$1=h(r,o);break;case "div":i$1=i(r,o);break}}catch{return null}return p$1(e$1(i$1),i$1)}function xa(e,t,n){if(e.type!==0||t.type!==0)return null;let r=e.value,o=t.value,i=e.uncertainty??0,a=t.uncertainty??0,u,s;switch(n){case "add":u=r+o,s=Math.hypot(i,a);break;case "sub":u=r-o,s=Math.hypot(i,a);break;case "mul":u=r*o,s=Math.hypot(o*i,r*a);break;case "div":u=r/o,s=Math.hypot(i/o,r*a/(o*o));break}return q(u,s)}function Sa(e,t){let n=et(e);if(n===null)return null;let r=et(t);return r===null?null:k(n,r)}function va(e,t,n$1,r,o){if(e.type===13)return e;if(t.type===13)return t;if(e.type===12)return e;if(t.type===12)return t;if(o&&(e.type===9||t.type===9)){let i=O(e),a=O(t);return i===null||a===null?P("SYMBOLIC_NONFINITE_OPERAND","A symbolic expression cannot combine with a value that has no exact number (NaN or infinity)."):K(Q$2({kind:o,left:i,right:a}))}if(e.type===0&&t.type===0)return n(n$1(e.value,t.value));if(e.type===2||t.type===2){let i=qn(e),a=qn(t);return r?s$1(r(i,a)):s$1(i+a)}if(e.type===6||t.type===6){if(o){let g=Po(e,t,o);if(g)return g}let{lv:i,rv:a,unit:u$1,sameMeasure:s}=he(e,t);if(!s){let g=e.type===6?e.unit:void 0,I=t.type===6?t.unit:void 0,q=_e(g,I,Do(o));return P("INCOMPATIBLE_UNITS",q??`Cannot combine incompatible units: ${g??"?"} and ${I??"?"}`)}let l=u(n$1(i,a),u$1),d=e.datetimeSpan===true&&t.datetimeSpan===true,h=e.datetimeSpan===true&&t.type===0||t.datetimeSpan===true&&e.type===0;return (d||h)&&(l.datetimeSpan=true),l}if(e.type===7&&t.type===7){let i=e.value,a=t.value;if(!V$1(i,a))return P("DIMENSION_MISMATCH",`Cannot combine matrices of different shapes: ${i.rows}x${i.cols} and ${a.rows}x${a.cols}`);let u=new Array(i.data.length);for(let s=0;s<i.data.length;s++)u[s]=n$1(i.data[s],a.data[s]);return C$2(i.rows,i.cols,u)}if(e.type===7){let i=e.value,a=t.toNumber(),u=i.data.map(s=>n$1(s,a));return C$2(i.rows,i.cols,u)}if(t.type===7){let i=t.value,a=e.toNumber(),u=i.data.map(s=>n$1(a,s));return C$2(i.rows,i.cols,u)}return n(n$1(e.toNumber(),t.toNumber()))}var Gn=254,jn=200,Te=class{constructor(){this.handlers=new Map;this.nextOpcode=jn+1;}register(t){this.handlers.set(t.opcode,t.handler);}unregister(t){this.handlers.delete(t);}get(t){return this.handlers.get(t)}has(t){return this.handlers.has(t)}allocateOpcode(){if(this.nextOpcode>Gn)throw c.config("OPCODE_POOL_EXHAUSTED",`OpRegistry: dynamic opcode pool exhausted (max ${Gn-jn} allocations).`);return this.nextOpcode++}},Ea=new Te;var Zn=ga$1(1);function Ve(e,t){return c$2.isCurrency(t)?e.exact??ha$1(e.toNumber()):null}function vt(e){if(!Number.isFinite(e))return null;if(Number.isInteger(e))return ga$1(BigInt(e));let t=String(e);return /^-?\d+\.\d+$/.test(t)?ia$1(t):null}function Hn(e,t,n){let r=Ve(e,n),o=vt(t);if(r!==null&&o!==null){let i=la(r,o);return v(ra$1(i),n,i)}return u(e.toNumber()*t,n)}function Wn(e,t,n,r){let o=Ve(e,t),i=vt(n);if(o!==null&&i!==null){let a=ja(Zn,r===1?i:ma(i)),u=la(o,a);return v(ra$1(u),t,u)}return u(e.toNumber()*(1+r*n),t)}function zn(e){let t=vt(e);return t===null?null:ja(Zn,t)}function Qn(e,t,n){let r=Ve(e,t),o=zn(n);if(r===null||o===null||na$1(o))return null;let i=pa(r,o);return v(ra$1(i),t,i)}function Jn(e,t,n){let r=Ve(e,t),o=zn(n);if(r===null||o===null||na$1(o))return null;let i=ka(r,pa(r,o));return v(ra$1(i),t,i)}function er(e,t){let n=e.unit,r=n!==void 0&&c$2.isCurrency(n)?Lo(e,n):null;if(r===null)return {unit:n,shares:[{value:e.toNumber()/t,count:t}]};let o=BigInt(t),i=r/o,a=r-i*o,u=Number(a<0n?-a:a),s=r<0n?-1n:1n,l=Xn(i,t-u);return u===0?{unit:n,shares:[l]}:{unit:n,shares:[l,Xn(i+s,u)]}}function Xn(e,t){let n=fa(e,2);return {value:ra$1(n),exact:n,count:t}}function Lo(e,t){let n=Ve(e,t);return n===null?null:oa$1(n,2).coef}var Fo=12;function tr(e,t){if(e.length===0||t.length===0)return [];let n=new Array(e.length+t.length-1).fill(a$1);return e.forEach((r,o)=>{t.forEach((i,a)=>{n[o+a]=f(n[o+a],h(r,i));});}),n}function Uo(e,t){let n=[b$2];for(let r=0;r<t;r++)n=tr(n,e);return n}function Mt(e,t){return e.map(n=>i(n,t))}function $o(e,t){let n=[],r=0;for(;r<e.length&&l(e[r]);)r++;r>0&&n.push({base:[a$1,b$2],power:r});let o=e.slice(r);if(o.length>1){let i=Rt([...o].reverse(),t);for(let a of i.factors){let u=C$1(a.base);if(u===null)return null;n.push({base:[...B(u,t)],power:a.power});}}return n.length>0?n:null}function Bo(e){let t=[];return e.forEach((n,r)=>{let o=n.base.length-1;for(let i=1;i<=n.power;i++)for(let a=0;a<o;a++)t.push({factor:r,power:i,degree:a});}),t}function qo(e,t,n){let r=Uo(t[e.factor].base,e.power),{quotient:o,remainder:i}=H$1(n,r);if(!G$1(i))return null;let a=new Array(e.degree).fill(a$1);return a.push(b$2),tr(o,a)}function Yo(e,t){let n=t.length;for(let r=0;r<n;r++){let o=-1;for(let i=r;i<n;i++)if(!l(e[i][r])){o=i;break}if(o===-1)return null;[e[r],e[o]]=[e[o],e[r]],[t[r],t[o]]=[t[o],t[r]];for(let i$1=0;i$1<n;i$1++){if(i$1===r||l(e[i$1][r]))continue;let a=i(e[i$1][r],e[r][r]);for(let u=r;u<n;u++)e[i$1][u]=g(e[i$1][u],h(a,e[r][u]));t[i$1]=g(t[i$1],h(a,t[r]));}}return t.map((r,o)=>i(r,e[o][o]))}function It(e,t,n){if(t.length<2||t.length-1>Fo)return null;let r=I(e,t),o=r.length>1?H$1(e,r).quotient:[...e],i=r.length>1?H$1(t,r).quotient:[...t];if(i.length===1)return {polynomial:Mt(o,i[0]),terms:[]};if(i.length===0)return null;let a=i[i.length-1],u=Mt(i,a),s=Mt(o,a),{quotient:l,remainder:d}=H$1(s,u);if(G$1(d))return {polynomial:l,terms:[]};let h=$o(u,n);if(h===null)return null;let g=Ko(h,u,d);return g===null?null:{polynomial:l,terms:g}}function Ko(e,t,n){let r=Bo(e),o=t.length-1;if(r.length!==o)return null;let i=[];for(let l of r){let d=qo(l,e,t);if(d===null)return null;i.push(d);}let a=[];for(let l=0;l<o;l++)a.push(i.map(d=>d[l]??a$1));let u=[];for(let l=0;l<o;l++)u.push(n[l]??a$1);let s=Yo(a,u);return s===null?null:Go(r,s,e)}function Go(e,t,n){let r=new Map;e.forEach((i,a)=>{let u=`${i.factor}:${i.power}`,s=r.get(u)??[];s[i.degree]=t[a],r.set(u,s);});let o=[];for(let[i,a]of r){let[u,s]=i.split(":").map(Number),l$1=[...a].map(d=>d??a$1);l$1.every(l)||o.push({numerator:l$1,base:n[u].base,power:s});}return o}function Oe(e,t){let n=new Map;return e.forEach((r,o)=>{l(r)||n.set(o===0?"":o===1?t:`${t}^${o}`,r);}),n.size===0?p(a$1):E({terms:n,vars:e.length>1?[t]:[]})}function nr(e){let t=Et(e);if(t===null)return e;let n=It(t.numerator,t.denominator,t.variable);if(n===null||n.terms.length===0)return e;let r$1=n.polynomial.length>0?Oe(n.polynomial,t.variable):null;for(let o of n.terms){let i=Oe(o.base,t.variable),a=o.power===1?i:r(i,p({n:BigInt(o.power),d:1n})),u=jo(o.numerator),s=u?o.numerator.map(d=>j(d)):o.numerator,l={kind:"div",left:Oe(s,t.variable),right:a};r$1===null?r$1=u?{kind:"neg",operand:l}:l:r$1={kind:u?"sub":"add",left:r$1,right:l};}return r$1===null?e:Q$2(r$1)}function jo(e){return e.some(t=>t.n<0n)&&e.every(t=>t.n<=0n)}function Et(e){if(e.kind!=="div")return null;let t=C$1(e.left),n=C$1(e.right);if(t===null||n===null)return null;let r=A(n);return r===null||t.vars.some(o=>o!==r)?null:{numerator:B(t,r),denominator:B(n,r),variable:r}}var kt=16;function rr(){return p(a$1)}function Q(){return p(b$2)}function Xo(e,t){switch(e){case "sin":return s("cos",[t]);case "cos":return {kind:"neg",operand:s("sin",[t])};case "tan":return {kind:"div",left:Q(),right:r(s("cos",[t]),p(2))};case "exp":return s("exp",[t]);case "log":return {kind:"div",left:Q(),right:t};case "sqrt":return {kind:"div",left:Q(),right:{kind:"mul",left:p(2),right:s("sqrt",[t])}};case "asin":return {kind:"div",left:Q(),right:s("sqrt",[or(t)])};case "acos":return {kind:"neg",operand:{kind:"div",left:Q(),right:s("sqrt",[or(t)])}};case "atan":return {kind:"div",left:Q(),right:Zo(t)};case "sinh":return s("cosh",[t]);case "cosh":return s("sinh",[t]);case "tanh":return {kind:"div",left:Q(),right:r(s("cosh",[t]),p(2))};case "abs":return s("sign",[t]);default:return null}}function or(e){return {kind:"sub",left:Q(),right:r(e,p(2))}}function Zo(e){return {kind:"add",left:Q(),right:r(e,p(2))}}function Ce(e,t,n=1){if(n<0||!Number.isInteger(n))throw c.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT","A derivative order must be a whole number, at least zero.");if(n>kt)throw c.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT",`A derivative order above ${kt} is not supported.`,{limit:kt});let r=Q$2(e);for(let o=0;o<n;o++)r=Q$2(F(r,t));return r}function F(e,t){switch(e.kind){case "const":case "complex":return rr();case "var":return e.name===t?Q():rr();case "add":return {kind:"add",left:F(e.left,t),right:F(e.right,t)};case "sub":return {kind:"sub",left:F(e.left,t),right:F(e.right,t)};case "neg":return {kind:"neg",operand:F(e.operand,t)};case "mul":return {kind:"add",left:{kind:"mul",left:F(e.left,t),right:e.right},right:{kind:"mul",left:e.left,right:F(e.right,t)}};case "div":return {kind:"div",left:{kind:"sub",left:{kind:"mul",left:F(e.left,t),right:e.right},right:{kind:"mul",left:e.left,right:F(e.right,t)}},right:r(e.right,p(2))};case "pow":return Ho(e,t);case "call":{if(e.args.length!==1)return wt(e,t);let n=Xo(e.name,e.args[0]);return n===null?wt(e,t):{kind:"mul",left:n,right:F(e.args[0],t)}}}}function Ho(e,t){if(e.exponent.kind==="const"){let n=p(g(e.exponent.value,b$2));return {kind:"mul",left:{kind:"mul",left:e.exponent,right:r(e.base,n)},right:F(e.base,t)}}return e.base.kind==="const"&&e.base.value.n>0n?{kind:"mul",left:{kind:"mul",left:e,right:s("log",[e.base])},right:F(e.exponent,t)}:wt(e,t)}function wt(e,t){return s("der",[e,q$1(t)])}function ir(e,t){let n=C$1(e);if(n===null||n.vars.filter(u=>u!==t).length>0||z$1(n,t)>1)return null;let o=B(n,t),i=o[0]??{n:0n,d:1n},a=o[1]??{n:0n,d:1n};return l(a)?null:{slope:a,intercept:i}}function Wo(e,t){let n=C$1(e);if(n===null)return null;let r$1=n.vars.filter(a=>a!==t);if(r$1.length>0)return {ok:false,reason:`it involves more than one unknown (${r$1.join(", ")})`};let o=B(n,t),i$1=p(0);return o.forEach((a,u)=>{if(l(a))return;let s=u+1,l$1=i(a,{n:BigInt(s),d:1n}),d={kind:"mul",left:p(l$1),right:s===1?q$1(t):r(q$1(t),p(s))};i$1={kind:"add",left:i$1,right:d};}),{ok:true,value:Q$2(i$1)}}function zo(e,t){if(e.kind!=="call"||e.args.length!==1)return null;let n=ir(e.args[0],t);if(n===null)return null;let r=e.args[0],o=i=>Q$2({kind:"div",left:i,right:p(n.slope)});switch(e.name){case "exp":return {ok:true,value:o(s("exp",[r]))};case "sin":return {ok:true,value:o({kind:"neg",operand:s("cos",[r])})};case "cos":return {ok:true,value:o(s("sin",[r]))};case "log":return {ok:true,value:o({kind:"sub",left:{kind:"mul",left:r,right:s("log",[r])},right:r})};default:return null}}function Qo(e,t){if(e.kind!=="div"||e.left.kind!=="const"||!_t(e.left.value))return null;let n=ir(e.right,t);if(n!==null)return {ok:true,value:Q$2({kind:"div",left:s("log",[e.right]),right:p(n.slope)})};let r=C$1(e.right);if(r!==null&&r.vars.length===1&&r.vars[0]===t){let o=B(r,t);if(o.length===3&&_t(o[0])&&l(o[1])&&_t(o[2]))return {ok:true,value:s("atan",[q$1(t)])}}return null}function _t(e){return e.n===1n&&e.d===1n}function Jo(e,t){let n=Et(e);if(n===null||n.variable!==t)return null;let r=It(n.numerator,n.denominator,t);if(r===null)return null;let o=r.polynomial.length>0?ni(r.polynomial,t):p(0);for(let i of r.terms){let a=ei(i,t);if(a===null)return {ok:false,reason:"its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have"};o={kind:"add",left:o,right:a};}return {ok:true,value:Q$2(o)}}function ei(e,t){let n=e.base.length-1,r$1=Oe(e.base,t);if(n===1){let o=e.numerator[0]??a$1;if(e.power===1)return {kind:"mul",left:p(o),right:s("log",[r$1])};let i$1=e.power-1,a=i(o,{n:BigInt(-i$1),d:1n});return {kind:"div",left:p(a),right:r(r$1,p({n:BigInt(i$1),d:1n}))}}return n!==2||e.power!==1?null:ti(e,t,r$1)}function ti(e,t,n){let r=e.numerator[0]??a$1,o=e.numerator[1]??a$1,[i,a]=e.base,u={n:1n,d:2n},s$1=h(a,u),l$1={kind:"mul",left:p(h(o,u)),right:s("log",[n])},d=g(r,h(o,s$1));if(l(d))return l$1;let h$1=O$1(g(i,h(s$1,s$1))),g$1={kind:"add",left:q$1(t),right:p(s$1)},I={kind:"mul",left:{kind:"div",left:p(d),right:h$1},right:s("atan",[{kind:"div",left:g$1,right:h$1}])};return l(o)?I:{kind:"add",left:l$1,right:I}}function ni(e,t){let n=p(0);return e.forEach((r$1,o)=>{if(l(r$1))return;let i$1=o+1,a=i(r$1,{n:BigInt(i$1),d:1n}),u={kind:"mul",left:p(a),right:i$1===1?q$1(t):r(q$1(t),p(i$1))};n={kind:"add",left:n,right:u};}),n}function De(e,t){let n=Q$2(e);if(!u$1(n).has(t))return {ok:true,value:Q$2({kind:"mul",left:n,right:q$1(t)})};let r=Wo(n,t);if(r!==null)return r;let o=zo(n,t);if(o!==null)return o;let i=Qo(n,t);if(i!==null)return i;let a=Jo(n,t);if(a!==null)return a;if(n.kind==="add"||n.kind==="sub"){let u=De(n.left,t);if(!u.ok)return u;let s=De(n.right,t);return s.ok?{ok:true,value:Q$2({kind:n.kind,left:u.value,right:s.value})}:s}if(n.kind==="mul"&&n.left.kind==="const"){let u=De(n.right,t);return u.ok?{ok:true,value:Q$2({kind:"mul",left:n.left,right:u.value})}:u}return {ok:false,reason:"no elementary antiderivative is known for this expression"}}var Tt=16;function ar(e,t,n,r$1){if(r$1<0||!Number.isInteger(r$1)||r$1>Tt)throw c.execution("SYMBOLIC_TAYLOR_DEGREE_LIMIT",`A Taylor degree must be a whole number from 0 to ${Tt}.`,{limit:Tt});let o=p(n),i$1=1n,a=p(a$1);for(let u=0;u<=r$1;u++){u>0&&(i$1*=BigInt(u));let s=Ce(e,t,u),l$1=Q$2(v$1(s,t,o));if(l$1.kind!=="const")throw c.execution("SYMBOLIC_TAYLOR_INEXACT",`The derivative of order ${u} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,{order:u});let d=i(l$1.value,{n:i$1,d:1n});if(l(d))continue;let h=l(n)?q$1(t):{kind:"sub",left:q$1(t),right:o},g=u===0?p(1):u===1?h:r(h,p(u));a={kind:"add",left:a,right:{kind:"mul",left:p(d),right:g}};}return Q$2(a)}function ur(e,t){return e.map(n=>t.map(r=>Ce(n,r)))}function ri(){let e=globalThis.Temporal;return e??void 0}function sr(e){if(e!==void 0&&typeof e!="string")return e;if(e==="date")return b;let t=ri();if(e==="temporal"){if(t===void 0)throw c.config("CALENDAR_TEMPORAL_UNAVAILABLE",'calendar: "temporal" was asked for, but this runtime has no Temporal. Node ships it from 26 (24 behind --harmony-temporal), and Chrome, Edge, Firefox and Opera ship it; Safari does not. Pass a polyfill-backed backend from "solve-engine/temporal", or use calendar: "auto" to compute on Date where Temporal is absent.');return b$1(t)}return t===void 0?b:b$1(t)}function oi(e={}){return {pluginFunctions:{},opRegistry:new Te,pluginFunctionOwners:{},networkEnabled:e.networkEnabled??true,calendar:sr(e.calendar)}}var lr=oi();var ii={1970:38.8,1971:40.5,1972:41.8,1973:44.4,1974:49.3,1975:53.8,1976:56.9,1977:60.6,1978:65.2,1979:72.6,1980:82.4,1981:90.9,1982:96.5,1983:99.6,1984:103.9,1985:107.6,1986:109.6,1987:113.6,1988:118.3,1989:124,1990:130.7,1991:136.2,1992:140.3,1993:144.5,1994:148.2,1995:152.4,1996:156.9,1997:160.5,1998:163,1999:166.6,2e3:172.2,2001:177.1,2002:179.9,2003:184,2004:188.9,2005:195.3,2006:201.6,2007:207.3,2008:215.3,2009:214.5,2010:218.1,2011:224.9,2012:229.6,2013:233,2014:236.7,2015:237,2016:240,2017:245.1,2018:251.1,2019:255.7,2020:258.8,2021:271,2022:292.7,2023:304.7,2024:313.7,2025:322.2,2026:332.7},mr=1970,fr=2026;function cr(e){return ii[Math.trunc(e)]}function Vt(e,t){let n=cr(e),r=cr(t);if(!(n===void 0||r===void 0||n===0))return r/n}function fu(e,t,n){let r=Vt(t,n);if(r!==void 0)return e*r}function ai(e){let t=Math.abs(e);return t<60?u(e,"s"):t<3600?u(e/60,"min"):t<86400?u(e/3600,"h"):u(e/86400,"d")}var ui=0;function Ot(e){if(e.type===6&&e.unit!==void 0){let t=a[e.unit.toLowerCase()];if(t!==void 0&&t[0]===ui)return e.toNumber()*t[1]}return e.toNumber()}function si(e,t){if(t===1)return e;let n=`${e}s`;return a[n.toLowerCase()]===void 0?e:n}function dr(e,t){let n$1,r=false;for(let o of e){if(Number.isNaN(o.toNumber())){r=true;continue}if(n$1===void 0){n$1=o;continue}let{lv:i,rv:a,sameMeasure:u}=he(n$1,o);if(!u){let s=n$1.type===6?n$1.unit:void 0,l=o.type===6?o.unit:void 0,d=_e(s,l,"compared");return P("INCOMPATIBLE_UNITS",d??`Cannot compare incompatible units: ${s??"?"} and ${l??"?"}`)}(t?a>i:a<i)&&(n$1=o);}return r?n(NaN):n$1===void 0?n(t?-1/0:1/0):n$1.type===6?n$1:n(n$1.toNumber())}function tt(e,t){return t===void 0?n(e):u(e,t)}function nt(e,t){return e.type===6&&e.unit!==void 0?u(t,e.unit):n(t)}function pr(e,t){let n=Number.isFinite(t)?Math.min(100,Math.max(0,Math.trunc(t))):0;if(e.exact!==void 0){let a=oa$1(e.exact,n);return rt(e,ra$1(a),n,a)}let r=e.toNumber();if(!Number.isFinite(r))return rt(e,r,n);let o=Math.pow(10,n),i=r*o;return !Number.isFinite(i)||Math.abs(i)>Number.MAX_SAFE_INTEGER?rt(e,r,n):rt(e,Math.round(i)/o,n)}function rt(e,t,n$1,r){let o=e.type===6&&e.unit!==void 0?u(t,e.unit):n(t);return o.decimalPlaces=n$1,r!==void 0&&(o.exact=r),o}function br(e,t,n){if(Number.isFinite(e)&&Number.isFinite(t))return null;let r=Number.isFinite(e)?t:e;return P("INVALID_INTEGER_OPERAND",`${n} needs two whole numbers, and ${Number.isNaN(r)?"one of them has no value":"one of them is infinite"}`)}function yr(e,t){let n=e,r=t;for(;r!==0;){let o=r;r=n%r,n=o;}return n}function li(e){let t=e.length;if(t===0)return 0;let n=e.reduce((r,o)=>r+o,0)/t;return e.reduce((r,o)=>r+(o-n)*(o-n),0)}function ot(e,t){let n=e.length;if(n===0)return 0;let r=t?n-1:n;return r<=0?0:li(e)/r}var ci=12,mi=new Set(["month","months","mo","mos","mth","mths"]);function J(e$1){return e$1.type!==6||e$1.unit===void 0?e$1.toNumber():c$1(e$1.unit)!=="time"?P("INVALID_TERM",`a term is a length of time, and "${e$1.unit}" is not: write it as days, months or years`):mi.has(e$1.unit)?e$1.toNumber()/ci:e(e$1.toNumber(),e$1.unit,"year")}var Cu={0:e=>{let t=e[0].toNumber();return t>=0?n(Math.sqrt(t)):C(s("sqrt",[p(t)]))},1:e=>e[0].type===7?ca(e[0].value):nt(e[0],Math.abs(e[0].toNumber())),2:e=>n(Math.sin(Ot(e[0]))),3:e=>n(Math.cos(Ot(e[0]))),4:e=>n(Math.tan(Ot(e[0]))),5:e=>n(Math.log(e[0].toNumber())),6:e=>nt(e[0],Math.ceil(e[0].toNumber())),7:e=>nt(e[0],Math.floor(e[0].toNumber())),8:e=>e.length>=2?pr(e[0],e[1].toNumber()):nt(e[0],Math.round(e[0].toNumber())),9:e=>dr(e,false),10:e=>dr(e,true),11:e=>n(Math.asin(e[0].toNumber())),12:e=>n(Math.acos(e[0].toNumber())),13:e=>n(Math.atan(e[0].toNumber())),14:e=>n(Math.atan2(e[0].toNumber(),e[1].toNumber())),15:e=>n(Math.sinh(e[0].toNumber())),16:e=>n(Math.cosh(e[0].toNumber())),17:e=>n(Math.tanh(e[0].toNumber())),18:e=>n(Math.asinh(e[0].toNumber())),19:e=>n(Math.acosh(e[0].toNumber())),20:e=>n(Math.atanh(e[0].toNumber())),21:e=>n(Math.cbrt(e[0].toNumber())),22:e=>n(Math.clz32(e[0].toNumber())),23:e=>n(Math.expm1(e[0].toNumber())),24:e=>n(Math.exp(e[0].toNumber())),25:e=>n(Math.fround(e[0].toNumber())),26:e=>n(Math.hypot(...e.map(t=>t.toNumber()))),27:e=>n(Math.imul(e[0].toNumber(),e[1].toNumber())),28:e=>n(Math.log10(e[0].toNumber())),29:e=>n(Math.log1p(e[0].toNumber())),30:e=>n(Math.log2(e[0].toNumber())),31:e=>e[0].type===7?e[1].type!==0?P("MATRIX_POWER_UNSUPPORTED",`pow: a matrix's exponent must be a whole number, as in "pow([1,2;3,4], 2)".`):$(e[0].value,e[1].value):e[1].type===7?P("MATRIX_POWER_UNSUPPORTED",'pow: a matrix may only be the base, as in "pow([1,2;3,4], 2)".'):n(St(e[0].toNumber(),e[1].toNumber())),32:()=>n(Math.random()),33:e=>n(Math.sign(e[0].toNumber())),34:e=>n(Math.trunc(e[0].toNumber())),35:e=>n(e[0].toNumber()*Math.PI/180),36:e=>n(e[0].toNumber()*180/Math.PI),37:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return t>n$1?P("INVALID_RANGE",`roll: invalid range, ${t} is greater than ${n$1}`):n(Math.floor(Math.random()*(n$1-t+1))+t)},38:e=>{let t=Math.trunc(Math.abs(e[0].toNumber())),n$1=Math.trunc(Math.abs(e[1].toNumber())),r=br(t,n$1,"gcd");return r||n(yr(t,n$1))},39:e=>{let t=Math.trunc(Math.abs(e[0].toNumber())),n$1=Math.trunc(Math.abs(e[1].toNumber())),r=br(t,n$1,"lcm");return r||(t===0||n$1===0?n(0):n(t/yr(t,n$1)*n$1))},40:e=>{let t=Math.trunc(e[0].toNumber()),n$1=Math.trunc(e[1].toNumber());if(t<0||n$1<0||n$1>t)return P("INVALID_RANGE",`permutation: invalid n=${t}, r=${n$1} (require 0 <= r <= n)`);let r=1;for(let o=0;o<n$1;o++)if(r*=t-o,!Number.isFinite(r))return P("PERMUTATION_OVERFLOW",`permutation: P(${t}, ${n$1}) exceeds the maximum representable double (it passed it after ${o+1} of ${n$1} factors)`);return n(r)},41:e=>{let t=Math.trunc(e[0].toNumber()),n$1=Math.trunc(e[1].toNumber());if(t<0||n$1<0||n$1>t)return P("INVALID_RANGE",`combination: invalid n=${t}, r=${n$1} (require 0 <= r <= n)`);let r=Math.min(n$1,t-n$1),o=1;for(let i=0;i<r;i++)if(o=o*(t-i)/(i+1),!Number.isFinite(o))return P("COMBINATION_OVERFLOW",`combination: C(${t}, ${n$1}) exceeds the maximum representable double (it passed it after ${i+1} of ${r} steps)`);return n(Math.round(o))},42:e=>{if(e.length===0)return n(0);let t=we(e,"averaged");if(t instanceof m)return t;let n$1=t.magnitudes.reduce((r,o)=>r+o,0);return tt(n$1/t.magnitudes.length,t.unit)},43:e=>{if(e.length===0)return n(0);let t=we(e,"ordered");if(t instanceof m)return t;let n$1=t.magnitudes.slice().sort((o,i)=>o-i),r=Math.floor(n$1.length/2);return tt(n$1.length%2===0?(n$1[r-1]+n$1[r])/2:n$1[r],t.unit)},44:e=>{let t=we(e,"added");return t instanceof m?t:tt(t.magnitudes.reduce((n,r)=>n+r,0),t.unit)},45:e=>n(e.length),46:e=>{let[t,n$1,r]=e,{lv:o,rv:i}=he(t,n$1);if(o===0)return P("PROPORTION_DIVIDE_BY_ZERO",`Cannot compute proportion: "${t.value}" is zero`);let a=r.toNumber()*(i/o);return r.type===6?u(a,r.unit):n(a)},47:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=e[2].toNumber();return n$1>r?P("INVALID_RANGE",`clamp: invalid range, ${n$1} is greater than ${r}`):n(Math.min(Math.max(t,n$1),r))},48:e=>r$1(e[0].toNumber()),49:e=>r$1(e[0].toNumber(),"bin"),50:e=>n(Math.trunc(e[0].toNumber())),51:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;if(1+n$1<=0)return P("INVALID_RATE",`compoundInterest: rate ${n$1} makes (1 + rate) non-positive`);let o=t*Math.pow(1+n$1,r);return e[0].type===6?u(o,e[0].unit):n(o)},52:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;if(1+n$1<=0)return P("INVALID_RATE",`interestEarned: rate ${n$1} makes (1 + rate) non-positive`);let o=t*(Math.pow(1+n$1,r)-1);return e[0].type===6?u(o,e[0].unit):n(o)},53:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);return typeof r!="number"?r:t<=0||n$1<=0?P("INVALID_RANGE","compoundInterestRate: principal and futureValue must both be positive"):r<=0?P("INVALID_RANGE","compoundInterestRate: years must be greater than 0"):n(Math.pow(n$1/t,1/r)-1)},54:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=e[2].toNumber();return t<=0||n$1<=0?P("INVALID_RANGE","compoundInterestYears: principal and futureValue must both be positive"):1+r<=0||r===0?P("INVALID_RATE",`compoundInterestYears: rate ${r} is not usable (must be > -1 and not 0)`):n(Math.log(n$1/t)/Math.log(1+r))},55:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;let o=e[3].toNumber();if(t<=0)return P("INVALID_RANGE","loanRepayment: principal must be positive");if(r<=0)return P("INVALID_RANGE","loanRepayment: years must be positive");if(n$1<0)return P("INVALID_RATE","loanRepayment: rate must not be negative");if(o<0)return P("INVALID_RANGE","loanRepayment: periodsPerYear must not be negative");let{totalRepayment:i}=Pt(t,n$1,r),a=o===0?i:i/(r*o);return e[0].type===6?u(a,e[0].unit):n(a)},56:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;let o=e[3].toNumber();if(t<=0)return P("INVALID_RANGE","loanInterest: principal must be positive");if(r<=0)return P("INVALID_RANGE","loanInterest: years must be positive");if(n$1<0)return P("INVALID_RATE","loanInterest: rate must not be negative");if(o<0)return P("INVALID_RANGE","loanInterest: periodsPerYear must not be negative");let{totalInterest:i}=Pt(t,n$1,r),a=o===0?i:i/(r*o);return e[0].type===6?u(a,e[0].unit):n(a)},57:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;if(t<=0)return P("INVALID_RANGE","monthlyPayment: principal must be positive");if(r<=0)return P("INVALID_RANGE","monthlyPayment: years must be positive");if(n$1<0)return P("INVALID_RATE","monthlyPayment: rate must not be negative");let{monthlyPayment:o}=Pt(t,n$1,r);return e[0].type===6?u(o,e[0].unit):n(o)},58:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return e[0].type===6?Wn(e[0],e[0].unit,n$1,1):n(t*(1+n$1))},59:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return 1+n$1<=0?P("INVALID_RATE",`taxRemove: rate ${n$1} makes (1 + rate) non-positive`):e[0].type===6?Qn(e[0],e[0].unit,n$1)??u(t/(1+n$1),e[0].unit):n(t/(1+n$1))},60:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=e[2].toNumber(),o=Vt(n$1,r);if(o===void 0)return P("INFLATION_YEAR_OUT_OF_RANGE",`inflationAdjust: fromYear ${n$1} or toYear ${r} is outside the bundled CPI table's range (${mr}-${fr})`);let i=t*o;return e[0].type===6?u(i,e[0].unit):n(i)},61:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return n(St(n$1,1/t))},62:e=>{let t=e[0].toNumber();if(!Number.isInteger(t)||t<0)return P("INVALID_FACTORIAL_INPUT",`fact: ${t} is not a non-negative integer`);if(t>170)return P("FACTORIAL_OVERFLOW",`fact: ${t}! exceeds the maximum representable double (170! is the largest finite factorial)`);let n$1=1;for(let r=2;r<=t;r++)n$1*=r;return n(n$1)},63:e=>e[0].type===7?ba(e[0].value):e[0],64:e=>e[0].type===7?ca(e[0].value):n(e[0].toNumber()),65:e=>e[0].type===7?da(e[0].value):n(1/e[0].toNumber()),66:e=>{let[t,n$1]=e;if(t.type===0&&n$1.type===0)return n(t.toNumber()*n$1.toNumber());let r=o=>o.type===7?o.value:{rows:1,cols:1,data:[o.toNumber()],hasSymbolic:false};return _(r(t),r(n$1))},67:e=>{let[t]=e;return t.type!==9?t:C(F$1(t.value))},68:e=>{let[t]=e;return t.type!==9?t:C(En(t.value))},69:e=>{let[t,n,r]=e;return r?.type!==3?P("SOLVE_REQUIRES_VARIABLE_NAME","solve's second argument must be the name of the unknown."):$n(t,n,r.value)},70:e=>{let[t,n,r]=e,o=Dt(n,"der");if(typeof o!="string")return o;let i=O(t);return i===null?P("SYMBOLIC_NONFINITE_OPERAND","der needs an expression with an exact value."):C(Ce(i,o,r?.toNumber()??1))},71:e=>{let[t,n]=e,r=Dt(n,"integral");if(typeof r!="string")return r;let o=O(t);if(o===null)return P("SYMBOLIC_NONFINITE_OPERAND","integral needs an expression with an exact value.");let i=De(o,r);return i.ok?C(i.value):P("SYMBOLIC_INTEGRAL_UNSUPPORTED",`Cannot integrate this: ${i.reason}.`)},72:e=>{let[t,n,r,o]=e,i=Dt(n,"taylor");if(typeof i!="string")return i;let a=O(t),u=O(r);return a===null||u===null||u.kind!=="const"?P("SYMBOLIC_NONFINITE_OPERAND","taylor needs an expression and an exact expansion point."):C(ar(a,i,u.value,o.toNumber()))},73:e=>{let t=[];for(let a of e){let u=O(a);if(u===null)return P("SYMBOLIC_NONFINITE_OPERAND","jacobian needs expressions with exact values.");t.push(u);}let n=new Set;for(let a of t)for(let u of u$1(a))n.add(u);let r=[...n].sort();if(r.length===0)return P("SYMBOLIC_JACOBIAN_NO_VARIABLES","jacobian needs at least one unknown to differentiate against.");let o=ur(t,r),i=[];for(let a of o)for(let u of a)i.push(W(u));return C$2(o.length,r.length,Y(o.length,r.length,i))},74:e=>C(w(o(a$1,d(e[0].toNumber())))),75:e=>Ct("conj",e[0]),76:e=>Ct("re",e[0]),77:e=>Ct("im",e[0]),78:e=>{let t=e[0];return t.type!==9?t:C(J$1(t.value))},79:e=>{let t=e[0];return t.type!==9?t:C(nr(t.value))},85:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();if(1+n$1<=0)return P("INVALID_RATE",`taxIn: rate ${n$1} makes (1 + rate) non-positive`);let r=t-t/(1+n$1);return e[0].type===6?Jn(e[0],e[0].unit,n$1)??u(r,e[0].unit):n(r)},86:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return e[0].type===6?Hn(e[0],n$1,e[0].unit):n(t*n$1)},87:e=>n(Math.sin(e[0].toNumber()*Math.PI/180)),88:e=>n(Math.cos(e[0].toNumber()*Math.PI/180)),89:e=>n(Math.tan(e[0].toNumber()*Math.PI/180)),90:e=>n(Math.asin(e[0].toNumber())*180/Math.PI),91:e=>n(Math.acos(e[0].toNumber())*180/Math.PI),92:e=>n(Math.atan(e[0].toNumber())*180/Math.PI),93:e=>u(e[0].toNumber(),"days"),94:e=>{let t$1=typeof e[1]?.value=="string"?e[1].value:void 0,n=typeof e[2]?.value=="string"?e[2].value:void 0;if(t$1===void 0||n===void 0)return P("UNKNOWN_UNIT",'both units have to be named, as in "12.5 minutes in minutes and seconds"');let r=a[t$1.toLowerCase()],o=a[n.toLowerCase()];if(r===void 0||o===void 0)return P("UNKNOWN_UNIT",`${t$1} and ${n}: one of these is not a unit`);if(r[0]!==o[0])return P("INCOMPATIBLE_UNITS",`${t$1} and ${n} measure different things`);if(o[1]>=r[1])return P("INCOMPATIBLE_UNITS",`${t$1} and ${n}: name the larger unit first`);let i=e[0],a$1=i.type===6&&i.unit!==void 0?a[i.unit.toLowerCase()]:void 0,u=i.toNumber()*(a$1?.[1]??r[1]),s=Math.floor(u/r[1]),l=Math.round((u-s*r[1])/o[1]*1e3)/1e3;return t(`${s} ${t$1} ${l} ${n}`)},95:e=>{let t=e[0],n=String(e[1].value),r=t.type===6&&t.unit!==void 0?t.unit:"";return r.includes("/")?P("INVALID_RATE_UNIT",`${r}/${n}: that is already a rate`):u(t.toNumber(),`${r}/${n}`)},96:e=>{let t=e[0],n$1=e[1];if(n$1.type===6&&t.type===6&&i$1(n$1.unit)){let l=j$1(t.toNumber(),t.unit,n$1.toNumber(),n$1.unit);if(l!==null)return ai(l)}if(n$1.type!==6||n$1.unit===void 0||!n$1.unit.includes("/"))return P("INVALID_RATE",'at: the right-hand side has to be a rate, as in "$30/hour"');let r=n$1.unit.indexOf("/"),o=n$1.unit.slice(0,r),i=n$1.unit.slice(r+1),a$1=t.type===6?t.unit:void 0,u$1=a[i.toLowerCase()],s=a$1===void 0?void 0:a[a$1.toLowerCase()];if(s!==void 0&&u$1!==void 0&&s[0]===u$1[0]){let d=t.toNumber()*s[1]/u$1[1]*n$1.toNumber();return o===""?n(d):u(d,o)}if(a$1!==void 0&&a$1===o){let l=t.toNumber()/n$1.toNumber();return u(l,si(i,l))}if(a$1===void 0){let l=t.toNumber()*n$1.toNumber();return o===""?n(l):u(l,o)}return P("INCOMPATIBLE_UNITS",`at: ${a$1} matches neither side of ${n$1.unit}`)},80:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;let o=e[3].toNumber();if(o<=0)return P("INVALID_RATE",`compounding: ${o} periods per year is not a period`);if(1+n$1/o<=0)return P("INVALID_RATE",`compounding: rate ${n$1} makes each period non-positive`);let i=t*Math.pow(1+n$1/o,o*r);return e[0].type===6?u(i,e[0].unit):n(i)},81:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;let o=e[3].toNumber();if(o<=0||1+n$1/o<=0)return P("INVALID_RATE",`compounding: rate ${n$1} over ${o} periods per year is not usable`);let i=t*(Math.pow(1+n$1/o,o*r)-1);return e[0].type===6?u(i,e[0].unit):n(i)},82:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber(),r=J(e[2]);if(typeof r!="number")return r;if(1+n$1<=0)return P("INVALID_RATE",`presentValue: rate ${n$1} makes (1 + rate) non-positive`);let o=t/Math.pow(1+n$1,r);return e[0].type===6?u(o,e[0].unit):n(o)},83:e=>{let t=e[0].toNumber(),n$1=e[1].toNumber();return t===0?P("INVALID_RATE","roi: nothing was invested, so there is no return on it"):n((n$1-t)/t)},84:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),r=J(e[2]);return typeof r!="number"?r:t<=0?P("INVALID_RATE","annual return: the amount invested must be positive"):r<=0?P("INVALID_RATE","annual return: the period must be longer than zero"):n<=0?P("INVALID_RATE","annual return: nothing was returned, so there is no annual rate"):N(Math.pow(n/t,1/r)-1)},97:e=>pr(e[0],e[1].toNumber()),98:e=>{let t=e[1].toNumber();return !Number.isInteger(t)||t<1?P("INVALID_RANGE",`split: the number of shares must be a whole number of at least 1, not ${e[1].toNumber()}.`):H(er(e[0],t))},99:e=>{let t=e[0].toNumber(),n$1=fi(e[1]),r=e[2].toNumber();if(n$1===null)return P("INVALID_RANGE",'savings goal: the duration must be in months or years, e.g. "in 2 years".');if(t<=0)return P("INVALID_RANGE","savings goal: the target must be positive.");if(n$1<=0)return P("INVALID_RANGE","savings goal: the duration must be positive.");if(r<0)return P("INVALID_RATE","savings goal: the rate must not be negative.");let o=di(t,r/12,n$1);return e[0].type===6?u(o,e[0].unit):n(o)},100:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),r=e[2].toNumber(),o=e[3].toNumber(),i=typeof e[4]?.value=="string"?e[4].value:"periods";if(t<=0)return P("INVALID_RANGE","savings goal: the target must be positive.");if(n<=0)return P("INVALID_RANGE","savings goal: the contribution must be positive.");if(o<0)return P("INVALID_RATE","savings goal: the rate must not be negative.");let a=pi(t,n,o/r);return u(a,i)},101:e=>n(Math.sqrt(ot(e.map(t=>t.toNumber()),false))),102:e=>n(Math.sqrt(ot(e.map(t=>t.toNumber()),true))),103:e=>n(ot(e.map(t=>t.toNumber()),false)),104:e=>n(ot(e.map(t=>t.toNumber()),true)),105:e=>{if(e.length===0)return n(0);let t=we(e,"compared");if(t instanceof m)return t;let n$1=t.magnitudes;return tt(Math.max(...n$1)-Math.min(...n$1),t.unit)},106:e=>{if(e.length===0)return n(0);let t=new Map,n$1=e[0].toNumber(),r=0;for(let o of e){let i=o.toNumber(),a=(t.get(i)??0)+1;t.set(i,a),a>r&&(r=a,n$1=i);}return n(n$1)},107:e=>{let t=0,n$1=0;for(let r=0;r+1<e.length;r+=2){let o=e[r].toNumber(),i=e[r+1].toNumber();t+=o*i,n$1+=i;}return n$1===0?P("WEIGHTED_AVERAGE_ZERO_WEIGHT","weighted average: the weights sum to zero, so there is nothing to divide by"):n(t/n$1)}};function fi(e){if(e.type!==6)return null;let t=e.unit;return t==="months"||t==="month"?e.toNumber():t==="years"||t==="year"?e.toNumber()*12:null}function di(e,t,n){return t===0?e/n:e*t/(Math.pow(1+t,n)-1)}function pi(e,t,n){let r=n===0?e/t:Math.log(1+e*n/t)/Math.log(1+n);return Math.ceil(r-1e-9)}function Ct(e,t){let n=O(t);return n===null?P("SYMBOLIC_NONFINITE_OPERAND",e+" needs a value with an exact number."):C(s(e,[n]))}function Dt(e,t){return e?.type!==3?P("SYMBOLIC_REQUIRES_VARIABLE_NAME",`${t} needs the name of an unknown.`):e.value}function Pt(e,t,n){let r=n*12,o=t/12,i=o===0?e/r:e*o/(1-Math.pow(1+o,-r)),a=i*r,u=a-e;return {monthlyPayment:i,totalRepayment:a,totalInterest:u}}var Du=lr.pluginFunctions,hr=65535,gr=0;function bi(){if(gr>hr)throw c.config("PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",`allocatePluginFunctionIndex: pool exhausted (max ${hr+1} allocations).`);return gr++}var Nr=new Map;function Pu(e){let t=Nr.get(e);return t===void 0&&(t=bi(),Nr.set(e,t)),t}var Lt=new Map;function Lu(e,t){let n=e.toLowerCase(),r=Lt.get(n);r&&r!==t&&console.warn(`[asConverterRegistry] Converter name "${n}" is already registered \u2014 overwriting.`),Lt.set(n,t);}function Fu(e){Lt.delete(e.toLowerCase());}var it=class it{constructor(){this.values=new Map;this.listeners=new Set;this.notifyDepth=0;}get(t){return this.values.get(t)}has(t){return this.values.has(t)}set(t,n){let r=this.values.get(t);this.values.set(t,n),!(r!==void 0&&yi(r,n))&&this.notify(t,n);}notify(t,n){if(!(this.notifyDepth>=it.MAX_NOTIFY_DEPTH)){this.notifyDepth++;try{for(let r of this.listeners)r(t,n);}finally{this.notifyDepth--;}}}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}clear(){this.values.clear(),this.listeners.clear(),this.notifyDepth=0;}};it.MAX_NOTIFY_DEPTH=64;var Ft=it;function yi(e,t){if(e.type!==t.type||e.unit!==t.unit||(e.timedOut??false)!==(t.timedOut??false))return false;let n=e.value,r=t.value;if(Array.isArray(n)||Array.isArray(r)){if(!Array.isArray(n)||!Array.isArray(r)||n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return false;return true}return Object.is(n,r)}var $u=new Ft;function Bu(e){return `global:${e}`}var hi={sydney:"Australia/Sydney",melbourne:"Australia/Melbourne",brisbane:"Australia/Brisbane",perth:"Australia/Perth",adelaide:"Australia/Adelaide",canberra:"Australia/Sydney",auckland:"Pacific/Auckland",wellington:"Pacific/Auckland",fiji:"Pacific/Fiji",chicago:"America/Chicago",seattle:"America/Los_Angeles",denver:"America/Denver",phoenix:"America/Phoenix",toronto:"America/Toronto",montreal:"America/Toronto",vancouver:"America/Vancouver",ottawa:"America/Toronto",honolulu:"Pacific/Honolulu",anchorage:"America/Anchorage",miami:"America/New_York",boston:"America/New_York",atlanta:"America/New_York",dallas:"America/Chicago",houston:"America/Chicago",lima:"America/Lima",bogota:"America/Bogota",caracas:"America/Caracas",santiago:"America/Santiago",montevideo:"America/Montevideo",quito:"America/Guayaquil",london:"Europe/London",paris:"Europe/Paris",berlin:"Europe/Berlin",madrid:"Europe/Madrid",rome:"Europe/Rome",amsterdam:"Europe/Amsterdam",dublin:"Europe/Dublin",lisbon:"Europe/Lisbon",vienna:"Europe/Vienna",zurich:"Europe/Zurich",geneva:"Europe/Zurich",moscow:"Europe/Moscow",istanbul:"Europe/Istanbul",athens:"Europe/Athens",stockholm:"Europe/Stockholm",oslo:"Europe/Oslo",helsinki:"Europe/Helsinki",warsaw:"Europe/Warsaw",prague:"Europe/Prague",budapest:"Europe/Budapest",brussels:"Europe/Brussels",copenhagen:"Europe/Copenhagen",reykjavik:"Atlantic/Reykjavik",kiev:"Europe/Kyiv",kyiv:"Europe/Kyiv",tokyo:"Asia/Tokyo",osaka:"Asia/Tokyo",beijing:"Asia/Shanghai",shanghai:"Asia/Shanghai",seoul:"Asia/Seoul",singapore:"Asia/Singapore",bangkok:"Asia/Bangkok",jakarta:"Asia/Jakarta",manila:"Asia/Manila",mumbai:"Asia/Kolkata",delhi:"Asia/Kolkata",bangalore:"Asia/Kolkata",dubai:"Asia/Dubai",abudhabi:"Asia/Dubai",karachi:"Asia/Karachi",dhaka:"Asia/Dhaka",hanoi:"Asia/Ho_Chi_Minh",taipei:"Asia/Taipei",islamabad:"Asia/Karachi",riyadh:"Asia/Riyadh",telaviv:"Asia/Jerusalem",jerusalem:"Asia/Jerusalem",cairo:"Africa/Cairo",lagos:"Africa/Lagos",nairobi:"Africa/Nairobi",johannesburg:"Africa/Johannesburg",casablanca:"Africa/Casablanca",accra:"Africa/Accra",tunis:"Africa/Tunis",addisababa:"Africa/Addis_Ababa",france:"Europe/Paris",germany:"Europe/Berlin",spain:"Europe/Madrid",italy:"Europe/Rome",japan:"Asia/Tokyo",china:"Asia/Shanghai",india:"Asia/Kolkata",brazil:"America/Sao_Paulo",russia:"Europe/Moscow",australia:"Australia/Sydney",canada:"America/Toronto",mexico:"America/Mexico_City",uk:"Europe/London",usa:"America/New_York",ireland:"Europe/Dublin",netherlands:"Europe/Amsterdam",sweden:"Europe/Stockholm",norway:"Europe/Oslo",poland:"Europe/Warsaw",turkey:"Europe/Istanbul",egypt:"Africa/Cairo",nigeria:"Africa/Lagos"},gi={"new york":"America/New_York","los angeles":"America/Los_Angeles","san francisco":"America/Los_Angeles","las vegas":"America/Los_Angeles","mexico city":"America/Mexico_City","hong kong":"Asia/Hong_Kong","kuala lumpur":"Asia/Kuala_Lumpur","sao paulo":"America/Sao_Paulo","buenos aires":"America/Argentina/Buenos_Aires","rio de janeiro":"America/Sao_Paulo","cape town":"Africa/Johannesburg","new delhi":"Asia/Kolkata","united kingdom":"Europe/London","united states":"America/New_York","south africa":"Africa/Johannesburg"},Ni={pst:"America/Los_Angeles",pdt:"America/Los_Angeles",est:"America/New_York",edt:"America/New_York",cst:"America/Chicago",cdt:"America/Chicago",mst:"America/Denver",mdt:"America/Denver",hst:"Pacific/Honolulu",bst:"Europe/London",cet:"Europe/Paris",cest:"Europe/Paris",jst:"Asia/Tokyo",ist:"Asia/Kolkata",aest:"Australia/Sydney",aedt:"Australia/Sydney"},Ri={...hi,...gi,...Ni};function Yu(e){let t=e.trim().toLowerCase();return t==="utc"||t==="gmt"?"UTC":Ri[t]??null}export{oi as A,lr as B,mr as C,fr as D,fu as E,Cu as F,Du as G,bi as H,Pu as I,Lt as J,Lu as K,Fu as L,$u as M,Bu as N,gi as O,Ri as P,Yu as Q,hn as a,yn as b,Ve as c,Hn as d,Wn as e,Ln as f,na as g,ra as h,oa as i,ia as j,$n as k,he as l,we as m,ya as n,ha as o,ga as p,qn as q,Na as r,Ra as s,St as t,Aa as u,xa as v,Sa as w,va as x,Te as y,Ea as z};//# sourceMappingURL=chunk-2JR7PALQ.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-2JR7PALQ.js.map
|