solve-engine 1.1.0 → 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-GUG7SNSV.js → chunk-7JM3F4KL.js} +39 -8
- package/dist/chunk-7JM3F4KL.js.map +1 -0
- package/dist/{chunk-XJGJCF2R.cjs → chunk-7USV76HV.cjs} +6 -6
- package/dist/{chunk-XJGJCF2R.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-MG6Q3DUO.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-G7Z4HJQA.js → chunk-CSDQMDU2.js} +4 -4
- package/dist/{chunk-G7Z4HJQA.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-OTN6SZOD.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-C75AFGVD.cjs → chunk-ICEKS6YC.cjs} +11 -11
- package/dist/{chunk-C75AFGVD.cjs.map → chunk-ICEKS6YC.cjs.map} +1 -1
- package/dist/{chunk-JIPATHVY.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-JJIXHXFQ.js → chunk-L5YHV6BQ.js} +5 -5
- package/dist/{chunk-JJIXHXFQ.js.map → chunk-L5YHV6BQ.js.map} +1 -1
- package/dist/{chunk-ZXCESUJS.cjs → chunk-LO7HU5WB.cjs} +8 -8
- package/dist/{chunk-ZXCESUJS.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-GQMUHVE3.js → chunk-ORM7CHYZ.js} +36 -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-OADDUPT3.js → chunk-RNKDIXDV.js} +4 -4
- package/dist/{chunk-OADDUPT3.js.map → chunk-RNKDIXDV.js.map} +1 -1
- package/dist/{chunk-SNHVVOJK.cjs → chunk-TC6BTUSU.cjs} +55 -24
- package/dist/chunk-TC6BTUSU.cjs.map +1 -0
- package/dist/{chunk-RRLHC37V.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-YTIYVHL7.cjs → chunk-YJHY7CMN.cjs} +108 -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-CtfJtPQc.d.cts → pipeline-D-PS9gVw.d.ts} +3 -3
- package/dist/{pipeline-DCd5M6Gk.d.ts → 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-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-GQMUHVE3.js.map +0 -1
- package/dist/chunk-GUG7SNSV.js.map +0 -1
- package/dist/chunk-JIPATHVY.js.map +0 -1
- package/dist/chunk-MG6Q3DUO.cjs.map +0 -1
- package/dist/chunk-NKW7LKYU.js.map +0 -1
- package/dist/chunk-NNQ2TYDF.js.map +0 -1
- package/dist/chunk-OTN6SZOD.cjs.map +0 -1
- package/dist/chunk-QFTDTX6K.cjs.map +0 -1
- package/dist/chunk-RRLHC37V.js.map +0 -1
- package/dist/chunk-SNHVVOJK.cjs.map +0 -1
- package/dist/chunk-SRGQ72IR.cjs.map +0 -1
- package/dist/chunk-UO6BUV6K.js.map +0 -1
- package/dist/chunk-WXEHD6TT.js.map +0 -1
- package/dist/chunk-YTIYVHL7.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["createTimeoutSignal","ErrorFactory"],"mappings":";;;;;;AAyBO,IAAM,cAAA,uBAA0C,GAAA,CAAI;AAAA,EAC1D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAC/D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAC/D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EACnC,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EA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AA;AAAA,EAAW,IAAA,EAAM,UAAA;AAAA,EAAY,GAAA,EAAK;AACzC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA/BW,wBAAA,CAkDa,gBAAA,GAAmB,GAAA;AAlDtC,IAAM,uBAAA,GAAN;AAsTA,IAAM,uBAAA,GAA0B,IAAI,uBAAA;AAIpC,IAAM,sBAAA,GAAyB","file":"chunk-ZVTWQLK4.cjs","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n return code.toUpperCase() in CurrencyExchangeService.CRYPTO_IDS;\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?base=${fromUpper}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids.join(\",\")}&vs_currencies=${vsCurrency}`;\n const response = await fetch(url, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["createTimeoutSignal","ErrorFactory"],"mappings":";;;;;;AAyBO,IAAM,cAAA,uBAA0C,GAAA,CAAI;AAAA,EAC1D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAC/D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAC/D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EACnC,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAC/D,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EACrB,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EACrB,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EACrB,KAAA;AAAA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\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n return code.toUpperCase() in CurrencyExchangeService.CRYPTO_IDS;\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?base=${fromUpper}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids.join(\",\")}&vs_currencies=${vsCurrency}`;\n const response = await fetch(url, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { LexerToken } from './chunk-
|
|
2
|
-
import { tokenTypeId } from './chunk-
|
|
3
|
-
import { ErrorFactory } from './chunk-
|
|
1
|
+
import { LexerToken } from './chunk-ORM7CHYZ.js';
|
|
2
|
+
import { tokenTypeId } from './chunk-NAWZATKT.js';
|
|
3
|
+
import { ErrorFactory } from './chunk-N7OA4WPJ.js';
|
|
4
4
|
|
|
5
5
|
// src/normalizer/TokenNormalizer.ts
|
|
6
6
|
var DEFAULT_OPTIONS = {
|
|
@@ -495,5 +495,5 @@ var BUILTIN_PHRASES = {
|
|
|
495
495
|
};
|
|
496
496
|
|
|
497
497
|
export { BUILTIN_PHRASES, PhraseTrie, TokenNormalizer, createBuiltinNormalizerRules, createFusedToken, implicitMultiplyRule, isInsideRangeContext };
|
|
498
|
-
//# sourceMappingURL=chunk-
|
|
499
|
-
//# sourceMappingURL=chunk-
|
|
498
|
+
//# sourceMappingURL=chunk-L5YHV6BQ.js.map
|
|
499
|
+
//# sourceMappingURL=chunk-L5YHV6BQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":[],"mappings":";;;;;AA2EA,IAAM,eAAA,GAA+C;AAAA,EACnD,SAAA,EAAW,GAAA;AAAA,EACX,SAAA,EAAW,GAAA;AAAA,EACX,UAAU,MAAM;AAAA,EAAC;AACnB,CAAA;AAwBO,SAAS,gBAAA,CACd,IAAA,EACA,IAAA,EACA,YAAA,EACO;AACP,EAAA,MAAM,KAAA,GAAQ,aAAa,CAAC,CAAA;AAC5B,EAAA,MAAM,IAAA,GAAO,YAAA,CAAa,YAAA,CAAa,MAAA,GAAS,CAAC,CAAA;AACjD,EAAA,MAAM,QAAQ,IAAI,UAAA;AAAA,IAChB,IAAA;AAAA,IACA,YAAY,IAAI,CAAA;AAAA,IAChB,IAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA,CAAM,MAAA;AAAA,IACN,MAAM,UAAA,IAAc,CAAA;AAAA,IACpB,KAAA,CAAM,IAAA;AAAA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,KAAK,kBAAkB,CAAA;AAAA,IACnC,WAAW,CAAA,CAAE,IAAA,KAAS,UAAA,IAAc,CAAA,CAAE,SAAS,QAAA,EAAU;AACvD,MAAA,SAAA,CAAU,GAAA,EAAI;AAAA,IAChB;AAAA,EACF;AACA,EAAA,OAAO,UAAU,MAAA,GAAS,CAAA,IAAK,SAAA,CAAU,SAAA,CAAU,SAAS,CAAC,CAAA;AAC/D;AAoBO,SAAS,4BAAA,GAAiD;AAC/D,EAAA,OAAO;AAAA;AAAA,IAEL,oBAAA;AAAqB,GACvB;AACF;AASO,IAAM,eAAA,GAA0C;AAAA,EACtD,iBAAA,EAAmB,OAAA;AAAA,EACnB,UAAA,EAAY,OAAA;AAAA,EACZ,aAAA,EAAe,aAAA;AAAA,EACf,aAAA,EAAe,aAAA;AAAA,EACf,UAAA,EAAY,UAAA;AAAA,EACZ,aAAA,EAAe,aAAA;AAAA,EACf,WAAA,EAAa,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKb,eAAA,EAAiB,aAAA;AAAA,EACjB,YAAA,EAAc;AACf","file":"chunk-JJIXHXFQ.js","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n this.rules.push(rule);\n this.sortedRulesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // ── Priority-sorted rules, cached across calls, see getSortedRules() ──\n const sorted = this.getSortedRules();\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n const result: Token[] = [];\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try every rule in priority order at this position\n for (const rule of sorted) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged\n result.push(current[pos]);\n pos++;\n }\n }\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (result.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${result.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: result.length, maxTokens }\n );\n }\n\n current = result;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Check trigger conditions ──\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":[],"mappings":";;;;;AA2EA,IAAM,eAAA,GAA+C;AAAA,EACnD,SAAA,EAAW,GAAA;AAAA,EACX,SAAA,EAAW,GAAA;AAAA,EACX,UAAU,MAAM;AAAA,EAAC;AACnB,CAAA;AAwBO,SAAS,gBAAA,CACd,IAAA,EACA,IAAA,EACA,YAAA,EACO;AACP,EAAA,MAAM,KAAA,GAAQ,aAAa,CAAC,CAAA;AAC5B,EAAA,MAAM,IAAA,GAAO,YAAA,CAAa,YAAA,CAAa,MAAA,GAAS,CAAC,CAAA;AACjD,EAAA,MAAM,QAAQ,IAAI,UAAA;AAAA,IAChB,IAAA;AAAA,IACA,YAAY,IAAI,CAAA;AAAA,IAChB,IAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA,CAAM,MAAA;AAAA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AAA,CAAM,aAAY,KAAM,MAAA,CAAA,CAAA;AAE/K,MAAA,SAAA,CAAU,KAAK,kBAAkB,CAAA;AAAA,IACnC,WAAW,CAAA,CAAE,IAAA,KAAS,UAAA,IAAc,CAAA,CAAE,SAAS,QAAA,EAAU;AACvD,MAAA,SAAA,CAAU,GAAA,EAAI;AAAA,IAChB;AAAA,EACF;AACA,EAAA,OAAO,UAAU,MAAA,GAAS,CAAA,IAAK,SAAA,CAAU,SAAA,CAAU,SAAS,CAAC,CAAA;AAC/D;AAoBO,SAAS,4BAAA,GAAiD;AAC/D,EAAA,OAAO;AAAA;AAAA,IAEL,oBAAA;AAAqB,GACvB;AACF;AASO,IAAM,eAAA,GAA0C;AAAA,EACtD,iBAAA,EAAmB,OAAA;AAAA,EACnB,UAAA,EAAY,OAAA;AAAA,EACZ,aAAA,EAAe,aAAA;AAAA,EACf,aAAA,EAAe,aAAA;AAAA,EACf,UAAA,EAAY,UAAA;AAAA,EACZ,aAAA,EAAe,aAAA;AAAA,EACf,WAAA,EAAa,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKb,eAAA,EAAiB,aAAA;AAAA,EACjB,YAAA,EAAc;AACf","file":"chunk-L5YHV6BQ.js","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n this.rules.push(rule);\n this.sortedRulesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // ── Priority-sorted rules, cached across calls, see getSortedRules() ──\n const sorted = this.getSortedRules();\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n const result: Token[] = [];\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try every rule in priority order at this position\n for (const rule of sorted) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged\n result.push(current[pos]);\n pos++;\n }\n }\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (result.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${result.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: result.length, maxTokens }\n );\n }\n\n current = result;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Check trigger conditions ──\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkMIGXCBXT_cjs = require('./chunk-MIGXCBXT.cjs');
|
|
4
4
|
|
|
5
5
|
// package.json
|
|
6
|
-
var version = "1.
|
|
6
|
+
var version = "1.2.0";
|
|
7
7
|
|
|
8
8
|
// src/constants/version.ts
|
|
9
9
|
var ENGINE_VERSION = version;
|
|
@@ -106,7 +106,7 @@ var ConfigManager = class {
|
|
|
106
106
|
if (current && typeof current === "object" && key in current) {
|
|
107
107
|
current = current[key];
|
|
108
108
|
} else {
|
|
109
|
-
throw
|
|
109
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.config(
|
|
110
110
|
"CONFIG_PATH_NOT_FOUND",
|
|
111
111
|
`Configuration path not found: ${path}`,
|
|
112
112
|
{ path }
|
|
@@ -124,7 +124,7 @@ var ConfigManager = class {
|
|
|
124
124
|
set(path, value) {
|
|
125
125
|
const keys = path.split(".");
|
|
126
126
|
if (keys.length < 2) {
|
|
127
|
-
throw
|
|
127
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.config(
|
|
128
128
|
"INVALID_CONFIG_PATH",
|
|
129
129
|
`Invalid path: ${path}. Must be in format 'section.property'`,
|
|
130
130
|
{ path }
|
|
@@ -133,7 +133,7 @@ var ConfigManager = class {
|
|
|
133
133
|
const section = keys[0];
|
|
134
134
|
const property = keys[1];
|
|
135
135
|
if (!(section in this.config)) {
|
|
136
|
-
throw
|
|
136
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.config(
|
|
137
137
|
"CONFIG_SECTION_NOT_FOUND",
|
|
138
138
|
`Configuration section not found: ${section}`,
|
|
139
139
|
{ section, path }
|
|
@@ -143,7 +143,7 @@ var ConfigManager = class {
|
|
|
143
143
|
if (sectionConfig && typeof sectionConfig === "object") {
|
|
144
144
|
sectionConfig[property] = value;
|
|
145
145
|
} else {
|
|
146
|
-
throw
|
|
146
|
+
throw chunkMIGXCBXT_cjs.ErrorFactory.config(
|
|
147
147
|
"CONFIG_PROPERTY_NOT_FOUND",
|
|
148
148
|
`Configuration property not found: ${path}`,
|
|
149
149
|
{ path }
|
|
@@ -205,5 +205,5 @@ exports.ConfigManager = ConfigManager;
|
|
|
205
205
|
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|
|
206
206
|
exports.ENGINE_VERSION = ENGINE_VERSION;
|
|
207
207
|
exports.mergeEngineConfig = mergeEngineConfig;
|
|
208
|
-
//# sourceMappingURL=chunk-
|
|
209
|
-
//# sourceMappingURL=chunk-
|
|
208
|
+
//# sourceMappingURL=chunk-LO7HU5WB.cjs.map
|
|
209
|
+
//# sourceMappingURL=chunk-LO7HU5WB.cjs.map
|