solve-engine 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{EngineError-B61GS1jp.d.cts → EngineError-CNA_rHY-.d.cts} +6 -0
- package/dist/{EngineError-B61GS1jp.d.ts → EngineError-CNA_rHY-.d.ts} +6 -0
- package/dist/{Lexer-BOs7euZe.d.cts → Lexer-B4C1qHXu.d.cts} +1 -1
- package/dist/{Lexer-CSI_lwbW.d.ts → Lexer-DKMlj7Sy.d.ts} +1 -1
- package/dist/{PackageCompatibility-B-7rK1TD.d.cts → PackageCompatibility-B6NX9IaN.d.cts} +1 -1
- package/dist/{PackageCompatibility-Dh59eF-X.d.ts → PackageCompatibility-Ceg5XdAp.d.ts} +1 -1
- package/dist/{PackageRegistry-BHWJP83F.d.cts → PackageRegistry-DnJYVw9G.d.cts} +55 -8
- package/dist/{PackageRegistry-_8rDlvxI.d.ts → PackageRegistry-DrCPQNyy.d.ts} +55 -8
- package/dist/{Parselet-BBT8riYh.d.ts → Parselet-Bhf7d0_W.d.ts} +2 -2
- package/dist/{Parselet-BHcgK9S7.d.cts → Parselet-Cv7S7KRt.d.cts} +2 -2
- package/dist/{ScopeManager-CxA24W5n.d.ts → ScopeManager-Bzq87GfA.d.ts} +10 -3
- package/dist/{ScopeManager-8vf02dwj.d.cts → ScopeManager-DRDBVfan.d.cts} +10 -3
- package/dist/{Token-B1hdkedD.d.cts → Token-CbP_OutD.d.cts} +9 -0
- package/dist/{Token-B1hdkedD.d.ts → Token-CbP_OutD.d.ts} +9 -0
- package/dist/{TokenNormalizer-C6VzZgHa.d.ts → TokenNormalizer-DCWdZjGz.d.ts} +1 -1
- package/dist/{TokenNormalizer-DRc1Js1V.d.cts → TokenNormalizer-DnlL7_8c.d.cts} +1 -1
- package/dist/{VMCheckpoints-MK--EBH2.d.ts → VMCheckpoints-C6c17Hbo.d.ts} +2 -2
- package/dist/{VMCheckpoints-ELYqITdF.d.cts → VMCheckpoints-dZxSMGHG.d.cts} +2 -2
- package/dist/{Value-BUi1RA3S.d.cts → Value-DZNQ_PU7.d.cts} +32 -5
- package/dist/{Value-BUi1RA3S.d.ts → Value-DZNQ_PU7.d.ts} +32 -5
- package/dist/{WorkerError-_-RkoQ5P.d.ts → WorkerError-B7t7R2-m.d.ts} +1 -1
- package/dist/{WorkerError-gzmaopj2.d.cts → WorkerError-Djd7GGGa.d.cts} +1 -1
- package/dist/{chunk-SSV46KFA.cjs → chunk-4K5W7EH2.cjs} +6 -6
- package/dist/{chunk-SSV46KFA.cjs.map → chunk-4K5W7EH2.cjs.map} +1 -1
- package/dist/{chunk-267JPOTF.js → chunk-5EFKSKMA.js} +11 -4
- package/dist/chunk-5EFKSKMA.js.map +1 -0
- package/dist/{chunk-536WPM2V.cjs → chunk-7AXJNQMF.cjs} +17 -3
- package/dist/chunk-7AXJNQMF.cjs.map +1 -0
- package/dist/{chunk-LHZ6VOA7.js → chunk-7JM3F4KL.js} +39 -8
- package/dist/chunk-7JM3F4KL.js.map +1 -0
- package/dist/{chunk-N5NNW4VG.cjs → chunk-7USV76HV.cjs} +6 -6
- package/dist/{chunk-N5NNW4VG.cjs.map → chunk-7USV76HV.cjs.map} +1 -1
- package/dist/{chunk-HIQ5HSZL.cjs → chunk-A2DZ5BEJ.cjs} +53 -46
- package/dist/{chunk-HIQ5HSZL.cjs.map → chunk-A2DZ5BEJ.cjs.map} +1 -1
- package/dist/{chunk-CKQMXMHR.cjs → chunk-AKNGX4TZ.cjs} +28 -11
- package/dist/chunk-AKNGX4TZ.cjs.map +1 -0
- package/dist/{chunk-I4GAWIPW.js → chunk-AOH6UR2L.js} +6 -6
- package/dist/{chunk-I4GAWIPW.js.map → chunk-AOH6UR2L.js.map} +1 -1
- package/dist/{chunk-T6ZYQJ63.cjs → chunk-BESTLPRK.cjs} +326 -214
- package/dist/chunk-BESTLPRK.cjs.map +1 -0
- package/dist/{chunk-Z7XGGLI2.js → chunk-BSPXMGIS.js} +3 -3
- package/dist/{chunk-Z7XGGLI2.js.map → chunk-BSPXMGIS.js.map} +1 -1
- package/dist/{chunk-SRGQ72IR.cjs → chunk-C2OMO3WN.cjs} +376 -370
- package/dist/chunk-C2OMO3WN.cjs.map +1 -0
- package/dist/{chunk-GLA4JXBO.js → chunk-CSDQMDU2.js} +4 -4
- package/dist/{chunk-GLA4JXBO.js.map → chunk-CSDQMDU2.js.map} +1 -1
- package/dist/{chunk-7KYSUDQO.js → chunk-F4UB4XIL.js} +4 -4
- package/dist/{chunk-7KYSUDQO.js.map → chunk-F4UB4XIL.js.map} +1 -1
- package/dist/{chunk-WXEHD6TT.js → chunk-FE4RC37D.js} +15 -9
- package/dist/chunk-FE4RC37D.js.map +1 -0
- package/dist/{chunk-7ZX6B7SY.cjs → chunk-FR7RNOPT.cjs} +637 -556
- package/dist/chunk-FR7RNOPT.cjs.map +1 -0
- package/dist/{chunk-QFTDTX6K.cjs → chunk-G2YPPLGX.cjs} +29 -2
- package/dist/chunk-G2YPPLGX.cjs.map +1 -0
- package/dist/{chunk-HVRVSI2Z.cjs → chunk-GDEU72RG.cjs} +86 -86
- package/dist/{chunk-HVRVSI2Z.cjs.map → chunk-GDEU72RG.cjs.map} +1 -1
- package/dist/{chunk-MN3LHRGV.cjs → chunk-HKTQCQ4Z.cjs} +860 -489
- package/dist/chunk-HKTQCQ4Z.cjs.map +1 -0
- package/dist/{chunk-XA4CKRML.cjs → chunk-HWHU642X.cjs} +2 -2
- package/dist/{chunk-XA4CKRML.cjs.map → chunk-HWHU642X.cjs.map} +1 -1
- package/dist/{chunk-CUR2WLI4.cjs → chunk-ICEKS6YC.cjs} +11 -11
- package/dist/{chunk-CUR2WLI4.cjs.map → chunk-ICEKS6YC.cjs.map} +1 -1
- package/dist/{chunk-NNZAEUDW.js → chunk-IJGOFP2J.js} +138 -26
- package/dist/chunk-IJGOFP2J.js.map +1 -0
- package/dist/{chunk-ENKKJYD3.js → chunk-IQJGDZOP.js} +4 -4
- package/dist/{chunk-ENKKJYD3.js.map → chunk-IQJGDZOP.js.map} +1 -1
- package/dist/{chunk-2TZKENDH.cjs → chunk-IT74O4BE.cjs} +15 -7
- package/dist/chunk-IT74O4BE.cjs.map +1 -0
- package/dist/{chunk-ZVTWQLK4.cjs → chunk-KXDQKVNX.cjs} +10 -10
- package/dist/{chunk-ZVTWQLK4.cjs.map → chunk-KXDQKVNX.cjs.map} +1 -1
- package/dist/{chunk-BYJBUL7U.js → chunk-L5YHV6BQ.js} +5 -5
- package/dist/{chunk-BYJBUL7U.js.map → chunk-L5YHV6BQ.js.map} +1 -1
- package/dist/{chunk-E23GZEWL.cjs → chunk-LO7HU5WB.cjs} +8 -8
- package/dist/{chunk-E23GZEWL.cjs.map → chunk-LO7HU5WB.cjs.map} +1 -1
- package/dist/{chunk-UO6BUV6K.js → chunk-LSALB3IN.js} +17 -3
- package/dist/chunk-LSALB3IN.js.map +1 -0
- package/dist/{chunk-J45BCEZ4.cjs → chunk-MI7OTUHL.cjs} +27 -27
- package/dist/{chunk-J45BCEZ4.cjs.map → chunk-MI7OTUHL.cjs.map} +1 -1
- package/dist/{chunk-B4HBEFTB.cjs → chunk-MIGXCBXT.cjs} +8 -2
- package/dist/chunk-MIGXCBXT.cjs.map +1 -0
- package/dist/{chunk-ERCOHGXD.js → chunk-N7OA4WPJ.js} +8 -2
- package/dist/chunk-N7OA4WPJ.js.map +1 -0
- package/dist/{chunk-4D6NIHE2.js → chunk-NAWZATKT.js} +29 -2
- package/dist/chunk-NAWZATKT.js.map +1 -0
- package/dist/{chunk-JG6ZJ2WU.js → chunk-ORM7CHYZ.js} +23 -5
- package/dist/chunk-ORM7CHYZ.js.map +1 -0
- package/dist/{chunk-B7NLZMQ3.cjs → chunk-PCZVMMWU.cjs} +8 -8
- package/dist/{chunk-B7NLZMQ3.cjs.map → chunk-PCZVMMWU.cjs.map} +1 -1
- package/dist/{chunk-DLEBSLF4.js → chunk-RNKDIXDV.js} +4 -4
- package/dist/{chunk-DLEBSLF4.js.map → chunk-RNKDIXDV.js.map} +1 -1
- package/dist/{chunk-YRIKITGF.cjs → chunk-TC6BTUSU.cjs} +55 -24
- package/dist/chunk-TC6BTUSU.cjs.map +1 -0
- package/dist/{chunk-4HQKTMWG.js → chunk-TPOK3UNI.js} +387 -17
- package/dist/chunk-TPOK3UNI.js.map +1 -0
- package/dist/{chunk-CCBZZQAE.js → chunk-UF6JG5SG.js} +2 -2
- package/dist/{chunk-CCBZZQAE.js.map → chunk-UF6JG5SG.js.map} +1 -1
- package/dist/{chunk-NKW7LKYU.js → chunk-WMQRJTAO.js} +88 -7
- package/dist/chunk-WMQRJTAO.js.map +1 -0
- package/dist/{chunk-ZMW6NU2K.cjs → chunk-YJHY7CMN.cjs} +95 -77
- package/dist/chunk-YJHY7CMN.cjs.map +1 -0
- package/dist/{chunk-3OWCDIPN.js → chunk-YNIWOYW6.js} +21 -4
- package/dist/chunk-YNIWOYW6.js.map +1 -0
- package/dist/{chunk-WWQEY7BV.js → chunk-ZN6YYPIW.js} +3 -3
- package/dist/{chunk-WWQEY7BV.js.map → chunk-ZN6YYPIW.js.map} +1 -1
- package/dist/{chunk-NNQ2TYDF.js → chunk-ZNFFTYWH.js} +11 -5
- package/dist/chunk-ZNFFTYWH.js.map +1 -0
- package/dist/constants.cjs +5 -5
- package/dist/constants.js +2 -2
- package/dist/engine.cjs +33 -33
- package/dist/engine.d.cts +27 -11
- package/dist/engine.d.ts +27 -11
- package/dist/engine.js +20 -20
- package/dist/errors.cjs +26 -26
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +2 -2
- package/dist/format.cjs +7 -7
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +4 -4
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/index.js +21 -21
- package/dist/language.cjs +7 -7
- package/dist/language.d.cts +10 -10
- package/dist/language.d.ts +10 -10
- package/dist/language.js +2 -2
- package/dist/lexer.cjs +16 -16
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +5 -5
- package/dist/normalizer.cjs +10 -10
- package/dist/normalizer.d.cts +3 -3
- package/dist/normalizer.d.ts +3 -3
- package/dist/normalizer.js +4 -4
- package/dist/packages.cjs +40 -36
- package/dist/packages.d.cts +37 -11
- package/dist/packages.d.ts +37 -11
- package/dist/packages.js +11 -11
- package/dist/parser.cjs +13 -13
- package/dist/parser.d.cts +4 -4
- package/dist/parser.d.ts +4 -4
- package/dist/parser.js +5 -5
- package/dist/{pipeline-DCd5M6Gk.d.ts → pipeline-D-PS9gVw.d.ts} +3 -3
- package/dist/{pipeline-CtfJtPQc.d.cts → pipeline-DtSBJ8TS.d.cts} +3 -3
- package/dist/resolvers.d.cts +2 -2
- package/dist/resolvers.d.ts +2 -2
- package/dist/testing.cjs +26 -26
- package/dist/testing.d.cts +10 -10
- package/dist/testing.d.ts +10 -10
- package/dist/testing.js +19 -19
- package/dist/uom.cjs +8 -8
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- package/dist/uom.js +4 -4
- package/dist/vm.cjs +32 -32
- package/dist/vm.d.cts +7 -7
- package/dist/vm.d.ts +7 -7
- package/dist/vm.js +7 -7
- package/dist/worker.cjs +38 -38
- package/dist/worker.d.cts +10 -10
- package/dist/worker.d.ts +10 -10
- package/dist/worker.js +20 -20
- package/package.json +1 -1
- package/dist/chunk-267JPOTF.js.map +0 -1
- package/dist/chunk-2TZKENDH.cjs.map +0 -1
- package/dist/chunk-3OWCDIPN.js.map +0 -1
- package/dist/chunk-4D6NIHE2.js.map +0 -1
- package/dist/chunk-4HQKTMWG.js.map +0 -1
- package/dist/chunk-536WPM2V.cjs.map +0 -1
- package/dist/chunk-7ZX6B7SY.cjs.map +0 -1
- package/dist/chunk-B4HBEFTB.cjs.map +0 -1
- package/dist/chunk-CKQMXMHR.cjs.map +0 -1
- package/dist/chunk-ERCOHGXD.js.map +0 -1
- package/dist/chunk-JG6ZJ2WU.js.map +0 -1
- package/dist/chunk-LHZ6VOA7.js.map +0 -1
- package/dist/chunk-MN3LHRGV.cjs.map +0 -1
- package/dist/chunk-NKW7LKYU.js.map +0 -1
- package/dist/chunk-NNQ2TYDF.js.map +0 -1
- package/dist/chunk-NNZAEUDW.js.map +0 -1
- package/dist/chunk-QFTDTX6K.cjs.map +0 -1
- package/dist/chunk-SRGQ72IR.cjs.map +0 -1
- package/dist/chunk-T6ZYQJ63.cjs.map +0 -1
- package/dist/chunk-UO6BUV6K.js.map +0 -1
- package/dist/chunk-WXEHD6TT.js.map +0 -1
- package/dist/chunk-YRIKITGF.cjs.map +0 -1
- package/dist/chunk-ZMW6NU2K.cjs.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { TokenTypes, tokenTypeId } from './chunk-
|
|
1
|
+
import { TokenTypes, tokenTypeId } from './chunk-NAWZATKT.js';
|
|
2
2
|
import { getLocale } from './chunk-XBTEO4OB.js';
|
|
3
|
-
import { ErrorFactory } from './chunk-
|
|
3
|
+
import { ErrorFactory } from './chunk-N7OA4WPJ.js';
|
|
4
4
|
|
|
5
5
|
// src/parser/BindingPower.ts
|
|
6
6
|
var BindingPower = {
|
|
@@ -329,5 +329,5 @@ function stripLocaleGrouping(text, localeCode) {
|
|
|
329
329
|
}
|
|
330
330
|
|
|
331
331
|
export { BindingPower, BytecodeBuilder, bigIntLiteralDigits, buildBindingPowerTable, invalidateBindingPowerTable };
|
|
332
|
-
//# sourceMappingURL=chunk-
|
|
333
|
-
//# sourceMappingURL=chunk-
|
|
332
|
+
//# sourceMappingURL=chunk-IQJGDZOP.js.map
|
|
333
|
+
//# sourceMappingURL=chunk-IQJGDZOP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":[],"mappings":";;;;;AA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AA,IAAI,WAAA,CAAY,IAAA,CAAK,aAAa,CAAA,EAAG,OAAO,aAAA;AAE5C,EAAA,MAAM,MAAA,GAAS,4BAAA,CAA6B,IAAA,CAAK,aAAa,IAC3D,aAAA,CAAc,KAAA,CAAM,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAChC,mBAAA,CAAoB,eAAe,UAAU,CAAA;AAEhD,EAAA,IAAI,CAAC,WAAA,CAAY,IAAA,CAAK,MAAM,CAAA,EAAG;AAC9B,IAAA,MAAM,SAAA,GAAY,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,MAAM,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,GAAA,GAAM,aAAA;AAC1F,IAAA,MAAM,YAAA,CAAa,OAAA;AAAA,MAClB,wBAAA;AAAA,MACA,CAAA,CAAA,EAAI,GAAG,CAAA,0BAAA,EAA6B,SAAS,+BAA+B,UAAU,CAAA,0DAAA,CAAA;AAAA,MACtF,EAAE,GAAA,EAAK,UAAA,EAAY,SAAA;AAAU,KAC9B;AAAA,EACD;AACA,EAAA,OAAO,MAAA;AACR;AASA,SAAS,mBAAA,CAAoB,MAAc,UAAA,EAA4B;AACtE,EAAA,MAAM,kBAAA,GAAqB,SAAA,CAAU,UAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA;AACzD,EAAA,OAAO,qBAAqB,IAAA,CAAK,KAAA,CAAM,kBAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAAI,IAAA;AACvE","file":"chunk-ENKKJYD3.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when registering an infix parselet via\n * `IPackageRegistry.registerInfixParselet`. See the built-in packages for\n * examples of picking an appropriate level (e.g. arithmetic `+`/`-` use\n * `Sum`, `*`/`/` use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: new Float64Array(this.numbers),\n\t\t\t// Defensive copy: .length = 0 in reset() would clear a shared reference.\n\t\t\t// Strings are rare (only UoM/datetime parselets emit them), so the copy\n\t\t\t// cost is negligible.\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\tthis.strings.length = 0;\n\t\tthis.stringIndex.clear();\n\t\tthis._hasAsync = false;\n\t\tthis.userFunctionBodies.length = 0;\n\t\tthis.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],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AAI,GAAA;AAG7D,EAAA,IAAI,WAAA,CAAY,IAAA,CAAK,aAAa,CAAA,EAAG,OAAO,aAAA;AAE5C,EAAA,MAAM,MAAA,GAAS,4BAAA,CAA6B,IAAA,CAAK,aAAa,IAC3D,aAAA,CAAc,KAAA,CAAM,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAChC,mBAAA,CAAoB,eAAe,UAAU,CAAA;AAEhD,EAAA,IAAI,CAAC,WAAA,CAAY,IAAA,CAAK,MAAM,CAAA,EAAG;AAC9B,IAAA,MAAM,SAAA,GAAY,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,MAAM,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,GAAA,GAAM,aAAA;AAC1F,IAAA,MAAM,YAAA,CAAa,OAAA;AAAA,MAClB,wBAAA;AAAA,MACA,CAAA,CAAA,EAAI,GAAG,CAAA,0BAAA,EAA6B,SAAS,+BAA+B,UAAU,CAAA,0DAAA,CAAA;AAAA,MACtF,EAAE,GAAA,EAAK,UAAA,EAAY,SAAA;AAAU,KAC9B;AAAA,EACD;AACA,EAAA,OAAO,MAAA;AACR;AASA,SAAS,mBAAA,CAAoB,MAAc,UAAA,EAA4B;AACtE,EAAA,MAAM,kBAAA,GAAqB,SAAA,CAAU,UAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA;AACzD,EAAA,OAAO,qBAAqB,IAAA,CAAK,KAAA,CAAM,kBAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAAI,IAAA;AACvE","file":"chunk-IQJGDZOP.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when registering an infix parselet via\n * `IPackageRegistry.registerInfixParselet`. See the built-in packages for\n * examples of picking an appropriate level (e.g. arithmetic `+`/`-` use\n * `Sum`, `*`/`/` use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: new Float64Array(this.numbers),\n\t\t\t// Defensive copy: .length = 0 in reset() would clear a shared reference.\n\t\t\t// Strings are rare (only UoM/datetime parselets emit them), so the copy\n\t\t\t// cost is negligible.\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\tthis.strings.length = 0;\n\t\tthis.stringIndex.clear();\n\t\tthis._hasAsync = false;\n\t\tthis.userFunctionBodies.length = 0;\n\t\tthis.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkMIGXCBXT_cjs = require('./chunk-MIGXCBXT.cjs');
|
|
4
4
|
|
|
5
5
|
// src/vm/AllocationBudget.ts
|
|
6
6
|
var depth = 0;
|
|
@@ -9,7 +9,7 @@ var limit = Number.POSITIVE_INFINITY;
|
|
|
9
9
|
var calls = 0;
|
|
10
10
|
var callLimit = Number.POSITIVE_INFINITY;
|
|
11
11
|
function exceeded(requested, what, alreadyUsed) {
|
|
12
|
-
return
|
|
12
|
+
return chunkMIGXCBXT_cjs.ErrorFactory.execution({
|
|
13
13
|
code: "ALLOCATION_LIMIT_EXCEEDED",
|
|
14
14
|
message: `Evaluating this expression would materialise ${requested.toLocaleString("en-US")} ${what}, past the limit of ${limit.toLocaleString("en-US")} elements for one evaluation`,
|
|
15
15
|
expected: `at most ${limit.toLocaleString("en-US")} elements materialised while evaluating one expression`,
|
|
@@ -46,7 +46,7 @@ function checkedArray(count, what) {
|
|
|
46
46
|
function chargeFunctionCall() {
|
|
47
47
|
if (depth === 0) return;
|
|
48
48
|
if (++calls > callLimit) {
|
|
49
|
-
throw
|
|
49
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.execution({
|
|
50
50
|
code: "FUNCTION_CALL_LIMIT_EXCEEDED",
|
|
51
51
|
message: `Evaluating this expression would make more than ${callLimit.toLocaleString("en-US")} user-defined-function calls, which is the limit for one evaluation`,
|
|
52
52
|
expected: `at most ${callLimit.toLocaleString("en-US")} function calls while evaluating one expression`,
|
|
@@ -74,6 +74,7 @@ var ValueType = /* @__PURE__ */ ((ValueType2) => {
|
|
|
74
74
|
ValueType2[ValueType2["Pending"] = 12] = "Pending";
|
|
75
75
|
ValueType2[ValueType2["Error"] = 13] = "Error";
|
|
76
76
|
ValueType2[ValueType2["Colour"] = 14] = "Colour";
|
|
77
|
+
ValueType2[ValueType2["Split"] = 15] = "Split";
|
|
77
78
|
return ValueType2;
|
|
78
79
|
})(ValueType || {});
|
|
79
80
|
var _ValueArena = class _ValueArena {
|
|
@@ -242,6 +243,7 @@ var Value = class {
|
|
|
242
243
|
}
|
|
243
244
|
if (this.type === 8 /* Range */) return 0;
|
|
244
245
|
if (this.type === 14 /* Colour */) return 0;
|
|
246
|
+
if (this.type === 15 /* Split */) return this.value.shares[0].value;
|
|
245
247
|
if (this.type === 9 /* Symbolic */) return 0;
|
|
246
248
|
if (this.type === 10 /* Boolean */) return this.value === true ? 1 : 0;
|
|
247
249
|
if (this._cachedNumber !== void 0) return this._cachedNumber;
|
|
@@ -263,6 +265,7 @@ var Value = class {
|
|
|
263
265
|
}
|
|
264
266
|
if (this.type === 8 /* Range */) return false;
|
|
265
267
|
if (this.type === 14 /* Colour */) return false;
|
|
268
|
+
if (this.type === 15 /* Split */) return false;
|
|
266
269
|
if (this.type === 9 /* Symbolic */) return false;
|
|
267
270
|
if (this.type === 10 /* Boolean */) return false;
|
|
268
271
|
if (typeof this.value === "number") return isNaN(this.value);
|
|
@@ -320,7 +323,7 @@ function isRateUnit(unit) {
|
|
|
320
323
|
function splitRateUnit(unit) {
|
|
321
324
|
const idx = unit.indexOf("/");
|
|
322
325
|
if (idx < 0) {
|
|
323
|
-
throw
|
|
326
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.internal(
|
|
324
327
|
"INVALID_RATE_UNIT",
|
|
325
328
|
`splitRateUnit: "${unit}" is not a rate unit (expected "numerator/denominator")`,
|
|
326
329
|
{ unit }
|
|
@@ -337,7 +340,7 @@ function isTimecodeUnit(unit) {
|
|
|
337
340
|
}
|
|
338
341
|
function timecodeFps(unit) {
|
|
339
342
|
if (!isTimecodeUnit(unit)) {
|
|
340
|
-
throw
|
|
343
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.internal(
|
|
341
344
|
"INVALID_TIMECODE_UNIT",
|
|
342
345
|
`timecodeFps: "${unit}" is not a timecode unit (expected "timecode@<fps>")`,
|
|
343
346
|
{ unit }
|
|
@@ -367,6 +370,10 @@ function colourValue(c) {
|
|
|
367
370
|
if (_arenaActive && _arena) return _arena.acquire(14 /* Colour */, c);
|
|
368
371
|
return new Value(14 /* Colour */, c);
|
|
369
372
|
}
|
|
373
|
+
function splitValue(data) {
|
|
374
|
+
if (_arenaActive && _arena) return _arena.acquire(15 /* Split */, data);
|
|
375
|
+
return new Value(15 /* Split */, data);
|
|
376
|
+
}
|
|
370
377
|
function symbolicValue(node) {
|
|
371
378
|
if (_arenaActive && _arena) return _arena.acquire(9 /* Symbolic */, node);
|
|
372
379
|
return new Value(9 /* Symbolic */, node);
|
|
@@ -438,11 +445,12 @@ exports.rangeValue = rangeValue;
|
|
|
438
445
|
exports.rateValue = rateValue;
|
|
439
446
|
exports.rowVectorValue = rowVectorValue;
|
|
440
447
|
exports.splitRateUnit = splitRateUnit;
|
|
448
|
+
exports.splitValue = splitValue;
|
|
441
449
|
exports.stringValue = stringValue;
|
|
442
450
|
exports.symbolicValue = symbolicValue;
|
|
443
451
|
exports.timecodeFps = timecodeFps;
|
|
444
452
|
exports.timecodeUnit = timecodeUnit;
|
|
445
453
|
exports.uomValue = uomValue;
|
|
446
454
|
exports.uomValueExact = uomValueExact;
|
|
447
|
-
//# sourceMappingURL=chunk-
|
|
448
|
-
//# sourceMappingURL=chunk-
|
|
455
|
+
//# sourceMappingURL=chunk-IT74O4BE.cjs.map
|
|
456
|
+
//# sourceMappingURL=chunk-IT74O4BE.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vm/AllocationBudget.ts","../src/vm/Value.ts"],"names":["ErrorFactory","ValueType","v"],"mappings":";;;;;AAwDA,IAAI,KAAA,GAAQ,CAAA;AAGZ,IAAI,IAAA,GAAO,CAAA;AAGX,IAAI,QAAQ,MAAA,CAAO,iBAAA;AAGnB,IAAI,KAAA,GAAQ,CAAA;AAGZ,IAAI,YAAY,MAAA,CAAO,iBAAA;AAMvB,SAAS,QAAA,CAAS,SAAA,EAAmB,IAAA,EAAc,WAAA,EAA4B;AAC9E,EAAA,OAAOA,+BAAa,SAAA,CAA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AS,cAAA,CAAe,CAAA,EAAU,CAAA,EAAW,CAAA,EAAyB;AAC5E,EAAA,IAAI,EAAE,IAAA,KAAS,EAAA,gBAAmB,CAAA,CAAE,IAAA,KAAS,kBAAmB,OAAO,CAAA;AACvE,EAAA,IAAI,CAAA,KAAM,WAAc,CAAA,CAAE,IAAA,KAAS,kBAAmB,CAAA,CAAE,IAAA,KAAS,mBAAoB,OAAO,CAAA;AAC5F,EAAA,IAAI,CAAA,KAAM,WAAc,CAAA,CAAE,IAAA,KAAS,kBAAmB,CAAA,CAAE,IAAA,KAAS,mBAAoB,OAAO,CAAA;AAC5F,EAAA,OAAO,IAAA;AACR;AAQO,SAAS,UAAU,MAAA,EAAwC;AACjE,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,QAAQ,CAAA,EAAA,EAAK;AACvC,IAAA,MAAM,CAAA,GAAI,OAAO,CAAC,CAAA;AAClB,IAAA,IAAI,EAAE,IAAA,KAAS,EAAA,gBAAmB,CAAA,CAAE,IAAA,KAAS,kBAAmB,OAAO,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,IAAA;AACR","file":"chunk-IT74O4BE.cjs","sourcesContent":["/**\n * The ceiling on how much memory one evaluation is allowed to ask for.\n *\n * The VM's other two counters bound how many opcodes run and how deep the value\n * stack gets, and both are checked BETWEEN opcodes. That leaves a hole the size\n * of a single opcode: whatever one opcode allocates in a loop of its own is\n * invisible to both, so twenty-four characters of input (`map(10*x,\n * 0:2000000000)`) could allocate until V8 aborted the process, which no\n * `try`/`catch` in the host can contain. Per-site caps close one hole each and\n * do not compose: two collections that are individually legal are legal\n * together, and an operation whose result is the PRODUCT of two legal inputs (a\n * matrix multiply) is bounded by neither of them.\n *\n * This is the counter that composes. Everything an evaluation materialises is\n * charged against one running tally, so the bound is on the total rather than\n * on any single step, and a new opcode inherits it by allocating through\n * {@link chargedArray} or by building a Value through a constructor that\n * already charges ({@link matrixValue}).\n *\n * The tally is module state rather than something threaded through every\n * signature. `executeBytecode()` opens an evaluation and every charge inside\n * that window lands on it, which is what lets a helper five call levels down\n * (`vm/MatrixOps.ts`'s `collectionToValues()`) charge without the four frames\n * in between passing a parameter along, and what keeps a charge down to an add\n * and a compare. This mirrors the value arena in `vm/Value.ts`, which is\n * ambient for the same reason and rests on the same fact: `executeBytecode()`\n * is synchronous, so exactly one evaluation is ever in flight in a realm.\n *\n * An \"element\" is one thing a user's input caused to exist: a `Value` in an\n * expanded collection, a cell in a matrix. They are counted rather than\n * measured in bytes, because a count is the quantity every call site already\n * has in hand before it allocates, and asking V8 how big something is costs\n * more than the allocation being guarded.\n *\n * A second tally lives here for the same structural reason and not because it\n * counts the same thing: {@link chargeFunctionCall} bounds how many\n * user-defined-function calls one evaluation may make in total. Surviving\n * reentry is the whole property both need, and this module is where reentry is\n * already tracked.\n *\n * @module AllocationBudget\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\n\n/**\n * How deep the evaluation is: 0 outside one, higher inside a reentrant call.\n *\n * `executeBytecode()` re-enters itself for a user-defined function call, a map\n * or reduce transform body, and an algebra verb's bound-unknown body. Only the\n * outermost entry clears the tally, so a runaway recursion cannot refresh its\n * own allowance the way it can refresh `maxInstructions` (each reentrant call\n * gets a fresh local instruction count, which is why function recursion needed\n * a separate guard of its own).\n */\nlet depth = 0;\n\n/** Elements charged so far in the evaluation currently in flight. */\nlet used = 0;\n\n/** The in-flight evaluation's ceiling, read from its VM when the evaluation opened. */\nlet limit = Number.POSITIVE_INFINITY;\n\n/** User-defined-function calls made so far in the evaluation currently in flight. */\nlet calls = 0;\n\n/** The in-flight evaluation's call ceiling, read from its VM when the evaluation opened. */\nlet callLimit = Number.POSITIVE_INFINITY;\n\n/**\n * The refusal itself, built in one place so the wording of the engine's most\n * likely \"this is too big\" message is not reinvented per site.\n */\nfunction exceeded(requested: number, what: string, alreadyUsed: number): Error {\n\treturn ErrorFactory.execution({\n\t\tcode: \"ALLOCATION_LIMIT_EXCEEDED\",\n\t\tmessage:\n\t\t\t`Evaluating this expression would materialise ${requested.toLocaleString(\"en-US\")} ${what}, ` +\n\t\t\t`past the limit of ${limit.toLocaleString(\"en-US\")} elements for one evaluation`,\n\t\texpected: `at most ${limit.toLocaleString(\"en-US\")} elements materialised while evaluating one expression`,\n\t\tfound: `a request for ${requested.toLocaleString(\"en-US\")} more ${what}, on top of ${alreadyUsed.toLocaleString(\"en-US\")} already materialised`,\n\t\tsuggestion: \"use a smaller collection or matrix, or raise the engine's vm.maxAllocatedElements setting\",\n\t\tcontext: { requested, what, used: alreadyUsed, limit },\n\t});\n}\n\n/**\n * Open an evaluation, taking its ceiling from the VM about to run it.\n *\n * @param vm - The VM running this program. Only consulted on the outermost\n * entry, so a reentrant call costs one increment.\n */\nexport function beginEvaluation(vm: VM): void {\n\tif (depth++ === 0) {\n\t\tused = 0;\n\t\tlimit = vm.getMaxAllocatedElements();\n\t\tcalls = 0;\n\t\tcallLimit = vm.getMaxFunctionCalls();\n\t}\n}\n\n/** Close the innermost evaluation. Always call from a `finally`, so a throw cannot leave one open. */\nexport function endEvaluation(): void {\n\tif (depth > 0) depth--;\n}\n\n/**\n * Record elements materialised by the evaluation in flight.\n *\n * Each thing is charged exactly once, where it comes into existence: a matrix\n * in `matrixValue()`, an expanded collection where it is expanded. A site that\n * knows a size in advance and whose result will be charged on birth uses\n * {@link checkAllocation} instead, so that refusing early does not mean\n * counting twice.\n *\n * Outside an evaluation this is a plain no-op rather than an error:\n * `matrixValue()` and the `vm/MatrixOps.ts` helpers are exported and get called\n * by tests, by the formatter and by hosts with no evaluation in flight, and\n * none of those is user input being executed.\n *\n * @param count - How many elements now exist.\n * @param what - What they are, in the plural and in a user's words (\"matrix\n * cells\", \"collection elements\"). Quoted verbatim in the error, so it should\n * name the thing rather than the code that makes it.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when this evaluation has had enough.\n * Recoverable: it describes this expression, not the engine.\n */\nexport function chargeAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\t// Written as a negated `>=` so that NaN takes this branch. A NaN count would\n\t// otherwise be added to the tally and make every later `used > limit`\n\t// comparison false, silently switching the guard off for the rest of the\n\t// evaluation, which is the one failure mode a safety limit must not have.\n\tif (!(count >= 0)) throw exceeded(count, what, used);\n\tused += count;\n\tif (used > limit) throw exceeded(count, what, used - count);\n}\n\n/**\n * Refuse an allocation this evaluation cannot afford, without recording it.\n *\n * For the sites that know how big a result will be BEFORE building it and whose\n * result is charged later, when it is born. A matrix product is the case that\n * matters: its size is the product of two operands that are each affordable, so\n * it has to be refused from the shapes alone, before `matrixMultiply()` takes\n * the memory. Charging here as well as at birth would bill every matrix twice\n * and halve the ceiling the host asked for.\n *\n * @param count - How many elements the result would have.\n * @param what - What they are, in the plural. See {@link chargeAllocation}.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when the evaluation could not afford them.\n */\nexport function checkAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\tif (!(count >= 0) || used + count > limit) throw exceeded(count, what, used);\n}\n\n/**\n * Check that an array is affordable, then allocate it.\n *\n * The intended way to build any user-sized array inside the VM whose contents\n * end up inside a Value that charges on birth, so that \"ask before you take\" is\n * a property of the allocator rather than something each new opcode has to be\n * told.\n *\n * @param count - Element count, checked before a single element exists.\n * @param what - What the elements are, in the plural. See {@link chargeAllocation}.\n * @returns An empty array of that length.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` before allocating anything, when the\n * evaluation cannot afford it.\n */\nexport function checkedArray<T>(count: number, what: string): T[] {\n\tcheckAllocation(count, what);\n\treturn new Array<T>(count);\n}\n\n/**\n * Record one user-defined-function call, and refuse the one past the ceiling.\n *\n * Lives in this module rather than in the VM for the single reason the element\n * tally does: it has to survive `executeBytecode()` re-entering itself. A call\n * count kept per invocation would be reset by the very calls it is counting,\n * which is exactly what happens to `maxInstructions` and exactly why counting\n * instructions could never bound this.\n *\n * The thing being bounded is BREADTH, which no existing guard could see.\n * `maxFunctionRecursionDepth` bounds nesting, and a doubling chain\n * (`f22(v) = f21(v) + f21(v)`, twenty-two lines of it) nests only twenty-two\n * deep while making 2,097,152 calls, which was a fatal heap abort in under a\n * second. Depth 22 against a limit of 50 is comfortably legal, and it was.\n *\n * @throws `FUNCTION_CALL_LIMIT_EXCEEDED` when this evaluation has made\n * enough. Recoverable: the engine is fine, this line is not.\n */\nexport function chargeFunctionCall(): void {\n\tif (depth === 0) return;\n\tif (++calls > callLimit) {\n\t\tthrow ErrorFactory.execution({\n\t\t\tcode: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n\t\t\tmessage:\n\t\t\t\t`Evaluating this expression would make more than ${callLimit.toLocaleString(\"en-US\")} ` +\n\t\t\t\t`user-defined-function calls, which is the limit for one evaluation`,\n\t\t\texpected: `at most ${callLimit.toLocaleString(\"en-US\")} function calls while evaluating one expression`,\n\t\t\tfound: \"a call past that limit, from a chain of functions that each call others more than once\",\n\t\t\tsuggestion: \"check for a function that calls itself (or a chain of them) more times than intended, or raise the engine's vm.maxFunctionCalls setting\",\n\t\t\tcontext: { calls, callLimit },\n\t\t});\n\t}\n}\n\n/**\n * Elements charged so far in the evaluation in flight, or in the one that just\n * finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function allocationUsed(): number {\n\treturn used;\n}\n\n/**\n * User-defined-function calls made so far in the evaluation in flight, or in\n * the one that just finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function functionCallsUsed(): number {\n\treturn calls;\n}\n\n/**\n * Drop all in-flight evaluation state.\n *\n * For tests that need a known starting point, and as a repair for a host that\n * somehow lost an `endEvaluation()`. Ordinary execution never needs it:\n * `executeBytecode()` pairs its own begin and end in a `finally`, and the\n * outermost begin clears the tally regardless of what came before.\n */\nexport function resetAllocationTracking(): void {\n\tdepth = 0;\n\tused = 0;\n\tlimit = Number.POSITIVE_INFINITY;\n\tcalls = 0;\n\tcallLimit = Number.POSITIVE_INFINITY;\n}\n","import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { chargeAllocation } from \"@solve-js/vm/AllocationBudget\";\nimport type { SymbolicNode, Rational } from \"@solve-js/symbolic\";\nimport type { DecimalData } from \"@solve-js/decimal\";\n\n/**\n * A single matrix cell. `boolean` covers element-wise comparison results\n * (`[1,6;3,8] < [5,2;7,4]` produces a Matrix of booleans, not numbers). A\n * `SymbolicNode` cell is a free-variable algebraic entry, e.g. `s =\n * [sx,0,0;0,sy,0;0,0,1]` where `sx`/`sy` are never assigned, so those\n * cells store a real `SymbolicNode` (a bare `var` node initially) rather\n * than degrading to `0`. See `MatrixOps.ts`'s `entryToSymbolic()`/\n * `symbolicToEntry()` for the two-way conversion every symbolic-aware\n * matrix op (multiply, inverse, determinant) uses.\n */\nexport type MatrixEntry = number | boolean | SymbolicNode;\n\n/**\n * A general rows×cols matrix, a vector is just a 1×N (row) or N×1 (column)\n * matrix. `data` is COLUMN-MAJOR (`data[row + col*rows]`), matching the\n * spec's own `a[index]` column-major indexing semantics directly (no\n * translation needed for single-index reads). `hasSymbolic` lets every\n * numeric matrix op fast-path the all-numeric case with one boolean check,\n * mirroring `binaryOp()`'s existing Number+Number fast path, computed by\n * `matrixValue()` itself (true the moment any cell is a `SymbolicNode`\n * object rather than a plain number/boolean), not something callers set\n * by hand.\n */\nexport interface MatrixData {\n\treadonly rows: number;\n\treadonly cols: number;\n\treadonly data: readonly MatrixEntry[];\n\treadonly hasSymbolic: boolean;\n}\n\n/** A first-class integer range `min:max`, both bounds inclusive. */\nexport interface RangeData {\n\treadonly min: number;\n\treadonly max: number;\n}\n\n/**\n * How a colour was authored, and therefore how it should display. It never\n * changes the channels: a colour is always stored as canonical sRGB (`r`,`g`,`b`\n * integers 0-255, `a` in 0-1), and `format` only decides whether `formatValue`\n * renders it as `#rrggbb`, `rgb(...)`, `hsl(...)` or a named keyword.\n */\nexport type ColourFormat = \"hex\" | \"rgb\" | \"rgba\" | \"hsl\" | \"hsla\" | \"named\";\n\n/**\n * A colour value. Canonical channels are sRGB (`r`,`g`,`b` are integers 0-255,\n * `a` is 0-1); HSL is never stored, it is derived on demand for display and for\n * hue/saturation/lightness operations, then re-quantised back to RGBA. A\n * `lighten` followed by an equal `darken` returns to within one rounding step of\n * the original (integer channels re-quantise each way), and does not drift on\n * repetition, rather than storing both HSL and RGB and letting them disagree.\n * `format`\n * records the authored/display form; `name` carries the CSS keyword only when\n * `format === \"named\"` (e.g. `\"rebeccapurple\"`). Lives in a {@link Value}'s\n * `value` slot exactly as {@link MatrixData}/{@link RangeData} do.\n */\nexport interface ColourData {\n\treadonly r: number;\n\treadonly g: number;\n\treadonly b: number;\n\treadonly a: number;\n\treadonly format: ColourFormat;\n\treadonly name?: string;\n}\n\n/**\n * One tier of a bill split: an amount and how many people pay it. An even\n * split is a single share; the odd-penny case is two shares (the base amount\n * most people pay, then the base plus a cent that the remaining `count` pay),\n * so the shares always add back to the exact total. `exact` carries the\n * base-ten cents of a currency share so display rounds from the decimal rather\n * than a drifted double, exactly as money does everywhere else.\n */\nexport interface SplitShare {\n\treadonly value: number;\n\treadonly exact?: DecimalData;\n\treadonly count: number;\n}\n\n/**\n * The result of a per-person bill split (`split $180 between 4`). `unit` is the\n * currency code when the amount was money, undefined for a bare number.\n * `shares` is ordered base-first: `shares[0]` is the \"each\" amount, and a\n * second share, when present, is the slightly larger amount the odd penny falls\n * on. Lives in a {@link Value}'s `value` slot exactly as {@link ColourData} and\n * {@link RangeData} do, a display-only payload the formatter renders.\n */\nexport interface SplitData {\n\treadonly unit?: string;\n\treadonly shares: readonly SplitShare[];\n}\n\n/**\n * Discriminated union tag for {@link Value} objects.\n *\n * Determines the runtime type of a Value and how its `value` field should\n * be interpreted. Used by the VM for type-aware dispatch in arithmetic,\n * comparison, and conversion operations.\n */\nexport enum ValueType {\n\t/** Plain 64-bit floating point number (IEEE 754 double) */\n\tNumber = 0,\n\tHex = 1,\n\tBigInt = 2,\n\tString = 3,\n\tDatetime = 4,\n\tPercentage = 5,\n\tUom = 6,\n\t/** General rows×cols matrix (a vector is a 1×N or N×1 matrix). Value is {@link MatrixData}. */\n\tMatrix = 7,\n\t/** A first-class integer range `min:max`, both inclusive. Value is {@link RangeData}. */\n\tRange = 8,\n\t/** A symbolic/algebraic expression tree (free-variable formula, not a concrete number). Value is a `SymbolicNode` (`@solve-js/symbolic`). */\n\tSymbolic = 9,\n\t/** Boolean true/false. Value is `boolean`. */\n\tBoolean = 10,\n\t/** Unit of measurement token (lexer only, not a runtime value). */\n\tUnit = 11,\n\t/** Async result pending resolution. Value stores the queryKey string. */\n\tPending = 12,\n\t/** Plugin-raised error propagated through the DAG. Value stores error code, unit stores message. */\n\tError = 13,\n\t/** A colour (hex/rgb/hsl/named). Value is {@link ColourData}. */\n\tColour = 14,\n\t/** A per-person bill split (`split $180 between 4`). Value is {@link SplitData}. */\n\tSplit = 15,\n}\n\n// ── ValueArena ────────────────────────────────────────────────────────────\n// Phase 5.3: Bump-allocator arena for zero-allocation Value reuse during scroll.\n// Instead of allocating new Value objects per instruction, we pre-allocate a\n// block and bump an index. A single arena.reset() per scroll frame recycles all\n// Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n\n/**\n * Bump-allocator arena for zero-allocation Value reuse during scroll.\n *\n * Instead of allocating new Value objects per instruction, pre-allocates a\n * block and bumps an index. `arena.reset()` per scroll frame recycles all\n * Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n *\n * Only active during Tier 2 scroll execution (ThreeTierEvaluator).\n */\nexport class ValueArena {\n\tprivate arena: Value[] = [];\n\tprivate index: number = 0;\n\t/** The block size to come back down to. Kept so {@link reset} can. */\n\tprivate readonly initialSize: number;\n\n\t/**\n\t * How much more than the last cycle needed the arena may go on holding\n\t * before it gives the difference back, and how much of it it keeps when it\n\t * does.\n\t *\n\t * A bump allocator that grows to serve one expensive line is working as\n\t * intended; one that never comes down is a leak wearing a cache's clothes.\n\t * `map(x*1, 1:100000)` is an ordinary line by every limit the engine has,\n\t * and it took the arena from 512 Values to 300,004, about 24MB that stayed\n\t * live through two forced full collections and through every later `1 + 1`,\n\t * because `acquire()` handles overflow with `push()` and `reset()` only\n\t * zeroed the bump index. The instance is module-level and survives\n\t * `disableValueArena()` on purpose, so that high-water mark was for the\n\t * life of the process.\n\t *\n\t * Keeping twice what the last cycle used, and only shrinking once holding\n\t * four times that, is what stops the release from becoming a different\n\t * performance bug: a steady scroll uses about the same number of Values\n\t * every frame, so it never meets the condition at all, and an alternating\n\t * heavy/light document degrades at worst to allocating the Values it would\n\t * have allocated with no arena in the first place.\n\t */\n\tprivate static readonly SHRINK_WHEN_HOLDING_TIMES = 4;\n\tprivate static readonly KEEP_TIMES = 2;\n\n\t/** Pre-allocate initial block. 512 Values covers ~30-line viewport comfortably. */\n\tconstructor(initialSize: number = 512) {\n\t\tthis.initialSize = initialSize;\n\t\tfor (let i = 0; i < initialSize; i++) {\n\t\t\tthis.arena.push(new Value(ValueType.Number, 0));\n\t\t}\n\t}\n\n\t/** Bump-allocate a recycled Value. Falls back to allocation only for overflow. */\n\tacquire(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string): Value {\n\t\tif (this.index < this.arena.length) {\n\t\t\tconst v = this.arena[this.index++];\n\t\t\tv.recycle(type, value, unit);\n\t\t\treturn v;\n\t\t}\n\t\t// Arena overflow, allocate fresh (rare, only for very complex expressions)\n\t\tconst v = new Value(type, value, unit);\n\t\tthis.arena.push(v);\n\t\tthis.index++;\n\t\treturn v;\n\t}\n\n\t/**\n\t * Reset for the next scroll frame, releasing a block the last frame turned\n\t * out not to need.\n\t *\n\t * Still O(1) in the ordinary case: one comparison against what the cycle\n\t * that just ended used, and the truncation only on the frame after an\n\t * unusually expensive one. Reading the usage here rather than at\n\t * `disableValueArena()` is what makes the policy \"the first cycle that does\n\t * not need the block gives it back\", which is the first thing a host does\n\t * after the line that grew it.\n\t */\n\treset(): void {\n\t\tconst usedLastCycle = this.index;\n\t\tthis.index = 0;\n\t\tif (this.arena.length <= this.initialSize) return;\n\t\tif (this.arena.length <= usedLastCycle * ValueArena.SHRINK_WHEN_HOLDING_TIMES) return;\n\t\t// Never below the initial block, and never above what is already held,\n\t\t// so this only ever truncates.\n\t\tthis.arena.length = Math.max(this.initialSize, usedLastCycle * ValueArena.KEEP_TIMES);\n\t}\n\n\t/** Current arena utilization (for diagnostics). */\n\tget usage(): number { return this.index; }\n\tget capacity(): number { return this.arena.length; }\n}\n\n// Module-level arena toggle. Single-threaded JS, so global state is safe.\n// The arena is ONLY active during Tier 2 scroll execution, the ThreeTierEvaluator\n// enables it before evaluating visible lines and disables it after.\n//\n// The arena INSTANCE survives disable(): constructing a ValueArena allocates\n// its whole initial block (512 Values), so dropping it on every disable would\n// pay that allocation cost again on the next enable, more garbage than the\n// arena saves. Instead, an `_arenaActive` flag gates use of the long-lived\n// instance; enable() just resets the bump index.\nlet _arena: ValueArena | null = null;\nlet _arenaActive = false;\n\n/** Enable the Value arena for zero-allocation scroll execution. */\nexport function enableValueArena(size?: number): ValueArena {\n\tif (!_arena) _arena = new ValueArena(size);\n\t_arena.reset();\n\t_arenaActive = true;\n\treturn _arena;\n}\n\n/** Disable the arena (returns to normal GC-collected allocation). */\nexport function disableValueArena(): void {\n\t_arenaActive = false;\n}\n\n/** Check if arena is active (used by STORE_VAR / HALT to decide cloning). */\nexport function isArenaActive(): boolean {\n\treturn _arenaActive;\n}\n\n/**\n * Allocate a Value that persists beyond the current arena cycle.\n * Used for values stored in variables (STORE_VAR) and final expression results\n * (HALT return), these must survive arena.reset() in the next scroll frame.\n */\nexport function persistentValue(v: Value): Value {\n\tconst p = new Value(v.type, v.value, v.unit);\n\t// The exact sidecar has to survive being stored in a variable, or a\n\t// referenced money value would silently drop back to the double: \"a = $0.10,\n\t// b = $0.20, a + b\" must still be exact across the STORE_VAR round trip.\n\tif (v.exact !== undefined) p.exact = v.exact;\n\t// The rational sidecar survives the same round trip, so \"a = 1/3, a + a + a\"\n\t// is exactly 1 rather than the drifted double a stored fraction would carry.\n\tif (v.rational !== undefined) p.rational = v.rational;\n\t// The uncertainty sidecar survives too, so \"a = 12.3 +/- 0.5, a * 4\" still\n\t// propagates the tolerance across the STORE_VAR round trip.\n\tif (v.uncertainty !== undefined) p.uncertainty = v.uncertainty;\n\treturn p;\n}\n\n// ── Dev-mode immutability guard (Part II, L5, Value model hardening) ──\n//\n// Value is documented immutable by convention, not enforcement: the arena\n// mutates objects in place via recycle() (by design, for Tier-2 scroll\n// performance), so Value can never be unconditionally frozen. This guard\n// freezes a Value ONLY when it is safe to do so, i.e. NOT while the arena\n// is active, since an arena-active Value may still be recycled later in\n// the same scroll frame. It is a no-op outside development builds (matches\n// the existing `process.env.NODE_ENV === \"development\"` convention used by\n// the app-layer logger) so there is zero runtime cost in production.\nconst isDevelopmentBuild = process.env.NODE_ENV === \"development\";\n\n/**\n * Freeze a Value in development builds, catching accidental external\n * mutation of \"immutable\" results early. Safe to call unconditionally\n * it is a no-op in production and a no-op whenever the arena is active\n * (an arena-active Value may still be recycle()'d before this scroll\n * frame ends, and freezing it would make recycle() throw).\n *\n * Intended for values leaving a public evaluation boundary\n * (ExpressionEngine.evaluateLine* / evaluateExpression), not for values\n * still moving through internal VM/arena machinery.\n */\nexport function freezeIfDev<T extends Value>(value: T): T {\n\tif (isDevelopmentBuild && !isArenaActive()) {\n\t\t// toNumber() lazily memoizes _cachedNumber for bigint/string values\n\t\t// (Number/Hex are already eagerly cached by the constructor), warm\n\t\t// it now so a later toNumber() call on the frozen object doesn't\n\t\t// try to write to a frozen field.\n\t\tvalue.toNumber();\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\n/**\n * Universal runtime value for the solve-js VM.\n *\n * Carries a {@link ValueType} discriminant, a polymorphic `value` payload,\n * and an optional `unit` string (for UoM values). Treated as immutable after\n * construction, the arena reuses objects internally via `recycle()`, but\n * external code should never mutate Value fields.\n *\n * A cached `_cachedNumber` avoids repeated `toNumber()` computation on\n * hot paths (ADD/SUB/MUL in the VM dispatch loop).\n */\nexport class Value {\n\t// Cached numeric representation, computed once on first toNumber() call.\n\t// Cleared on recycle() when the arena reuses this Value for a new value.\n\tprivate _cachedNumber: number | undefined;\n\n\t// Fields are NOT readonly, the arena reuses Value objects by calling\n\t// recycle() which overwrites all fields. External code should treat Values\n\t// as immutable after construction (arena handles mutation internally).\n\tpublic type: ValueType;\n\tpublic value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode;\n\tpublic unit?: string;\n\t/** Set by async resolvers when a fetch timed out, the result is a fallback (typically 0). */\n\tpublic timedOut?: boolean;\n\t/**\n\t * The exact base-ten value this Value stands for, when it has one.\n\t *\n\t * A sidecar rather than a replacement for `value`: money and decimal-point\n\t * literals set it to a {@link DecimalData} so that same-currency arithmetic\n\t * and display can be exact (\"$0.10 + $0.20\" is \"$0.30\", not\n\t * \"$0.30000000000000004\"), while `value` stays the nearest double so every\n\t * existing consumer that reads `.value` or `toNumber()` is unchanged. The\n\t * plain Number-times-Number fast paths deliberately ignore it, which is why\n\t * a bare \"0.1 + 0.2\" still answers the double it always did: exactness is\n\t * carried only where a unit-bearing operand asks for it. Cleared by\n\t * {@link recycle} so a reused arena Value never inherits a stale exact.\n\t */\n\tpublic exact?: DecimalData;\n\t/**\n\t * The exact rational value this Value stands for, when it has one.\n\t *\n\t * The second sidecar, the same shape as {@link exact} and for the same\n\t * reason: a fraction has no exact base-ten form (`1/3` is not any decimal),\n\t * so exact fraction arithmetic needs a numerator/denominator pair rather\n\t * than a coefficient and a scale. Integer division seeds it (\"1/3\" carries\n\t * the {@link Rational} 1/3), and `+`, `-`, `*`, `/` between rational-bearing\n\t * numbers keep it reduced, so \"1/49 * 49\" is exactly 1 and \"5/6 - 1/6 - 1/6\n\t * - 1/6 - 1/6 - 1/6\" is exactly 0 rather than the 1.6e-16 the doubles drift\n\t * to. `value` still holds the nearest double, recomputed from the exact\n\t * rational so accumulation error never creeps in, which is why the default\n\t * display and every `.value`/`toNumber()` reader are unchanged. Only a\n\t * fraction written with \"/\" carries it, so a decimal literal (\"0.1\") and a\n\t * transcendental result (\"sqrt(2)\") stay the plain doubles they were.\n\t * Cleared by {@link recycle} alongside {@link exact}.\n\t */\n\tpublic rational?: Rational;\n\t/**\n\t * The one-sigma uncertainty (standard error) this value carries, when it\n\t * has one.\n\t *\n\t * The third sidecar, the same shape as {@link exact} and {@link rational}\n\t * and for the same reason: a measurement written `12.3 ± 0.5` is still the\n\t * number 12.3 everywhere it is read as one, so the type stays\n\t * {@link ValueType.Number} and `value` stays the center, while this non\n\t * negative field carries the tolerance. The `±` (or ASCII `+/-`) operator\n\t * seeds it, and `+`, `-`, `*`, `/` propagate it in quadrature for\n\t * independent errors (see `vm/VMConversion.ts`'s `uncertainOp`). Everything\n\t * else (a comparison, a transcendental function, a unit conversion) reads\n\t * the center through `toNumber()` and drops the tolerance, which is why a\n\t * value with no uncertainty behaves exactly as a plain number always did.\n\t * Cleared by {@link recycle} alongside the other two sidecars.\n\t */\n\tpublic uncertainty?: number;\n\t/**\n\t * The number of decimal places this value should DISPLAY at, when it has been\n\t * given an explicit precision.\n\t *\n\t * A display sidecar, not a value one: `value` is unchanged, so every\n\t * `.value`/`toNumber()` reader and all arithmetic behave exactly as before,\n\t * and a value with no `decimalPlaces` formats the way it always did (the\n\t * global two-place default with trailing zeros trimmed). It is set only by an\n\t * explicit precision request, `<x> to N dp` and `round(x, N)`, so that\n\t * `3.14159 to 4 dp` shows `3.1416` and `1.5 to 2 dp` shows `1.50` rather than\n\t * the value being rounded but then displayed at the default two places. It is\n\t * NOT propagated through arithmetic (a later `+ 1` re-decides precision),\n\t * which is why nothing that did not ask for a precision is affected. Cleared\n\t * by {@link recycle} alongside the other sidecars.\n\t */\n\tpublic decimalPlaces?: number;\n\n\tconstructor(\n\t\ttype: ValueType,\n\t\tvalue: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode,\n\t\tunit?: string\n\t) {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Eagerly cache for Number and Hex types (the most common case).\n\t\t// This avoids a method call + type-check on first toNumber().\n\t\tif (typeof value === 'number') {\n\t\t\tthis._cachedNumber = value;\n\t\t}\n\t}\n\n\t/**\n\t * Phase 5.3: Reset all fields for arena reuse.\n\t * Called by ValueArena.acquire(), zero allocation, just field assignment.\n\t */\n\trecycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string): void {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Clear cache, value changed, cached number is stale.\n\t\t// Re-eager-cache for Number type (most common).\n\t\tthis._cachedNumber = typeof value === 'number' ? value : undefined;\n\t\t// Clear timeout flag, recycled Values shouldn't inherit stale metadata.\n\t\tthis.timedOut = undefined;\n\t\t// Clear the exact sidecar for the same reason: a reused Value that once\n\t\t// held money must not carry that money's decimal into a plain number.\n\t\tthis.exact = undefined;\n\t\t// The rational sidecar clears with it: a reused Value that once held a\n\t\t// fraction must not carry that fraction into a plain number.\n\t\tthis.rational = undefined;\n\t\t// The uncertainty sidecar clears the same way: a reused Value that once\n\t\t// carried a tolerance must not lend it to a plain number.\n\t\tthis.uncertainty = undefined;\n\t\t// The display-precision sidecar clears too: a reused Value that once had\n\t\t// an explicit `to N dp` must not display a plain number at that precision.\n\t\tthis.decimalPlaces = undefined;\n\t}\n\n\tisNumber(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Number;\n\t}\n\n\tisHex(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Hex;\n\t}\n\n\tisBigInt(): this is Value & { value: bigint } {\n\t\treturn this.type === ValueType.BigInt;\n\t}\n\n\tisString(): this is Value & { value: string } {\n\t\treturn this.type === ValueType.String;\n\t}\n\n\tisMatrix(): this is Value & { value: MatrixData } {\n\t\treturn this.type === ValueType.Matrix;\n\t}\n\n\t/** A Matrix shaped like a vector, 1×N (row) or N×1 (column). */\n\tisVectorShape(): boolean {\n\t\tif (this.type !== ValueType.Matrix) return false;\n\t\tconst m = this.value as MatrixData;\n\t\treturn m.rows === 1 || m.cols === 1;\n\t}\n\n\tisRange(): this is Value & { value: RangeData } {\n\t\treturn this.type === ValueType.Range;\n\t}\n\n\tisColour(): this is Value & { value: ColourData } {\n\t\treturn this.type === ValueType.Colour;\n\t}\n\n\tisSymbolic(): this is Value & { value: SymbolicNode } {\n\t\treturn this.type === ValueType.Symbolic;\n\t}\n\n\ttoNumber(): number {\n\t\t// Pending/Error have no numeric representation at all, 0 (established\n\t\t// convention). A genuinely multi-cell Matrix has no single numeric\n\t\t// representation either (real callers branch on `.isMatrix()` BEFORE\n\t\t// reaching this fallback. See e.g. VM.ts's MUL/comparison dispatch)\n\t\t// but a 1x1 Matrix, the shape `float(x)`'s legacy sugar produces, see\n\t\t// packages/vector/parselets/FloatParselet.ts, IS a scalar in every\n\t\t// meaningful sense, so it degrades to that single cell's numeric value\n\t\t// rather than 0 (this exact case used to work \"by accident\" pre-Matrix,\n\t\t// since `parseFloat([2].toString())` happened to yield `2`).\n\t\tif (this.type === ValueType.Pending) return 0;\n\t\tif (this.type === ValueType.Error) return 0;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return m.data[0];\n\t\t\treturn 0;\n\t\t}\n\t\tif (this.type === ValueType.Range) return 0;\n\t\t// A colour is a struct of channels, not a scalar; like Matrix/Range it has\n\t\t// no single numeric reading. Callers branch on `.isColour()` first.\n\t\tif (this.type === ValueType.Colour) return 0;\n\t\t// A split is a structured multi-share result; its scalar reading is the\n\t\t// \"each\" (base) share, so a numeric consumer or the worker DTO's number\n\t\t// field still gets a sensible value where a caller does not branch first.\n\t\tif (this.type === ValueType.Split) return (this.value as SplitData).shares[0].value;\n\t\t// A symbolic expression has no single concrete numeric value by\n\t\t// definition (it's a free-variable formula), 0, matching the\n\t\t// Pending/Error/Range convention. Real callers branch on\n\t\t// `.isSymbolic()` BEFORE reaching this fallback (see\n\t\t// `VMConversion.ts`'s `binaryOp()`).\n\t\tif (this.type === ValueType.Symbolic) return 0;\n\t\t// A boolean has an obvious numeric reading and no branch used to give it\n\t\t// one, so it fell through to `parseFloat(true)` -> NaN -> 0, and BOTH\n\t\t// booleans read as zero: `true == false` answered true, and every\n\t\t// arithmetic path that mixes a boolean with a number (\"true and 5\")\n\t\t// contributed nothing. 1/0 is the reading every language with a numeric\n\t\t// boolean coercion uses, and the one `if 1 then` already implies.\n\t\tif (this.type === ValueType.Boolean) return this.value === true ? 1 : 0;\n\n\t\tif (this._cachedNumber !== undefined) return this._cachedNumber;\n\n\t\tif (typeof this.value === 'bigint') {\n\t\t\tthis._cachedNumber = Number(this.value);\n\t\t\treturn this._cachedNumber;\n\t\t}\n\t\t// Prevent silent NaN propagation from non-numeric strings\n\t\tconst result = parseFloat(this.value as string);\n\t\tthis._cachedNumber = isNaN(result) ? 0 : result;\n\t\treturn this._cachedNumber;\n\t}\n\n\tisNaN(): boolean {\n\t\tif (this.type === ValueType.Pending) return false;\n\t\tif (this.type === ValueType.Error) return false;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return isNaN(m.data[0]);\n\t\t\treturn false;\n\t\t}\n\t\tif (this.type === ValueType.Range) return false;\n\t\tif (this.type === ValueType.Colour) return false;\n\t\tif (this.type === ValueType.Split) return false;\n\t\tif (this.type === ValueType.Symbolic) return false;\n\t\t// Matches toNumber()'s boolean reading above. Without this a Boolean\n\t\t// reached the string branch at the bottom and `parseFloat(true)` made\n\t\t// every boolean report itself as NaN.\n\t\tif (this.type === ValueType.Boolean) return false;\n\t\tif (typeof this.value === 'number') return isNaN(this.value);\n\t\tif (typeof this.value === 'bigint') return false;\n\t\treturn isNaN(parseFloat(this.value as string));\n\t}\n}\n\n/**\n * Create a Number-typed Value. Uses the arena when active for zero-allocation.\n * This is the most common factory, over 90% of all Value creations.\n */\nexport function numberValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Number, n);\n\treturn new Value(ValueType.Number, n);\n}\n\n/**\n * A Number that also carries the exact decimal it was written as.\n *\n * The type stays {@link ValueType.Number} and `value` stays the nearest double,\n * so this Value behaves exactly like any other number everywhere it is read as\n * one. The `exact` sidecar only matters when it later meets a currency: that is\n * what lets \"$0.70 * 1.10\" be exact while \"0.1 + 0.2\" stays the double it was.\n * Decimal-point literals are compiled to this (see the PUSH_DECIMAL opcode).\n */\nexport function numberValueExact(n: number, exact: DecimalData): Value {\n\tconst v = numberValue(n);\n\tv.exact = exact;\n\treturn v;\n}\n\n/**\n * A Number that also carries the exact rational it evaluates to.\n *\n * The rational counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the nearest double (recomputed\n * from the rational, so a chain of fraction operations never accumulates\n * float error), so this reads as an ordinary number everywhere. The `rational`\n * sidecar is what keeps the next fraction operation and any `as fraction`\n * exact. Integer division produces this (see the DIV opcode).\n */\nexport function numberValueRational(n: number, rational: Rational): Value {\n\tconst v = numberValue(n);\n\tv.rational = rational;\n\treturn v;\n}\n\n/**\n * A Number that also carries a one-sigma uncertainty (standard error).\n *\n * The uncertainty counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the center, so this reads as an\n * ordinary number everywhere. The `uncertainty` sidecar is what lets `+`, `-`,\n * `*`, `/` propagate the tolerance in quadrature. The `±` operator produces\n * this (see the MAKE_UNCERTAIN opcode), as does any of those four ops when an\n * operand already carries one. The magnitude is stored as given, callers pass a\n * non-negative value (`Math.abs` at the seam, quadrature results are already\n * non-negative).\n */\nexport function numberValueUncertain(n: number, uncertainty: number): Value {\n\tconst v = numberValue(n);\n\tv.uncertainty = uncertainty;\n\treturn v;\n}\n\n/** Which base a {@link ValueType.Hex} value is displayed in. */\nexport type DisplayBase = \"hex\" | \"bin\" | \"oct\";\n\n/**\n * Create a Hex-typed Value: a **number** that displays in another base.\n *\n * The type is numeric on purpose, and that is the whole point of it. A base is\n * a way of writing a quantity, not a different kind of quantity, so `0xFF + 1`\n * has to be 256. Returning a string instead makes it 1, because a string reads\n * as zero in arithmetic, and nothing about that failure is visible at the point\n * of use.\n *\n * @param n - The number itself, in full precision. A `bigint` is accepted for\n * the same reason the type is numeric at all: `12345678901234567890n as hex`\n * has an exact answer, and forcing it through a double first rendered\n * 0xAB54A98CEB1F0800 for a value ending 0AD2.\n * @param base - How to display it, defaulting to hexadecimal. Carried in the\n * `unit` slot, which is free for this type.\n */\nexport function hexValue(n: number | bigint, base: DisplayBase = \"hex\"): Value {\n\tconst tag = base === \"hex\" ? undefined : base;\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Hex, n, tag);\n\treturn new Value(ValueType.Hex, n, tag);\n}\n\n/** Create a BigInt-typed Value (arbitrary-precision integer). */\nexport function bigIntValue(n: bigint): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.BigInt, n);\n\treturn new Value(ValueType.BigInt, n);\n}\n\n/** Create a String-typed Value. */\nexport function stringValue(s: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.String, s);\n\treturn new Value(ValueType.String, s);\n}\n\n/** Create a Unit-of-Measurement Value (typed number with unit annotation). */\nexport function uomValue(n: number, unit: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Uom, n, unit);\n\treturn new Value(ValueType.Uom, n, unit);\n}\n\n/**\n * A unit-of-measurement Value that also carries an exact decimal magnitude.\n *\n * This is how money keeps its precision: `value` is the nearest double (so\n * `toNumber()` and every existing Uom path are unchanged), and `exact` is the\n * decimal the amount really is. Same-currency arithmetic reads `exact` to stay\n * exact, and the formatter reads it to round a half-cent the way a ledger does\n * rather than the way `toFixed` does on a double.\n */\nexport function uomValueExact(n: number, unit: string, exact: DecimalData): Value {\n\tconst v = uomValue(n, unit);\n\tv.exact = exact;\n\treturn v;\n}\n\n// ── Rate, \"quantity per unit of something\" (SoulverCore: `$99/week`\n// `3 hours/day`, `30 fps`). Represented as a `ValueType.Uom` (no new\n// ValueType, a rate IS a unit-of-measurement, just a compound one) whose\n// `unit` string is `\"<numerator>/<denominator>\"`. The numerator is an\n// opaque label (may be a real convertible unit like \"USD\"/\"km\", or a bare\n// tag like \"frames\" that the `convert` package doesn't know about, rate\n// arithmetic never needs to convert the numerator, only compare it for\n// equality when combining two rates). The denominator MUST be a unit\n// `convertUnit()`/`getMeasure()` (uom/UomConverter.ts) recognizes, since\n// that's the part rate arithmetic actually rescales. See `vm/VM.ts`'s\n// `RATE_CONVERT`/`RATE_MUL`/`RATE_DIV` opcodes for the operations built on\n// this representation.\n\n/** Create a Rate value: `magnitude` of `numeratorUnit` per one `denominatorUnit`. */\nexport function rateValue(magnitude: number, numeratorUnit: string, denominatorUnit: string): Value {\n\treturn uomValue(magnitude, `${numeratorUnit}/${denominatorUnit}`);\n}\n\n/** Whether `unit` is a compound rate unit (`\"X/Y\"`) rather than a plain unit. */\nexport function isRateUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.includes(\"/\");\n}\n\n/**\n * Split a rate unit string into its numerator/denominator halves.\n * @throws if `unit` isn't a rate unit, check with {@link isRateUnit} first.\n */\nexport function splitRateUnit(unit: string): { numerator: string; denominator: string } {\n\tconst idx = unit.indexOf(\"/\");\n\tif (idx < 0) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_RATE_UNIT\",\n\t\t\t`splitRateUnit: \"${unit}\" is not a rate unit (expected \"numerator/denominator\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn { numerator: unit.slice(0, idx), denominator: unit.slice(idx + 1) };\n}\n\n/** Join a numerator/denominator pair back into a rate unit string. */\nexport function joinRateUnit(numeratorUnit: string, denominatorUnit: string): string {\n\treturn `${numeratorUnit}/${denominatorUnit}`;\n}\n\n// ── Video timecode, \"HH:MM:SS:FF at a given fps\" (SoulverCore: video\n// editing timecode literals, e.g. `01:02:03:04 at 30fps`). Represented the\n// same way Rate is above: NOT a new ValueType, just a `ValueType.Uom` whose\n// `unit` string is `\"timecode@<fps>\"` and whose numeric `value` is the\n// TOTAL FRAME COUNT since 00:00:00:00 at that fps, e.g. \"00:00:01:00 at\n// 30fps\" is `Uom(30, \"timecode@30\")`.\n//\n// Storing the total frame count (rather than four separate H/M/S/F fields)\n// means ordinary integer addition/subtraction on the numeric value is\n// ALREADY correct carry/borrow-aware arithmetic with zero extra logic\n// e.g. \"frame 29 + 2 frames\" at 30fps is just `29 + 2 = 31`, and 31 total\n// frames at 30fps IS frame 1 of the next second, with no explicit carry\n// step required. Carry/borrow only needs to be reconstructed when\n// converting a total frame count back into HH:MM:SS:FF display notation\n// see `packages/time/timecode/TimecodeMath.ts`'s `framesToTimecodeString()`.\n// See `vm/VM.ts`'s ADD/SUB dispatch for the arithmetic built on this\n// representation (timecode + frames, + duration, + timecode, - timecode).\n\nconst TIMECODE_UNIT_PREFIX = \"timecode@\";\n\n/** Build a timecode Uom unit string embedding its frame rate, e.g. `timecodeUnit(30)` -> `\"timecode@30\"`. */\nexport function timecodeUnit(fps: number): string {\n\treturn `${TIMECODE_UNIT_PREFIX}${fps}`;\n}\n\n/** Whether `unit` is a compound video-timecode unit (`\"timecode@<fps>\"`). */\nexport function isTimecodeUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.startsWith(TIMECODE_UNIT_PREFIX);\n}\n\n/**\n * Extract the fps from a timecode unit string.\n * @throws if `unit` isn't a timecode unit, check with {@link isTimecodeUnit} first.\n */\nexport function timecodeFps(unit: string): number {\n\tif (!isTimecodeUnit(unit)) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_TIMECODE_UNIT\",\n\t\t\t`timecodeFps: \"${unit}\" is not a timecode unit (expected \"timecode@<fps>\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn parseFloat(unit.slice(TIMECODE_UNIT_PREFIX.length));\n}\n\n/**\n * Create a Matrix value from an explicit shape + column-major data array.\n * `data.length` must equal `rows*cols`, callers building a matrix from\n * row-major source syntax (e.g. the `[1,2;3,4]` literal) must transpose\n * into column-major order before calling this; see `MatrixOps.ts`'s\n * `rowMajorToColumnMajor()`.\n */\nexport function matrixValue(rows: number, cols: number, data: readonly MatrixEntry[]): Value {\n\t// Every matrix in the engine is born here, which makes this the one place\n\t// that can charge for one without each producer having to remember to. The\n\t// charge lands after `data` exists, so it is a backstop rather than a\n\t// refusal: it cannot stop a single allocation that is already fatal (the\n\t// sites whose size is knowable in advance charge before allocating, see\n\t// `vm/VM.ts`'s matrix cases), but it does stop the second one, and it means\n\t// an opcode added later inherits the bound without being told about it.\n\t// Free in relative terms: the hasSymbolic scan just below is already O(n)\n\t// over the same cells.\n\tchargeAllocation(data.length, \"matrix cells\");\n\t// A SymbolicNode cell is the only object-typed MatrixEntry variant\n\t// (number/boolean are primitives), a cheap, always-correct way to\n\t// derive hasSymbolic without asking every caller to track it by hand.\n\t// The `\"kind\" in cell` half is a tripwire, not redundancy. MatrixEntry is\n\t// `number | boolean | SymbolicNode`, so an object cell should always be a\n\t// node; requiring the discriminant means a Rational that escaped\n\t// MatrixOps.ts's symbolicToEntry() shows up as a wrong result rather than as\n\t// a matrix that silently believes it is symbolic.\n\tconst hasSymbolic = data.some(cell => typeof cell === \"object\" && cell !== null && \"kind\" in cell);\n\tconst m: MatrixData = { rows, cols, data, hasSymbolic };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Matrix, m);\n\treturn new Value(ValueType.Matrix, m);\n}\n\n/** A 1×N row-vector Matrix, row-major and column-major storage are identical for a single row. */\nexport function rowVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(1, data.length, data);\n}\n\n/** An N×1 column-vector Matrix, row-major and column-major storage are identical for a single column. */\nexport function colVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(data.length, 1, data);\n}\n\n/** Create a Range value, a first-class integer range `min:max`, both bounds inclusive. */\nexport function rangeValue(min: number, max: number): Value {\n\tconst r: RangeData = { min, max };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Range, r);\n\treturn new Value(ValueType.Range, r);\n}\n\n/**\n * Create a Colour value from canonical sRGB channels plus a display format.\n * Arena-backed like the other synchronous factories; the `ColourData` struct in\n * the `value` slot is immutable, so arena recycle is safe with no extra clearing\n * (matching {@link matrixValue}/{@link rangeValue}).\n */\nexport function colourValue(c: ColourData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Colour, c);\n\treturn new Value(ValueType.Colour, c);\n}\n\n/**\n * Create a Split value from its structured per-share payload. Arena-backed like\n * the other synchronous factories; the {@link SplitData} struct in the `value`\n * slot is immutable, so arena recycle is safe with no extra clearing (matching\n * {@link colourValue}/{@link rangeValue}).\n */\nexport function splitValue(data: SplitData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Split, data);\n\treturn new Value(ValueType.Split, data);\n}\n\n/** Create a Symbolic value, a free-variable algebraic expression tree (`symbolic/SymbolicNode.ts`'s `SymbolicNode`), not a concrete number. */\nexport function symbolicValue(node: SymbolicNode): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Symbolic, node);\n\treturn new Value(ValueType.Symbolic, node);\n}\n\n\n\n/** Create a Boolean-typed Value. */\nexport function boolValue(b: boolean): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Boolean, b);\n\treturn new Value(ValueType.Boolean, b);\n}\n\n/** Create a Datetime-typed Value (Unix timestamp in milliseconds). */\nexport function datetimeValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Datetime, n);\n\treturn new Value(ValueType.Datetime, n);\n}\n\n/** Create a Percentage-typed Value (stored as fraction, e.g. 0.5 for 50%). */\nexport function percentageValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Percentage, n);\n\treturn new Value(ValueType.Percentage, n);\n}\n\n/**\n * Create a Pending value, signals that an async result is not yet resolved.\n * The value field stores the queryKey string for deduplication and diagnostics.\n * Pending values should NEVER be stored in the arena (they persist across\n * scroll frames until resolution completes).\n */\nexport function pendingValue(queryKey: string): Value {\n\treturn new Value(ValueType.Pending, queryKey);\n}\n\n/**\n * Create an Error value, propagated through the DAG when a plugin raises an error.\n * The value field stores the EngineError code, unit stores the message.\n * Downstream consumers (lines that depend on errored data) bubble this up.\n * Should NEVER be stored in the arena.\n */\nexport function errorValue(code: string, message: string): Value {\n\treturn new Value(ValueType.Error, code, message);\n}\n\n/**\n * The first operand carrying a fault rather than a quantity, if any does.\n *\n * `Error` and `Pending` both read as the number 0 through {@link Value.toNumber},\n * by a convention that only holds up as long as nothing asks. Every opcode and\n * builtin that reaches for an operand's number without asking its type first\n * therefore computes with a zero it cannot tell apart from a real one, and\n * hands back an answer dressed in whatever type it was going to produce\n * anyway. That is how `(5 kg to m) to s` came to answer `0.00 s`: the failed\n * conversion is an Error, the second conversion read it as zero, and the unit\n * the reader asked for made the result look like a conversion that worked.\n *\n * Operands are checked left to right, matching evaluation order, and the\n * faulted Value is returned AS IT IS rather than replaced with a fresh one, so\n * the original code and message (or the pending query key) reach the caller\n * unchanged. `binaryOp` (vm/VMConversion.ts) and `OpCode.EXP` already did this\n * inline; this is the same rule for every other site, in one place so a site\n * added later can adopt it in a line.\n *\n * Three operands cover every call site in the VM (`MAT_INDEX2` and `MAT_SLICE`\n * are the widest). A variadic signature would allocate an arguments array on\n * paths that run per instruction; see {@link faultedIn} for the list case.\n *\n * @returns The faulted operand, or `null` when all of them carry a value.\n */\nexport function faultedOperand(a: Value, b?: Value, c?: Value): Value | null {\n\tif (a.type === ValueType.Error || a.type === ValueType.Pending) return a;\n\tif (b !== undefined && (b.type === ValueType.Error || b.type === ValueType.Pending)) return b;\n\tif (c !== undefined && (c.type === ValueType.Error || c.type === ValueType.Pending)) return c;\n\treturn null;\n}\n\n/**\n * {@link faultedOperand} over an already-built list, for the call sites that\n * have one (a builtin's arguments, a plugin function's).\n *\n * @returns The first faulted element, or `null` when every element carries a value.\n */\nexport function faultedIn(values: readonly Value[]): Value | null {\n\tfor (let i = 0; i < values.length; i++) {\n\t\tconst v = values[i];\n\t\tif (v.type === ValueType.Error || v.type === ValueType.Pending) return v;\n\t}\n\treturn null;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkVEKIWQ3F_cjs = require('./chunk-VEKIWQ3F.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkMIGXCBXT_cjs = require('./chunk-MIGXCBXT.cjs');
|
|
5
5
|
|
|
6
6
|
// src/uom/Iso4217.ts
|
|
7
7
|
var ISO_4217_CODES = /* @__PURE__ */ new Set([
|
|
@@ -225,7 +225,7 @@ var _CurrencyExchangeService = class _CurrencyExchangeService {
|
|
|
225
225
|
);
|
|
226
226
|
try {
|
|
227
227
|
const response = await fetch(`https://api.frankfurter.dev/v2/rates?base=${fromUpper}`, { signal: fetchSignal });
|
|
228
|
-
if (!response.ok) throw
|
|
228
|
+
if (!response.ok) throw chunkMIGXCBXT_cjs.ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });
|
|
229
229
|
const data = await response.json();
|
|
230
230
|
const rates = Array.isArray(data) ? Object.fromEntries(
|
|
231
231
|
data.filter((entry) => {
|
|
@@ -234,7 +234,7 @@ var _CurrencyExchangeService = class _CurrencyExchangeService {
|
|
|
234
234
|
return typeof candidate.quote === "string" && typeof candidate.rate === "number";
|
|
235
235
|
}).map((entry) => [entry.quote.toUpperCase(), entry.rate])
|
|
236
236
|
) : data.rates ?? {};
|
|
237
|
-
if (rates[toUpper] === void 0) throw
|
|
237
|
+
if (rates[toUpper] === void 0) throw chunkMIGXCBXT_cjs.ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });
|
|
238
238
|
this.baseTables.set(fromUpper, {
|
|
239
239
|
fetchedAt: Date.now(),
|
|
240
240
|
rates: { ...rates, [fromUpper]: 1 }
|
|
@@ -269,22 +269,22 @@ var _CurrencyExchangeService = class _CurrencyExchangeService {
|
|
|
269
269
|
const data = await this.fetchCoinGeckoPrices([fromId, toId], "usd", fetchSignal);
|
|
270
270
|
const fromUsd = data[fromId]?.usd;
|
|
271
271
|
const toUsd = data[toId]?.usd;
|
|
272
|
-
if (typeof fromUsd !== "number") throw
|
|
273
|
-
if (typeof toUsd !== "number") throw
|
|
272
|
+
if (typeof fromUsd !== "number") throw chunkMIGXCBXT_cjs.ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });
|
|
273
|
+
if (typeof toUsd !== "number") throw chunkMIGXCBXT_cjs.ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });
|
|
274
274
|
rate = fromUsd / toUsd;
|
|
275
275
|
} else if (fromIsCrypto) {
|
|
276
276
|
const fromId = _CurrencyExchangeService.CRYPTO_IDS[fromUpper];
|
|
277
277
|
const vs = toUpper.toLowerCase();
|
|
278
278
|
const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);
|
|
279
279
|
const value = data[fromId]?.[vs];
|
|
280
|
-
if (typeof value !== "number") throw
|
|
280
|
+
if (typeof value !== "number") throw chunkMIGXCBXT_cjs.ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });
|
|
281
281
|
rate = value;
|
|
282
282
|
} else {
|
|
283
283
|
const toId = _CurrencyExchangeService.CRYPTO_IDS[toUpper];
|
|
284
284
|
const vs = fromUpper.toLowerCase();
|
|
285
285
|
const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);
|
|
286
286
|
const priceOfToInFrom = data[toId]?.[vs];
|
|
287
|
-
if (typeof priceOfToInFrom !== "number") throw
|
|
287
|
+
if (typeof priceOfToInFrom !== "number") throw chunkMIGXCBXT_cjs.ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });
|
|
288
288
|
rate = 1 / priceOfToInFrom;
|
|
289
289
|
}
|
|
290
290
|
this.baseTables.set(fromUpper, {
|
|
@@ -299,7 +299,7 @@ var _CurrencyExchangeService = class _CurrencyExchangeService {
|
|
|
299
299
|
async fetchCoinGeckoPrices(ids, vsCurrency, signal) {
|
|
300
300
|
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids.join(",")}&vs_currencies=${vsCurrency}`;
|
|
301
301
|
const response = await fetch(url, { signal });
|
|
302
|
-
if (!response.ok) throw
|
|
302
|
+
if (!response.ok) throw chunkMIGXCBXT_cjs.ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });
|
|
303
303
|
return response.json();
|
|
304
304
|
}
|
|
305
305
|
/**
|
|
@@ -455,5 +455,5 @@ var sharedCurrencyExchange = currencyExchangeService;
|
|
|
455
455
|
exports.CurrencyExchangeService = CurrencyExchangeService;
|
|
456
456
|
exports.currencyExchangeService = currencyExchangeService;
|
|
457
457
|
exports.sharedCurrencyExchange = sharedCurrencyExchange;
|
|
458
|
-
//# sourceMappingURL=chunk-
|
|
459
|
-
//# sourceMappingURL=chunk-
|
|
458
|
+
//# sourceMappingURL=chunk-KXDQKVNX.cjs.map
|
|
459
|
+
//# sourceMappingURL=chunk-KXDQKVNX.cjs.map
|