solve-engine 1.0.1 → 1.1.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.
Files changed (237) hide show
  1. package/dist/{BytecodeBuilder-B0xskcv5.d.cts → BytecodeBuilder-Bp9xeTmX.d.cts} +4 -0
  2. package/dist/{BytecodeBuilder-B0xskcv5.d.ts → BytecodeBuilder-Bp9xeTmX.d.ts} +4 -0
  3. package/dist/{Configuration-B-G5gTRn.d.cts → Configuration-C9W8tJv_.d.cts} +53 -1
  4. package/dist/{Configuration-B-G5gTRn.d.ts → Configuration-C9W8tJv_.d.ts} +53 -1
  5. package/dist/{EngineError-LU7W7AgI.d.cts → EngineError-B61GS1jp.d.cts} +14 -0
  6. package/dist/{EngineError-LU7W7AgI.d.ts → EngineError-B61GS1jp.d.ts} +14 -0
  7. package/dist/FormattingSettings-CJHyxcYu.d.cts +27 -0
  8. package/dist/FormattingSettings-CJHyxcYu.d.ts +27 -0
  9. package/dist/{Lexer-D78E2yDW.d.cts → Lexer-BOs7euZe.d.cts} +58 -1
  10. package/dist/{Lexer-BN5mt30n.d.ts → Lexer-CSI_lwbW.d.ts} +58 -1
  11. package/dist/PackageCompatibility-B-7rK1TD.d.cts +76 -0
  12. package/dist/PackageCompatibility-Dh59eF-X.d.ts +76 -0
  13. package/dist/{PackageRegistry-B37mRvvz.d.cts → PackageRegistry-BHWJP83F.d.cts} +449 -11
  14. package/dist/{PackageRegistry-DCUEzbQt.d.ts → PackageRegistry-_8rDlvxI.d.ts} +449 -11
  15. package/dist/{Parselet-BaySkMV3.d.ts → Parselet-BBT8riYh.d.ts} +12 -3
  16. package/dist/{Parselet-DuI1Pjiq.d.cts → Parselet-BHcgK9S7.d.cts} +12 -3
  17. package/dist/{ScopeManager-B6GzdhVG.d.cts → ScopeManager-8vf02dwj.d.cts} +56 -5
  18. package/dist/{ScopeManager-udv4Twwq.d.ts → ScopeManager-CxA24W5n.d.ts} +56 -5
  19. package/dist/{Token-BzG5G4ja.d.cts → Token-B1hdkedD.d.cts} +9 -0
  20. package/dist/{Token-BzG5G4ja.d.ts → Token-B1hdkedD.d.ts} +9 -0
  21. package/dist/{TokenNormalizer-t_GotBxr.d.ts → TokenNormalizer-C6VzZgHa.d.ts} +1 -1
  22. package/dist/{TokenNormalizer-DGVa24Q-.d.cts → TokenNormalizer-DRc1Js1V.d.cts} +1 -1
  23. package/dist/{VMCheckpoints-DwLjivM7.d.cts → VMCheckpoints-ELYqITdF.d.cts} +3 -3
  24. package/dist/{VMCheckpoints-BiaIlOOY.d.ts → VMCheckpoints-MK--EBH2.d.ts} +3 -3
  25. package/dist/{Value-CXJqDH9J.d.cts → Value-BUi1RA3S.d.cts} +124 -5
  26. package/dist/{Value-CXJqDH9J.d.ts → Value-BUi1RA3S.d.ts} +124 -5
  27. package/dist/WorkerError-_-RkoQ5P.d.ts +75 -0
  28. package/dist/WorkerError-gzmaopj2.d.cts +75 -0
  29. package/dist/{chunk-GQCOSXMG.js → chunk-267JPOTF.js} +43 -5
  30. package/dist/chunk-267JPOTF.js.map +1 -0
  31. package/dist/{chunk-JMXUNXQS.cjs → chunk-2TZKENDH.cjs} +51 -8
  32. package/dist/chunk-2TZKENDH.cjs.map +1 -0
  33. package/dist/chunk-3OWCDIPN.js +215 -0
  34. package/dist/chunk-3OWCDIPN.js.map +1 -0
  35. package/dist/{chunk-VB37OC6I.js → chunk-4D6NIHE2.js} +40 -3
  36. package/dist/chunk-4D6NIHE2.js.map +1 -0
  37. package/dist/{chunk-TY3TLZAW.cjs → chunk-536WPM2V.cjs} +18 -2
  38. package/dist/chunk-536WPM2V.cjs.map +1 -0
  39. package/dist/chunk-5HRB36DK.js +405 -0
  40. package/dist/chunk-5HRB36DK.js.map +1 -0
  41. package/dist/chunk-5ON7PUAZ.js +12 -0
  42. package/dist/chunk-5ON7PUAZ.js.map +1 -0
  43. package/dist/{chunk-KV7UW6T6.js → chunk-7KYSUDQO.js} +12 -5
  44. package/dist/chunk-7KYSUDQO.js.map +1 -0
  45. package/dist/{chunk-6WFMPTGB.cjs → chunk-7ZX6B7SY.cjs} +774 -528
  46. package/dist/chunk-7ZX6B7SY.cjs.map +1 -0
  47. package/dist/chunk-ALYRJ72W.cjs +434 -0
  48. package/dist/chunk-ALYRJ72W.cjs.map +1 -0
  49. package/dist/{chunk-5KMIY374.cjs → chunk-B4HBEFTB.cjs} +17 -2
  50. package/dist/chunk-B4HBEFTB.cjs.map +1 -0
  51. package/dist/chunk-B7NLZMQ3.cjs +74 -0
  52. package/dist/chunk-B7NLZMQ3.cjs.map +1 -0
  53. package/dist/{chunk-UQ3UIZJC.js → chunk-BLI4NIQY.js} +6 -2
  54. package/dist/chunk-BLI4NIQY.js.map +1 -0
  55. package/dist/{chunk-BHTNFEGZ.cjs → chunk-C75AFGVD.cjs} +11 -11
  56. package/dist/{chunk-BHTNFEGZ.cjs.map → chunk-C75AFGVD.cjs.map} +1 -1
  57. package/dist/{chunk-G535KJEG.js → chunk-CCBZZQAE.js} +2 -2
  58. package/dist/{chunk-G535KJEG.js.map → chunk-CCBZZQAE.js.map} +1 -1
  59. package/dist/chunk-CKQMXMHR.cjs +219 -0
  60. package/dist/chunk-CKQMXMHR.cjs.map +1 -0
  61. package/dist/{chunk-PFUESQTW.cjs → chunk-EJ3ILXX6.cjs} +48 -2
  62. package/dist/chunk-EJ3ILXX6.cjs.map +1 -0
  63. package/dist/{chunk-526PMQOA.js → chunk-ENKKJYD3.js} +10 -4
  64. package/dist/chunk-ENKKJYD3.js.map +1 -0
  65. package/dist/{chunk-5X2PTP6F.cjs → chunk-ENRIK36Q.cjs} +2 -12
  66. package/dist/chunk-ENRIK36Q.cjs.map +1 -0
  67. package/dist/{chunk-3D7V24DG.js → chunk-ERCOHGXD.js} +17 -2
  68. package/dist/chunk-ERCOHGXD.js.map +1 -0
  69. package/dist/{chunk-IF532O7C.js → chunk-FD5ZZHEU.js} +3 -12
  70. package/dist/chunk-FD5ZZHEU.js.map +1 -0
  71. package/dist/{chunk-TBN7DEHO.js → chunk-G7Z4HJQA.js} +11 -5
  72. package/dist/chunk-G7Z4HJQA.js.map +1 -0
  73. package/dist/{chunk-QY25VWBF.js → chunk-GQMUHVE3.js} +142 -6
  74. package/dist/chunk-GQMUHVE3.js.map +1 -0
  75. package/dist/chunk-GUG7SNSV.js +1764 -0
  76. package/dist/chunk-GUG7SNSV.js.map +1 -0
  77. package/dist/{chunk-UM6BVY2S.cjs → chunk-HIQ5HSZL.cjs} +175 -43
  78. package/dist/chunk-HIQ5HSZL.cjs.map +1 -0
  79. package/dist/{chunk-HVQFNJKE.cjs → chunk-HVRVSI2Z.cjs} +104 -86
  80. package/dist/chunk-HVRVSI2Z.cjs.map +1 -0
  81. package/dist/{chunk-3LAEG75D.js → chunk-I4GAWIPW.js} +24 -6
  82. package/dist/chunk-I4GAWIPW.js.map +1 -0
  83. package/dist/{chunk-PA4VC73I.cjs → chunk-J45BCEZ4.cjs} +33 -27
  84. package/dist/chunk-J45BCEZ4.cjs.map +1 -0
  85. package/dist/{chunk-V5PYO44Y.js → chunk-JIPATHVY.js} +1853 -2638
  86. package/dist/chunk-JIPATHVY.js.map +1 -0
  87. package/dist/{chunk-YPPPYLSR.js → chunk-JJIXHXFQ.js} +5 -5
  88. package/dist/{chunk-YPPPYLSR.js.map → chunk-JJIXHXFQ.js.map} +1 -1
  89. package/dist/chunk-L2TE7PMO.cjs +14 -0
  90. package/dist/chunk-L2TE7PMO.cjs.map +1 -0
  91. package/dist/{chunk-B7TLZABL.cjs → chunk-MG6Q3DUO.cjs} +1962 -2746
  92. package/dist/chunk-MG6Q3DUO.cjs.map +1 -0
  93. package/dist/{chunk-R3PY4G7J.js → chunk-MVTOCRV2.js} +48 -3
  94. package/dist/chunk-MVTOCRV2.js.map +1 -0
  95. package/dist/{chunk-Y7FT4IQT.js → chunk-NKW7LKYU.js} +266 -28
  96. package/dist/chunk-NKW7LKYU.js.map +1 -0
  97. package/dist/{chunk-O3ANBHSA.js → chunk-NNQ2TYDF.js} +123 -5
  98. package/dist/chunk-NNQ2TYDF.js.map +1 -0
  99. package/dist/{chunk-5F4C26RU.js → chunk-OADDUPT3.js} +4 -4
  100. package/dist/{chunk-5F4C26RU.js.map → chunk-OADDUPT3.js.map} +1 -1
  101. package/dist/{chunk-3AFRJYP4.cjs → chunk-OTN6SZOD.cjs} +1868 -393
  102. package/dist/chunk-OTN6SZOD.cjs.map +1 -0
  103. package/dist/{chunk-5LI5EPGJ.cjs → chunk-QFTDTX6K.cjs} +40 -3
  104. package/dist/chunk-QFTDTX6K.cjs.map +1 -0
  105. package/dist/{chunk-HMOISHXR.js → chunk-RRLHC37V.js} +1530 -57
  106. package/dist/chunk-RRLHC37V.js.map +1 -0
  107. package/dist/chunk-SNHVVOJK.cjs +1768 -0
  108. package/dist/chunk-SNHVVOJK.cjs.map +1 -0
  109. package/dist/{chunk-HDP7VK3C.cjs → chunk-SRGQ72IR.cjs} +649 -349
  110. package/dist/chunk-SRGQ72IR.cjs.map +1 -0
  111. package/dist/{chunk-4B2CNWQU.cjs → chunk-SSV46KFA.cjs} +14 -7
  112. package/dist/chunk-SSV46KFA.cjs.map +1 -0
  113. package/dist/{chunk-AJA6LUI7.js → chunk-UO6BUV6K.js} +18 -2
  114. package/dist/chunk-UO6BUV6K.js.map +1 -0
  115. package/dist/chunk-WWQEY7BV.js +67 -0
  116. package/dist/chunk-WWQEY7BV.js.map +1 -0
  117. package/dist/{chunk-5WVP4YHP.js → chunk-WXEHD6TT.js} +333 -33
  118. package/dist/chunk-WXEHD6TT.js.map +1 -0
  119. package/dist/{chunk-47LRVGOT.cjs → chunk-XA4CKRML.cjs} +2 -2
  120. package/dist/{chunk-47LRVGOT.cjs.map → chunk-XA4CKRML.cjs.map} +1 -1
  121. package/dist/{chunk-6KFYJ6TD.cjs → chunk-XIYYHA65.cjs} +6 -2
  122. package/dist/chunk-XIYYHA65.cjs.map +1 -0
  123. package/dist/{chunk-KBSXGXPM.cjs → chunk-XJGJCF2R.cjs} +6 -6
  124. package/dist/{chunk-KBSXGXPM.cjs.map → chunk-XJGJCF2R.cjs.map} +1 -1
  125. package/dist/{chunk-YWQ6V4ZN.cjs → chunk-YTIYVHL7.cjs} +211 -75
  126. package/dist/chunk-YTIYVHL7.cjs.map +1 -0
  127. package/dist/{chunk-TMA4RCEN.js → chunk-Z7XGGLI2.js} +3 -3
  128. package/dist/{chunk-TMA4RCEN.js.map → chunk-Z7XGGLI2.js.map} +1 -1
  129. package/dist/{chunk-A2N2GFCG.cjs → chunk-ZVTWQLK4.cjs} +10 -10
  130. package/dist/{chunk-A2N2GFCG.cjs.map → chunk-ZVTWQLK4.cjs.map} +1 -1
  131. package/dist/{chunk-2XLQPQKI.cjs → chunk-ZXCESUJS.cjs} +15 -9
  132. package/dist/chunk-ZXCESUJS.cjs.map +1 -0
  133. package/dist/constants.cjs +5 -5
  134. package/dist/constants.d.cts +1 -1
  135. package/dist/constants.d.ts +1 -1
  136. package/dist/constants.js +2 -2
  137. package/dist/engine.cjs +52 -35
  138. package/dist/engine.d.cts +13 -13
  139. package/dist/engine.d.ts +13 -13
  140. package/dist/engine.js +26 -21
  141. package/dist/errors.cjs +44 -19
  142. package/dist/errors.d.cts +3 -2
  143. package/dist/errors.d.ts +3 -2
  144. package/dist/errors.js +2 -1
  145. package/dist/format.cjs +19 -169
  146. package/dist/format.cjs.map +1 -1
  147. package/dist/format.d.cts +18 -26
  148. package/dist/format.d.ts +18 -26
  149. package/dist/format.js +7 -171
  150. package/dist/format.js.map +1 -1
  151. package/dist/index.cjs +250 -31
  152. package/dist/index.cjs.map +1 -1
  153. package/dist/index.d.cts +110 -74
  154. package/dist/index.d.ts +110 -74
  155. package/dist/index.js +228 -23
  156. package/dist/index.js.map +1 -1
  157. package/dist/language.cjs +9 -9
  158. package/dist/language.d.cts +12 -12
  159. package/dist/language.d.ts +12 -12
  160. package/dist/language.js +3 -3
  161. package/dist/lexer.cjs +16 -16
  162. package/dist/lexer.d.cts +3 -3
  163. package/dist/lexer.d.ts +3 -3
  164. package/dist/lexer.js +5 -5
  165. package/dist/normalizer.cjs +10 -10
  166. package/dist/normalizer.d.cts +3 -3
  167. package/dist/normalizer.d.ts +3 -3
  168. package/dist/normalizer.js +4 -4
  169. package/dist/packages.cjs +45 -36
  170. package/dist/packages.d.cts +135 -31
  171. package/dist/packages.d.ts +135 -31
  172. package/dist/packages.js +14 -13
  173. package/dist/parser.cjs +16 -16
  174. package/dist/parser.d.cts +6 -5
  175. package/dist/parser.d.ts +6 -5
  176. package/dist/parser.js +6 -6
  177. package/dist/{pipeline-BEb3hujr.d.cts → pipeline-CtfJtPQc.d.cts} +3 -3
  178. package/dist/{pipeline-B6k5lCB7.d.ts → pipeline-DCd5M6Gk.d.ts} +3 -3
  179. package/dist/resolvers.d.cts +3 -3
  180. package/dist/resolvers.d.ts +3 -3
  181. package/dist/testing.cjs +478 -0
  182. package/dist/testing.cjs.map +1 -0
  183. package/dist/testing.d.cts +271 -0
  184. package/dist/testing.d.ts +271 -0
  185. package/dist/testing.js +470 -0
  186. package/dist/testing.js.map +1 -0
  187. package/dist/uom.cjs +16 -16
  188. package/dist/uom.d.cts +3 -3
  189. package/dist/uom.d.ts +3 -3
  190. package/dist/uom.js +6 -6
  191. package/dist/utilities.cjs +6 -5
  192. package/dist/utilities.js +2 -1
  193. package/dist/vm.cjs +34 -34
  194. package/dist/vm.d.cts +8 -8
  195. package/dist/vm.d.ts +8 -8
  196. package/dist/vm.js +9 -9
  197. package/dist/worker.cjs +493 -0
  198. package/dist/worker.cjs.map +1 -0
  199. package/dist/worker.d.cts +509 -0
  200. package/dist/worker.d.ts +509 -0
  201. package/dist/worker.js +484 -0
  202. package/dist/worker.js.map +1 -0
  203. package/package.json +21 -1
  204. package/dist/chunk-2XLQPQKI.cjs.map +0 -1
  205. package/dist/chunk-3AFRJYP4.cjs.map +0 -1
  206. package/dist/chunk-3D7V24DG.js.map +0 -1
  207. package/dist/chunk-3LAEG75D.js.map +0 -1
  208. package/dist/chunk-4B2CNWQU.cjs.map +0 -1
  209. package/dist/chunk-526PMQOA.js.map +0 -1
  210. package/dist/chunk-5KMIY374.cjs.map +0 -1
  211. package/dist/chunk-5LI5EPGJ.cjs.map +0 -1
  212. package/dist/chunk-5WVP4YHP.js.map +0 -1
  213. package/dist/chunk-5X2PTP6F.cjs.map +0 -1
  214. package/dist/chunk-6KFYJ6TD.cjs.map +0 -1
  215. package/dist/chunk-6WFMPTGB.cjs.map +0 -1
  216. package/dist/chunk-AJA6LUI7.js.map +0 -1
  217. package/dist/chunk-B7TLZABL.cjs.map +0 -1
  218. package/dist/chunk-GQCOSXMG.js.map +0 -1
  219. package/dist/chunk-HDP7VK3C.cjs.map +0 -1
  220. package/dist/chunk-HMOISHXR.js.map +0 -1
  221. package/dist/chunk-HVQFNJKE.cjs.map +0 -1
  222. package/dist/chunk-IF532O7C.js.map +0 -1
  223. package/dist/chunk-JMXUNXQS.cjs.map +0 -1
  224. package/dist/chunk-KV7UW6T6.js.map +0 -1
  225. package/dist/chunk-O3ANBHSA.js.map +0 -1
  226. package/dist/chunk-PA4VC73I.cjs.map +0 -1
  227. package/dist/chunk-PFUESQTW.cjs.map +0 -1
  228. package/dist/chunk-QY25VWBF.js.map +0 -1
  229. package/dist/chunk-R3PY4G7J.js.map +0 -1
  230. package/dist/chunk-TBN7DEHO.js.map +0 -1
  231. package/dist/chunk-TY3TLZAW.cjs.map +0 -1
  232. package/dist/chunk-UM6BVY2S.cjs.map +0 -1
  233. package/dist/chunk-UQ3UIZJC.js.map +0 -1
  234. package/dist/chunk-V5PYO44Y.js.map +0 -1
  235. package/dist/chunk-VB37OC6I.js.map +0 -1
  236. package/dist/chunk-Y7FT4IQT.js.map +0 -1
  237. package/dist/chunk-YWQ6V4ZN.cjs.map +0 -1
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+
3
+ var chunkN7FNVFXW_cjs = require('./chunk-N7FNVFXW.cjs');
4
+ var chunkALYRJ72W_cjs = require('./chunk-ALYRJ72W.cjs');
5
+ var chunkHIQ5HSZL_cjs = require('./chunk-HIQ5HSZL.cjs');
6
+ var chunkOUHT5Z36_cjs = require('./chunk-OUHT5Z36.cjs');
7
+
8
+ // src/format/FormattingSettings.ts
9
+ var DEFAULT_FORMATTING_SETTINGS = {
10
+ floatResult: {
11
+ decimalPlaces: 2,
12
+ enableSeperator: true
13
+ },
14
+ numberResult: {
15
+ decimalSeparatorLocale: "en-US"
16
+ },
17
+ hexResult: {
18
+ enablePadding: false,
19
+ paddingZeros: 0
20
+ },
21
+ unitOfMeasurementResult: {
22
+ decimalPlaces: 2
23
+ },
24
+ percentageResult: {
25
+ decimalPlaces: 2
26
+ }
27
+ };
28
+
29
+ // src/format/FormatEngine.ts
30
+ function formatNumber(value, locale, settings, decimalPlaces) {
31
+ const sep = settings.floatResult.enableSeperator;
32
+ const loc = settings.numberResult.decimalSeparatorLocale;
33
+ if (decimalPlaces !== void 0 && Number.isFinite(value)) {
34
+ const formatted2 = value.toLocaleString(loc || "en-US", {
35
+ minimumFractionDigits: decimalPlaces,
36
+ maximumFractionDigits: decimalPlaces,
37
+ useGrouping: sep
38
+ });
39
+ return `${locale.display.resultPrefix}${formatted2}`;
40
+ }
41
+ const dp = settings.floatResult.decimalPlaces;
42
+ const formatted = chunkN7FNVFXW_cjs.autoFormatIntegerOrFloat(value, dp, sep, loc);
43
+ return `${locale.display.resultPrefix}${formatted}`;
44
+ }
45
+ function formatUncertain(center, uncertainty, locale, settings) {
46
+ const dp = settings.floatResult.decimalPlaces;
47
+ const useGrouping = settings.floatResult.enableSeperator;
48
+ const loc = settings.numberResult.decimalSeparatorLocale || "en-US";
49
+ const spreadMax = Math.max(dp, 1);
50
+ const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });
51
+ const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });
52
+ return `${locale.display.resultPrefix}${centerText} \xB1 ${spreadText}`;
53
+ }
54
+ function formatHex(value, settings, base) {
55
+ if (typeof value === "number" && !Number.isFinite(value)) return `= ${value}`;
56
+ const negative = typeof value === "bigint" ? value < 0n : value < 0;
57
+ const sign = negative ? "-" : "";
58
+ const digits = (radix) => typeof value === "bigint" ? (negative ? -value : value).toString(radix) : Math.abs(Math.trunc(value)).toString(radix);
59
+ if (base === "bin") return `= ${sign}0b${digits(2)}`;
60
+ if (base === "oct") return `= ${sign}0o${digits(8)}`;
61
+ const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;
62
+ const hex = digits(16).toUpperCase().padStart(padding, "0");
63
+ return `= ${sign}0x${hex}`;
64
+ }
65
+ var MAX_DISPLAYED_BIGINT_DIGITS = 2e4;
66
+ function formatBigInt(value) {
67
+ const magnitude = value < 0n ? -value : value;
68
+ if (Number.isFinite(Number(magnitude))) return `= ${value}`;
69
+ const bits = magnitude.toString(16).length * 4;
70
+ if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;
71
+ const log10 = bits * Math.LN2 / Math.LN10;
72
+ const exponent = Math.floor(log10);
73
+ const mantissa = Math.pow(10, log10 - exponent);
74
+ const sign = value < 0n ? "-" : "";
75
+ return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString("en-US")} digits, too large to print)`;
76
+ }
77
+ function formatString(value) {
78
+ return `= ${value}`;
79
+ }
80
+ function formatBoolean(value) {
81
+ return `= ${value}`;
82
+ }
83
+ function formatDatetime(value, locale) {
84
+ const d = new Date(value);
85
+ const dateStr = d.toLocaleDateString(locale.code, { weekday: "long", year: "numeric", month: "long", day: "numeric" });
86
+ const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;
87
+ if (isMidnight) return `= ${dateStr}`;
88
+ return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;
89
+ }
90
+ function formatMsDuration(ms) {
91
+ const sign = ms < 0 ? "-" : "";
92
+ const totalSeconds = Math.round(Math.abs(ms) / 1e3);
93
+ const hours = Math.floor(totalSeconds / 3600);
94
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
95
+ const seconds = totalSeconds % 60;
96
+ const mm = String(minutes).padStart(2, "0");
97
+ if (seconds === 0) return `${sign}${hours}:${mm}`;
98
+ const ss = String(seconds).padStart(2, "0");
99
+ return `${sign}${hours}:${mm}:${ss}`;
100
+ }
101
+ function formatUom(value, unit, locale, settings, exact) {
102
+ if (unit === "ms") return `= ${formatMsDuration(value)}`;
103
+ const dp = settings.unitOfMeasurementResult.decimalPlaces;
104
+ const timeSpanUnits = ["days", "weeks", "hours", "minutes", "seconds", "day", "week", "hour", "minute", "second"];
105
+ const isTimeSpan = unit && timeSpanUnits.includes(unit);
106
+ let formatted;
107
+ if (isTimeSpan && value === Math.floor(value)) {
108
+ formatted = value.toString();
109
+ } else {
110
+ formatted = value.toFixed(dp);
111
+ }
112
+ const currencyDisplay = unit ? chunkHIQ5HSZL_cjs.CURRENCY_DISPLAY[unit.toUpperCase()] : void 0;
113
+ if (currencyDisplay) {
114
+ const moneyText = exact ? chunkHIQ5HSZL_cjs.decimalToFixed(exact, dp) : formatted;
115
+ const sep = currencyDisplay.spaced ? " " : "";
116
+ const withSymbol = currencyDisplay.position === "prefix" ? `${currencyDisplay.symbol}${sep}${moneyText}` : `${moneyText}${sep}${currencyDisplay.symbol}`;
117
+ return `= ${withSymbol}`;
118
+ }
119
+ const genericText = exact ? chunkHIQ5HSZL_cjs.decimalToFixed(exact, dp) : formatted;
120
+ return `= ${genericText} ${unit || ""}`.trim();
121
+ }
122
+ function formatMatrixEntry(entry, settings) {
123
+ if (typeof entry === "boolean") return entry ? "true" : "false";
124
+ if (typeof entry === "object" && entry !== null) return chunkHIQ5HSZL_cjs.formatSymbolic(entry);
125
+ const dp = settings.floatResult.decimalPlaces;
126
+ const sep = settings.floatResult.enableSeperator;
127
+ const loc = settings.numberResult.decimalSeparatorLocale;
128
+ return chunkN7FNVFXW_cjs.autoFormatIntegerOrFloat(entry, dp, sep, loc);
129
+ }
130
+ function formatMatrix(m, locale, settings) {
131
+ const rowMajor = chunkHIQ5HSZL_cjs.columnMajorToRowMajor(m);
132
+ const rows = [];
133
+ for (let r = 0; r < m.rows; r++) {
134
+ const cells = [];
135
+ for (let c = 0; c < m.cols; c++) {
136
+ cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));
137
+ }
138
+ rows.push(cells.join(", "));
139
+ }
140
+ return `${locale.display.resultPrefix}[${rows.join("; ")}]`;
141
+ }
142
+ function formatMatrixAligned(m, settings) {
143
+ const us = settings || DEFAULT_FORMATTING_SETTINGS;
144
+ const rowMajor = chunkHIQ5HSZL_cjs.columnMajorToRowMajor(m);
145
+ const cells = [];
146
+ for (let r = 0; r < m.rows; r++) {
147
+ const row = [];
148
+ for (let c = 0; c < m.cols; c++) {
149
+ row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));
150
+ }
151
+ cells.push(row);
152
+ }
153
+ const colWidth = [];
154
+ for (let c = 0; c < m.cols; c++) {
155
+ let width = 0;
156
+ for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);
157
+ colWidth.push(width);
158
+ }
159
+ return cells.map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(" ")} ]`).join("\n");
160
+ }
161
+ function formatRange(min, max, locale) {
162
+ return `${locale.display.resultPrefix}${min}:${max}`;
163
+ }
164
+ function formatPercentage(value, locale, settings) {
165
+ const dp = settings.percentageResult.decimalPlaces;
166
+ const formatted = (value * 100).toFixed(dp);
167
+ return `= ${formatted}${locale.display.percentageSuffix}`;
168
+ }
169
+ function formatUnit(value, unit) {
170
+ return `= ${value} ${unit || ""}`.trim();
171
+ }
172
+ function formatValue(value, settings) {
173
+ const us = settings || DEFAULT_FORMATTING_SETTINGS;
174
+ const localeCode = us.numberResult.decimalSeparatorLocale || "en";
175
+ const locale = chunkOUHT5Z36_cjs.getLocale(localeCode);
176
+ switch (value.type) {
177
+ case 0 /* Number */:
178
+ if (value.uncertainty !== void 0) {
179
+ return formatUncertain(value.value, value.uncertainty, locale, us);
180
+ }
181
+ return formatNumber(value.value, locale, us, value.decimalPlaces);
182
+ case 1 /* Hex */:
183
+ return formatHex(value.value, us, value.unit);
184
+ case 2 /* BigInt */:
185
+ return formatBigInt(value.value);
186
+ case 3 /* String */:
187
+ return formatString(value.value);
188
+ case 10 /* Boolean */:
189
+ return formatBoolean(value.value);
190
+ case 4 /* Datetime */:
191
+ return formatDatetime(value.value, locale);
192
+ case 6 /* Uom */:
193
+ return formatUom(value.value, value.unit, locale, us, value.exact);
194
+ case 7 /* Matrix */:
195
+ return formatMatrix(value.value, locale, us);
196
+ case 8 /* Range */: {
197
+ const r = value.value;
198
+ return formatRange(r.min, r.max, locale);
199
+ }
200
+ case 14 /* Colour */:
201
+ return `${locale.display.resultPrefix}${chunkALYRJ72W_cjs.formatColour(value.value)}`;
202
+ case 9 /* Symbolic */:
203
+ return chunkHIQ5HSZL_cjs.formatSymbolic(value.value);
204
+ case 5 /* Percentage */:
205
+ return formatPercentage(value.value, locale, us);
206
+ case 11 /* Unit */:
207
+ return formatUnit(value.value, value.unit);
208
+ case 13 /* Error */:
209
+ return value.unit ?? String(value.value);
210
+ default:
211
+ return `= ${String(value.value)}`;
212
+ }
213
+ }
214
+
215
+ exports.DEFAULT_FORMATTING_SETTINGS = DEFAULT_FORMATTING_SETTINGS;
216
+ exports.formatMatrixAligned = formatMatrixAligned;
217
+ exports.formatValue = formatValue;
218
+ //# sourceMappingURL=chunk-CKQMXMHR.cjs.map
219
+ //# sourceMappingURL=chunk-CKQMXMHR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["formatted","autoFormatIntegerOrFloat","CURRENCY_DISPLAY","decimalToFixed","formatSymbolic","columnMajorToRowMajor","getLocale","formatColour"],"mappings":";;;;;;;;AAyBO,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ACE,MAAA,OAAO,SAAA,CAAU,MAAM,KAAA,EAAiB,KAAA,CAAM,MAAM,MAAA,EAAQ,EAAA,EAAI,MAAM,KAAK,CAAA;AAAA,IAC7E,KAAA,CAAA;AACE,MAAA,OAAO,YAAA,CAAa,KAAA,CAAM,KAAA,EAAqB,MAAA,EAAQ,EAAE,CAAA;AAAA,IAC3D,KAAA,CAAA,cAAsB;AACpB,MAAA,MAAM,IAAI,KAAA,CAAM,KAAA;AAChB,MAAA,OAAO,WAAA,CAAY,CAAA,CAAE,GAAA,EAAK,CAAA,CAAE,KAAK,MAAM,CAAA;AAAA,IACzC;AAAA,IACA,KAAA,EAAA;AACE,MAAA,OAAO,CAAA,EAAG,OAAO,OAAA,CAAQ,YAAY,GAAGC,8BAAA,CAAa,KAAA,CAAM,KAAmB,CAAC,CAAA,CAAA;AAAA,IACjF,KAAA,CAAA;AACE,MAAA,OAAOH,gCAAA,CAAe,MAAM,KAAqB,CAAA;AAAA,IACnD,KAAA,CAAA;AACE,MAAA,OAAO,gBAAA,CAAiB,KAAA,CAAM,KAAA,EAAiB,MAAA,EAAQ,EAAE,CAAA;AAAA,IAC3D,KAAA,EAAA;AACE,MAAA,OAAO,UAAA,CAAW,KAAA,CAAM,KAAA,EAAiB,KAAA,CAAM,IAAI,CAAA;AAAA,IACrD,KAAA,EAAA;AAKE,MAAA,OAAO,KAAA,CAAM,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA;AAAA,IACzC;AACE,MAAA,OAAO,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,KAAK,CAAC,CAAA,CAAA;AAAA;AAErC","file":"chunk-CKQMXMHR.cjs","sourcesContent":["/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale): string {\n const d = new Date(value);\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = value.toString();\n } else {\n // For other values, use the configured decimal places\n formatted = value.toFixed(dp);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? decimalToFixed(exact, dp) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? decimalToFixed(exact, dp) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const [value] = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}
@@ -164,8 +164,54 @@ function getBestUnit(value, unit) {
164
164
  return { value, unit: u };
165
165
  }
166
166
  }
167
+ function expandUnitToRate(value, unit) {
168
+ const slash = unit.indexOf("/");
169
+ if (slash >= 0) {
170
+ return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };
171
+ }
172
+ const ext = chunkAMOJYLG2_cjs.EXTENDED_UNITS[unit];
173
+ if (ext !== void 0 && ext.measure === "speed") {
174
+ return { value: value * ext.toBase, numerator: "m", denominator: "s" };
175
+ }
176
+ return null;
177
+ }
178
+ function rateAxisFactor(from, to) {
179
+ if (from === to) return 1;
180
+ if (from === "" || to === "") return null;
181
+ const fromMeasure = getMeasure(from);
182
+ const toMeasure = getMeasure(to);
183
+ if (fromMeasure === void 0 || toMeasure === void 0 || fromMeasure !== toMeasure) {
184
+ return null;
185
+ }
186
+ return convertUnit(1, from, to);
187
+ }
188
+ function convertRate(value, from, to) {
189
+ const source = expandUnitToRate(value, from);
190
+ if (source === null) return null;
191
+ let targetNumerator;
192
+ let targetDenominator;
193
+ let targetScale;
194
+ const slash = to.indexOf("/");
195
+ if (slash >= 0) {
196
+ targetNumerator = to.slice(0, slash);
197
+ targetDenominator = to.slice(slash + 1);
198
+ targetScale = 1;
199
+ } else {
200
+ const ext = chunkAMOJYLG2_cjs.EXTENDED_UNITS[to];
201
+ if (ext === void 0 || ext.measure !== "speed") return null;
202
+ targetNumerator = "m";
203
+ targetDenominator = "s";
204
+ targetScale = ext.toBase;
205
+ }
206
+ const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);
207
+ if (numeratorFactor === null) return null;
208
+ const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);
209
+ if (denominatorFactor === null) return null;
210
+ return source.value * numeratorFactor / denominatorFactor / targetScale;
211
+ }
167
212
 
168
213
  exports.canConvert = canConvert;
214
+ exports.convertRate = convertRate;
169
215
  exports.convertUnit = convertUnit;
170
216
  exports.getBestUnit = getBestUnit;
171
217
  exports.getConvertiblePossibilities = getConvertiblePossibilities;
@@ -173,5 +219,5 @@ exports.getMeasure = getMeasure;
173
219
  exports.isConvertibleUnit = isConvertibleUnit;
174
220
  exports.isWorkdayUnit = isWorkdayUnit;
175
221
  exports.resolveUnit = resolveUnit;
176
- //# sourceMappingURL=chunk-PFUESQTW.cjs.map
177
- //# sourceMappingURL=chunk-PFUESQTW.cjs.map
222
+ //# sourceMappingURL=chunk-EJ3ILXX6.cjs.map
223
+ //# sourceMappingURL=chunk-EJ3ILXX6.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uom/UnitConversion.ts","../src/uom/UomConverter.ts"],"names":["UNIT_TABLE","UNIT_DIFFERENCES","BEST_UNITS_METRIC","EXTENDED_UNITS","MEASURE_KIND_NAMES","MEASURE_SYMBOLS"],"mappings":";;;;;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A,CAAO,WAAA,EAAa,iBAAiB,CAAA;AAC9E,EAAA,IAAI,iBAAA,KAAsB,MAAM,OAAO,IAAA;AAEvC,EAAA,OAAQ,MAAA,CAAO,KAAA,GAAQ,eAAA,GAAmB,iBAAA,GAAoB,WAAA;AAChE","file":"chunk-EJ3ILXX6.cjs","sourcesContent":["/**\n * The unit conversion algorithm, ported from the `convert` npm package v7.0.2\n * alongside its tables (see `generated/UnitTable.generated.ts` and\n * THIRD-PARTY-NOTICES.md).\n *\n * Transliterated expression for expression rather than rewritten. Floating\n * point is not associative, so `(q + d) * (a / b) - d2` and any algebraically\n * equal rearrangement disagree in the last bits. Those bits are observable:\n * `0.5 l` best-converts to `500.00000000000006 mL` today, and the test suite\n * pins several conversions to ten decimal places.\n *\n * This module is deliberately unaware of the engine's own additions. Workdays,\n * extended units, currency and the caches all live in `UomConverter.ts`, which\n * layers them on top of these three functions.\n */\n\nimport {\n UNIT_TABLE,\n UNIT_DIFFERENCES,\n BEST_UNITS_METRIC,\n type UnitEntry,\n} from \"./generated/UnitTable.generated\";\n\n/**\n * The generated tables re-keyed into Maps once at module load.\n *\n * Not a micro-optimization. A 1456-key object literal lands in V8's dictionary\n * mode, and guarding a read on it against inherited names (`constructor`,\n * `toString`) costs about 123ns per call with either `hasOwnProperty.call` or\n * `Object.hasOwn`, measured. `Map.get` is about 6ns and needs no guard at all,\n * because a Map has no prototype chain to fall through to. That is a 20x\n * difference on the single hottest operation in the unit system: `convertRaw`\n * performs two of these per call, and `LanguageService` sweeps all 1456 keys\n * to build completions.\n */\nconst UNIT_LOOKUP: ReadonlyMap<string, UnitEntry> = new Map(Object.entries(UNIT_TABLE));\n\n/**\n * Temperature offsets, as a Map for the same reason.\n *\n * Also removes a latent hazard: the upstream code tests membership with `in`,\n * and `\"toString\" in UNIT_DIFFERENCES` is true, so an inherited name reaching\n * that branch would add a function to a number.\n */\nconst DIFFERENCE_LOOKUP: ReadonlyMap<string, number> = new Map(Object.entries(UNIT_DIFFERENCES));\n\n/**\n * Looks up a unit spelling.\n *\n * @returns its `[kind, ratio]` entry, or `undefined` if the spelling is not a\n * unit. Case-sensitive: no normalization or aliasing happens anywhere in this\n * module.\n *\n * The one deliberate deviation from upstream. `convert` tests membership with\n * `in` and reads the property directly, so inherited names like \"constructor\"\n * and \"toString\" reach its measure comparison and fail there with \"Cannot\n * convert between different measures\" instead of \"is not a valid unit\". Both\n * throw a RangeError and both report no measure, so nothing downstream can\n * tell the difference, and naming the real problem is the better message.\n */\nexport function lookupUnit(unit: string): UnitEntry | undefined {\n return UNIT_LOOKUP.get(unit);\n}\n\n/**\n * Converts `quantity` from one unit to another.\n *\n * THROWS a `RangeError` for an unknown unit or a pair in different measures.\n * Callers depend on that: `VM.ts`'s `extractDurationMs()` calls this with an\n * arbitrary unit inside a bare try/catch and treats the throw as \"not a\n * duration, contribute zero\". Returning NaN or the input unchanged instead\n * would turn `<date> + 5 kg` into an Invalid Date rather than a no-op.\n */\nexport function convertRaw(quantity: number, from: string, to: string): number {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const parsedTo = UNIT_LOOKUP.get(to);\n if (parsedTo === undefined) {\n throw new RangeError(`${to} is not a valid unit`);\n }\n\n return convertResolved(quantity, from, to, parsedFrom, parsedTo);\n}\n\n/**\n * The conversion arithmetic, for callers that have already looked both units\n * up and want to skip doing it twice.\n *\n * Split out for `UomConverter.convertUnit()`, which has to check whether\n * either side is a workday or an extended unit before it can dispatch, and\n * would otherwise resolve each unit once to decide and again to convert. The\n * entries MUST be the ones this module returned for these exact spellings.\n */\nexport function convertResolved(\n quantity: number,\n from: string,\n to: string,\n fromEntry: UnitEntry,\n toEntry: UnitEntry\n): number {\n const parsedFrom = fromEntry;\n const parsedTo = toEntry;\n\n if (parsedFrom[0] !== parsedTo[0]) {\n // DELIBERATE DEVIATION from the ported original, which silently reinterpreted\n // \"m\" as minutes whenever the other side was a time unit. That is a guess,\n // and this project's stated position is that refusing to guess is the safer\n // default for a tool doing arithmetic on someone's real numbers (see\n // docs/architecture/design-decisions.md). The guess was not harmless: it\n // reached `<date> + <duration>` through VM.ts's extractDurationMs(), where\n // `today + 5 m` silently added five MINUTES for someone who wrote metres.\n //\n // Minutes are spelled \"min\", \"minute\" or \"minutes\", all of which the table\n // has always accepted.\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n\n const fromRatio = parsedFrom[1];\n const toRatio = parsedTo[1];\n\n // Only six units in the whole table carry an offset, so the common path is\n // both misses. Reading the Map once per side and reusing the value beats\n // testing membership and then reading it again.\n const fromDifference = DIFFERENCE_LOOKUP.get(from);\n const toDifference = DIFFERENCE_LOOKUP.get(to);\n\n // Scales that do not share an origin (temperature) need the offset applied\n // around the ratio. Do not refactor the four branches into one expression:\n // the grouping is what makes the result bit-identical to the original.\n if (fromDifference !== undefined) {\n if (toDifference !== undefined) {\n return (quantity + fromDifference) * (fromRatio / toRatio) - toDifference;\n }\n return (quantity + fromDifference) * (fromRatio / toRatio);\n }\n\n if (toDifference !== undefined) {\n return quantity * (fromRatio / toRatio) - toDifference;\n }\n\n return quantity * (fromRatio / toRatio);\n}\n\n/**\n * Picks the most readable metric unit for a magnitude and converts to it.\n *\n * Only the metric lists are ported; nothing has ever requested the imperial\n * ones. Note the final conversion goes from the ORIGINAL unit to the chosen\n * one directly rather than via the smallest unit, which is what keeps the\n * result exact.\n */\nexport function convertToBestMetric(\n quantity: number,\n from: string\n): { quantity: number; unit: string } {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const best = BEST_UNITS_METRIC[parsedFrom[0]];\n const smallestUnit = best[0][0];\n let bestUnit = smallestUnit;\n\n const baseQuantity = convertRaw(quantity, from, smallestUnit);\n const absQuantity = baseQuantity < 0 ? -baseQuantity : baseQuantity;\n\n // Thresholds are expressed in the smallest unit and ascend, so the last one\n // the magnitude reaches wins. Breaking early rather than scanning the whole\n // list matters for zero and for negatives, which stay on the smallest unit.\n for (let i = 0; i < best.length; i++) {\n const bestEntry = best[i];\n if (absQuantity >= bestEntry[1]) {\n bestUnit = bestEntry[0];\n } else {\n break;\n }\n }\n\n return { quantity: convertRaw(quantity, from, bestUnit), unit: bestUnit };\n}\n","/**\n * UoM Converter, built on the in-house unit tables in `UnitConversion.ts` and\n * `generated/UnitTable.generated.ts` (ported from the `convert` npm package\n * v7.0.2 so the engine ships with no runtime dependencies).\n *\n * Units are strictly case-sensitive and are looked up without aliasing. No unit\n * remapping, what you type is what you get.\n * e.g. 'C' = Celsius, 'c' = cup; 'MB' = megabytes, 'mb' = millibits.\n *\n * This file owns everything the base tables do not: the workday shim, the\n * extended (custom-measure) units, and the two caches.\n */\n\nimport { lookupUnit, convertRaw, convertResolved, convertToBestMetric } from \"@solve-js/uom/UnitConversion\";\nimport { MEASURE_KIND_NAMES, MEASURE_SYMBOLS, UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\nimport { EXTENDED_UNITS } from \"@solve-js/uom/ExtendedUnits\";\n\n// ── \"workday\", a synthetic unit with no entry in the base table ───────────\n//\n// A business day (Mon-Fri) backing the datetime package's `<date> + N\n// workdays` arithmetic and `$X/workday` Rate literals\n// (packages/datetime/). NOT a real physical unit, a business day has no\n// fixed duration, since it depends on which calendar dates are weekends\n// so the ported base table has no concept of it and can't be\n// taught one without monkey-patching its internal unit table.\n//\n// For RATE-MATH purposes only (e.g. \"$500/workday x 4 weeks\" needs a\n// workday count to multiply by), a workday is treated as a FIXED 7/5 of a\n// calendar day: 5 workdays span exactly 7 calendar days in a whole week,\n// so this ratio is exact for whole-week spans and a reasonable linear\n// approximation otherwise. This is deliberately NOT the same\n// calendar-aware, weekend-skipping logic real \"<date> + N workdays\" date\n// arithmetic needs (see vm/VM.ts's addBusinessDays()), that can't be\n// reduced to a fixed ratio, since the exact skip pattern depends on which\n// day of the week the calculation actually starts from.\n//\n// Handled here as a thin pre/post layer in front of the normal\n// base-table path (rather than inside the tables themselves) so every\n// caller of getMeasure()/convertUnit()/canConvert() automatically gets\n// workday support for free.\nconst WORKDAY_UNIT_NAMES = new Set([\"workday\", \"workdays\"]);\nconst WORKDAY_TO_DAY_FACTOR = 7 / 5; // 1 workday == 1.4 calendar days\n\n/** Whether `unit` is the synthetic \"workday\" unit (see module note above). */\nexport function isWorkdayUnit(unit: string | undefined): unit is string {\n return typeof unit === \"string\" && WORKDAY_UNIT_NAMES.has(unit);\n}\n\n/**\n * Validate `unit` against the known unit table.\n *\n * @returns `unit` unchanged in all cases. This does NOT normalize casing\n * or aliasing (units are strictly case-sensitive, see the module note\n * above). A unit the table doesn't recognize is still\n * returned as-is (not thrown), so callers must not assume a returned\n * string is actually convertible, check with {@link isConvertibleUnit}\n * or {@link canConvert} first if that matters.\n *\n * Kept as an identity function purely for API compatibility. It used to guard\n * a validity cache, which existed because validating a unit meant a\n * throw/catch round trip through the old dependency. Validation is now a Map\n * lookup, so the cache cost more than it saved: worse, it was capped at 1000\n * entries against a 1456-unit table, so any sweep over the full vocabulary\n * (which is exactly what LanguageService does to build completions) evicted\n * on almost every call. That one change took the full-table sweep from 7.7ms\n * to under 20us.\n */\nexport function resolveUnit(unit: string): string {\n return unit;\n}\n\n// MEASURE_KIND_NAMES now comes from the generated table (it is derived data,\n// so the generator emits it rather than it being retyped here). The reason it\n// is a module-level constant has not changed: getMeasure() runs at least twice\n// per conversion, and this used to be reallocated on every call.\n\n/**\n * Get the measure/dimension kind for `unit` (e.g. `\"length\"`, `\"mass\"`,\n * `\"temperature\"`), used to check whether two units are even in the same\n * dimension before attempting a conversion.\n *\n * @returns `undefined` if `unit` isn't recognized, rather than throwing.\n */\nexport function getMeasure(unit: string): string | undefined {\n // Workday is a Time-measure unit by convention (see isWorkdayUnit's doc\n // comment) and is not in the base table, so resolve its measure via \"day\"\n // instead of attempting the real lookup below.\n if (isWorkdayUnit(unit)) return getMeasure(\"day\");\n\n // Extended (custom) categories the base table has no measure kind for,\n // see ExtendedUnits.ts.\n const extended = EXTENDED_UNITS[unit];\n if (extended) return extended.measure;\n\n const entry = lookupUnit(unit);\n if (entry === undefined) return undefined;\n\n return MEASURE_KIND_NAMES[entry[0]];\n}\n\n/**\n * Check whether `from` can be converted to `to`. Same unit, or same\n * measure kind (length, mass, ...) and the underlying tables accept the pair.\n * Never throws; returns `false` on any failure.\n */\nexport function canConvert(from: string, to: string): boolean {\n if (from === to) return true;\n if (isWorkdayUnit(from) || isWorkdayUnit(to)) {\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n return !!fromMeasure && fromMeasure === toMeasure;\n }\n // One table read per side, comparing numeric kind ids. The old shape called\n // getMeasure() on each side (two more reads) purely to compare the resulting\n // STRINGS, then did a throwaway conversion to confirm what the kind check had\n // already established.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return fromEntry[0] === toEntry[0];\n }\n\n // Extended (custom) categories aren't in the base table at all, so they are\n // compared on their own measure names instead.\n const fromExtended = EXTENDED_UNITS[from];\n const toExtended = EXTENDED_UNITS[to];\n if (fromExtended !== undefined && toExtended !== undefined) {\n return fromExtended.measure === toExtended.measure;\n }\n\n // Mixed: one side is in the base table and the other is extended. That used\n // to be refused outright, on the grounds that the two measure spaces are\n // disjoint. They are not, once an extended unit names a measure the base\n // table also has: `furlong` is a length and so is `m`, and the ratio between\n // them is exactly what both tables already record.\n return bridgesToBaseMeasure(from, to) || bridgesToBaseMeasure(to, from);\n}\n\n/**\n * Whether `extendedUnit` extends a measure the base table also knows, so a\n * value in it can reach `baseUnit`.\n *\n * The bridge works because both tables express a unit as a ratio to the same\n * physical base: the generated table's length ratios are metres and its mass\n * ratios are grams, and an extended unit declaring `measure: \"length\"` states\n * its `toBase` in the same metres. Composing the two ratios is then ordinary\n * arithmetic rather than a second conversion system.\n *\n * A measure the base table has no concept of, such as pace, still fails here,\n * which is the behaviour this replaced and the reason the check is by measure\n * name rather than by presence in the extended table.\n */\nfunction bridgesToBaseMeasure(extendedUnit: string, baseUnit: string): boolean {\n const extended = EXTENDED_UNITS[extendedUnit];\n if (extended === undefined) return false;\n\n const base = lookupUnit(resolveUnit(baseUnit));\n if (base === undefined) return false;\n\n return MEASURE_KIND_NAMES[base[0]] === extended.measure;\n}\n\n/**\n * Convert `value` from unit `from` to unit `to`.\n *\n * Does not validate that the conversion is possible, callers should check\n * with {@link canConvert} first if `from`/`to` aren't already known-good.\n *\n * THROWS a RangeError for an unknown unit or a cross-measure pair. `VM.ts`'s\n * `extractDurationMs()` depends on that, see {@link convertRaw}.\n *\n * This used to memoize a per-pair conversion factor in an LFU cache. The cache\n * is gone: computing the factor is now two Map reads, while the cache cost a\n * template-string key allocation on every call plus the LFU's own frequency\n * bookkeeping, so it was slower than the work it avoided. Removing it is\n * bit-exact, not merely close: the cache stored `convertRaw(1, f, t)`, which is\n * exactly `fromRatio / toRatio`, and then multiplied, which is the identical\n * expression `convertRaw(value, f, t)` evaluates. It also deleted the special\n * case that existed only to keep offset-based temperature pairs out of a\n * factor cache.\n */\nexport function convertUnit(value: number, from: string, to: string): number {\n if (from === to) return value;\n\n // Fast path first: two ordinary units, which is nearly every call. Resolving\n // both here and handing the entries to convertResolved() avoids looking them\n // up again inside convertRaw(). Neither workdays nor extended units appear in\n // the base table, so they always fall through to the branches below and this\n // ordering cannot steal a case from them. UnitVocabulary.spec.ts pins that\n // the two vocabularies stay disjoint.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return convertResolved(value, from, to, fromEntry, toEntry);\n }\n\n // Workday <-> any other Time-measure unit: pivot through \"day\" using the\n // fixed 7/5 ratio (see isWorkdayUnit's doc comment above).\n if (isWorkdayUnit(from) && isWorkdayUnit(to)) return value; // \"workday\" <-> \"workdays\" alias\n if (isWorkdayUnit(from)) {\n const days = value * WORKDAY_TO_DAY_FACTOR;\n return to === \"day\" ? days : convertUnit(days, \"day\", to);\n }\n if (isWorkdayUnit(to)) {\n const days = from === \"day\" ? value : convertUnit(value, from, \"day\");\n return days / WORKDAY_TO_DAY_FACTOR;\n }\n\n // Extended (custom) categories the base table has no measure kind for\n // (see ExtendedUnits.ts), compute the ratio directly from each unit's\n // factor-to-base value instead of calling convertRaw(), which would throw\n // on an unrecognized unit string. Every extended category is a pure linear\n // ratio scale (no Temperature-style offset), so this is always safe.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\n return value * (fExt.toBase / tExt.toBase);\n }\n\n // One side extended, the other in the base table, sharing a measure. Convert\n // through the measure's base unit, which both tables state their ratios\n // against: an extended length declares its `toBase` in metres, and the\n // generated table's length ratios are metres too.\n if (fExt !== undefined && bridgesToBaseMeasure(from, to)) {\n return convertRaw(value * fExt.toBase, baseUnitFor(to), to);\n }\n if (tExt !== undefined && bridgesToBaseMeasure(to, from)) {\n return convertRaw(value, from, baseUnitFor(from)) / tExt.toBase;\n }\n\n // Offsets, cross-measure rejection and the unknown-unit throw all live in\n // convertRaw. Nothing is layered on top here any more.\n return convertRaw(value, from, to);\n}\n\n/**\n * The unit a measure states its ratios against, found from any unit in it.\n *\n * Read out of the table rather than hard-coded, so it cannot drift from the\n * ratios it has to agree with: the base is whichever unit of that measure has\n * a ratio of exactly one.\n */\nfunction baseUnitFor(unit: string): string {\n const entry = lookupUnit(resolveUnit(unit));\n if (entry === undefined) return unit;\n\n for (const symbol of Object.keys(UNIT_TABLE)) {\n const candidate = UNIT_TABLE[symbol];\n if (candidate[0] === entry[0] && candidate[1] === 1) return symbol;\n }\n return unit;\n}\n\n/**\n * List every unit symbol in the same measure/dimension as `unit` (wiki:\n * Units-Of-Measurement, \"Conversion Possibilities\", `sourceUnit to ?`\n * e.g. `cm to ?\"` → every Length unit). Excludes `unit` itself.\n *\n * Reads MEASURE_SYMBOLS, which is a curated symbols-only vocabulary and\n * deliberately NOT the keys of the unit table filtered by kind. The two\n * differ: Volume's symbols include `c` and `pt` but not `cup`/`cups`, and\n * Time's include `wk` and `mo` but not `week`/`month`. Deriving this list\n * from the unit table instead would roughly quadruple every answer.\n *\n * @returns `[]` if `unit` isn't recognized, rather than throwing.\n */\nexport function getConvertiblePossibilities(unit: string): string[] {\n const resolved = resolveUnit(unit);\n const entry = lookupUnit(resolved);\n if (entry === undefined) return [];\n const symbols = MEASURE_SYMBOLS[entry[0]];\n if (!symbols) return [];\n return symbols.filter((s) => s !== resolved);\n}\n\n/** Check whether `unit` is a unit the conversion tables recognize. Never throws. */\nexport function isConvertibleUnit(unit: string): boolean {\n if (isWorkdayUnit(unit)) return true;\n if (EXTENDED_UNITS[unit]) return true;\n return lookupUnit(resolveUnit(unit)) !== undefined;\n}\n\n/**\n * Convert `value` (in `unit`) to whichever unit of the same measure gives\n * the most human-readable magnitude, e.g. 1500 metres becomes 1.5 km. Falls\n * back to returning `value`/`unit` unchanged if `unit` isn't recognized,\n * which is what every extended unit and workday does.\n *\n * Note the chosen unit is drawn from the best-unit lists, which are not\n * restricted to spellings the lexer accepts: 0.5 l reports \"mL\".\n */\nexport function getBestUnit(value: number, unit: string): { value: number; unit: string } {\n const u = resolveUnit(unit);\n try {\n const result = convertToBestMetric(value, u);\n return { value: result.quantity, unit: result.unit };\n } catch {\n return { value, unit: u };\n }\n}\n\n// ── Rate and derived-unit conversion ───────────────────────────────────────\n//\n// A rate value carries a compound unit spelled \"numerator/denominator\" (e.g.\n// \"km/h\", \"m/s\"), see vm/Value.ts's rateValue(). Plain convertUnit() cannot\n// touch one, because neither half is the whole unit and getMeasure(\"km/h\") is\n// undefined. This section converts a rate to another rate, and bridges a rate\n// to the single-token speed spellings (mph, kph, mps, ...) that ExtendedUnits.ts\n// already carries, so \"100 km/h in mph\" and \"60 mph in km/h\" resolve instead of\n// reporting incompatible units.\n\n/** A rate reduced to a numerator unit over a denominator unit. */\ninterface RateForm {\n /** Magnitude, scaled so `value numerator/denominator` is the physical quantity. */\n value: number;\n /** Numerator unit spelling, or `\"\"` for a countless rate such as `30/week`. */\n numerator: string;\n /** Denominator unit spelling. */\n denominator: string;\n}\n\n/**\n * Express `value unit` as a numerator/denominator rate, or `null` when `unit`\n * is neither a compound rate spelling nor a single-token speed alias.\n *\n * A speed alias (mph, kph, ...) is one unit standing for a length/time rate, so\n * it expands to the base pair `m`/`s` with its value scaled by the alias's\n * metres-per-second factor. That collapses both inputs to one shape, so a\n * single routine handles rate/rate and rate/alias without a second code path.\n */\nfunction expandUnitToRate(value: number, unit: string): RateForm | null {\n const slash = unit.indexOf(\"/\");\n if (slash >= 0) {\n return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };\n }\n const ext = EXTENDED_UNITS[unit];\n if (ext !== undefined && ext.measure === \"speed\") {\n // 1 alias == ext.toBase m/s, so `value alias` is `value * toBase` m/s.\n return { value: value * ext.toBase, numerator: \"m\", denominator: \"s\" };\n }\n return null;\n}\n\n/**\n * The factor that turns one `from` into `to` along a single rate axis, or\n * `null` when the two cannot line up.\n *\n * Same spelling needs no conversion. A countless axis (`\"\"`) only lines up with\n * another countless one, never with a real unit. Otherwise both sides must name\n * the same measure, which is what keeps a length numerator from pairing with a\n * mass one.\n */\nfunction rateAxisFactor(from: string, to: string): number | null {\n if (from === to) return 1;\n if (from === \"\" || to === \"\") return null;\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n if (fromMeasure === undefined || toMeasure === undefined || fromMeasure !== toMeasure) {\n return null;\n }\n return convertUnit(1, from, to);\n}\n\n/**\n * Convert `value` from a rate/speed unit `from` to a rate/speed unit `to`,\n * returning the converted magnitude, or `null` when the pair is not\n * rate-convertible (so the caller falls back to its own incompatible-units\n * handling).\n *\n * Handles rate to rate (`10 m/s in km/h`), rate to speed alias\n * (`100 km/h in mph`) and speed alias to rate (`60 mph in km/h`). Plain\n * same-measure pairs (`kph in mph`, `km in miles`) never reach here, they are\n * resolved by {@link convertUnit} first.\n *\n * The rule is the ordinary one for a quotient of quantities: convert the\n * numerator and the denominator each on their own, so `A/B -> C/D` scales by\n * `(A->C) / (B->D)`.\n */\nexport function convertRate(value: number, from: string, to: string): number | null {\n const source = expandUnitToRate(value, from);\n if (source === null) return null;\n\n // The target is either a rate spelling or a single-token speed alias. An\n // alias expands to the base m/s pair, and `targetScale` is what the base-form\n // magnitude is divided by to read out in the alias itself.\n let targetNumerator: string;\n let targetDenominator: string;\n let targetScale: number;\n const slash = to.indexOf(\"/\");\n if (slash >= 0) {\n targetNumerator = to.slice(0, slash);\n targetDenominator = to.slice(slash + 1);\n targetScale = 1;\n } else {\n const ext = EXTENDED_UNITS[to];\n if (ext === undefined || ext.measure !== \"speed\") return null;\n targetNumerator = \"m\";\n targetDenominator = \"s\";\n targetScale = ext.toBase;\n }\n\n const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);\n if (numeratorFactor === null) return null;\n const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);\n if (denominatorFactor === null) return null;\n\n return (source.value * numeratorFactor) / denominatorFactor / targetScale;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { TokenTypes, tokenTypeId } from './chunk-VB37OC6I.js';
1
+ import { TokenTypes, tokenTypeId } from './chunk-4D6NIHE2.js';
2
2
  import { getLocale } from './chunk-XBTEO4OB.js';
3
- import { ErrorFactory } from './chunk-3D7V24DG.js';
3
+ import { ErrorFactory } from './chunk-ERCOHGXD.js';
4
4
 
5
5
  // src/parser/BindingPower.ts
6
6
  var BindingPower = {
@@ -47,6 +47,12 @@ var BindingPower = {
47
47
  // `<<`, `>>`, `>>>`
48
48
  Sum: 30,
49
49
  Product: 40,
50
+ // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,
51
+ // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as
52
+ // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as
53
+ // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is
54
+ // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.
55
+ Uncertainty: 45,
50
56
  // `^`, RIGHT-associative: "2 ^ 3 ^ 2" is 2^(3^2) = 512, as in mathematics,
51
57
  // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression
52
58
  // and BinaryOpParselet for the two places that associativity is implemented.
@@ -323,5 +329,5 @@ function stripLocaleGrouping(text, localeCode) {
323
329
  }
324
330
 
325
331
  export { BindingPower, BytecodeBuilder, bigIntLiteralDigits, buildBindingPowerTable, invalidateBindingPowerTable };
326
- //# sourceMappingURL=chunk-526PMQOA.js.map
327
- //# sourceMappingURL=chunk-526PMQOA.js.map
332
+ //# sourceMappingURL=chunk-ENKKJYD3.js.map
333
+ //# sourceMappingURL=chunk-ENKKJYD3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":[],"mappings":";;;;;AAWO,IAAM,YAAA,GAAe;AAAA,EAC1B,MAAA,EAAQ,CAAA;AAAA,EACR,UAAA,EAAY,EAAA;AAAA,EACZ,SAAA,EAAW,EAAA;AAAA;AAAA,EACX,UAAA,EAAY,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaZ,WAAA,EAAa,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAab,SAAA,EAAW,EAAA;AAAA;AAAA,EACX,UAAA,EAAY,EAAA;AAAA;AAAA,EACZ,UAAA,EAAY,EAAA;AAAA;AAAA,EACZ,WAAA,EAAa,EAAA;AAAA;AAAA,EACb,KAAA,EAAO,EAAA;AAAA;AAAA,EACP,GAAA,EAAK,EAAA;AAAA,EACL,OAAA,EAAS,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,WAAA,EAAa,E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A,EAAK,UAAA,EAAY,SAAA;AAAU,KAC9B;AAAA,EACD;AACA,EAAA,OAAO,MAAA;AACR;AASA,SAAS,mBAAA,CAAoB,MAAc,UAAA,EAA4B;AACtE,EAAA,MAAM,kBAAA,GAAqB,SAAA,CAAU,UAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA;AACzD,EAAA,OAAO,qBAAqB,IAAA,CAAK,KAAA,CAAM,kBAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAAI,IAAA;AACvE","file":"chunk-ENKKJYD3.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when registering an infix parselet via\n * `IPackageRegistry.registerInfixParselet`. See the built-in packages for\n * examples of picking an appropriate level (e.g. arithmetic `+`/`-` use\n * `Sum`, `*`/`/` use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: new Float64Array(this.numbers),\n\t\t\t// Defensive copy: .length = 0 in reset() would clear a shared reference.\n\t\t\t// Strings are rare (only UoM/datetime parselets emit them), so the copy\n\t\t\t// cost is negligible.\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\tthis.strings.length = 0;\n\t\tthis.stringIndex.clear();\n\t\tthis._hasAsync = false;\n\t\tthis.userFunctionBodies.length = 0;\n\t\tthis.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
@@ -89,16 +89,6 @@ var abortLogger = {
89
89
  }
90
90
  };
91
91
 
92
- // src/utilities/Hash.ts
93
- function djb2Hash(str) {
94
- let hash = 5381;
95
- for (let i = 0; i < str.length; i++) {
96
- hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
97
- }
98
- return hash >>> 0;
99
- }
100
-
101
92
  exports.abortLogger = abortLogger;
102
- exports.djb2Hash = djb2Hash;
103
- //# sourceMappingURL=chunk-5X2PTP6F.cjs.map
104
- //# sourceMappingURL=chunk-5X2PTP6F.cjs.map
93
+ //# sourceMappingURL=chunk-ENRIK36Q.cjs.map
94
+ //# sourceMappingURL=chunk-ENRIK36Q.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities/AbortControllerLogger.ts"],"names":[],"mappings":";;;AA4BA,IAAM,iBAAiB,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,IAAI,eAAA,KAAoB,MAAA;AAQlF,IAAM,WAAA,GAAc;AAAA;AAAA,EAE1B,IAAI,OAAA,GAAmB;AACtB,IAAA,OAAO,cAAA;AAAA,EACR,CAAA;AAAA;AAAA;AAAA;AA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B,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,MAAM,6CAA6C,CAAA;AAAA,EAC5D,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,kBAAA,CAAmB,UAAkB,OAAA,EAAuB;AAC3D,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA;AAAA,MACP,CAAA,2BAAA,EAA8B,QAAQ,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA;AAAA,KACnD;AAAA,EACD;AACD","file":"chunk-ENRIK36Q.cjs","sourcesContent":["/**\n * Debug logging for the AbortController lifecycle in the \"One AbortController\n * Per Keystroke\" pattern.\n *\n * Enabled when `process.env.DEBUG_ABORTCTRL === \"true\"`.\n *\n * This is **opt-in only**, even in development mode you must explicitly\n * set the flag to avoid log noise from large documents.\n *\n * Logs controller creation, abortion, signal linking, keystroke signal\n * propagation, and stale-data discard guards. All messages are output via\n * `console.debug` with an `[AbortCtrl]` prefix so they can be filtered\n * in the DevTools console.\n *\n * ── Usage ─────────────────────────────────────────────────────────────\n * import { abortLogger } from \"@solve-js/utilities/AbortControllerLogger\";\n *\n * // Enable explicitly (before the plugin boots):\n * // process.env.DEBUG_ABORTCTRL = \"true\";\n *\n * abortLogger.keystrokeCreated();\n * abortLogger.localControllerCreated(\"executeAndStore\");\n * abortLogger.signalLinked(\"executeAndStore\", \"keystroke\");\n * abortLogger.keystrokeAborted(\"New keystroke\");\n * abortLogger.staleDataDiscarded(\"USD:GBP\", \"signal aborted\");\n * abortLogger.keystrokeSignalSet(true); // signal set, not aborted\n * abortLogger.keystrokeSignalCleared();\n */\nconst isDebugEnabled = typeof process !== \"undefined\" && process.env.DEBUG_ABORTCTRL === \"true\";\n\n/**\n * Records abort-signal lifecycle for debugging cancellation.\n *\n * Keystroke cancellation is hard to reason about after the fact, because the\n * evidence is gone by the time anything looks wrong. This keeps it.\n */\nexport const abortLogger = {\n\t/** Whether debug logging is currently active. */\n\tget enabled(): boolean {\n\t\treturn isDebugEnabled;\n\t},\n\n\t// ── Keystroke-level controller (MarkdownEditorViewPlugin) ──────\n\n\t/**\n\t * Log creation of the keystroke-level AbortController.\n\t * Called in the plugin constructor and on each new keystroke.\n\t */\n\tkeystrokeCreated(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE CREATED\");\n\t},\n\n\t/**\n\t * Log abortion of the keystroke-level AbortController.\n\t * @param reason Why the keystroke was aborted (e.g. \"New keystroke\",\n\t * \"Document switch\", \"Plugin destroyed\").\n\t */\n\tkeystrokeAborted(reason: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] KEYSTROKE ABORTED: ${reason}`);\n\t},\n\n\t// ── Local per-evaluation controllers (ExpressionEngine) ─────────\n\n\t/**\n\t * Log creation of a local AbortController that is linked to the\n\t * keystroke signal.\n\t * @param source Which code path created the controller\n\t * (e.g. \"executeAndStore\", \"executeRaw\", \"preflight\", \"vm\").\n\t */\n\tlocalControllerCreated(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL CREATED (${source})`);\n\t},\n\n\t/**\n\t * Log that a local AbortController was linked to the keystroke signal.\n\t * When the keystroke signal is aborted, this local controller will\n\t * be aborted automatically.\n\t * @param source The code path that created the controller.\n\t */\n\tsignalLinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL LINKED (${source}) → keystroke`);\n\t},\n\n\t/**\n\t * Log that a local AbortController's listener was removed from the\n\t * keystroke signal (cleanup).\n\t * @param source The code path.\n\t */\n\tsignalUnlinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL UNLINKED (${source})`);\n\t},\n\n\t// ── Keystroke signal propagation (ThreeTierEvaluator → ExpressionEngine) ──\n\n\t/**\n\t * Log that the keystroke signal was propagated INTO the engine.\n\t * @param isAborted Whether the signal was already aborted when set.\n\t */\n\tkeystrokeSignalSet(isAborted: boolean): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] KEYSTROKE_SIGNAL → engine (aborted=${isAborted})`,\n\t\t);\n\t},\n\n\t/**\n\t * Log that the keystroke signal was CLEARED from the engine\n\t * (typically in the evaluator's finally block).\n\t */\n\tkeystrokeSignalCleared(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE_SIGNAL cleared (null)\");\n\t},\n\n\t// ── Stale-data discard guards (resolveAsync) ────────────────────\n\n\t/**\n\t * Log that a stale async result was discarded because its signal\n\t * was aborted.\n\t * @param queryKey The cache key for the discarded result.\n\t * @param context Additional context (e.g. \"after await\", \"after error\").\n\t */\n\tstaleDataDiscarded(queryKey: string, context: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] STALE DISCARD: ${queryKey} (${context})`,\n\t\t);\n\t},\n};\n"]}