solve-engine 1.2.0 → 2.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 (385) hide show
  1. package/README.md +12 -17
  2. package/dist/{BytecodeBuilder-Bp9xeTmX.d.cts → BytecodeBuilder-DGGeByAP.d.cts} +18 -0
  3. package/dist/{BytecodeBuilder-Bp9xeTmX.d.ts → BytecodeBuilder-DGGeByAP.d.ts} +18 -0
  4. package/dist/{Configuration-C9W8tJv_.d.cts → Configuration-B6W0-T67.d.cts} +17 -4
  5. package/dist/{Configuration-C9W8tJv_.d.ts → Configuration-B6W0-T67.d.ts} +17 -4
  6. package/dist/{EngineError-CNA_rHY-.d.cts → EngineError-Ce1lPkjZ.d.cts} +2 -0
  7. package/dist/{EngineError-CNA_rHY-.d.ts → EngineError-Ce1lPkjZ.d.ts} +2 -0
  8. package/dist/{PackageCompatibility-B6NX9IaN.d.cts → PackageCompatibility-Bn5jnBtA.d.cts} +2 -2
  9. package/dist/{PackageCompatibility-Ceg5XdAp.d.ts → PackageCompatibility-CIvq2MP5.d.ts} +2 -2
  10. package/dist/{PackageRegistry-DrCPQNyy.d.ts → PackageRegistry-DzeiWcv4.d.ts} +93 -172
  11. package/dist/{PackageRegistry-DnJYVw9G.d.cts → PackageRegistry-dpdurBVO.d.cts} +93 -172
  12. package/dist/{Parselet-Bhf7d0_W.d.ts → Parselet-B-zoPrTa.d.ts} +8 -5
  13. package/dist/{Parselet-Cv7S7KRt.d.cts → Parselet-C4Wu055_.d.cts} +8 -5
  14. package/dist/{ScopeManager-Bzq87GfA.d.ts → ScopeManager-C2LDOrDx.d.ts} +7 -16
  15. package/dist/{ScopeManager-DRDBVfan.d.cts → ScopeManager-D7uMXbhS.d.cts} +7 -16
  16. package/dist/{VMCheckpoints-C6c17Hbo.d.ts → VMCheckpoints-CGyFhivM.d.ts} +3 -3
  17. package/dist/{VMCheckpoints-dZxSMGHG.d.cts → VMCheckpoints-I9jg3jWR.d.cts} +3 -3
  18. package/dist/{Value-DZNQ_PU7.d.cts → Value-CCi_Eecs.d.cts} +40 -0
  19. package/dist/{Value-DZNQ_PU7.d.ts → Value-CCi_Eecs.d.ts} +40 -0
  20. package/dist/{WorkerError-Djd7GGGa.d.cts → WorkerError-B4p6PNfx.d.cts} +1 -1
  21. package/dist/{WorkerError-B7t7R2-m.d.ts → WorkerError-Dhj9BQ_A.d.ts} +1 -1
  22. package/dist/chunk-2JMFUQZH.js +2 -0
  23. package/dist/chunk-2JMFUQZH.js.map +1 -0
  24. package/dist/chunk-2LFLR3VZ.cjs +2 -0
  25. package/dist/chunk-2LFLR3VZ.cjs.map +1 -0
  26. package/dist/chunk-2RWAXT6O.js +0 -1
  27. package/dist/chunk-32GC2FHC.cjs +2 -0
  28. package/dist/chunk-32GC2FHC.cjs.map +1 -0
  29. package/dist/chunk-4BZIYU7S.cjs +3 -0
  30. package/dist/chunk-4BZIYU7S.cjs.map +1 -0
  31. package/dist/chunk-4E4YVQKK.js +5 -0
  32. package/dist/chunk-4E4YVQKK.js.map +1 -0
  33. package/dist/chunk-4QVBSG6B.cjs +2 -0
  34. package/dist/chunk-4QVBSG6B.cjs.map +1 -0
  35. package/dist/chunk-5FO4PDIG.js +2 -0
  36. package/dist/chunk-5FO4PDIG.js.map +1 -0
  37. package/dist/chunk-5IJD5L3O.cjs +2 -0
  38. package/dist/chunk-5IJD5L3O.cjs.map +1 -0
  39. package/dist/chunk-62LMTO4F.js +2 -0
  40. package/dist/chunk-62LMTO4F.js.map +1 -0
  41. package/dist/chunk-6G3PMEPA.js +2 -0
  42. package/dist/chunk-6G3PMEPA.js.map +1 -0
  43. package/dist/chunk-6INX773F.cjs +2 -0
  44. package/dist/chunk-6INX773F.cjs.map +1 -0
  45. package/dist/chunk-76F3LCIL.js +4 -0
  46. package/dist/chunk-76F3LCIL.js.map +1 -0
  47. package/dist/chunk-7BXPCWKM.cjs +2 -0
  48. package/dist/chunk-7BXPCWKM.cjs.map +1 -0
  49. package/dist/chunk-7GK3XEZF.js +2 -0
  50. package/dist/chunk-7GK3XEZF.js.map +1 -0
  51. package/dist/chunk-AXMQG5TS.cjs +2 -0
  52. package/dist/chunk-AXMQG5TS.cjs.map +1 -0
  53. package/dist/chunk-CIQOK7Q4.cjs +2 -0
  54. package/dist/chunk-CIQOK7Q4.cjs.map +1 -0
  55. package/dist/chunk-E2Q3PQ2G.js +3 -0
  56. package/dist/chunk-E2Q3PQ2G.js.map +1 -0
  57. package/dist/chunk-E6Z4NQAS.js +2 -0
  58. package/dist/chunk-E6Z4NQAS.js.map +1 -0
  59. package/dist/chunk-EFJCC6FJ.cjs +2 -0
  60. package/dist/chunk-EFJCC6FJ.cjs.map +1 -0
  61. package/dist/chunk-ESUN2THE.cjs +2 -0
  62. package/dist/chunk-ESUN2THE.cjs.map +1 -0
  63. package/dist/chunk-EVAOPEO4.js +2 -0
  64. package/dist/chunk-EVAOPEO4.js.map +1 -0
  65. package/dist/chunk-EVI6OHQH.cjs +2 -0
  66. package/dist/chunk-EVI6OHQH.cjs.map +1 -0
  67. package/dist/chunk-FDE5HWDI.cjs +2 -0
  68. package/dist/chunk-FDE5HWDI.cjs.map +1 -0
  69. package/dist/chunk-FWW3M36J.cjs +2 -0
  70. package/dist/chunk-FWW3M36J.cjs.map +1 -0
  71. package/dist/chunk-G7TBEQRQ.js +2 -0
  72. package/dist/chunk-G7TBEQRQ.js.map +1 -0
  73. package/dist/chunk-GK2OHWRF.cjs +5 -0
  74. package/dist/chunk-GK2OHWRF.cjs.map +1 -0
  75. package/dist/chunk-HFKDWQUL.js +2 -0
  76. package/dist/chunk-HFKDWQUL.js.map +1 -0
  77. package/dist/chunk-HLBYHXQD.cjs +3 -0
  78. package/dist/chunk-HLBYHXQD.cjs.map +1 -0
  79. package/dist/chunk-I52MYCVI.js +3 -0
  80. package/dist/chunk-I52MYCVI.js.map +1 -0
  81. package/dist/chunk-IANAMBJQ.cjs +2 -0
  82. package/dist/chunk-IANAMBJQ.cjs.map +1 -0
  83. package/dist/chunk-IJMNVBIS.js +2 -0
  84. package/dist/chunk-IJMNVBIS.js.map +1 -0
  85. package/dist/chunk-J4LZD4ZY.js +3 -0
  86. package/dist/chunk-J4LZD4ZY.js.map +1 -0
  87. package/dist/chunk-JAK3RAFA.cjs +2 -0
  88. package/dist/chunk-JAK3RAFA.cjs.map +1 -0
  89. package/dist/chunk-JFAJN3C2.cjs +2 -0
  90. package/dist/chunk-JFAJN3C2.cjs.map +1 -0
  91. package/dist/chunk-JPFCXLJV.js +2 -0
  92. package/dist/chunk-JPFCXLJV.js.map +1 -0
  93. package/dist/chunk-JUIJ6NRD.cjs +3 -0
  94. package/dist/chunk-JUIJ6NRD.cjs.map +1 -0
  95. package/dist/chunk-MIQBJGGR.js +2 -0
  96. package/dist/chunk-MIQBJGGR.js.map +1 -0
  97. package/dist/chunk-MPB7KUN5.js +3 -0
  98. package/dist/chunk-MPB7KUN5.js.map +1 -0
  99. package/dist/chunk-MSYX32PF.cjs +2 -0
  100. package/dist/chunk-MSYX32PF.cjs.map +1 -0
  101. package/dist/chunk-MVZUTETT.js +2 -0
  102. package/dist/chunk-MVZUTETT.js.map +1 -0
  103. package/dist/chunk-N7N7MPMK.cjs +2 -0
  104. package/dist/chunk-N7N7MPMK.cjs.map +1 -0
  105. package/dist/chunk-NGBBNL4K.cjs +1 -3
  106. package/dist/chunk-OVKDDTXO.cjs +3 -0
  107. package/dist/chunk-OVKDDTXO.cjs.map +1 -0
  108. package/dist/chunk-P6WPEUAJ.cjs +2 -0
  109. package/dist/chunk-P6WPEUAJ.cjs.map +1 -0
  110. package/dist/chunk-PS272DZJ.cjs +2 -0
  111. package/dist/chunk-PS272DZJ.cjs.map +1 -0
  112. package/dist/chunk-R2ENWQ76.js +2 -0
  113. package/dist/chunk-R2ENWQ76.js.map +1 -0
  114. package/dist/chunk-R2SZFJTT.cjs +2 -0
  115. package/dist/chunk-R2SZFJTT.cjs.map +1 -0
  116. package/dist/chunk-RAF57WYO.js +2 -0
  117. package/dist/chunk-RAF57WYO.js.map +1 -0
  118. package/dist/chunk-RSF25YSJ.js +2 -0
  119. package/dist/chunk-RSF25YSJ.js.map +1 -0
  120. package/dist/chunk-SOMGSIO4.cjs +3 -0
  121. package/dist/chunk-SOMGSIO4.cjs.map +1 -0
  122. package/dist/chunk-SYYE3QAX.cjs +2 -0
  123. package/dist/chunk-SYYE3QAX.cjs.map +1 -0
  124. package/dist/chunk-TCZSPH4A.js +2 -0
  125. package/dist/chunk-TCZSPH4A.js.map +1 -0
  126. package/dist/chunk-TLG7VZRX.cjs +2 -0
  127. package/dist/chunk-TLG7VZRX.cjs.map +1 -0
  128. package/dist/chunk-TN5E6JU6.js +2 -0
  129. package/dist/chunk-TN5E6JU6.js.map +1 -0
  130. package/dist/chunk-TRBXW6HW.js +2 -0
  131. package/dist/{chunk-AQNHHJMJ.cjs.map → chunk-TRBXW6HW.js.map} +1 -1
  132. package/dist/chunk-TTFO4YDP.cjs +2 -0
  133. package/dist/chunk-TTFO4YDP.cjs.map +1 -0
  134. package/dist/chunk-TWC7K3ZX.js +2 -0
  135. package/dist/chunk-TWC7K3ZX.js.map +1 -0
  136. package/dist/chunk-U4AEVL5Z.js +2 -0
  137. package/dist/chunk-U4AEVL5Z.js.map +1 -0
  138. package/dist/chunk-UURM7P3P.cjs +4 -0
  139. package/dist/chunk-UURM7P3P.cjs.map +1 -0
  140. package/dist/chunk-VAGS5JS7.cjs +2 -0
  141. package/dist/chunk-VAGS5JS7.cjs.map +1 -0
  142. package/dist/chunk-W2JAR233.js +2 -0
  143. package/dist/chunk-W2JAR233.js.map +1 -0
  144. package/dist/chunk-WGZ3FNHI.js +2 -0
  145. package/dist/chunk-WGZ3FNHI.js.map +1 -0
  146. package/dist/chunk-XEIDV5JP.js +2 -0
  147. package/dist/chunk-XEIDV5JP.js.map +1 -0
  148. package/dist/chunk-XNIWQHXY.js +2 -0
  149. package/dist/chunk-XNIWQHXY.js.map +1 -0
  150. package/dist/chunk-Y7O4D3BJ.cjs +2 -0
  151. package/dist/chunk-Y7O4D3BJ.cjs.map +1 -0
  152. package/dist/chunk-YAHGSBMC.js +2 -0
  153. package/dist/chunk-YAHGSBMC.js.map +1 -0
  154. package/dist/chunk-YAYBVVG2.js +3 -0
  155. package/dist/chunk-YAYBVVG2.js.map +1 -0
  156. package/dist/chunk-YJ2OPULK.js +2 -0
  157. package/dist/chunk-YJ2OPULK.js.map +1 -0
  158. package/dist/chunk-YVKHEAFT.js +2 -0
  159. package/dist/chunk-YVKHEAFT.js.map +1 -0
  160. package/dist/chunk-ZCNBT44X.cjs +2 -0
  161. package/dist/chunk-ZCNBT44X.cjs.map +1 -0
  162. package/dist/chunk-ZLRJ7TDP.cjs +2 -0
  163. package/dist/chunk-ZLRJ7TDP.cjs.map +1 -0
  164. package/dist/constants.cjs +1 -21
  165. package/dist/constants.d.cts +1 -1
  166. package/dist/constants.d.ts +1 -1
  167. package/dist/constants.js +1 -4
  168. package/dist/engine.cjs +1 -94
  169. package/dist/engine.d.cts +10 -11
  170. package/dist/engine.d.ts +10 -11
  171. package/dist/engine.js +1 -37
  172. package/dist/errors.cjs +1 -105
  173. package/dist/errors.d.cts +3 -3
  174. package/dist/errors.d.ts +3 -3
  175. package/dist/errors.js +1 -4
  176. package/dist/format.cjs +1 -26
  177. package/dist/format.d.cts +2 -2
  178. package/dist/format.d.ts +2 -2
  179. package/dist/format.js +1 -9
  180. package/dist/index.cjs +1 -314
  181. package/dist/index.cjs.map +1 -1
  182. package/dist/index.d.cts +52 -20
  183. package/dist/index.d.ts +52 -20
  184. package/dist/index.js +1 -278
  185. package/dist/index.js.map +1 -1
  186. package/dist/language.cjs +1 -369
  187. package/dist/language.cjs.map +1 -1
  188. package/dist/language.d.cts +9 -10
  189. package/dist/language.d.ts +9 -10
  190. package/dist/language.js +1 -348
  191. package/dist/language.js.map +1 -1
  192. package/dist/lexer.cjs +1 -63
  193. package/dist/lexer.js +1 -10
  194. package/dist/normalizer.cjs +1 -39
  195. package/dist/normalizer.js +1 -10
  196. package/dist/packages.cjs +1 -132
  197. package/dist/packages.d.cts +8 -9
  198. package/dist/packages.d.ts +8 -9
  199. package/dist/packages.js +1 -23
  200. package/dist/parser.cjs +1 -54
  201. package/dist/parser.d.cts +8 -8
  202. package/dist/parser.d.ts +8 -8
  203. package/dist/parser.js +1 -9
  204. package/dist/{pipeline-D-PS9gVw.d.ts → pipeline-72QmQlGx.d.ts} +1 -1
  205. package/dist/{pipeline-DtSBJ8TS.d.cts → pipeline-DCQicwWX.d.cts} +1 -1
  206. package/dist/resolvers.cjs +1 -12
  207. package/dist/resolvers.d.cts +2 -2
  208. package/dist/resolvers.d.ts +2 -2
  209. package/dist/resolvers.js +1 -3
  210. package/dist/services.cjs +1 -20
  211. package/dist/services.js +1 -3
  212. package/dist/testing.cjs +3 -477
  213. package/dist/testing.cjs.map +1 -1
  214. package/dist/testing.d.cts +9 -10
  215. package/dist/testing.d.ts +9 -10
  216. package/dist/testing.js +3 -469
  217. package/dist/testing.js.map +1 -1
  218. package/dist/uom.cjs +1 -55
  219. package/dist/uom.d.cts +2 -2
  220. package/dist/uom.d.ts +2 -2
  221. package/dist/uom.js +1 -10
  222. package/dist/utilities.cjs +1 -36
  223. package/dist/utilities.js +1 -7
  224. package/dist/vm.cjs +1 -295
  225. package/dist/vm.cjs.map +1 -1
  226. package/dist/vm.d.cts +22 -10
  227. package/dist/vm.d.ts +22 -10
  228. package/dist/vm.js +1 -193
  229. package/dist/vm.js.map +1 -1
  230. package/dist/worker.cjs +2 -492
  231. package/dist/worker.cjs.map +1 -1
  232. package/dist/worker.d.cts +16 -17
  233. package/dist/worker.d.ts +16 -17
  234. package/dist/worker.js +2 -483
  235. package/dist/worker.js.map +1 -1
  236. package/package.json +1 -13
  237. package/dist/chunk-3BOK2LDK.js +0 -17
  238. package/dist/chunk-3BOK2LDK.js.map +0 -1
  239. package/dist/chunk-3VGDNEE3.js +0 -84
  240. package/dist/chunk-3VGDNEE3.js.map +0 -1
  241. package/dist/chunk-4K5W7EH2.cjs +0 -112
  242. package/dist/chunk-4K5W7EH2.cjs.map +0 -1
  243. package/dist/chunk-5EFKSKMA.js +0 -413
  244. package/dist/chunk-5EFKSKMA.js.map +0 -1
  245. package/dist/chunk-5HRB36DK.js +0 -405
  246. package/dist/chunk-5HRB36DK.js.map +0 -1
  247. package/dist/chunk-5ON7PUAZ.js +0 -12
  248. package/dist/chunk-5ON7PUAZ.js.map +0 -1
  249. package/dist/chunk-7AXJNQMF.cjs +0 -297
  250. package/dist/chunk-7AXJNQMF.cjs.map +0 -1
  251. package/dist/chunk-7JM3F4KL.js +0 -1795
  252. package/dist/chunk-7JM3F4KL.js.map +0 -1
  253. package/dist/chunk-7USV76HV.cjs +0 -341
  254. package/dist/chunk-7USV76HV.cjs.map +0 -1
  255. package/dist/chunk-A2DZ5BEJ.cjs +0 -1930
  256. package/dist/chunk-A2DZ5BEJ.cjs.map +0 -1
  257. package/dist/chunk-ADBA3XBE.cjs +0 -20
  258. package/dist/chunk-ADBA3XBE.cjs.map +0 -1
  259. package/dist/chunk-AKNGX4TZ.cjs +0 -236
  260. package/dist/chunk-AKNGX4TZ.cjs.map +0 -1
  261. package/dist/chunk-ALYRJ72W.cjs +0 -434
  262. package/dist/chunk-ALYRJ72W.cjs.map +0 -1
  263. package/dist/chunk-AMOJYLG2.cjs +0 -1692
  264. package/dist/chunk-AMOJYLG2.cjs.map +0 -1
  265. package/dist/chunk-AOH6UR2L.js +0 -825
  266. package/dist/chunk-AOH6UR2L.js.map +0 -1
  267. package/dist/chunk-AQNHHJMJ.cjs +0 -261
  268. package/dist/chunk-B7LXJ6LC.cjs +0 -36
  269. package/dist/chunk-B7LXJ6LC.cjs.map +0 -1
  270. package/dist/chunk-BESTLPRK.cjs +0 -6919
  271. package/dist/chunk-BESTLPRK.cjs.map +0 -1
  272. package/dist/chunk-BLI4NIQY.js +0 -98
  273. package/dist/chunk-BLI4NIQY.js.map +0 -1
  274. package/dist/chunk-BSPXMGIS.js +0 -455
  275. package/dist/chunk-BSPXMGIS.js.map +0 -1
  276. package/dist/chunk-C2OMO3WN.cjs +0 -2806
  277. package/dist/chunk-C2OMO3WN.cjs.map +0 -1
  278. package/dist/chunk-CSDQMDU2.js +0 -204
  279. package/dist/chunk-CSDQMDU2.js.map +0 -1
  280. package/dist/chunk-EJ3ILXX6.cjs +0 -223
  281. package/dist/chunk-EJ3ILXX6.cjs.map +0 -1
  282. package/dist/chunk-ENRIK36Q.cjs +0 -94
  283. package/dist/chunk-ENRIK36Q.cjs.map +0 -1
  284. package/dist/chunk-F4UB4XIL.js +0 -109
  285. package/dist/chunk-F4UB4XIL.js.map +0 -1
  286. package/dist/chunk-FD5ZZHEU.js +0 -92
  287. package/dist/chunk-FD5ZZHEU.js.map +0 -1
  288. package/dist/chunk-FE4RC37D.js +0 -2801
  289. package/dist/chunk-FE4RC37D.js.map +0 -1
  290. package/dist/chunk-FEAIOR7N.cjs +0 -91
  291. package/dist/chunk-FEAIOR7N.cjs.map +0 -1
  292. package/dist/chunk-FR7RNOPT.cjs +0 -3303
  293. package/dist/chunk-FR7RNOPT.cjs.map +0 -1
  294. package/dist/chunk-G2YPPLGX.cjs +0 -484
  295. package/dist/chunk-G2YPPLGX.cjs.map +0 -1
  296. package/dist/chunk-GCM5JHMX.js +0 -88
  297. package/dist/chunk-GCM5JHMX.js.map +0 -1
  298. package/dist/chunk-GDEU72RG.cjs +0 -829
  299. package/dist/chunk-GDEU72RG.cjs.map +0 -1
  300. package/dist/chunk-HKTQCQ4Z.cjs +0 -8383
  301. package/dist/chunk-HKTQCQ4Z.cjs.map +0 -1
  302. package/dist/chunk-HWHU642X.cjs +0 -316
  303. package/dist/chunk-HWHU642X.cjs.map +0 -1
  304. package/dist/chunk-ICEKS6YC.cjs +0 -507
  305. package/dist/chunk-ICEKS6YC.cjs.map +0 -1
  306. package/dist/chunk-IJGOFP2J.js +0 -6904
  307. package/dist/chunk-IJGOFP2J.js.map +0 -1
  308. package/dist/chunk-IQJGDZOP.js +0 -333
  309. package/dist/chunk-IQJGDZOP.js.map +0 -1
  310. package/dist/chunk-IT74O4BE.cjs +0 -456
  311. package/dist/chunk-IT74O4BE.cjs.map +0 -1
  312. package/dist/chunk-KXDQKVNX.cjs +0 -459
  313. package/dist/chunk-KXDQKVNX.cjs.map +0 -1
  314. package/dist/chunk-L2TE7PMO.cjs +0 -14
  315. package/dist/chunk-L2TE7PMO.cjs.map +0 -1
  316. package/dist/chunk-L5YHV6BQ.js +0 -499
  317. package/dist/chunk-L5YHV6BQ.js.map +0 -1
  318. package/dist/chunk-LO7HU5WB.cjs +0 -209
  319. package/dist/chunk-LO7HU5WB.cjs.map +0 -1
  320. package/dist/chunk-LSALB3IN.js +0 -292
  321. package/dist/chunk-LSALB3IN.js.map +0 -1
  322. package/dist/chunk-MI7OTUHL.cjs +0 -339
  323. package/dist/chunk-MI7OTUHL.cjs.map +0 -1
  324. package/dist/chunk-MIGXCBXT.cjs +0 -381
  325. package/dist/chunk-MIGXCBXT.cjs.map +0 -1
  326. package/dist/chunk-MVTOCRV2.js +0 -213
  327. package/dist/chunk-MVTOCRV2.js.map +0 -1
  328. package/dist/chunk-N7FNVFXW.cjs +0 -32
  329. package/dist/chunk-N7FNVFXW.cjs.map +0 -1
  330. package/dist/chunk-N7OA4WPJ.js +0 -362
  331. package/dist/chunk-N7OA4WPJ.js.map +0 -1
  332. package/dist/chunk-NAWZATKT.js +0 -478
  333. package/dist/chunk-NAWZATKT.js.map +0 -1
  334. package/dist/chunk-NLNDMWZC.js +0 -31
  335. package/dist/chunk-NLNDMWZC.js.map +0 -1
  336. package/dist/chunk-ORM7CHYZ.js +0 -1531
  337. package/dist/chunk-ORM7CHYZ.js.map +0 -1
  338. package/dist/chunk-OUHT5Z36.cjs +0 -393
  339. package/dist/chunk-OUHT5Z36.cjs.map +0 -1
  340. package/dist/chunk-PCZVMMWU.cjs +0 -74
  341. package/dist/chunk-PCZVMMWU.cjs.map +0 -1
  342. package/dist/chunk-RNKDIXDV.js +0 -336
  343. package/dist/chunk-RNKDIXDV.js.map +0 -1
  344. package/dist/chunk-SBUFNJVE.js +0 -258
  345. package/dist/chunk-SBUFNJVE.js.map +0 -1
  346. package/dist/chunk-TC6BTUSU.cjs +0 -1799
  347. package/dist/chunk-TC6BTUSU.cjs.map +0 -1
  348. package/dist/chunk-TPOK3UNI.js +0 -8355
  349. package/dist/chunk-TPOK3UNI.js.map +0 -1
  350. package/dist/chunk-UF6JG5SG.js +0 -312
  351. package/dist/chunk-UF6JG5SG.js.map +0 -1
  352. package/dist/chunk-UKQHXPGW.js +0 -30
  353. package/dist/chunk-UKQHXPGW.js.map +0 -1
  354. package/dist/chunk-V4XG5QF6.js +0 -1685
  355. package/dist/chunk-V4XG5QF6.js.map +0 -1
  356. package/dist/chunk-VEKIWQ3F.cjs +0 -39
  357. package/dist/chunk-VEKIWQ3F.cjs.map +0 -1
  358. package/dist/chunk-WMQRJTAO.js +0 -3266
  359. package/dist/chunk-WMQRJTAO.js.map +0 -1
  360. package/dist/chunk-X6K3HUOY.cjs +0 -86
  361. package/dist/chunk-X6K3HUOY.cjs.map +0 -1
  362. package/dist/chunk-XBTEO4OB.js +0 -391
  363. package/dist/chunk-XBTEO4OB.js.map +0 -1
  364. package/dist/chunk-XIYYHA65.cjs +0 -101
  365. package/dist/chunk-XIYYHA65.cjs.map +0 -1
  366. package/dist/chunk-YJHY7CMN.cjs +0 -1534
  367. package/dist/chunk-YJHY7CMN.cjs.map +0 -1
  368. package/dist/chunk-YLJ4XMA6.js +0 -33
  369. package/dist/chunk-YLJ4XMA6.js.map +0 -1
  370. package/dist/chunk-YNIWOYW6.js +0 -232
  371. package/dist/chunk-YNIWOYW6.js.map +0 -1
  372. package/dist/chunk-Z2XP767T.cjs +0 -35
  373. package/dist/chunk-Z2XP767T.cjs.map +0 -1
  374. package/dist/chunk-Z4X2RWOF.js +0 -37
  375. package/dist/chunk-Z4X2RWOF.js.map +0 -1
  376. package/dist/chunk-ZN6YYPIW.js +0 -67
  377. package/dist/chunk-ZN6YYPIW.js.map +0 -1
  378. package/dist/chunk-ZNFFTYWH.js +0 -1854
  379. package/dist/chunk-ZNFFTYWH.js.map +0 -1
  380. package/dist/variables.cjs +0 -17
  381. package/dist/variables.cjs.map +0 -1
  382. package/dist/variables.d.cts +0 -87
  383. package/dist/variables.d.ts +0 -87
  384. package/dist/variables.js +0 -4
  385. package/dist/variables.js.map +0 -1
@@ -1,3266 +0,0 @@
1
- import { VariableResolver } from './chunk-GCM5JHMX.js';
2
- import { sharedCurrencyExchange } from './chunk-BSPXMGIS.js';
3
- import { decimalFromInteger, toPolynomial, polyDegree, polyCoefficients, fromPolynomial, constNode, rationalDiv, rationalNeg, powNode, callNode, decimalCompare, isRationalZero, rationalMul, rationalSub, rationalAdd, rationalToNumber, rationalCompare, simplifySymbolic, sameShape, decimalFromNumberIfExact, decimalMultiply, decimalToNumber, decimalAdd, decimalNegate, cancelSymbolic, complexNode, complex, RATIONAL_ZERO, rationalFromNumber, freeVariables, symbolicToEntry, rowMajorToColumnMajor, expandSymbolic, matrixMultiply, inverse, determinant, transpose, matrixPower, exactIntegerSqrt, surdNode, rational, decimalIsZero, decimalDivide, decimalSubtract, decimalFromLiteral, decimalRound, substitute, varNode, isRationalOne, RATIONAL_ONE, polyUnivariateVar, COMPLEX_I, squareFreePart, makeDecimal, coefficientGcd, polynomialDivide, isZeroPolynomial, exactRationalSqrt, symbolicKey, compareMonomials, signedSurdNode, monomialFromKey, monomialToKey, exactIntegerCbrt } from './chunk-ZNFFTYWH.js';
4
- import { faultedOperand, errorValue, numberValueRational, numberValueUncertain, symbolicValue, numberValue, bigIntValue, uomValue, matrixValue, uomValueExact, splitValue, percentageValue, stringValue, hexValue } from './chunk-5EFKSKMA.js';
5
- import { getMeasure, convertUnit } from './chunk-MVTOCRV2.js';
6
- import { UNIT_TABLE } from './chunk-V4XG5QF6.js';
7
- import { ErrorFactory } from './chunk-N7OA4WPJ.js';
8
-
9
- // src/symbolic/MultivariateFactor.ts
10
- function exactRoot(value, degree) {
11
- const rootOf = degree === 2 ? exactIntegerSqrt : exactIntegerCbrt;
12
- const numerator = rootOf(value.n);
13
- const denominator = rootOf(value.d);
14
- return numerator === null || denominator === null ? null : { n: numerator, d: denominator };
15
- }
16
- function monomialRoot(key, degree) {
17
- const monomial = monomialFromKey(key);
18
- const root = /* @__PURE__ */ new Map();
19
- for (const [name, exponent] of monomial) {
20
- if (exponent % degree !== 0) return null;
21
- root.set(name, exponent / degree);
22
- }
23
- return monomialToKey(root);
24
- }
25
- function monomialMul(a, b) {
26
- const product2 = monomialFromKey(a);
27
- for (const [name, exponent] of monomialFromKey(b)) {
28
- product2.set(name, (product2.get(name) ?? 0) + exponent);
29
- }
30
- return monomialToKey(product2);
31
- }
32
- function monomialDiv(a, b) {
33
- const quotient = monomialFromKey(a);
34
- for (const [name, exponent] of monomialFromKey(b)) {
35
- const remaining = (quotient.get(name) ?? 0) - exponent;
36
- if (remaining <= 0) quotient.delete(name);
37
- else quotient.set(name, remaining);
38
- }
39
- return monomialToKey(quotient);
40
- }
41
- function monomialGcd(a, b) {
42
- const left = monomialFromKey(a);
43
- const shared = /* @__PURE__ */ new Map();
44
- for (const [name, exponent] of monomialFromKey(b)) {
45
- const other = left.get(name);
46
- if (other !== void 0) shared.set(name, Math.min(other, exponent));
47
- }
48
- return monomialToKey(shared);
49
- }
50
- function namesOf(keys) {
51
- const names = /* @__PURE__ */ new Set();
52
- for (const key of keys) for (const name of monomialFromKey(key).keys()) names.add(name);
53
- return [...names].sort();
54
- }
55
- function termsToNode(terms) {
56
- const map = /* @__PURE__ */ new Map();
57
- for (const term of terms) map.set(term.key, term.coefficient);
58
- return fromPolynomial({ terms: map, vars: namesOf(terms.map((term) => term.key)) });
59
- }
60
- function product(factors) {
61
- let result = factors[0];
62
- for (let i = 1; i < factors.length; i++) result = { kind: "mul", left: result, right: factors[i] };
63
- return result;
64
- }
65
- function orderedTerms(p) {
66
- const terms = [...p.terms].map(([key, coefficient]) => ({ key, coefficient }));
67
- return terms.sort((a, b) => compareMonomials(a.key, b.key, p.vars));
68
- }
69
- function factorMultivariate(p) {
70
- if (p.vars.length < 2) return null;
71
- const terms = orderedTerms(p);
72
- if (terms.length === 2) return factorBinomial(terms[0], terms[1]);
73
- if (terms.length === 3) return factorPerfectSquare(terms);
74
- if (terms.length === 4) return factorByGrouping(terms);
75
- return null;
76
- }
77
- function factorBinomial(first, second) {
78
- const firstPositive = first.coefficient.n > 0n;
79
- const secondPositive = second.coefficient.n > 0n;
80
- if (!firstPositive) return null;
81
- const squares = asPowerPair(first, second, 2);
82
- if (squares !== null && !secondPositive) {
83
- return product([
84
- termsToNode([squares.a, negated(squares.b)]),
85
- termsToNode([squares.a, squares.b])
86
- ]);
87
- }
88
- const cubes = asPowerPair(first, second, 3);
89
- if (cubes === null) return null;
90
- const linear = secondPositive ? termsToNode([cubes.a, cubes.b]) : termsToNode([cubes.a, negated(cubes.b)]);
91
- const middle = secondPositive ? negated(multiplyTerms(cubes.a, cubes.b)) : multiplyTerms(cubes.a, cubes.b);
92
- return product([linear, termsToNode([squareOf(cubes.a), middle, squareOf(cubes.b)])]);
93
- }
94
- function asPowerPair(first, second, degree) {
95
- const magnitude2 = second.coefficient.n < 0n ? rationalNeg(second.coefficient) : second.coefficient;
96
- const firstRoot = exactRoot(first.coefficient, degree);
97
- const secondRoot = exactRoot(magnitude2, degree);
98
- if (firstRoot === null || secondRoot === null) return null;
99
- const firstKey = monomialRoot(first.key, degree);
100
- const secondKey = monomialRoot(second.key, degree);
101
- if (firstKey === null || secondKey === null) return null;
102
- return { a: { key: firstKey, coefficient: firstRoot }, b: { key: secondKey, coefficient: secondRoot } };
103
- }
104
- function negated(term) {
105
- return { key: term.key, coefficient: rationalNeg(term.coefficient) };
106
- }
107
- function multiplyTerms(a, b) {
108
- return { key: monomialMul(a.key, b.key), coefficient: rationalMul(a.coefficient, b.coefficient) };
109
- }
110
- function squareOf(term) {
111
- return multiplyTerms(term, term);
112
- }
113
- function factorPerfectSquare(terms) {
114
- const [first, middle, last] = terms;
115
- if (first.coefficient.n < 0n || last.coefficient.n < 0n) return null;
116
- const roots = asPowerPair(first, last, 2);
117
- if (roots === null) return null;
118
- const cross = multiplyTerms(roots.a, roots.b);
119
- if (cross.key !== middle.key) return null;
120
- const twice = rationalMul(cross.coefficient, { n: 2n, d: 1n });
121
- const negative = middle.coefficient.n < 0n;
122
- const magnitude2 = negative ? rationalNeg(middle.coefficient) : middle.coefficient;
123
- if (!isRationalOne(rationalDiv(magnitude2, twice))) return null;
124
- const base = termsToNode([roots.a, negative ? negated(roots.b) : roots.b]);
125
- return { kind: "pow", base, exponent: constNode(2) };
126
- }
127
- function factorByGrouping(terms) {
128
- const pairings = [
129
- [[0, 1], [2, 3]],
130
- [[0, 2], [1, 3]],
131
- [[0, 3], [1, 2]]
132
- ];
133
- for (const pairing of pairings) {
134
- const first = splitPair(terms[pairing[0][0]], terms[pairing[0][1]]);
135
- const second = splitPair(terms[pairing[1][0]], terms[pairing[1][1]]);
136
- if (first === null || second === null) continue;
137
- if (!cofactorsAgree(first.cofactor, second.cofactor)) continue;
138
- return product([
139
- termsToNode([first.common, second.common]),
140
- termsToNode(first.cofactor)
141
- ]);
142
- }
143
- return null;
144
- }
145
- function splitPair(first, second) {
146
- const shared = monomialGcd(first.key, second.key);
147
- const common = { key: shared, coefficient: first.coefficient };
148
- const cofactor = [
149
- { key: monomialDiv(first.key, shared), coefficient: { n: 1n, d: 1n } },
150
- { key: monomialDiv(second.key, shared), coefficient: rationalDiv(second.coefficient, first.coefficient) }
151
- ];
152
- return cofactor[0].key === cofactor[1].key ? null : { common, cofactor };
153
- }
154
- function cofactorsAgree(a, b) {
155
- if (a.length !== b.length) return false;
156
- return a.every((term, index) => term.key === b[index].key && term.coefficient.n === b[index].coefficient.n && term.coefficient.d === b[index].coefficient.d);
157
- }
158
-
159
- // src/symbolic/Factor.ts
160
- var FACTOR_MAX_DEGREE = 12;
161
- var FACTOR_MAX_ROOT_CANDIDATES = 4096;
162
- function gcd(a, b) {
163
- let x = a < 0n ? -a : a;
164
- let y = b < 0n ? -b : b;
165
- while (y !== 0n) {
166
- const remainder = x % y;
167
- x = y;
168
- y = remainder;
169
- }
170
- return x;
171
- }
172
- function lcm(a, b) {
173
- if (a === 0n || b === 0n) return 0n;
174
- return a / gcd(a, b) * b;
175
- }
176
- function divisors(value) {
177
- const magnitude2 = value < 0n ? -value : value;
178
- if (magnitude2 === 0n) return null;
179
- const found = [];
180
- for (let candidate = 1n; candidate * candidate <= magnitude2; candidate++) {
181
- if (magnitude2 % candidate !== 0n) continue;
182
- found.push(candidate);
183
- const paired = magnitude2 / candidate;
184
- if (paired !== candidate) found.push(paired);
185
- if (found.length > FACTOR_MAX_ROOT_CANDIDATES) return null;
186
- }
187
- return found;
188
- }
189
- function evaluateAt(descending, x) {
190
- let total = RATIONAL_ZERO;
191
- for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
192
- return total;
193
- }
194
- function divideByRoot(descending, root) {
195
- const quotient = [descending[0]];
196
- for (let i = 1; i < descending.length - 1; i++) {
197
- quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
198
- }
199
- return quotient;
200
- }
201
- function rationalRoots(descending) {
202
- if (descending.length < 2) return [];
203
- let multiplier = 1n;
204
- for (const coeff of descending) multiplier = lcm(multiplier, coeff.d);
205
- const integers = descending.map((coeff) => coeff.n * multiplier / coeff.d);
206
- const leading = integers[0];
207
- const trailing = integers[integers.length - 1];
208
- if (trailing === 0n) return [];
209
- const numeratorDivisors = divisors(trailing);
210
- const denominatorDivisors = divisors(leading);
211
- if (numeratorDivisors === null || denominatorDivisors === null) {
212
- throw ErrorFactory.execution(
213
- "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
214
- "This polynomial's coefficients have too many divisors to search for rational roots.",
215
- { limit: FACTOR_MAX_ROOT_CANDIDATES }
216
- );
217
- }
218
- if (numeratorDivisors.length * denominatorDivisors.length > FACTOR_MAX_ROOT_CANDIDATES) {
219
- throw ErrorFactory.execution(
220
- "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
221
- "This polynomial has too many candidate rational roots to test.",
222
- { limit: FACTOR_MAX_ROOT_CANDIDATES }
223
- );
224
- }
225
- const roots = [];
226
- const seen = /* @__PURE__ */ new Set();
227
- for (const p of numeratorDivisors) {
228
- for (const q of denominatorDivisors) {
229
- for (const sign of [1n, -1n]) {
230
- const candidate = { n: sign * p / gcd(p, q), d: q / gcd(p, q) };
231
- const key = `${candidate.n}/${candidate.d}`;
232
- if (seen.has(key)) continue;
233
- seen.add(key);
234
- if (isRationalZero(evaluateAt(descending, candidate))) roots.push(candidate);
235
- }
236
- }
237
- }
238
- return roots;
239
- }
240
- function linearFactorNode(variable, root) {
241
- if (isRationalZero(root)) return varNode(variable);
242
- return root.n > 0n ? { kind: "sub", left: varNode(variable), right: constNode(root) } : { kind: "add", left: varNode(variable), right: constNode(rationalNeg(root)) };
243
- }
244
- function coefficientsToNode(descending, variable) {
245
- const degree = descending.length - 1;
246
- const terms = /* @__PURE__ */ new Map();
247
- descending.forEach((coeff, index) => {
248
- if (isRationalZero(coeff)) return;
249
- const power3 = degree - index;
250
- terms.set(power3 === 0 ? "" : power3 === 1 ? variable : `${variable}^${power3}`, coeff);
251
- });
252
- return fromPolynomial({ terms, vars: terms.size > 0 ? [variable] : [] });
253
- }
254
- function factorUnivariate(descending, variable) {
255
- const factors = [];
256
- let remaining = [...descending];
257
- let roots = rationalRoots(remaining);
258
- while (roots.length > 0 && remaining.length > 2) {
259
- for (const root of roots) {
260
- let multiplicity = 0;
261
- while (remaining.length > 1 && isRationalZero(evaluateAt(remaining, root))) {
262
- remaining = divideByRoot(remaining, root);
263
- multiplicity++;
264
- }
265
- if (multiplicity > 0) factors.push({ base: linearFactorNode(variable, root), power: multiplicity });
266
- }
267
- roots = remaining.length > 2 ? rationalRoots(remaining) : [];
268
- }
269
- const leftoverDegree = remaining.length - 1;
270
- if (leftoverDegree >= 1) {
271
- factors.push({ base: coefficientsToNode(remaining, variable), power: 1 });
272
- return { content: RATIONAL_ONE, factors };
273
- }
274
- return { content: remaining.length === 1 ? remaining[0] : RATIONAL_ONE, factors };
275
- }
276
- function factorizationToNode(factorization) {
277
- const pieces = [];
278
- if (!isRationalOne(factorization.content)) pieces.push(constNode(factorization.content));
279
- for (const factor of factorization.factors) {
280
- pieces.push(factor.power === 1 ? factor.base : powNode(factor.base, constNode({ n: BigInt(factor.power), d: 1n })));
281
- }
282
- if (pieces.length === 0) return constNode(RATIONAL_ONE);
283
- let result = pieces[0];
284
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
285
- return result;
286
- }
287
- function contentOf(p) {
288
- let numeratorGcd = 0n;
289
- let denominatorLcm = 1n;
290
- for (const coeff of p.terms.values()) {
291
- numeratorGcd = gcd(numeratorGcd, coeff.n);
292
- denominatorLcm = lcm(denominatorLcm, coeff.d);
293
- }
294
- if (numeratorGcd === 0n) return RATIONAL_ONE;
295
- return { n: numeratorGcd, d: denominatorLcm };
296
- }
297
- function extractCommonMonomial(p) {
298
- const common = /* @__PURE__ */ new Map();
299
- for (const name of p.vars) {
300
- let lowest = Infinity;
301
- for (const key of p.terms.keys()) {
302
- const exponent = exponentOf(key, name);
303
- if (exponent < lowest) lowest = exponent;
304
- }
305
- if (lowest > 0 && lowest !== Infinity) common.set(name, lowest);
306
- }
307
- if (common.size === 0) return { monomial: common, reduced: p };
308
- const terms = /* @__PURE__ */ new Map();
309
- for (const [key, coeff] of p.terms) {
310
- const exponents = parseKey(key);
311
- for (const [name, shared] of common) exponents.set(name, (exponents.get(name) ?? 0) - shared);
312
- terms.set(buildKey(exponents), coeff);
313
- }
314
- const names = /* @__PURE__ */ new Set();
315
- for (const key of terms.keys()) for (const name of parseKey(key).keys()) names.add(name);
316
- return { monomial: common, reduced: { terms, vars: [...names].sort() } };
317
- }
318
- function exponentOf(key, name) {
319
- return parseKey(key).get(name) ?? 0;
320
- }
321
- function parseKey(key) {
322
- const exponents = /* @__PURE__ */ new Map();
323
- if (key === "") return exponents;
324
- for (const factor of key.split("*")) {
325
- const caret = factor.indexOf("^");
326
- if (caret === -1) exponents.set(factor, 1);
327
- else exponents.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));
328
- }
329
- return exponents;
330
- }
331
- function buildKey(exponents) {
332
- const names = [...exponents.keys()].filter((name) => (exponents.get(name) ?? 0) > 0).sort();
333
- return names.map((name) => exponents.get(name) === 1 ? name : `${name}^${exponents.get(name)}`).join("*");
334
- }
335
- function monomialNode(monomial) {
336
- const names = [...monomial.keys()].sort();
337
- let result = null;
338
- for (const name of names) {
339
- const exponent = monomial.get(name);
340
- const factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));
341
- result = result === null ? factor : { kind: "mul", left: result, right: factor };
342
- }
343
- return result;
344
- }
345
- function factorSymbolic(node) {
346
- const polynomial = toPolynomial(node);
347
- if (polynomial === null || polynomial.terms.size === 0) return node;
348
- if (polyDegree(polynomial) > FACTOR_MAX_DEGREE) return node;
349
- if (polynomial.vars.length === 0) return node;
350
- const content = contentOf(polynomial);
351
- const primitive = isRationalOne(content) ? polynomial : scaleTerms(polynomial, rationalDiv(RATIONAL_ONE, content));
352
- const { monomial, reduced } = extractCommonMonomial(primitive);
353
- const monomialFactor = monomialNode(monomial);
354
- const variable = polyUnivariateVar(reduced);
355
- if (variable === null) {
356
- const patterned = factorMultivariate(reduced);
357
- if (patterned !== null) return assemble(content, monomialFactor, patterned);
358
- const pieces2 = buildPieces(content, monomialFactor, reduced);
359
- return pieces2 ?? node;
360
- }
361
- const descending = [...polyCoefficients(reduced, variable)].reverse();
362
- const factorization = factorUnivariate(descending, variable);
363
- const combinedContent = rationalMul(content, factorization.content);
364
- const isUnchanged = factorization.factors.length <= 1 && (factorization.factors[0]?.power ?? 1) === 1 && monomialFactor === null && isRationalOne(combinedContent);
365
- if (isUnchanged) return node;
366
- const pieces = [];
367
- if (!isRationalOne(combinedContent)) pieces.push(constNode(combinedContent));
368
- if (monomialFactor !== null) pieces.push(monomialFactor);
369
- pieces.push(factorizationToNode({ content: RATIONAL_ONE, factors: factorization.factors }));
370
- let result = pieces[0];
371
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
372
- return result;
373
- }
374
- function scaleTerms(p, k) {
375
- const terms = /* @__PURE__ */ new Map();
376
- for (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));
377
- return { terms, vars: p.vars };
378
- }
379
- function assemble(content, monomialFactor, factored) {
380
- const pieces = [];
381
- if (!isRationalOne(content)) pieces.push(constNode(content));
382
- if (monomialFactor !== null) pieces.push(monomialFactor);
383
- pieces.push(factored);
384
- let result = pieces[0];
385
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
386
- return result;
387
- }
388
- function buildPieces(content, monomialFactor, reduced) {
389
- if (monomialFactor === null && isRationalOne(content)) return null;
390
- const pieces = [];
391
- if (!isRationalOne(content)) pieces.push(constNode(content));
392
- if (monomialFactor !== null) pieces.push(monomialFactor);
393
- pieces.push(fromPolynomial(reduced));
394
- let result = pieces[0];
395
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
396
- return result;
397
- }
398
-
399
- // src/symbolic/CubicQuartic.ts
400
- var TWO = { n: 2n, d: 1n };
401
- var THREE = { n: 3n, d: 1n };
402
- var FOUR = { n: 4n, d: 1n };
403
- function depressCubic(a, b, c, d) {
404
- const shift = rationalNeg(rationalDiv(b, rationalMul(THREE, a)));
405
- const p = rationalDiv(
406
- rationalSub(rationalMul(THREE, rationalMul(a, c)), rationalMul(b, b)),
407
- rationalMul(THREE, rationalMul(a, a))
408
- );
409
- const twoBCubed = rationalMul(TWO, rationalMul(b, rationalMul(b, b)));
410
- const nineABC = rationalMul({ n: 9n, d: 1n }, rationalMul(a, rationalMul(b, c)));
411
- const twentySevenAAD = rationalMul({ n: 27n, d: 1n }, rationalMul(rationalMul(a, a), d));
412
- const q = rationalDiv(
413
- rationalAdd(rationalSub(twoBCubed, nineABC), twentySevenAAD),
414
- rationalMul({ n: 27n, d: 1n }, rationalMul(a, rationalMul(a, a)))
415
- );
416
- return { p, q, shift };
417
- }
418
- function solveCubic(a, b, c, d) {
419
- const { p, q, shift } = depressCubic(a, b, c, d);
420
- const discriminant = rationalNeg(
421
- rationalAdd(
422
- rationalMul(FOUR, rationalMul(p, rationalMul(p, p))),
423
- rationalMul({ n: 27n, d: 1n }, rationalMul(q, q))
424
- )
425
- );
426
- if (rationalCompare(discriminant, RATIONAL_ZERO) > 0) {
427
- return { exact: [], approximate: trigonometricRoots(p, q, shift) };
428
- }
429
- if (isRationalZero(discriminant)) return { exact: repeatedCubicRoots(p, q, shift), approximate: [] };
430
- return { exact: cardanoRoots(p, q, shift), approximate: [] };
431
- }
432
- function repeatedCubicRoots(p, q, shift) {
433
- if (isRationalZero(p)) return [constNode(shift)];
434
- const simple = rationalAdd(rationalDiv(rationalMul(THREE, q), p), shift);
435
- const repeated = rationalAdd(rationalNeg(rationalDiv(rationalMul(THREE, q), rationalMul(TWO, p))), shift);
436
- const ordered = [simple, repeated].sort(rationalCompare);
437
- return ordered.map(constNode);
438
- }
439
- function cardanoRoots(p, q, shift) {
440
- const half = rationalNeg(rationalDiv(q, TWO));
441
- const radicand = rationalAdd(
442
- rationalMul(rationalDiv(q, TWO), rationalDiv(q, TWO)),
443
- rationalMul(rationalDiv(p, THREE), rationalMul(rationalDiv(p, THREE), rationalDiv(p, THREE)))
444
- );
445
- const inner = surdNode(radicand);
446
- const u = { kind: "call", name: "cbrt", args: [{ kind: "add", left: constNode(half), right: inner }] };
447
- const v = { kind: "call", name: "cbrt", args: [{ kind: "sub", left: constNode(half), right: inner }] };
448
- const sum = { kind: "add", left: u, right: v };
449
- const difference = { kind: "sub", left: u, right: v };
450
- const real = { kind: "add", left: constNode(shift), right: { kind: "div", left: { kind: "neg", operand: sum }, right: constNode(TWO) } };
451
- const imaginary = {
452
- kind: "mul",
453
- left: { kind: "div", left: { kind: "mul", left: difference, right: surdNode(THREE) }, right: constNode(TWO) },
454
- right: complexNode(COMPLEX_I)
455
- };
456
- return [
457
- { kind: "add", left: constNode(shift), right: sum },
458
- { kind: "sub", left: real, right: imaginary },
459
- { kind: "add", left: real, right: imaginary }
460
- ];
461
- }
462
- function trigonometricRoots(p, q, shift) {
463
- const pNumber = rationalToNumber(p);
464
- const qNumber = rationalToNumber(q);
465
- const shiftNumber = rationalToNumber(shift);
466
- const magnitude2 = 2 * Math.sqrt(-pNumber / 3);
467
- const ratio = 3 * qNumber / (2 * pNumber) * Math.sqrt(-3 / pNumber);
468
- const angle = Math.acos(Math.min(1, Math.max(-1, ratio))) / 3;
469
- return [0, 1, 2].map((k) => magnitude2 * Math.cos(angle - 2 * Math.PI * k / 3) + shiftNumber).sort((left, right) => left - right);
470
- }
471
- function depressQuartic(b, c, d, e) {
472
- const shift = rationalNeg(rationalDiv(b, FOUR));
473
- const bb = rationalMul(b, b);
474
- const p = rationalSub(c, rationalDiv(rationalMul(THREE, bb), { n: 8n, d: 1n }));
475
- const q = rationalAdd(
476
- rationalSub(d, rationalDiv(rationalMul(b, c), TWO)),
477
- rationalDiv(rationalMul(bb, b), { n: 8n, d: 1n })
478
- );
479
- const r = rationalSub(
480
- rationalAdd(
481
- rationalSub(e, rationalDiv(rationalMul(b, d), FOUR)),
482
- rationalDiv(rationalMul(bb, c), { n: 16n, d: 1n })
483
- ),
484
- rationalDiv(rationalMul(THREE, rationalMul(bb, bb)), { n: 256n, d: 1n })
485
- );
486
- return { p, q, r, shift };
487
- }
488
- function solveQuartic(a, b, c, d, e, solveQuadratic2) {
489
- const monic = (value) => rationalDiv(value, a);
490
- const { p, q, r, shift } = depressQuartic(monic(b), monic(c), monic(d), monic(e));
491
- const roots = isRationalZero(q) ? biquadraticRoots(p, r) : splitQuarticRoots(p, q, r, solveQuadratic2);
492
- if (roots === null) return null;
493
- const shifted = isRationalZero(shift) ? roots : roots.map((root) => ({ kind: "add", left: constNode(shift), right: root }));
494
- return { exact: distinct(shifted), approximate: [] };
495
- }
496
- function distinct(roots) {
497
- const seen = /* @__PURE__ */ new Set();
498
- const unique = [];
499
- for (const root of roots) {
500
- const key = symbolicKey(simplifySymbolic(root));
501
- if (seen.has(key)) continue;
502
- seen.add(key);
503
- unique.push(root);
504
- }
505
- return unique;
506
- }
507
- function biquadraticRoots(p, r) {
508
- const discriminant = rationalSub(rationalMul(p, p), rationalMul(FOUR, r));
509
- if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) return complexBiquadraticRoots(p, r);
510
- const root = exactRationalSqrt(discriminant);
511
- if (root !== null) return rationalSquareRoots(rationalNeg(p), root, isRationalZero(discriminant));
512
- return nestedSquareRoots(p, r, discriminant);
513
- }
514
- function rationalSquareRoots(negatedP, root, repeated) {
515
- const values = repeated ? [rationalDiv(negatedP, TWO)] : [rationalDiv(rationalAdd(negatedP, root), TWO), rationalDiv(rationalSub(negatedP, root), TWO)];
516
- const roots = [];
517
- for (const value of values) {
518
- if (isRationalZero(value)) {
519
- roots.push(constNode(RATIONAL_ZERO));
520
- continue;
521
- }
522
- const square = signedSurdNode(value);
523
- roots.push({ kind: "neg", operand: square }, square);
524
- }
525
- return roots;
526
- }
527
- function nestedSquareRoots(p, r, discriminant) {
528
- const negatedP = constNode(rationalNeg(p));
529
- const surd = surdNode(discriminant);
530
- const negativeP = rationalCompare(p, RATIONAL_ZERO) <= 0;
531
- const solutions = [
532
- { node: halved({ kind: "add", left: negatedP, right: surd }), positive: negativeP || rationalCompare(r, RATIONAL_ZERO) <= 0 },
533
- { node: halved({ kind: "sub", left: negatedP, right: surd }), positive: negativeP && rationalCompare(r, RATIONAL_ZERO) >= 0 }
534
- ];
535
- const roots = [];
536
- for (const { node, positive } of solutions) {
537
- const radicand = positive ? node : { kind: "neg", operand: node };
538
- const magnitude2 = { kind: "call", name: "sqrt", args: [radicand] };
539
- const square = positive ? magnitude2 : { kind: "mul", left: magnitude2, right: complexNode(COMPLEX_I) };
540
- roots.push({ kind: "neg", operand: square }, square);
541
- }
542
- return roots;
543
- }
544
- function halved(node) {
545
- return { kind: "div", left: node, right: constNode(TWO) };
546
- }
547
- function complexBiquadraticRoots(p, r) {
548
- const centre = rationalDiv(rationalNeg(p), TWO);
549
- const modulus = exactRationalSqrt(r);
550
- const re = modulus === null ? nestedSurd(surdNode(r), centre) : surdNode(rationalDiv(rationalAdd(modulus, centre), TWO));
551
- const imaginaryMagnitude = modulus === null ? nestedSurd(surdNode(r), rationalNeg(centre)) : surdNode(rationalDiv(rationalSub(modulus, centre), TWO));
552
- const im = { kind: "mul", left: imaginaryMagnitude, right: complexNode(COMPLEX_I) };
553
- const first = { kind: "add", left: re, right: im };
554
- const second = { kind: "sub", left: re, right: im };
555
- return [
556
- { kind: "neg", operand: first },
557
- { kind: "neg", operand: second },
558
- second,
559
- first
560
- ];
561
- }
562
- function nestedSurd(surd, offset) {
563
- const shifted = offset.n >= 0n ? { kind: "add", left: surd, right: constNode(offset) } : { kind: "sub", left: surd, right: constNode(rationalNeg(offset)) };
564
- return { kind: "call", name: "sqrt", args: [halved(shifted)] };
565
- }
566
- function splitQuarticRoots(p, q, r, solveQuadratic2) {
567
- const resolvent = [
568
- { n: 1n, d: 1n },
569
- rationalMul(TWO, p),
570
- rationalSub(rationalMul(p, p), rationalMul(FOUR, r)),
571
- rationalNeg(rationalMul(q, q))
572
- ];
573
- for (const z of rationalRoots(resolvent)) {
574
- if (rationalCompare(z, RATIONAL_ZERO) <= 0) continue;
575
- const alpha = exactRationalSqrt(z);
576
- if (alpha === null) continue;
577
- const sum = rationalAdd(p, z);
578
- const difference = rationalDiv(q, alpha);
579
- const beta = rationalDiv(rationalSub(sum, difference), TWO);
580
- const gamma = rationalDiv(rationalAdd(sum, difference), TWO);
581
- const one2 = { n: 1n, d: 1n };
582
- return [
583
- ...solveQuadratic2(one2, alpha, beta),
584
- ...solveQuadratic2(one2, rationalNeg(alpha), gamma)
585
- ];
586
- }
587
- return null;
588
- }
589
-
590
- // src/symbolic/NumericRoots.ts
591
- var DURAND_KERNER_MAX_ITERATIONS = 200;
592
- var DURAND_KERNER_TOLERANCE = 1e-14;
593
- var ROOT_RESIDUAL_TOLERANCE = 1e-10;
594
- var ROOT_SEPARATION_TOLERANCE = 1e-10;
595
- var AXIS_SNAP_TOLERANCE = 1e-9;
596
- var CONJUGATE_PAIR_TOLERANCE = 1e-8;
597
- var NEWTON_POLISH_STEPS = 4;
598
- function subtract(a, b) {
599
- return { re: a.re - b.re, im: a.im - b.im };
600
- }
601
- function multiply(a, b) {
602
- return { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re };
603
- }
604
- function divide(a, b) {
605
- if (Math.abs(b.re) >= Math.abs(b.im)) {
606
- const ratio2 = b.im / b.re;
607
- const denominator2 = b.re + b.im * ratio2;
608
- return { re: (a.re + a.im * ratio2) / denominator2, im: (a.im - a.re * ratio2) / denominator2 };
609
- }
610
- const ratio = b.re / b.im;
611
- const denominator = b.re * ratio + b.im;
612
- return { re: (a.re * ratio + a.im) / denominator, im: (a.im * ratio - a.re) / denominator };
613
- }
614
- function magnitude(z) {
615
- return Math.hypot(z.re, z.im);
616
- }
617
- function evaluateAt2(descending, z) {
618
- let re = 0;
619
- let im = 0;
620
- for (const coefficient of descending) {
621
- const nextRe = re * z.re - im * z.im + coefficient;
622
- im = re * z.im + im * z.re;
623
- re = nextRe;
624
- }
625
- return { re, im };
626
- }
627
- function evaluationScale(descending, z) {
628
- const radius = magnitude(z);
629
- let total = 0;
630
- for (const coefficient of descending) total = total * radius + Math.abs(coefficient);
631
- return total;
632
- }
633
- function differentiate(descending) {
634
- const degree = descending.length - 1;
635
- const derivative = [];
636
- for (let i = 0; i < degree; i++) derivative.push(descending[i] * (degree - i));
637
- return derivative;
638
- }
639
- function squareFreeDoubles(descending) {
640
- const ascending = [...descending].reverse();
641
- const squareFree = [...squareFreePart(ascending)].reverse();
642
- const doubles = squareFree.map(rationalToNumber);
643
- if (doubles.some((value) => !Number.isFinite(value))) return null;
644
- return doubles;
645
- }
646
- function initialEstimates(monic) {
647
- const degree = monic.length - 1;
648
- let largest = 0;
649
- for (let i = 1; i < monic.length; i++) largest = Math.max(largest, Math.abs(monic[i]));
650
- const radius = 1 + largest;
651
- const centre = -monic[1] / degree;
652
- const estimates = [];
653
- for (let k = 0; k < degree; k++) {
654
- const angle = 2 * Math.PI * k / degree + Math.PI / (2 * degree);
655
- estimates.push({ re: centre + radius * Math.cos(angle), im: radius * Math.sin(angle) });
656
- }
657
- return estimates;
658
- }
659
- function durandKerner(monic) {
660
- const degree = monic.length - 1;
661
- const estimates = initialEstimates(monic);
662
- for (let iteration = 0; iteration < DURAND_KERNER_MAX_ITERATIONS; iteration++) {
663
- let largestStep = 0;
664
- let largestRoot = 1;
665
- for (let i = 0; i < degree; i++) {
666
- let denominator = { re: 1, im: 0 };
667
- for (let j = 0; j < degree; j++) {
668
- if (i !== j) denominator = multiply(denominator, subtract(estimates[i], estimates[j]));
669
- }
670
- if (denominator.re === 0 && denominator.im === 0) {
671
- estimates[i] = { re: estimates[i].re + 1e-6 * (i + 1), im: estimates[i].im + 1e-6 };
672
- continue;
673
- }
674
- const step = divide(evaluateAt2(monic, estimates[i]), denominator);
675
- if (!Number.isFinite(step.re) || !Number.isFinite(step.im)) return null;
676
- estimates[i] = subtract(estimates[i], step);
677
- largestStep = Math.max(largestStep, magnitude(step));
678
- largestRoot = Math.max(largestRoot, magnitude(estimates[i]));
679
- }
680
- if (largestStep <= DURAND_KERNER_TOLERANCE * largestRoot) return estimates;
681
- }
682
- return null;
683
- }
684
- function polish(monic, derivative, start) {
685
- let candidate = start;
686
- for (let step = 0; step < NEWTON_POLISH_STEPS; step++) {
687
- const slope = evaluateAt2(derivative, candidate);
688
- if (slope.re === 0 && slope.im === 0) break;
689
- const next = subtract(candidate, divide(evaluateAt2(monic, candidate), slope));
690
- if (!Number.isFinite(next.re) || !Number.isFinite(next.im)) break;
691
- candidate = next;
692
- }
693
- return candidate;
694
- }
695
- function snapToAxes(monic, derivative, z) {
696
- const scale2 = Math.max(1, magnitude(z));
697
- if (z.im !== 0 && Math.abs(z.im) <= AXIS_SNAP_TOLERANCE * scale2) {
698
- const candidate = polish(monic, derivative, { re: z.re, im: 0 });
699
- if (isRootWithinTolerance(monic, candidate)) return { re: candidate.re, im: 0 };
700
- }
701
- if (z.re !== 0 && Math.abs(z.re) <= AXIS_SNAP_TOLERANCE * scale2) {
702
- const candidate = polish(monic, derivative, { re: 0, im: z.im });
703
- if (isRootWithinTolerance(monic, candidate)) return { re: 0, im: candidate.im };
704
- }
705
- return z;
706
- }
707
- function isRootWithinTolerance(monic, z) {
708
- if (!Number.isFinite(z.re) || !Number.isFinite(z.im)) return false;
709
- return magnitude(evaluateAt2(monic, z)) <= ROOT_RESIDUAL_TOLERANCE * evaluationScale(monic, z);
710
- }
711
- function pairConjugates(roots) {
712
- const result = [...roots];
713
- const paired = result.map((root) => root.im === 0);
714
- for (let i = 0; i < result.length; i++) {
715
- if (paired[i]) continue;
716
- const wanted = { re: result[i].re, im: -result[i].im };
717
- let partner = -1;
718
- let closest = Number.POSITIVE_INFINITY;
719
- for (let j = i + 1; j < result.length; j++) {
720
- if (paired[j]) continue;
721
- const distance = magnitude(subtract(result[j], wanted));
722
- if (distance < closest) {
723
- closest = distance;
724
- partner = j;
725
- }
726
- }
727
- if (partner === -1 || closest > CONJUGATE_PAIR_TOLERANCE * Math.max(1, magnitude(result[i]))) continue;
728
- const re = (result[i].re + result[partner].re) / 2;
729
- const im = (Math.abs(result[i].im) + Math.abs(result[partner].im)) / 2;
730
- const sign = result[i].im < 0 ? -1 : 1;
731
- result[i] = { re, im: sign * im };
732
- result[partner] = { re, im: -sign * im };
733
- paired[i] = true;
734
- paired[partner] = true;
735
- }
736
- return result;
737
- }
738
- function allSeparated(roots) {
739
- for (let i = 0; i < roots.length; i++) {
740
- for (let j = i + 1; j < roots.length; j++) {
741
- const scale2 = Math.max(1, magnitude(roots[i]), magnitude(roots[j]));
742
- if (magnitude(subtract(roots[i], roots[j])) <= ROOT_SEPARATION_TOLERANCE * scale2) return false;
743
- }
744
- }
745
- return true;
746
- }
747
- function approximateRoots(descending) {
748
- const monic = squareFreeDoubles(descending);
749
- if (monic === null) return null;
750
- if (monic.length < 2) return [];
751
- const converged = durandKerner(monic);
752
- if (converged === null) return null;
753
- const derivative = differentiate(monic);
754
- const roots = pairConjugates(converged).map((root) => snapToAxes(monic, derivative, root));
755
- for (const root of roots) {
756
- if (!isRootWithinTolerance(monic, root)) return null;
757
- }
758
- if (!allSeparated(roots)) return null;
759
- return [...roots].sort((a, b) => a.re - b.re || a.im - b.im);
760
- }
761
-
762
- // src/symbolic/Solve.ts
763
- var SOLVE_MAX_DEGREE = 8;
764
- function evaluateRational(descending, x) {
765
- let total = RATIONAL_ZERO;
766
- for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
767
- return total;
768
- }
769
- function divideByRoot2(descending, root) {
770
- const quotient = [descending[0]];
771
- for (let i = 1; i < descending.length - 1; i++) {
772
- quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
773
- }
774
- return quotient;
775
- }
776
- function solveQuadratic(a, b, c) {
777
- const discriminant = rationalSub(rationalMul(b, b), rationalMul(rational4(), rationalMul(a, c)));
778
- const twoA = rationalMul(rational2(), a);
779
- if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) {
780
- return complexQuadraticRoots(rationalNeg(b), discriminant, twoA);
781
- }
782
- if (isRationalZero(discriminant)) return [constNode(rationalDiv(rationalNeg(b), twoA))];
783
- const rootN = exactIntegerSqrt(discriminant.n);
784
- const rootD = exactIntegerSqrt(discriminant.d);
785
- if (rootN !== null && rootD !== null) {
786
- const root = { n: rootN, d: rootD };
787
- const plus = rationalDiv(rationalAdd(rationalNeg(b), root), twoA);
788
- const minus = rationalDiv(rationalSub(rationalNeg(b), root), twoA);
789
- return rationalCompare(minus, plus) <= 0 ? [constNode(minus), constNode(plus)] : [constNode(plus), constNode(minus)];
790
- }
791
- const surd = surdNode(discriminant);
792
- const ascending = rationalCompare(twoA, RATIONAL_ZERO) > 0;
793
- const lower = { kind: "div", left: { kind: "sub", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
794
- const upper = { kind: "div", left: { kind: "add", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
795
- return ascending ? [lower, upper] : [upper, lower];
796
- }
797
- function complexQuadraticRoots(negatedB, discriminant, twoA) {
798
- const magnitude2 = rationalNeg(discriminant);
799
- const rootN = exactIntegerSqrt(magnitude2.n);
800
- const rootD = exactIntegerSqrt(magnitude2.d);
801
- if (rootN !== null && rootD !== null) {
802
- const imaginary2 = rationalDiv({ n: rootN, d: rootD }, twoA);
803
- const real2 = rationalDiv(negatedB, twoA);
804
- return [
805
- complexNode(complex(real2, rationalNeg(imaginary2))),
806
- complexNode(complex(real2, imaginary2))
807
- ];
808
- }
809
- const real = rationalDiv(negatedB, twoA);
810
- const scaledRadicand = rationalDiv(magnitude2, rationalMul(twoA, twoA));
811
- const imaginary = { kind: "mul", left: surdNode(scaledRadicand), right: complexNode(COMPLEX_I) };
812
- if (isRationalZero(real)) {
813
- return [{ kind: "neg", operand: imaginary }, imaginary];
814
- }
815
- return [
816
- { kind: "sub", left: constNode(real), right: imaginary },
817
- { kind: "add", left: constNode(real), right: imaginary }
818
- ];
819
- }
820
- function rational2() {
821
- return { n: 2n, d: 1n };
822
- }
823
- function rational4() {
824
- return { n: 4n, d: 1n };
825
- }
826
- function realApproximation(value) {
827
- return { re: value, im: 0 };
828
- }
829
- function solveForVariable(lhs, rhs, variable) {
830
- const polynomial = toPolynomial({ kind: "sub", left: lhs, right: rhs });
831
- if (polynomial === null) {
832
- return {
833
- kind: "unsupported",
834
- reason: "this is not a polynomial equation (it divides by an unknown, or calls a function of one)"
835
- };
836
- }
837
- const others = polynomial.vars.filter((name) => name !== variable);
838
- const degree = polyDegree(polynomial, variable);
839
- if (others.length > 0) {
840
- if (degree !== 1) {
841
- return {
842
- kind: "unsupported",
843
- reason: `solving for "${variable}" needs the equation to be linear in it when other unknowns (${others.join(", ")}) are present`
844
- };
845
- }
846
- return solveLinearWithOtherUnknowns(polynomial, variable);
847
- }
848
- if (degree === 0) {
849
- return polynomial.terms.size === 0 ? { kind: "identity" } : { kind: "contradiction" };
850
- }
851
- if (degree > SOLVE_MAX_DEGREE) {
852
- return { kind: "unsupported", reason: `degree ${degree} is above the supported maximum of ${SOLVE_MAX_DEGREE}` };
853
- }
854
- const descending = [...polyCoefficients(polynomial, variable)].reverse();
855
- return solveUnivariate(descending);
856
- }
857
- function solveLinearWithOtherUnknowns(polynomial, variable) {
858
- const coefficientTerms = /* @__PURE__ */ new Map();
859
- const constantTerms = /* @__PURE__ */ new Map();
860
- for (const [key, coeff] of polynomial.terms) {
861
- const factors = key.split("*").filter((part) => part.length > 0);
862
- const index = factors.indexOf(variable);
863
- if (index === -1) {
864
- constantTerms.set(key, coeff);
865
- } else {
866
- factors.splice(index, 1);
867
- coefficientTerms.set(factors.join("*"), coeff);
868
- }
869
- }
870
- const namesOf2 = (terms) => {
871
- const names = /* @__PURE__ */ new Set();
872
- for (const key of terms.keys()) {
873
- for (const part of key.split("*")) {
874
- if (part.length > 0) names.add(part.split("^")[0]);
875
- }
876
- }
877
- return [...names].sort();
878
- };
879
- const coefficient = fromPolynomial({ terms: coefficientTerms, vars: namesOf2(coefficientTerms) });
880
- const constant = fromPolynomial({ terms: constantTerms, vars: namesOf2(constantTerms) });
881
- return {
882
- kind: "roots",
883
- exact: [{ kind: "div", left: { kind: "neg", operand: constant }, right: coefficient }],
884
- approximate: []
885
- };
886
- }
887
- function closedFormRoots(descending) {
888
- if (descending.length === 4) {
889
- return solveCubic(descending[0], descending[1], descending[2], descending[3]);
890
- }
891
- if (descending.length === 5) {
892
- return solveQuartic(descending[0], descending[1], descending[2], descending[3], descending[4], solveQuadratic);
893
- }
894
- return null;
895
- }
896
- function extractRationalRoots(descending) {
897
- const roots = [];
898
- let remaining = [...descending];
899
- let powersOfX = 0;
900
- while (remaining.length > 1 && isRationalZero(remaining[remaining.length - 1])) {
901
- remaining = remaining.slice(0, -1);
902
- powersOfX++;
903
- }
904
- if (powersOfX > 0) roots.push(RATIONAL_ZERO);
905
- while (remaining.length > 1) {
906
- const found = rationalRoots(remaining);
907
- if (found.length === 0) break;
908
- for (const root of found) {
909
- let multiplicity = 0;
910
- while (remaining.length > 1 && isRationalZero(evaluateRational(remaining, root))) {
911
- remaining = divideByRoot2(remaining, root);
912
- multiplicity++;
913
- }
914
- if (multiplicity > 0) roots.push(root);
915
- }
916
- }
917
- return { roots: roots.sort(rationalCompare), remaining };
918
- }
919
- function solveUnivariate(descending) {
920
- const { roots, remaining } = extractRationalRoots(descending);
921
- const exact = roots.map(constNode);
922
- const approximate = [];
923
- const leftoverDegree = remaining.length - 1;
924
- const solvedDegree = descending.length - remaining.length;
925
- if (leftoverDegree <= 0) return finish(exact, approximate, solvedDegree, 0, "");
926
- if (leftoverDegree === 1) {
927
- exact.push(constNode(rationalDiv(rationalNeg(remaining[1]), remaining[0])));
928
- return finish(exact, approximate, solvedDegree + 1, 0, "");
929
- }
930
- if (leftoverDegree === 2) {
931
- exact.push(...solveQuadratic(remaining[0], remaining[1], remaining[2]));
932
- return finish(exact, approximate, solvedDegree + 2, 0, "");
933
- }
934
- const closedForm = closedFormRoots(remaining);
935
- if (closedForm !== null) {
936
- exact.push(...closedForm.exact);
937
- approximate.push(...closedForm.approximate.map(realApproximation));
938
- return finish(exact, approximate, solvedDegree + leftoverDegree, 0, "");
939
- }
940
- const numeric = approximateRoots(remaining);
941
- if (numeric !== null) {
942
- approximate.push(...numeric);
943
- return finish(exact, approximate, solvedDegree + leftoverDegree, 0, "");
944
- }
945
- return finish(
946
- exact,
947
- approximate,
948
- solvedDegree,
949
- leftoverDegree,
950
- `a degree-${leftoverDegree} factor of it has no exact solution here and the numerical method did not converge on that factor`
951
- );
952
- }
953
- function finish(exact, approximate, solvedDegree, unsolvedDegree, reason) {
954
- const found = exact.length + approximate.length;
955
- const incoherent = solvedDegree >= 1 && (found < 1 || found > solvedDegree);
956
- if (unsolvedDegree > 0 || incoherent) {
957
- return {
958
- kind: "incomplete",
959
- exact,
960
- approximate,
961
- // A distinct root can stand for several equal ones, so the count found
962
- // is a lower bound on what it covers. The degree left unsolved is not.
963
- missing: incoherent ? Math.max(1, solvedDegree + unsolvedDegree - found) : unsolvedDegree,
964
- reason: incoherent ? `${found} root${found === 1 ? "" : "s"} were produced for a degree-${solvedDegree + unsolvedDegree} equation, which does not add up` : reason
965
- };
966
- }
967
- return { kind: "roots", exact, approximate };
968
- }
969
-
970
- // src/vm/SymbolicOps.ts
971
- var SYMBOLIC_BUILTIN_NAMES = {
972
- 0: "sqrt",
973
- 1: "abs",
974
- 2: "sin",
975
- 3: "cos",
976
- 4: "tan",
977
- 5: "log",
978
- 6: "ceil",
979
- 7: "floor",
980
- 8: "round",
981
- 11: "asin",
982
- 12: "acos",
983
- 13: "atan",
984
- 14: "atan2",
985
- 15: "sinh",
986
- 16: "cosh",
987
- 17: "tanh",
988
- 18: "asinh",
989
- 19: "acosh",
990
- 20: "atanh",
991
- 21: "cbrt",
992
- 23: "expm1",
993
- 24: "exp",
994
- 26: "hypot",
995
- 28: "log10",
996
- 29: "log1p",
997
- 30: "log2",
998
- 33: "sign",
999
- 34: "trunc",
1000
- // Spelled exactly as `builtinNameToIndex` accepts them, all lower case. A
1001
- // `call` node's name is what gets displayed, so a name the parser would not
1002
- // accept back would render an expression the user cannot retype.
1003
- 35: "degtorad",
1004
- 36: "radtodeg",
1005
- 61: "root",
1006
- 62: "fact"
1007
- };
1008
- var POW_BUILTIN_INDEX = 31;
1009
- var SYMBOLIC_NATIVE_BUILTINS = /* @__PURE__ */ new Set([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]);
1010
- function valueToSymbolic(v) {
1011
- if (v.type === 9 /* Symbolic */) return v.value;
1012
- if (v.type === 13 /* Error */ || v.type === 12 /* Pending */) return null;
1013
- const numeric = v.toNumber();
1014
- if (!Number.isFinite(numeric)) return null;
1015
- return constNode(rationalFromNumber(numeric));
1016
- }
1017
- function symbolicToValue(node) {
1018
- const simplified = simplifySymbolic(node);
1019
- if (simplified.kind === "const") return numberValue(rationalToNumber(simplified.value));
1020
- return symbolicValue(simplified);
1021
- }
1022
- function unsupported(what) {
1023
- return errorValue(
1024
- "SYMBOLIC_UNSUPPORTED_FUNCTION",
1025
- `"${what}" cannot be applied to an expression that still contains an unknown.`
1026
- );
1027
- }
1028
- function symbolicPow(l, r) {
1029
- const base = valueToSymbolic(l);
1030
- const exponent = valueToSymbolic(r);
1031
- if (base === null || exponent === null) return unsupported("^");
1032
- return symbolicToValue(powNode(base, exponent));
1033
- }
1034
- function symbolicNeg(v) {
1035
- const operand = valueToSymbolic(v);
1036
- if (operand === null) return unsupported("-");
1037
- return symbolicToValue({ kind: "neg", operand });
1038
- }
1039
- function symbolicBuiltin(index, args) {
1040
- const nodes = [];
1041
- for (const arg of args) {
1042
- const faulted = faultedOperand(arg);
1043
- if (faulted) return faulted;
1044
- const node = valueToSymbolic(arg);
1045
- if (node === null) return unsupported(SYMBOLIC_BUILTIN_NAMES[index] ?? `builtin ${index}`);
1046
- nodes.push(node);
1047
- }
1048
- if (index === POW_BUILTIN_INDEX && nodes.length === 2) {
1049
- return symbolicToValue(powNode(nodes[0], nodes[1]));
1050
- }
1051
- const name = SYMBOLIC_BUILTIN_NAMES[index];
1052
- if (name === void 0) return unsupported(`builtin ${index}`);
1053
- return symbolicToValue(callNode(name, nodes));
1054
- }
1055
- function rootToValue(root) {
1056
- const value = symbolicToValue(root);
1057
- if (value.type === 0 /* Number */ && !Number.isInteger(value.toNumber())) return symbolicValue(root);
1058
- return value;
1059
- }
1060
- function approximateRootToValue(root) {
1061
- if (root.im === 0) return numberValue(root.re);
1062
- return symbolicValue(complexNode(complex(rationalFromNumber(root.re), rationalFromNumber(root.im))));
1063
- }
1064
- function solveOutcomeToValue(outcome) {
1065
- switch (outcome.kind) {
1066
- case "identity":
1067
- return stringValue("true for every value");
1068
- case "contradiction":
1069
- return stringValue("no solution");
1070
- case "unsupported":
1071
- return errorValue("SYMBOLIC_SOLVE_UNSUPPORTED", `Cannot solve this equation: ${outcome.reason}.`);
1072
- case "incomplete": {
1073
- const found = outcome.exact.length + outcome.approximate.length;
1074
- return errorValue(
1075
- "SYMBOLIC_SOLVE_INCOMPLETE",
1076
- `Only ${found} of this equation's ${found + outcome.missing} roots could be found: ${outcome.reason}.`
1077
- );
1078
- }
1079
- case "roots": {
1080
- const values = outcome.exact.map(rootToValue);
1081
- for (const approximate of outcome.approximate) values.push(approximateRootToValue(approximate));
1082
- if (values.length === 0) return stringValue("no solution");
1083
- if (values.length === 1) return values[0];
1084
- return matrixValue(1, values.length, values.map((v) => v.type === 9 /* Symbolic */ ? v.value : v.toNumber()));
1085
- }
1086
- }
1087
- }
1088
- function solveEquationValues(lhsValue, rhsValue, variable) {
1089
- const lhs = valueToSymbolic(lhsValue);
1090
- const rhs = valueToSymbolic(rhsValue);
1091
- if (lhs === null || rhs === null) {
1092
- return errorValue("SYMBOLIC_NONFINITE_OPERAND", "An equation side has no exact value to solve with.");
1093
- }
1094
- return solveOutcomeToValue(solveForVariable(lhs, rhs, variable));
1095
- }
1096
-
1097
- // src/vm/VMConversion.ts
1098
- function unifyUom(l, r) {
1099
- if (l.type === 6 /* Uom */ && r.type === 6 /* Uom */) {
1100
- if (l.unit === r.unit) {
1101
- return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
1102
- }
1103
- const lMeasure = getMeasure(l.unit);
1104
- const rMeasure = getMeasure(r.unit);
1105
- const isCurrency = sharedCurrencyExchange.isCurrency(l.unit) && sharedCurrencyExchange.isCurrency(r.unit);
1106
- if (lMeasure && lMeasure === rMeasure) {
1107
- const rvConverted = convertUnit(r.toNumber(), r.unit, l.unit);
1108
- return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
1109
- }
1110
- if (isCurrency) {
1111
- const rvConverted = sharedCurrencyExchange.convertSync(r.toNumber(), r.unit, l.unit);
1112
- if (rvConverted !== null) {
1113
- return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
1114
- }
1115
- }
1116
- return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: false };
1117
- }
1118
- if (l.type === 6 /* Uom */) {
1119
- return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
1120
- }
1121
- if (r.type === 6 /* Uom */) {
1122
- return { lv: l.toNumber(), rv: r.toNumber(), unit: r.unit, sameMeasure: true };
1123
- }
1124
- return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: true };
1125
- }
1126
- var UNIFIED_COMPARISON_TOLERANCE = 1e-12;
1127
- function largestFiniteMagnitude(a, b, c) {
1128
- let scale2 = 0;
1129
- if (Number.isFinite(a) && Math.abs(a) > scale2) scale2 = Math.abs(a);
1130
- if (Number.isFinite(b) && Math.abs(b) > scale2) scale2 = Math.abs(b);
1131
- if (Number.isFinite(c) && Math.abs(c) > scale2) scale2 = Math.abs(c);
1132
- return scale2;
1133
- }
1134
- function compareUom(l, r) {
1135
- const { lv, rv, sameMeasure } = unifyUom(l, r);
1136
- if (!sameMeasure) return { lv, rv, equal: false, sameMeasure: false };
1137
- if (l.type === 6 /* Uom */ && r.type === 6 /* Uom */ && l.unit !== void 0 && l.unit === r.unit && l.exact !== void 0 && r.exact !== void 0 && sharedCurrencyExchange.isCurrency(l.unit)) {
1138
- return { lv, rv, equal: decimalCompare(l.exact, r.exact) === 0, sameMeasure: true };
1139
- }
1140
- if (lv === rv) return { lv, rv, equal: true, sameMeasure: true };
1141
- if (!Number.isFinite(lv) || !Number.isFinite(rv)) return { lv, rv, equal: false, sameMeasure: true };
1142
- const scale2 = largestFiniteMagnitude(lv, rv, r.toNumber());
1143
- return { lv, rv, equal: Math.abs(lv - rv) <= scale2 * UNIFIED_COMPARISON_TOLERANCE, sameMeasure: true };
1144
- }
1145
- var MEASURE_NOUNS = {
1146
- time: "duration",
1147
- luminousIntensity: "luminous intensity"
1148
- };
1149
- var UNCOUNTABLE_MEASURES = /* @__PURE__ */ new Set(["money", "data"]);
1150
- var COMBINE_VERBS = {
1151
- add: "added",
1152
- sub: "subtracted",
1153
- mul: "multiplied",
1154
- div: "divided"
1155
- };
1156
- function describeMeasure(unit) {
1157
- if (sharedCurrencyExchange.isCurrency(unit)) return "money";
1158
- const measure = getMeasure(unit);
1159
- if (measure === void 0) return void 0;
1160
- return MEASURE_NOUNS[measure] ?? measure;
1161
- }
1162
- function withMeasureArticle(noun) {
1163
- if (UNCOUNTABLE_MEASURES.has(noun)) return noun;
1164
- return /^[aeiou]/.test(noun) ? `an ${noun}` : `a ${noun}`;
1165
- }
1166
- function describeMeasureMismatch(lUnit, rUnit, verb) {
1167
- const left = lUnit === void 0 ? void 0 : describeMeasure(lUnit);
1168
- const right = rUnit === void 0 ? void 0 : describeMeasure(rUnit);
1169
- if (left !== void 0 && right !== void 0 && left !== right) {
1170
- return `${left} and ${right} cannot be ${verb}`;
1171
- }
1172
- return void 0;
1173
- }
1174
- function combineVerb(op) {
1175
- return op !== void 0 ? COMBINE_VERBS[op] ?? "combined" : "combined";
1176
- }
1177
- function describeConversionMismatch(fromUnit, toUnit) {
1178
- const from = describeMeasure(fromUnit);
1179
- const to = describeMeasure(toUnit);
1180
- if (from !== void 0 && to !== void 0 && from !== to) {
1181
- return `${withMeasureArticle(from)} cannot be converted to ${withMeasureArticle(to)}`;
1182
- }
1183
- return void 0;
1184
- }
1185
- function incomparableUnitsError(l, r) {
1186
- const lUnit = l.type === 6 /* Uom */ ? l.unit : void 0;
1187
- const rUnit = r.type === 6 /* Uom */ ? r.unit : void 0;
1188
- const named = describeMeasureMismatch(lUnit, rUnit, "compared");
1189
- return errorValue("INCOMPATIBLE_UNITS", named ?? `Cannot compare incompatible units: ${lUnit ?? "?"} and ${rUnit ?? "?"}`);
1190
- }
1191
- function toBigIntOperand(v) {
1192
- if (v.type === 2 /* BigInt */) return v.value;
1193
- const n = v.toNumber();
1194
- if (!Number.isInteger(n)) {
1195
- const shown = Number.isNaN(n) ? "NaN" : String(n);
1196
- throw ErrorFactory.execution(
1197
- "BIGINT_INEXACT_OPERAND",
1198
- `A whole-number (n) value can only be combined with another whole number, and ${shown} is not one`,
1199
- { operand: shown }
1200
- );
1201
- }
1202
- return BigInt(n);
1203
- }
1204
- function bigIntDivisionByZero() {
1205
- return ErrorFactory.execution(
1206
- "BIGINT_DIVISION_BY_ZERO",
1207
- "Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity"
1208
- );
1209
- }
1210
- function compareBigIntOperands(l, r) {
1211
- const lb = exactBigInt(l);
1212
- const rb = exactBigInt(r);
1213
- if (lb === null || rb === null) return null;
1214
- if (lb < rb) return -1;
1215
- if (lb > rb) return 1;
1216
- return 0;
1217
- }
1218
- function exactBigInt(v) {
1219
- if (v.type === 2 /* BigInt */) return v.value;
1220
- const n = v.toNumber();
1221
- return Number.isInteger(n) ? BigInt(n) : null;
1222
- }
1223
- function power(base, exponent) {
1224
- if (Number.isFinite(exponent)) return Math.pow(base, exponent);
1225
- if (base === 1) return 1;
1226
- if (base === -1 && !Number.isNaN(exponent)) return 1;
1227
- return Math.pow(base, exponent);
1228
- }
1229
- function operandExactDecimal(v) {
1230
- if (v.exact !== void 0) return v.exact;
1231
- return decimalFromNumberIfExact(v.toNumber());
1232
- }
1233
- function exactMoneyOp(l, r, op) {
1234
- const lMoney = l.type === 6 /* Uom */ && l.unit !== void 0 && l.exact !== void 0 && sharedCurrencyExchange.isCurrency(l.unit);
1235
- const rMoney = r.type === 6 /* Uom */ && r.unit !== void 0 && r.exact !== void 0 && sharedCurrencyExchange.isCurrency(r.unit);
1236
- if (!lMoney && !rMoney) return null;
1237
- let ld;
1238
- let rd;
1239
- let unit;
1240
- if (lMoney && rMoney) {
1241
- if (l.unit !== r.unit || op === "div") return null;
1242
- ld = l.exact;
1243
- rd = r.exact;
1244
- unit = l.unit;
1245
- } else if (lMoney && r.type !== 6 /* Uom */) {
1246
- ld = l.exact;
1247
- unit = l.unit;
1248
- rd = operandExactDecimal(r);
1249
- } else if (rMoney && l.type !== 6 /* Uom */) {
1250
- rd = r.exact;
1251
- unit = r.unit;
1252
- ld = operandExactDecimal(l);
1253
- } else {
1254
- return null;
1255
- }
1256
- if (ld === null || rd === null) return null;
1257
- let result;
1258
- switch (op) {
1259
- case "add":
1260
- result = decimalAdd(ld, rd);
1261
- break;
1262
- case "sub":
1263
- result = decimalSubtract(ld, rd);
1264
- break;
1265
- case "mul":
1266
- result = decimalMultiply(ld, rd);
1267
- break;
1268
- case "div":
1269
- if (decimalIsZero(rd)) return null;
1270
- result = decimalDivide(ld, rd);
1271
- break;
1272
- }
1273
- return uomValueExact(decimalToNumber(result), unit, result);
1274
- }
1275
- function operandRational(v) {
1276
- if (v.rational !== void 0) return v.rational;
1277
- if ((v.type === 0 /* Number */ || v.type === 1 /* Hex */) && typeof v.value === "number" && Number.isInteger(v.value)) {
1278
- return rational(BigInt(v.value));
1279
- }
1280
- return null;
1281
- }
1282
- function exactRationalOp(l, r, op) {
1283
- const lr = operandRational(l);
1284
- if (lr === null) return null;
1285
- const rr = operandRational(r);
1286
- if (rr === null) return null;
1287
- if (op === "div" && isRationalZero(rr)) return null;
1288
- let result;
1289
- try {
1290
- switch (op) {
1291
- case "add":
1292
- result = rationalAdd(lr, rr);
1293
- break;
1294
- case "sub":
1295
- result = rationalSub(lr, rr);
1296
- break;
1297
- case "mul":
1298
- result = rationalMul(lr, rr);
1299
- break;
1300
- case "div":
1301
- result = rationalDiv(lr, rr);
1302
- break;
1303
- }
1304
- } catch {
1305
- return null;
1306
- }
1307
- return numberValueRational(rationalToNumber(result), result);
1308
- }
1309
- function uncertainOp(l, r, op) {
1310
- if (l.type !== 0 /* Number */ || r.type !== 0 /* Number */) return null;
1311
- const a = l.value;
1312
- const b = r.value;
1313
- const sa = l.uncertainty ?? 0;
1314
- const sb = r.uncertainty ?? 0;
1315
- let center;
1316
- let sigma;
1317
- switch (op) {
1318
- case "add":
1319
- center = a + b;
1320
- sigma = Math.hypot(sa, sb);
1321
- break;
1322
- case "sub":
1323
- center = a - b;
1324
- sigma = Math.hypot(sa, sb);
1325
- break;
1326
- case "mul":
1327
- center = a * b;
1328
- sigma = Math.hypot(b * sa, a * sb);
1329
- break;
1330
- case "div":
1331
- center = a / b;
1332
- sigma = Math.hypot(sa / b, a * sb / (b * b));
1333
- break;
1334
- }
1335
- return numberValueUncertain(center, sigma);
1336
- }
1337
- function compareRationalOperands(l, r) {
1338
- const lr = operandRational(l);
1339
- if (lr === null) return null;
1340
- const rr = operandRational(r);
1341
- if (rr === null) return null;
1342
- return rationalCompare(lr, rr);
1343
- }
1344
- function binaryOp(l, r, op, bigOp, symbolicOp) {
1345
- if (l.type === 13 /* Error */) return l;
1346
- if (r.type === 13 /* Error */) return r;
1347
- if (l.type === 12 /* Pending */) return l;
1348
- if (r.type === 12 /* Pending */) return r;
1349
- if (symbolicOp && (l.type === 9 /* Symbolic */ || r.type === 9 /* Symbolic */)) {
1350
- const left = valueToSymbolic(l);
1351
- const right = valueToSymbolic(r);
1352
- if (left === null || right === null) {
1353
- return errorValue(
1354
- "SYMBOLIC_NONFINITE_OPERAND",
1355
- "A symbolic expression cannot combine with a value that has no exact number (NaN or infinity)."
1356
- );
1357
- }
1358
- const node = { kind: symbolicOp, left, right };
1359
- return symbolicValue(simplifySymbolic(node));
1360
- }
1361
- if (l.type === 0 /* Number */ && r.type === 0 /* Number */) {
1362
- return numberValue(op(l.value, r.value));
1363
- }
1364
- if (l.type === 2 /* BigInt */ || r.type === 2 /* BigInt */) {
1365
- const lb = toBigIntOperand(l);
1366
- const rb = toBigIntOperand(r);
1367
- if (bigOp) return bigIntValue(bigOp(lb, rb));
1368
- return bigIntValue(lb + rb);
1369
- }
1370
- if (l.type === 6 /* Uom */ || r.type === 6 /* Uom */) {
1371
- if (symbolicOp) {
1372
- const exactMoney = exactMoneyOp(l, r, symbolicOp);
1373
- if (exactMoney) return exactMoney;
1374
- }
1375
- const { lv, rv, unit, sameMeasure } = unifyUom(l, r);
1376
- if (!sameMeasure) {
1377
- const lUnit = l.type === 6 /* Uom */ ? l.unit : void 0;
1378
- const rUnit = r.type === 6 /* Uom */ ? r.unit : void 0;
1379
- const named = describeMeasureMismatch(lUnit, rUnit, combineVerb(symbolicOp));
1380
- return errorValue("INCOMPATIBLE_UNITS", named ?? `Cannot combine incompatible units: ${lUnit ?? "?"} and ${rUnit ?? "?"}`);
1381
- }
1382
- return uomValue(op(lv, rv), unit);
1383
- }
1384
- if (l.type === 7 /* Matrix */ && r.type === 7 /* Matrix */) {
1385
- const lm = l.value;
1386
- const rm = r.value;
1387
- if (!sameShape(lm, rm)) {
1388
- return errorValue("DIMENSION_MISMATCH", `Cannot combine matrices of different shapes: ${lm.rows}x${lm.cols} and ${rm.rows}x${rm.cols}`);
1389
- }
1390
- const result = new Array(lm.data.length);
1391
- for (let i = 0; i < lm.data.length; i++) result[i] = op(lm.data[i], rm.data[i]);
1392
- return matrixValue(lm.rows, lm.cols, result);
1393
- }
1394
- if (l.type === 7 /* Matrix */) {
1395
- const lm = l.value;
1396
- const scalar = r.toNumber();
1397
- const result = lm.data.map((v) => op(v, scalar));
1398
- return matrixValue(lm.rows, lm.cols, result);
1399
- }
1400
- if (r.type === 7 /* Matrix */) {
1401
- const rm = r.value;
1402
- const scalar = l.toNumber();
1403
- const result = rm.data.map((v) => op(scalar, v));
1404
- return matrixValue(rm.rows, rm.cols, result);
1405
- }
1406
- return numberValue(op(l.toNumber(), r.toNumber()));
1407
- }
1408
-
1409
- // src/vm/OpRegistry.ts
1410
- var MAX_OPCODE = 254;
1411
- var DYNAMIC_OPCODE_START = 200;
1412
- var OpRegistry = class {
1413
- constructor() {
1414
- this.handlers = /* @__PURE__ */ new Map();
1415
- this.nextOpcode = DYNAMIC_OPCODE_START + 1;
1416
- }
1417
- register(registration) {
1418
- this.handlers.set(registration.opcode, registration.handler);
1419
- }
1420
- /**
1421
- * Remove a previously registered opcode handler.
1422
- * Used by package unregistration to reverse shared-registry contributions.
1423
- */
1424
- unregister(opcode) {
1425
- this.handlers.delete(opcode);
1426
- }
1427
- get(opcode) {
1428
- return this.handlers.get(opcode);
1429
- }
1430
- has(opcode) {
1431
- return this.handlers.has(opcode);
1432
- }
1433
- /**
1434
- * Allocate a unique opcode for a plugin's custom bytecode handler.
1435
- *
1436
- * Returns the next available opcode (starting at 201). Each call
1437
- * returns a distinct value. Plugins should call this once during
1438
- * registration and store the result.
1439
- *
1440
- * @throws If the dynamic opcode pool is exhausted.
1441
- * @returns A unique opcode number for the calling plugin.
1442
- */
1443
- allocateOpcode() {
1444
- if (this.nextOpcode > MAX_OPCODE) {
1445
- throw ErrorFactory.config(
1446
- "OPCODE_POOL_EXHAUSTED",
1447
- `OpRegistry: dynamic opcode pool exhausted (max ${MAX_OPCODE - DYNAMIC_OPCODE_START} allocations).`
1448
- );
1449
- }
1450
- return this.nextOpcode++;
1451
- }
1452
- };
1453
- var sharedOpRegistry = new OpRegistry();
1454
-
1455
- // src/vm/MoneyExact.ts
1456
- var ONE_DECIMAL = decimalFromInteger(1);
1457
- function moneyExactMagnitude(operand, unit) {
1458
- if (!sharedCurrencyExchange.isCurrency(unit)) return null;
1459
- return operand.exact ?? decimalFromNumberIfExact(operand.toNumber());
1460
- }
1461
- function decimalFromShortDecimal(n) {
1462
- if (!Number.isFinite(n)) return null;
1463
- if (Number.isInteger(n)) return decimalFromInteger(BigInt(n));
1464
- const s = String(n);
1465
- if (!/^-?\d+\.\d+$/.test(s)) return null;
1466
- return decimalFromLiteral(s);
1467
- }
1468
- function scaleMoneyExact(amount, factor, unit) {
1469
- const base = moneyExactMagnitude(amount, unit);
1470
- const factorDecimal = decimalFromShortDecimal(factor);
1471
- if (base !== null && factorDecimal !== null) {
1472
- const result = decimalMultiply(base, factorDecimal);
1473
- return uomValueExact(decimalToNumber(result), unit, result);
1474
- }
1475
- return uomValue(amount.toNumber() * factor, unit);
1476
- }
1477
- function scaleMoneyByPercent(money, unit, percent, sign) {
1478
- const base = moneyExactMagnitude(money, unit);
1479
- const percentDecimal = decimalFromShortDecimal(percent);
1480
- if (base !== null && percentDecimal !== null) {
1481
- const factor = decimalAdd(ONE_DECIMAL, sign === 1 ? percentDecimal : decimalNegate(percentDecimal));
1482
- const result = decimalMultiply(base, factor);
1483
- return uomValueExact(decimalToNumber(result), unit, result);
1484
- }
1485
- return uomValue(money.toNumber() * (1 + sign * percent), unit);
1486
- }
1487
- function onePlusRateDecimal(rate) {
1488
- const rateDecimal = decimalFromShortDecimal(rate);
1489
- return rateDecimal === null ? null : decimalAdd(ONE_DECIMAL, rateDecimal);
1490
- }
1491
- function removeTaxExact(money, unit, rate) {
1492
- const base = moneyExactMagnitude(money, unit);
1493
- const divisor = onePlusRateDecimal(rate);
1494
- if (base === null || divisor === null || decimalIsZero(divisor)) return null;
1495
- const quotient = decimalDivide(base, divisor);
1496
- return uomValueExact(decimalToNumber(quotient), unit, quotient);
1497
- }
1498
- function taxInExact(money, unit, rate) {
1499
- const base = moneyExactMagnitude(money, unit);
1500
- const divisor = onePlusRateDecimal(rate);
1501
- if (base === null || divisor === null || decimalIsZero(divisor)) return null;
1502
- const tax = decimalSubtract(base, decimalDivide(base, divisor));
1503
- return uomValueExact(decimalToNumber(tax), unit, tax);
1504
- }
1505
- function splitEachExact(amount, n) {
1506
- const unit = amount.unit;
1507
- const cents = unit !== void 0 && sharedCurrencyExchange.isCurrency(unit) ? centsOfMoney(amount, unit) : null;
1508
- if (cents === null) {
1509
- return { unit, shares: [{ value: amount.toNumber() / n, count: n }] };
1510
- }
1511
- const divisor = BigInt(n);
1512
- const baseCents = cents / divisor;
1513
- const remainder = cents - baseCents * divisor;
1514
- const extraShares = Number(remainder < 0n ? -remainder : remainder);
1515
- const step = cents < 0n ? -1n : 1n;
1516
- const base = centShare(baseCents, n - extraShares);
1517
- if (extraShares === 0) return { unit, shares: [base] };
1518
- return { unit, shares: [base, centShare(baseCents + step, extraShares)] };
1519
- }
1520
- function centShare(cents, count) {
1521
- const exact = makeDecimal(cents, 2);
1522
- return { value: decimalToNumber(exact), exact, count };
1523
- }
1524
- function centsOfMoney(amount, unit) {
1525
- const base = moneyExactMagnitude(amount, unit);
1526
- return base === null ? null : decimalRound(base, 2).coef;
1527
- }
1528
-
1529
- // src/symbolic/PartialFractions.ts
1530
- var APART_MAX_DEGREE = 12;
1531
- function multiply2(a, b) {
1532
- if (a.length === 0 || b.length === 0) return [];
1533
- const product2 = new Array(a.length + b.length - 1).fill(RATIONAL_ZERO);
1534
- a.forEach((left, i) => {
1535
- b.forEach((right, j) => {
1536
- product2[i + j] = rationalAdd(product2[i + j], rationalMul(left, right));
1537
- });
1538
- });
1539
- return product2;
1540
- }
1541
- function power2(base, exponent) {
1542
- let result = [RATIONAL_ONE];
1543
- for (let i = 0; i < exponent; i++) result = multiply2(result, base);
1544
- return result;
1545
- }
1546
- function scale(coefficients, factor) {
1547
- return coefficients.map((coefficient) => rationalDiv(coefficient, factor));
1548
- }
1549
- function denominatorFactors(ascending, variable) {
1550
- const factors = [];
1551
- let lowest = 0;
1552
- while (lowest < ascending.length && isRationalZero(ascending[lowest])) lowest++;
1553
- if (lowest > 0) factors.push({ base: [RATIONAL_ZERO, RATIONAL_ONE], power: lowest });
1554
- const remaining = ascending.slice(lowest);
1555
- if (remaining.length > 1) {
1556
- const factorization = factorUnivariate([...remaining].reverse(), variable);
1557
- for (const factor of factorization.factors) {
1558
- const polynomial = toPolynomial(factor.base);
1559
- if (polynomial === null) return null;
1560
- factors.push({ base: [...polyCoefficients(polynomial, variable)], power: factor.power });
1561
- }
1562
- }
1563
- return factors.length > 0 ? factors : null;
1564
- }
1565
- function enumerateUnknowns(factors) {
1566
- const unknowns = [];
1567
- factors.forEach((factor, index) => {
1568
- const factorDegree = factor.base.length - 1;
1569
- for (let p = 1; p <= factor.power; p++) {
1570
- for (let degree = 0; degree < factorDegree; degree++) {
1571
- unknowns.push({ factor: index, power: p, degree });
1572
- }
1573
- }
1574
- });
1575
- return unknowns;
1576
- }
1577
- function unknownColumn(unknown, factors, denominator) {
1578
- const divisor = power2(factors[unknown.factor].base, unknown.power);
1579
- const { quotient, remainder } = polynomialDivide(denominator, divisor);
1580
- if (!isZeroPolynomial(remainder)) return null;
1581
- const shift = new Array(unknown.degree).fill(RATIONAL_ZERO);
1582
- shift.push(RATIONAL_ONE);
1583
- return multiply2(quotient, shift);
1584
- }
1585
- function solveLinearSystem(matrix, target) {
1586
- const size = target.length;
1587
- for (let column = 0; column < size; column++) {
1588
- let pivot = -1;
1589
- for (let row = column; row < size; row++) {
1590
- if (!isRationalZero(matrix[row][column])) {
1591
- pivot = row;
1592
- break;
1593
- }
1594
- }
1595
- if (pivot === -1) return null;
1596
- [matrix[column], matrix[pivot]] = [matrix[pivot], matrix[column]];
1597
- [target[column], target[pivot]] = [target[pivot], target[column]];
1598
- for (let row = 0; row < size; row++) {
1599
- if (row === column || isRationalZero(matrix[row][column])) continue;
1600
- const factor = rationalDiv(matrix[row][column], matrix[column][column]);
1601
- for (let k = column; k < size; k++) {
1602
- matrix[row][k] = rationalSub(matrix[row][k], rationalMul(factor, matrix[column][k]));
1603
- }
1604
- target[row] = rationalSub(target[row], rationalMul(factor, target[column]));
1605
- }
1606
- }
1607
- return target.map((value, index) => rationalDiv(value, matrix[index][index]));
1608
- }
1609
- function partialFractions(numerator, denominator, variable) {
1610
- if (denominator.length < 2 || denominator.length - 1 > APART_MAX_DEGREE) return null;
1611
- const shared = coefficientGcd(numerator, denominator);
1612
- const reducedNumerator = shared.length > 1 ? polynomialDivide(numerator, shared).quotient : [...numerator];
1613
- const reducedDenominator = shared.length > 1 ? polynomialDivide(denominator, shared).quotient : [...denominator];
1614
- if (reducedDenominator.length === 1) {
1615
- return { polynomial: scale(reducedNumerator, reducedDenominator[0]), terms: [] };
1616
- }
1617
- if (reducedDenominator.length === 0) return null;
1618
- const leading = reducedDenominator[reducedDenominator.length - 1];
1619
- const monicDenominator = scale(reducedDenominator, leading);
1620
- const scaledNumerator = scale(reducedNumerator, leading);
1621
- const { quotient, remainder } = polynomialDivide(scaledNumerator, monicDenominator);
1622
- if (isZeroPolynomial(remainder)) return { polynomial: quotient, terms: [] };
1623
- const factors = denominatorFactors(monicDenominator, variable);
1624
- if (factors === null) return null;
1625
- const terms = solveForNumerators(factors, monicDenominator, remainder);
1626
- return terms === null ? null : { polynomial: quotient, terms };
1627
- }
1628
- function solveForNumerators(factors, denominator, remainder) {
1629
- const unknowns = enumerateUnknowns(factors);
1630
- const size = denominator.length - 1;
1631
- if (unknowns.length !== size) return null;
1632
- const columns = [];
1633
- for (const unknown of unknowns) {
1634
- const column = unknownColumn(unknown, factors, denominator);
1635
- if (column === null) return null;
1636
- columns.push(column);
1637
- }
1638
- const matrix = [];
1639
- for (let row = 0; row < size; row++) {
1640
- matrix.push(columns.map((column) => column[row] ?? RATIONAL_ZERO));
1641
- }
1642
- const target = [];
1643
- for (let row = 0; row < size; row++) target.push(remainder[row] ?? RATIONAL_ZERO);
1644
- const solution = solveLinearSystem(matrix, target);
1645
- if (solution === null) return null;
1646
- return groupSolution(unknowns, solution, factors);
1647
- }
1648
- function groupSolution(unknowns, solution, factors) {
1649
- const grouped = /* @__PURE__ */ new Map();
1650
- unknowns.forEach((unknown, index) => {
1651
- const key = `${unknown.factor}:${unknown.power}`;
1652
- const existing = grouped.get(key) ?? [];
1653
- existing[unknown.degree] = solution[index];
1654
- grouped.set(key, existing);
1655
- });
1656
- const terms = [];
1657
- for (const [key, coefficients] of grouped) {
1658
- const [factorIndex, termPower] = key.split(":").map(Number);
1659
- const filled = [...coefficients].map((value) => value ?? RATIONAL_ZERO);
1660
- if (filled.every(isRationalZero)) continue;
1661
- terms.push({ numerator: filled, base: factors[factorIndex].base, power: termPower });
1662
- }
1663
- return terms;
1664
- }
1665
- function coefficientsToNode2(coefficients, variable) {
1666
- const terms = /* @__PURE__ */ new Map();
1667
- coefficients.forEach((coefficient, exponent) => {
1668
- if (isRationalZero(coefficient)) return;
1669
- terms.set(exponent === 0 ? "" : exponent === 1 ? variable : `${variable}^${exponent}`, coefficient);
1670
- });
1671
- if (terms.size === 0) return constNode(RATIONAL_ZERO);
1672
- return fromPolynomial({ terms, vars: coefficients.length > 1 ? [variable] : [] });
1673
- }
1674
- function apartSymbolic(node) {
1675
- const parts = asRationalFunction(node);
1676
- if (parts === null) return node;
1677
- const decomposition = partialFractions(parts.numerator, parts.denominator, parts.variable);
1678
- if (decomposition === null || decomposition.terms.length === 0) return node;
1679
- let result = decomposition.polynomial.length > 0 ? coefficientsToNode2(decomposition.polynomial, parts.variable) : null;
1680
- for (const term of decomposition.terms) {
1681
- const base = coefficientsToNode2(term.base, parts.variable);
1682
- const denominator = term.power === 1 ? base : powNode(base, constNode({ n: BigInt(term.power), d: 1n }));
1683
- const negative = isNegativeNumerator(term.numerator);
1684
- const numerator = negative ? term.numerator.map((coefficient) => rationalNeg(coefficient)) : term.numerator;
1685
- const piece = {
1686
- kind: "div",
1687
- left: coefficientsToNode2(numerator, parts.variable),
1688
- right: denominator
1689
- };
1690
- if (result === null) result = negative ? { kind: "neg", operand: piece } : piece;
1691
- else result = { kind: negative ? "sub" : "add", left: result, right: piece };
1692
- }
1693
- return result === null ? node : simplifySymbolic(result);
1694
- }
1695
- function isNegativeNumerator(coefficients) {
1696
- return coefficients.some((coefficient) => coefficient.n < 0n) && coefficients.every((coefficient) => coefficient.n <= 0n);
1697
- }
1698
- function asRationalFunction(node) {
1699
- if (node.kind !== "div") return null;
1700
- const numerator = toPolynomial(node.left);
1701
- const denominator = toPolynomial(node.right);
1702
- if (numerator === null || denominator === null) return null;
1703
- const variable = polyUnivariateVar(denominator);
1704
- if (variable === null) return null;
1705
- if (numerator.vars.some((name) => name !== variable)) return null;
1706
- return {
1707
- numerator: polyCoefficients(numerator, variable),
1708
- denominator: polyCoefficients(denominator, variable),
1709
- variable
1710
- };
1711
- }
1712
-
1713
- // src/symbolic/Derivative.ts
1714
- var DERIVATIVE_MAX_ORDER = 16;
1715
- function zero() {
1716
- return constNode(RATIONAL_ZERO);
1717
- }
1718
- function one() {
1719
- return constNode(RATIONAL_ONE);
1720
- }
1721
- function functionDerivative(name, argument) {
1722
- switch (name) {
1723
- case "sin":
1724
- return callNode("cos", [argument]);
1725
- case "cos":
1726
- return { kind: "neg", operand: callNode("sin", [argument]) };
1727
- case "tan":
1728
- return { kind: "div", left: one(), right: powNode(callNode("cos", [argument]), constNode(2)) };
1729
- case "exp":
1730
- return callNode("exp", [argument]);
1731
- case "log":
1732
- return { kind: "div", left: one(), right: argument };
1733
- case "sqrt":
1734
- return {
1735
- kind: "div",
1736
- left: one(),
1737
- right: { kind: "mul", left: constNode(2), right: callNode("sqrt", [argument]) }
1738
- };
1739
- case "asin":
1740
- return { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) };
1741
- case "acos":
1742
- return { kind: "neg", operand: { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) } };
1743
- case "atan":
1744
- return { kind: "div", left: one(), right: onePlusSquare(argument) };
1745
- case "sinh":
1746
- return callNode("cosh", [argument]);
1747
- case "cosh":
1748
- return callNode("sinh", [argument]);
1749
- case "tanh":
1750
- return { kind: "div", left: one(), right: powNode(callNode("cosh", [argument]), constNode(2)) };
1751
- case "abs":
1752
- return callNode("sign", [argument]);
1753
- default:
1754
- return null;
1755
- }
1756
- }
1757
- function oneMinusSquare(argument) {
1758
- return { kind: "sub", left: one(), right: powNode(argument, constNode(2)) };
1759
- }
1760
- function onePlusSquare(argument) {
1761
- return { kind: "add", left: one(), right: powNode(argument, constNode(2)) };
1762
- }
1763
- function differentiate2(node, variable, order = 1) {
1764
- if (order < 0 || !Number.isInteger(order)) {
1765
- throw ErrorFactory.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT", "A derivative order must be a whole number, at least zero.");
1766
- }
1767
- if (order > DERIVATIVE_MAX_ORDER) {
1768
- throw ErrorFactory.execution(
1769
- "SYMBOLIC_DERIVATIVE_ORDER_LIMIT",
1770
- `A derivative order above ${DERIVATIVE_MAX_ORDER} is not supported.`,
1771
- { limit: DERIVATIVE_MAX_ORDER }
1772
- );
1773
- }
1774
- let result = simplifySymbolic(node);
1775
- for (let i = 0; i < order; i++) result = simplifySymbolic(derive(result, variable));
1776
- return result;
1777
- }
1778
- function derive(node, variable) {
1779
- switch (node.kind) {
1780
- case "const":
1781
- case "complex":
1782
- return zero();
1783
- case "var":
1784
- return node.name === variable ? one() : zero();
1785
- case "add":
1786
- return { kind: "add", left: derive(node.left, variable), right: derive(node.right, variable) };
1787
- case "sub":
1788
- return { kind: "sub", left: derive(node.left, variable), right: derive(node.right, variable) };
1789
- case "neg":
1790
- return { kind: "neg", operand: derive(node.operand, variable) };
1791
- case "mul":
1792
- return {
1793
- kind: "add",
1794
- left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1795
- right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1796
- };
1797
- case "div":
1798
- return {
1799
- kind: "div",
1800
- left: {
1801
- kind: "sub",
1802
- left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1803
- right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1804
- },
1805
- right: powNode(node.right, constNode(2))
1806
- };
1807
- case "pow":
1808
- return derivePow(node, variable);
1809
- case "call": {
1810
- if (node.args.length !== 1) return unevaluated(node, variable);
1811
- const outer = functionDerivative(node.name, node.args[0]);
1812
- if (outer === null) return unevaluated(node, variable);
1813
- return { kind: "mul", left: outer, right: derive(node.args[0], variable) };
1814
- }
1815
- }
1816
- }
1817
- function derivePow(node, variable) {
1818
- if (node.exponent.kind === "const") {
1819
- const reduced = constNode(rationalSub(node.exponent.value, RATIONAL_ONE));
1820
- return {
1821
- kind: "mul",
1822
- left: { kind: "mul", left: node.exponent, right: powNode(node.base, reduced) },
1823
- right: derive(node.base, variable)
1824
- };
1825
- }
1826
- if (node.base.kind === "const" && node.base.value.n > 0n) {
1827
- return {
1828
- kind: "mul",
1829
- left: { kind: "mul", left: node, right: callNode("log", [node.base]) },
1830
- right: derive(node.exponent, variable)
1831
- };
1832
- }
1833
- return unevaluated(node, variable);
1834
- }
1835
- function unevaluated(node, variable) {
1836
- return callNode("der", [node, varNode(variable)]);
1837
- }
1838
-
1839
- // src/symbolic/Integral.ts
1840
- function asLinear(node, variable) {
1841
- const polynomial = toPolynomial(node);
1842
- if (polynomial === null) return null;
1843
- const others = polynomial.vars.filter((name) => name !== variable);
1844
- if (others.length > 0) return null;
1845
- if (polyDegree(polynomial, variable) > 1) return null;
1846
- const ascending = polyCoefficients(polynomial, variable);
1847
- const intercept = ascending[0] ?? { n: 0n, d: 1n };
1848
- const slope = ascending[1] ?? { n: 0n, d: 1n };
1849
- return isRationalZero(slope) ? null : { slope, intercept };
1850
- }
1851
- function integratePolynomial(node, variable) {
1852
- const polynomial = toPolynomial(node);
1853
- if (polynomial === null) return null;
1854
- const others = polynomial.vars.filter((name) => name !== variable);
1855
- if (others.length > 0) {
1856
- return { ok: false, reason: `it involves more than one unknown (${others.join(", ")})` };
1857
- }
1858
- const ascending = polyCoefficients(polynomial, variable);
1859
- let result = constNode(0);
1860
- ascending.forEach((coeff, power3) => {
1861
- if (isRationalZero(coeff)) return;
1862
- const nextPower = power3 + 1;
1863
- const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1864
- const term = {
1865
- kind: "mul",
1866
- left: constNode(scaled),
1867
- right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1868
- };
1869
- result = { kind: "add", left: result, right: term };
1870
- });
1871
- return { ok: true, value: simplifySymbolic(result) };
1872
- }
1873
- function integrateStandardForm(node, variable) {
1874
- if (node.kind !== "call" || node.args.length !== 1) return null;
1875
- const linear = asLinear(node.args[0], variable);
1876
- if (linear === null) return null;
1877
- const inner = node.args[0];
1878
- const divideBySlope = (value) => simplifySymbolic({ kind: "div", left: value, right: constNode(linear.slope) });
1879
- switch (node.name) {
1880
- case "exp":
1881
- return { ok: true, value: divideBySlope(callNode("exp", [inner])) };
1882
- case "sin":
1883
- return { ok: true, value: divideBySlope({ kind: "neg", operand: callNode("cos", [inner]) }) };
1884
- case "cos":
1885
- return { ok: true, value: divideBySlope(callNode("sin", [inner])) };
1886
- case "log":
1887
- return {
1888
- ok: true,
1889
- value: divideBySlope({
1890
- kind: "sub",
1891
- left: { kind: "mul", left: inner, right: callNode("log", [inner]) },
1892
- right: inner
1893
- })
1894
- };
1895
- default:
1896
- return null;
1897
- }
1898
- }
1899
- function integrateReciprocalForms(node, variable) {
1900
- if (node.kind !== "div") return null;
1901
- if (node.left.kind !== "const" || !isRationalOneNode(node.left.value)) return null;
1902
- const linear = asLinear(node.right, variable);
1903
- if (linear !== null) {
1904
- return {
1905
- ok: true,
1906
- value: simplifySymbolic({
1907
- kind: "div",
1908
- left: callNode("log", [node.right]),
1909
- right: constNode(linear.slope)
1910
- })
1911
- };
1912
- }
1913
- const denominator = toPolynomial(node.right);
1914
- if (denominator !== null && denominator.vars.length === 1 && denominator.vars[0] === variable) {
1915
- const ascending = polyCoefficients(denominator, variable);
1916
- const isOnePlusSquare = ascending.length === 3 && isRationalOneNode(ascending[0]) && isRationalZero(ascending[1]) && isRationalOneNode(ascending[2]);
1917
- if (isOnePlusSquare) return { ok: true, value: callNode("atan", [varNode(variable)]) };
1918
- }
1919
- return null;
1920
- }
1921
- function isRationalOneNode(value) {
1922
- return value.n === 1n && value.d === 1n;
1923
- }
1924
- function integrateRationalFunction(node, variable) {
1925
- const parts = asRationalFunction(node);
1926
- if (parts === null || parts.variable !== variable) return null;
1927
- const decomposition = partialFractions(parts.numerator, parts.denominator, variable);
1928
- if (decomposition === null) return null;
1929
- let result = decomposition.polynomial.length > 0 ? polynomialAntiderivative(decomposition.polynomial, variable) : constNode(0);
1930
- for (const term of decomposition.terms) {
1931
- const piece = integrateTerm(term, variable);
1932
- if (piece === null) {
1933
- return {
1934
- ok: false,
1935
- reason: "its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have"
1936
- };
1937
- }
1938
- result = { kind: "add", left: result, right: piece };
1939
- }
1940
- return { ok: true, value: simplifySymbolic(result) };
1941
- }
1942
- function integrateTerm(term, variable) {
1943
- const baseDegree = term.base.length - 1;
1944
- const base = coefficientsToNode2(term.base, variable);
1945
- if (baseDegree === 1) {
1946
- const coefficient = term.numerator[0] ?? RATIONAL_ZERO;
1947
- if (term.power === 1) {
1948
- return { kind: "mul", left: constNode(coefficient), right: callNode("log", [base]) };
1949
- }
1950
- const reduced = term.power - 1;
1951
- const scaled = rationalDiv(coefficient, { n: BigInt(-reduced), d: 1n });
1952
- return {
1953
- kind: "div",
1954
- left: constNode(scaled),
1955
- right: powNode(base, constNode({ n: BigInt(reduced), d: 1n }))
1956
- };
1957
- }
1958
- if (baseDegree !== 2 || term.power !== 1) return null;
1959
- return integrateQuadraticTerm(term, variable, base);
1960
- }
1961
- function integrateQuadraticTerm(term, variable, base) {
1962
- const constant = term.numerator[0] ?? RATIONAL_ZERO;
1963
- const linear = term.numerator[1] ?? RATIONAL_ZERO;
1964
- const [q, p] = term.base;
1965
- const half = { n: 1n, d: 2n };
1966
- const halfP = rationalMul(p, half);
1967
- const logarithm = {
1968
- kind: "mul",
1969
- left: constNode(rationalMul(linear, half)),
1970
- right: callNode("log", [base])
1971
- };
1972
- const leftover = rationalSub(constant, rationalMul(linear, halfP));
1973
- if (isRationalZero(leftover)) return logarithm;
1974
- const width = surdNode(rationalSub(q, rationalMul(halfP, halfP)));
1975
- const shifted = {
1976
- kind: "add",
1977
- left: varNode(variable),
1978
- right: constNode(halfP)
1979
- };
1980
- const arctangent = {
1981
- kind: "mul",
1982
- left: { kind: "div", left: constNode(leftover), right: width },
1983
- right: callNode("atan", [{ kind: "div", left: shifted, right: width }])
1984
- };
1985
- return isRationalZero(linear) ? arctangent : { kind: "add", left: logarithm, right: arctangent };
1986
- }
1987
- function polynomialAntiderivative(ascending, variable) {
1988
- let result = constNode(0);
1989
- ascending.forEach((coeff, exponent) => {
1990
- if (isRationalZero(coeff)) return;
1991
- const nextPower = exponent + 1;
1992
- const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1993
- const term = {
1994
- kind: "mul",
1995
- left: constNode(scaled),
1996
- right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1997
- };
1998
- result = { kind: "add", left: result, right: term };
1999
- });
2000
- return result;
2001
- }
2002
- function integrate(node, variable) {
2003
- const simplified = simplifySymbolic(node);
2004
- if (!freeVariables(simplified).has(variable)) {
2005
- return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified, right: varNode(variable) }) };
2006
- }
2007
- const polynomial = integratePolynomial(simplified, variable);
2008
- if (polynomial !== null) return polynomial;
2009
- const standard = integrateStandardForm(simplified, variable);
2010
- if (standard !== null) return standard;
2011
- const reciprocal = integrateReciprocalForms(simplified, variable);
2012
- if (reciprocal !== null) return reciprocal;
2013
- const rationalFunction = integrateRationalFunction(simplified, variable);
2014
- if (rationalFunction !== null) return rationalFunction;
2015
- if (simplified.kind === "add" || simplified.kind === "sub") {
2016
- const left = integrate(simplified.left, variable);
2017
- if (!left.ok) return left;
2018
- const right = integrate(simplified.right, variable);
2019
- if (!right.ok) return right;
2020
- return {
2021
- ok: true,
2022
- value: simplifySymbolic({ kind: simplified.kind, left: left.value, right: right.value })
2023
- };
2024
- }
2025
- if (simplified.kind === "mul" && simplified.left.kind === "const") {
2026
- const inner = integrate(simplified.right, variable);
2027
- if (!inner.ok) return inner;
2028
- return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified.left, right: inner.value }) };
2029
- }
2030
- return {
2031
- ok: false,
2032
- reason: "no elementary antiderivative is known for this expression"
2033
- };
2034
- }
2035
-
2036
- // src/symbolic/Taylor.ts
2037
- var TAYLOR_MAX_DEGREE = 16;
2038
- function taylorSeries(node, variable, point, degree) {
2039
- if (degree < 0 || !Number.isInteger(degree) || degree > TAYLOR_MAX_DEGREE) {
2040
- throw ErrorFactory.execution(
2041
- "SYMBOLIC_TAYLOR_DEGREE_LIMIT",
2042
- `A Taylor degree must be a whole number from 0 to ${TAYLOR_MAX_DEGREE}.`,
2043
- { limit: TAYLOR_MAX_DEGREE }
2044
- );
2045
- }
2046
- const pointNode = constNode(point);
2047
- let factorial = 1n;
2048
- let result = constNode(RATIONAL_ZERO);
2049
- for (let order = 0; order <= degree; order++) {
2050
- if (order > 0) factorial *= BigInt(order);
2051
- const derivative = differentiate2(node, variable, order);
2052
- const atPoint = simplifySymbolic(substitute(derivative, variable, pointNode));
2053
- if (atPoint.kind !== "const") {
2054
- throw ErrorFactory.execution(
2055
- "SYMBOLIC_TAYLOR_INEXACT",
2056
- `The derivative of order ${order} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,
2057
- { order }
2058
- );
2059
- }
2060
- const coefficient = rationalDiv(atPoint.value, { n: factorial, d: 1n });
2061
- if (isRationalZero(coefficient)) continue;
2062
- const shifted = isRationalZero(point) ? varNode(variable) : { kind: "sub", left: varNode(variable), right: pointNode };
2063
- const power3 = order === 0 ? constNode(1) : order === 1 ? shifted : powNode(shifted, constNode(order));
2064
- result = { kind: "add", left: result, right: { kind: "mul", left: constNode(coefficient), right: power3 } };
2065
- }
2066
- return simplifySymbolic(result);
2067
- }
2068
- function jacobian(functions, variables) {
2069
- return functions.map((fn) => variables.map((variable) => differentiate2(fn, variable)));
2070
- }
2071
-
2072
- // src/engine/EngineContext.ts
2073
- function createEngineContext() {
2074
- return {
2075
- pluginFunctions: {},
2076
- opRegistry: new OpRegistry(),
2077
- variableResolver: new VariableResolver(),
2078
- pluginFunctionOwners: {}
2079
- };
2080
- }
2081
- var defaultEngineContext = createEngineContext();
2082
-
2083
- // src/packages/finance/data/CpiTable.ts
2084
- var CPI_TABLE = {
2085
- 1970: 38.8,
2086
- 1971: 40.5,
2087
- 1972: 41.8,
2088
- 1973: 44.4,
2089
- 1974: 49.3,
2090
- 1975: 53.8,
2091
- 1976: 56.9,
2092
- 1977: 60.6,
2093
- 1978: 65.2,
2094
- 1979: 72.6,
2095
- 1980: 82.4,
2096
- 1981: 90.9,
2097
- 1982: 96.5,
2098
- 1983: 99.6,
2099
- 1984: 103.9,
2100
- 1985: 107.6,
2101
- 1986: 109.6,
2102
- 1987: 113.6,
2103
- 1988: 118.3,
2104
- 1989: 124,
2105
- 1990: 130.7,
2106
- 1991: 136.2,
2107
- 1992: 140.3,
2108
- 1993: 144.5,
2109
- 1994: 148.2,
2110
- 1995: 152.4,
2111
- 1996: 156.9,
2112
- 1997: 160.5,
2113
- 1998: 163,
2114
- 1999: 166.6,
2115
- 2e3: 172.2,
2116
- 2001: 177.1,
2117
- 2002: 179.9,
2118
- 2003: 184,
2119
- 2004: 188.9,
2120
- 2005: 195.3,
2121
- 2006: 201.6,
2122
- 2007: 207.3,
2123
- 2008: 215.3,
2124
- 2009: 214.5,
2125
- 2010: 218.1,
2126
- 2011: 224.9,
2127
- 2012: 229.6,
2128
- 2013: 233,
2129
- 2014: 236.7,
2130
- 2015: 237,
2131
- 2016: 240,
2132
- 2017: 245.1,
2133
- 2018: 251.1,
2134
- 2019: 255.7,
2135
- 2020: 258.8,
2136
- 2021: 271,
2137
- 2022: 292.7,
2138
- 2023: 304.7,
2139
- 2024: 313.7,
2140
- // 2025-2026 were projected from model knowledge and are now derived from
2141
- // the IMF monthly CPI series (statisticsoftheworld.com,
2142
- // IMF.CPI.YOY.M?geo=USA), chained forward from the published 2024 figure
2143
- // using annual mean year-over-year rates. 2026 covers January to June only,
2144
- // so it remains a partial year and will move.
2145
- //
2146
- // The projections were 320.6 and 327.4, low by 0.49% and 1.63%. Everything
2147
- // from 2021 to 2024 reproduced the same series to within 0.02%, which is
2148
- // what makes those two the only entries worth changing.
2149
- 2025: 322.2,
2150
- 2026: 332.7
2151
- };
2152
- var CPI_MIN_YEAR = 1970;
2153
- var CPI_MAX_YEAR = 2026;
2154
- function getCpi(year) {
2155
- return CPI_TABLE[Math.trunc(year)];
2156
- }
2157
- function inflationRatio(fromYear, toYear) {
2158
- const fromCpi = getCpi(fromYear);
2159
- const toCpi = getCpi(toYear);
2160
- if (fromCpi === void 0 || toCpi === void 0 || fromCpi === 0) return void 0;
2161
- return toCpi / fromCpi;
2162
- }
2163
- function adjustForInflation(amount, fromYear, toYear) {
2164
- const ratio = inflationRatio(fromYear, toYear);
2165
- if (ratio === void 0) return void 0;
2166
- return amount * ratio;
2167
- }
2168
-
2169
- // src/vm/VMBuiltins.ts
2170
- var ANGLE_KIND = 0;
2171
- function angleInRadians(value) {
2172
- if (value.type === 6 /* Uom */ && value.unit !== void 0) {
2173
- const entry = UNIT_TABLE[value.unit.toLowerCase()];
2174
- if (entry !== void 0 && entry[0] === ANGLE_KIND) return value.toNumber() * entry[1];
2175
- }
2176
- return value.toNumber();
2177
- }
2178
- function pluraliseUnit(unit, count) {
2179
- if (count === 1) return unit;
2180
- const plural = `${unit}s`;
2181
- return UNIT_TABLE[plural.toLowerCase()] === void 0 ? unit : plural;
2182
- }
2183
- function extremum(args, wantLargest) {
2184
- let best;
2185
- let hasNaN = false;
2186
- for (const a of args) {
2187
- if (Number.isNaN(a.toNumber())) {
2188
- hasNaN = true;
2189
- continue;
2190
- }
2191
- if (best === void 0) {
2192
- best = a;
2193
- continue;
2194
- }
2195
- const { lv, rv, sameMeasure } = unifyUom(best, a);
2196
- if (!sameMeasure) {
2197
- const bestUnit = best.type === 6 /* Uom */ ? best.unit : void 0;
2198
- const otherUnit = a.type === 6 /* Uom */ ? a.unit : void 0;
2199
- const named = describeMeasureMismatch(bestUnit, otherUnit, "compared");
2200
- return errorValue(
2201
- "INCOMPATIBLE_UNITS",
2202
- named ?? `Cannot compare incompatible units: ${bestUnit ?? "?"} and ${otherUnit ?? "?"}`
2203
- );
2204
- }
2205
- if (wantLargest ? rv > lv : rv < lv) best = a;
2206
- }
2207
- if (hasNaN) return numberValue(NaN);
2208
- if (best === void 0) return numberValue(wantLargest ? -Infinity : Infinity);
2209
- return best.type === 6 /* Uom */ ? best : numberValue(best.toNumber());
2210
- }
2211
- function keepUnit(operand, magnitude2) {
2212
- if (operand.type === 6 /* Uom */ && operand.unit !== void 0) return uomValue(magnitude2, operand.unit);
2213
- return numberValue(magnitude2);
2214
- }
2215
- function roundToPlaces(source, places) {
2216
- const p = Number.isFinite(places) ? Math.min(100, Math.max(0, Math.trunc(places))) : 0;
2217
- if (source.exact !== void 0) {
2218
- const rounded = decimalRound(source.exact, p);
2219
- return withPlaces(source, decimalToNumber(rounded), p, rounded);
2220
- }
2221
- const value = source.toNumber();
2222
- if (!Number.isFinite(value)) return withPlaces(source, value, p);
2223
- const scale2 = Math.pow(10, p);
2224
- const scaled = value * scale2;
2225
- if (!Number.isFinite(scaled) || Math.abs(scaled) > Number.MAX_SAFE_INTEGER) return withPlaces(source, value, p);
2226
- return withPlaces(source, Math.round(scaled) / scale2, p);
2227
- }
2228
- function withPlaces(source, magnitude2, places, exact) {
2229
- const result = source.type === 6 /* Uom */ && source.unit !== void 0 ? uomValue(magnitude2, source.unit) : numberValue(magnitude2);
2230
- result.decimalPlaces = places;
2231
- if (exact !== void 0) result.exact = exact;
2232
- return result;
2233
- }
2234
- function nonFiniteEuclidOperand(a, b, name) {
2235
- if (Number.isFinite(a) && Number.isFinite(b)) return null;
2236
- const culprit = Number.isFinite(a) ? b : a;
2237
- return errorValue(
2238
- "INVALID_INTEGER_OPERAND",
2239
- `${name} needs two whole numbers, and ${Number.isNaN(culprit) ? "one of them has no value" : "one of them is infinite"}`
2240
- );
2241
- }
2242
- function euclidGcd(a, b) {
2243
- let x = a;
2244
- let y = b;
2245
- while (y !== 0) {
2246
- const t = y;
2247
- y = x % y;
2248
- x = t;
2249
- }
2250
- return x;
2251
- }
2252
- var builtinFunctions = {
2253
- // ── Populated below ──
2254
- // sqrt: a negative argument has a complex answer now that there is a complex
2255
- // number to give, so this no longer quietly returns NaN. The exact path runs
2256
- // first, so sqrt(-4) is 2i rather than an approximation.
2257
- 0: (args) => {
2258
- const value = args[0].toNumber();
2259
- if (value >= 0) return numberValue(Math.sqrt(value));
2260
- return symbolicToValue(callNode("sqrt", [constNode(value)]));
2261
- },
2262
- // abs(a): for a Matrix, "|a|" (Calca's determinant-pipe notation) is a
2263
- // valid alias for det(a) (index 64), reusing the SAME implementation
2264
- // not a separate one. Plain-number abs is unaffected.
2265
- 1: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : keepUnit(args[0], Math.abs(args[0].toNumber())),
2266
- // sin/cos/tan accept an angle with a unit; see angleInRadians().
2267
- 2: (args) => numberValue(Math.sin(angleInRadians(args[0]))),
2268
- 3: (args) => numberValue(Math.cos(angleInRadians(args[0]))),
2269
- 4: (args) => numberValue(Math.tan(angleInRadians(args[0]))),
2270
- 5: (args) => numberValue(Math.log(args[0].toNumber())),
2271
- // round/ceil/floor keep a unit for the same reason abs does; see keepUnit().
2272
- 6: (args) => keepUnit(args[0], Math.ceil(args[0].toNumber())),
2273
- 7: (args) => keepUnit(args[0], Math.floor(args[0].toNumber())),
2274
- 8: (args) => args.length >= 2 ? (
2275
- // round(x, n): round to n decimal places and display at that precision.
2276
- roundToPlaces(args[0], args[1].toNumber())
2277
- ) : (
2278
- // round(x): nearest whole number, the way it always was.
2279
- keepUnit(args[0], Math.round(args[0].toNumber()))
2280
- ),
2281
- // min/max: see extremum() for why the winner is carried around as a Value
2282
- // rather than as a running number.
2283
- 9: (args) => extremum(args, false),
2284
- 10: (args) => extremum(args, true),
2285
- 11: (args) => numberValue(Math.asin(args[0].toNumber())),
2286
- 12: (args) => numberValue(Math.acos(args[0].toNumber())),
2287
- 13: (args) => numberValue(Math.atan(args[0].toNumber())),
2288
- 14: (args) => numberValue(Math.atan2(args[0].toNumber(), args[1].toNumber())),
2289
- 15: (args) => numberValue(Math.sinh(args[0].toNumber())),
2290
- 16: (args) => numberValue(Math.cosh(args[0].toNumber())),
2291
- 17: (args) => numberValue(Math.tanh(args[0].toNumber())),
2292
- 18: (args) => numberValue(Math.asinh(args[0].toNumber())),
2293
- 19: (args) => numberValue(Math.acosh(args[0].toNumber())),
2294
- 20: (args) => numberValue(Math.atanh(args[0].toNumber())),
2295
- 21: (args) => numberValue(Math.cbrt(args[0].toNumber())),
2296
- 22: (args) => numberValue(Math.clz32(args[0].toNumber())),
2297
- 23: (args) => numberValue(Math.expm1(args[0].toNumber())),
2298
- 24: (args) => numberValue(Math.exp(args[0].toNumber())),
2299
- 25: (args) => numberValue(Math.fround(args[0].toNumber())),
2300
- // hypot: left as .map()+spread (unlike min/max above), Math.hypot uses
2301
- // a numerically-stable scaling algorithm internally to avoid overflow
2302
- // for very large/small inputs; a naive manual reimplementation risks
2303
- // silently changing results at the extremes, so the tiny array
2304
- // allocation here is the safer trade.
2305
- 26: (args) => numberValue(Math.hypot(...args.map((a) => a.toNumber()))),
2306
- 27: (args) => numberValue(Math.imul(args[0].toNumber(), args[1].toNumber())),
2307
- 28: (args) => numberValue(Math.log10(args[0].toNumber())),
2308
- 29: (args) => numberValue(Math.log1p(args[0].toNumber())),
2309
- 30: (args) => numberValue(Math.log2(args[0].toNumber())),
2310
- // pow(): the spelled-out form of `^`, so a Matrix base means the same
2311
- // repeated matrix multiplication `^` means. Without this branch
2312
- // `pow([1,2;3,4], 2)` was Math.pow of a value whose toNumber() is 0, and
2313
- // came back as the number 0. See vm/MatrixOps.ts's matrixPower().
2314
- 31: (args) => {
2315
- if (args[0].type === 7 /* Matrix */) {
2316
- if (args[1].type !== 0 /* Number */) {
2317
- return errorValue("MATRIX_POWER_UNSUPPORTED", `pow: a matrix's exponent must be a whole number, as in "pow([1,2;3,4], 2)".`);
2318
- }
2319
- return matrixPower(args[0].value, args[1].value);
2320
- }
2321
- if (args[1].type === 7 /* Matrix */) {
2322
- return errorValue("MATRIX_POWER_UNSUPPORTED", `pow: a matrix may only be the base, as in "pow([1,2;3,4], 2)".`);
2323
- }
2324
- return numberValue(power(args[0].toNumber(), args[1].toNumber()));
2325
- },
2326
- 32: () => numberValue(Math.random()),
2327
- // takes no arguments, unlike its neighbours
2328
- 33: (args) => numberValue(Math.sign(args[0].toNumber())),
2329
- 34: (args) => numberValue(Math.trunc(args[0].toNumber())),
2330
- 35: (args) => numberValue(args[0].toNumber() * Math.PI / 180),
2331
- 36: (args) => numberValue(args[0].toNumber() * 180 / Math.PI),
2332
- // 37: diceRoll(from, to), random integer in range [from, to] inclusive.
2333
- // A reversed range (from > to) used to silently produce values outside
2334
- // [to, from] via a negative-length Math.random() spread (e.g.
2335
- // "roll(6, 1)" returning values like 2-5, never 1 or 6) instead of
2336
- // erroring on the invalid input.
2337
- 37: (args) => {
2338
- const from = args[0].toNumber();
2339
- const to = args[1].toNumber();
2340
- if (from > to) {
2341
- return errorValue("INVALID_RANGE", `roll: invalid range, ${from} is greater than ${to}`);
2342
- }
2343
- return numberValue(Math.floor(Math.random() * (to - from + 1)) + from);
2344
- },
2345
- // gcd(a, b), Euclidean algorithm. Negative inputs are treated by
2346
- // magnitude (gcd is conventionally defined over non-negative integers).
2347
- 38: (args) => {
2348
- const a = Math.trunc(Math.abs(args[0].toNumber()));
2349
- const b = Math.trunc(Math.abs(args[1].toNumber()));
2350
- const nonFinite = nonFiniteEuclidOperand(a, b, "gcd");
2351
- if (nonFinite) return nonFinite;
2352
- return numberValue(euclidGcd(a, b));
2353
- },
2354
- // lcm(a, b) = |a*b| / gcd(a, b), via the same Euclidean gcd inline
2355
- // (a standalone gcd() call site, no shared helper needed for two uses).
2356
- 39: (args) => {
2357
- const a = Math.trunc(Math.abs(args[0].toNumber()));
2358
- const b = Math.trunc(Math.abs(args[1].toNumber()));
2359
- const nonFinite = nonFiniteEuclidOperand(a, b, "lcm");
2360
- if (nonFinite) return nonFinite;
2361
- if (a === 0 || b === 0) return numberValue(0);
2362
- return numberValue(a / euclidGcd(a, b) * b);
2363
- },
2364
- // permutation(n, r) = n! / (n-r)!, computed as a running product
2365
- // rather than two full factorials, so it stays exact for n well
2366
- // beyond where n! itself would exceed Number.MAX_SAFE_INTEGER.
2367
- //
2368
- // The loop stops the moment the product stops being a representable
2369
- // double, which is both the answer `fact` (index 62) already gives for
2370
- // the same question and the thing that bounds the loop at all. `r` comes
2371
- // straight off the stack: `permutation(1000000000000, 1000000000000)`
2372
- // used to run a trillion iterations, of which the first ~170 computed
2373
- // something and the rest multiplied Infinity by a number, and it had not
2374
- // returned after thirty seconds. Every factor here is at least 1 and they
2375
- // descend from `n`, so a product that is still finite after 170 steps
2376
- // means the factors are small, which in turn means `r <= n` is small: the
2377
- // early exit bounds the trip count without a separate estimate, and
2378
- // without ever refusing a permutation that does have an answer.
2379
- 40: (args) => {
2380
- const n = Math.trunc(args[0].toNumber());
2381
- const r = Math.trunc(args[1].toNumber());
2382
- if (n < 0 || r < 0 || r > n) {
2383
- return errorValue("INVALID_RANGE", `permutation: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
2384
- }
2385
- let result = 1;
2386
- for (let i = 0; i < r; i++) {
2387
- result *= n - i;
2388
- if (!Number.isFinite(result)) {
2389
- return errorValue(
2390
- "PERMUTATION_OVERFLOW",
2391
- `permutation: P(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${r} factors)`
2392
- );
2393
- }
2394
- }
2395
- return numberValue(result);
2396
- },
2397
- // combination(n, r) = n! / (r! * (n-r)!), multiply-then-divide one
2398
- // step at a time (standard technique) keeps every intermediate result
2399
- // an integer, avoiding the overflow a naive factorial-ratio would hit.
2400
- //
2401
- // Same early exit, and needed for the same reason: `k = min(r, n-r)`
2402
- // halves the trip count and bounds nothing, so `combination(1e12, 5e11)`
2403
- // asked for five hundred billion iterations. The running value is C(n, i),
2404
- // which grows monotonically to the middle, so once it is past what a
2405
- // double can hold it never comes back, and the largest run this can now
2406
- // take is the thousand-odd steps C(n, k) needs to cross that line.
2407
- 41: (args) => {
2408
- const n = Math.trunc(args[0].toNumber());
2409
- const r = Math.trunc(args[1].toNumber());
2410
- if (n < 0 || r < 0 || r > n) {
2411
- return errorValue("INVALID_RANGE", `combination: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
2412
- }
2413
- const k = Math.min(r, n - r);
2414
- let result = 1;
2415
- for (let i = 0; i < k; i++) {
2416
- result = result * (n - i) / (i + 1);
2417
- if (!Number.isFinite(result)) {
2418
- return errorValue(
2419
- "COMBINATION_OVERFLOW",
2420
- `combination: C(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${k} steps)`
2421
- );
2422
- }
2423
- }
2424
- return numberValue(Math.round(result));
2425
- },
2426
- // average(...), arithmetic mean of any number of arguments. Backs the
2427
- // MathPhrases package's "average of X, Y, Z" (packages/mathphrases/).
2428
- 42: (args) => {
2429
- if (args.length === 0) return numberValue(0);
2430
- const sum = args.reduce((acc, a) => acc + a.toNumber(), 0);
2431
- return numberValue(sum / args.length);
2432
- },
2433
- // median(...), middle value; average of the two middle values for an
2434
- // even argument count.
2435
- 43: (args) => {
2436
- if (args.length === 0) return numberValue(0);
2437
- const sorted = args.map((a) => a.toNumber()).sort((a, b) => a - b);
2438
- const mid = Math.floor(sorted.length / 2);
2439
- return numberValue(
2440
- sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
2441
- );
2442
- },
2443
- // total(...), sum of any number of arguments.
2444
- 44: (args) => numberValue(args.reduce((acc, a) => acc + a.toNumber(), 0)),
2445
- // count(...), number of arguments passed.
2446
- 45: (args) => numberValue(args.length),
2447
- // proportion(a, b, c) -> d such that a:b = c:d, i.e. d = c * (b/a)
2448
- // "A is to B as C is to what". Unit-aware via unifyUom: "5 km is to
2449
- // 500m as 5 cm is to what" unifies 5km/500m to a 10:1 ratio (500m ==
2450
- // 0.5km), so 5cm at the same ratio -> 0.5cm. Falls back to plain
2451
- // toNumber() ratios when the units aren't the same measure (unifyUom's
2452
- // own fallback) rather than guessing at an unsupported conversion.
2453
- 46: (args) => {
2454
- const [a, b, c] = args;
2455
- const { lv: aNum, rv: bNum } = unifyUom(a, b);
2456
- if (aNum === 0) {
2457
- return errorValue("PROPORTION_DIVIDE_BY_ZERO", `Cannot compute proportion: "${a.value}" is zero`);
2458
- }
2459
- const result = c.toNumber() * (bNum / aNum);
2460
- return c.type === 6 /* Uom */ ? uomValue(result, c.unit) : numberValue(result);
2461
- },
2462
- // clamp(value, lo, hi), restrict value to [lo, hi]. Backs
2463
- // "clamp X between Y and Z" / "clamp X from Y to Z".
2464
- 47: (args) => {
2465
- const value = args[0].toNumber();
2466
- const lo = args[1].toNumber();
2467
- const hi = args[2].toNumber();
2468
- if (lo > hi) {
2469
- return errorValue("INVALID_RANGE", `clamp: invalid range, ${lo} is greater than ${hi}`);
2470
- }
2471
- return numberValue(Math.min(Math.max(value, lo), hi));
2472
- },
2473
- // hex(n), Python/JS-style call-syntax hex formatting, e.g. hex(255) ->
2474
- // "0xFF". Distinct from the Converters package's `255 as hex` (see
2475
- // packages/converters/parselets/AsConverterParselet.ts): "as hex"
2476
- // produces a ValueType.Hex (a typed NUMBER that still participates in
2477
- // arithmetic, formatted specially on display), while hex() is a plain
2478
- // function call that returns an ordinary String value, matching
2479
- // Python's hex()/JS convention of a function returning display text,
2480
- // not a numeric type.
2481
- 48: (args) => hexValue(args[0].toNumber()),
2482
- // bin(n). Same call-syntax shape as hex() above, e.g. bin(10) -> "0b1010".
2483
- 49: (args) => hexValue(args[0].toNumber(), "bin"),
2484
- // int(x), coerce ANY value (Number, Percentage, Uom, String, Hex, ...)
2485
- // to a plain integer Number, truncating any fractional part toward
2486
- // zero (Math.trunc semantics: int(5.7) -> 5, int(-5.7) -> -5). Distinct
2487
- // from the Converters package's `x as number` (TO_NUMBER opcode),
2488
- // which only strips a unit/percentage wrapper and keeps any decimal
2489
- // part (e.g. "5.7 as number" -> 5.7), int() additionally truncates.
2490
- 50: (args) => numberValue(Math.trunc(args[0].toNumber())),
2491
- // ── Finance (packages/finance/) ──────────────────────────────────────
2492
- // All finance builtins preserve the principal/amount argument's Uom
2493
- // unit (e.g. a currency like "$") onto the result, matching
2494
- // ProportionParselet's convention (index 46, above), a plain-number
2495
- // input produces a plain-number result.
2496
- //
2497
- // `rate` arguments are always a decimal fraction (e.g. 0.07 for 7%)
2498
- // this is how "%" already normalizes everywhere else in this codebase
2499
- // (see packages/percentage/parselets/PercentParselet.ts: "7%" divides
2500
- // by 100 at parse time, producing a plain Number 0.07, not a distinct
2501
- // percentage type). Writing "at 7" instead of "at 7%" in a phrase form
2502
- // passes 7 as-is (not 0.07), the "%" is not implicit.
2503
- // compoundFutureValue(principal, rate, years) -> FV = P*(1+r)^years.
2504
- // Backs "compound interest on $P over Y years at R%" and the
2505
- // compoundInterest(principal, rate, years) function-call form.
2506
- 51: (args) => {
2507
- const principal = args[0].toNumber();
2508
- const rate = args[1].toNumber();
2509
- const years = args[2].toNumber();
2510
- if (1 + rate <= 0) {
2511
- return errorValue("INVALID_RATE", `compoundInterest: rate ${rate} makes (1 + rate) non-positive`);
2512
- }
2513
- const fv = principal * Math.pow(1 + rate, years);
2514
- return args[0].type === 6 /* Uom */ ? uomValue(fv, args[0].unit) : numberValue(fv);
2515
- },
2516
- // compoundInterestEarned(principal, rate, years) -> FV - principal, the
2517
- // interest-only portion. Backs "interest on $P over Y years at R%" and
2518
- // the interestEarned(principal, rate, years) function-call form.
2519
- 52: (args) => {
2520
- const principal = args[0].toNumber();
2521
- const rate = args[1].toNumber();
2522
- const years = args[2].toNumber();
2523
- if (1 + rate <= 0) {
2524
- return errorValue("INVALID_RATE", `interestEarned: rate ${rate} makes (1 + rate) non-positive`);
2525
- }
2526
- const interest = principal * (Math.pow(1 + rate, years) - 1);
2527
- return args[0].type === 6 /* Uom */ ? uomValue(interest, args[0].unit) : numberValue(interest);
2528
- },
2529
- // compoundInterestRate(principal, futureValue, years) -> the rate (as a
2530
- // decimal fraction) needed to grow principal to futureValue over years.
2531
- // Function-call only, no clean phrase form for a reverse calculation
2532
- // like this without inventing awkward new keywords, so it's scoped to
2533
- // compoundInterestRate(...) rather than a natural-language phrase.
2534
- 53: (args) => {
2535
- const principal = args[0].toNumber();
2536
- const futureValue = args[1].toNumber();
2537
- const years = args[2].toNumber();
2538
- if (principal <= 0 || futureValue <= 0) {
2539
- return errorValue("INVALID_RANGE", `compoundInterestRate: principal and futureValue must both be positive`);
2540
- }
2541
- if (years <= 0) {
2542
- return errorValue("INVALID_RANGE", `compoundInterestRate: years must be greater than 0`);
2543
- }
2544
- return numberValue(Math.pow(futureValue / principal, 1 / years) - 1);
2545
- },
2546
- // compoundInterestYears(principal, futureValue, rate) -> the number of
2547
- // years needed to grow principal to futureValue at a fixed rate.
2548
- // Function-call only, same reasoning as index 53 above.
2549
- 54: (args) => {
2550
- const principal = args[0].toNumber();
2551
- const futureValue = args[1].toNumber();
2552
- const rate = args[2].toNumber();
2553
- if (principal <= 0 || futureValue <= 0) {
2554
- return errorValue("INVALID_RANGE", `compoundInterestYears: principal and futureValue must both be positive`);
2555
- }
2556
- if (1 + rate <= 0 || rate === 0) {
2557
- return errorValue("INVALID_RATE", `compoundInterestYears: rate ${rate} is not usable (must be > -1 and not 0)`);
2558
- }
2559
- return numberValue(Math.log(futureValue / principal) / Math.log(1 + rate));
2560
- },
2561
- // loanRepayment(principal, rate, years, periodsPerYear), standard
2562
- // amortizing-loan repayment (mortgage formula), redistributed evenly
2563
- // across `periodsPerYear` periods/year: 365=daily, 12=monthly, 1=annual,
2564
- // 0=total over the life of the loan. The loan is ALWAYS amortized
2565
- // monthly internally (the standard mortgage convention) regardless of
2566
- // periodsPerYear, "daily"/"annual"/"total" are the same total
2567
- // repayment redistributed, not separately-amortized loans. Verified
2568
- // against real worked numbers (principal=$10,000, rate=6%, years=6):
2569
- // monthly $165.73, annual $1,988.75 (== total/years exactly), daily
2570
- // $5.45 (== total/(years*365)), total $11,932.48.
2571
- // Backs "daily/monthly/annual/total repayment on $P over Y years at R%".
2572
- 55: (args) => {
2573
- const principal = args[0].toNumber();
2574
- const rate = args[1].toNumber();
2575
- const years = args[2].toNumber();
2576
- const periodsPerYear = args[3].toNumber();
2577
- if (principal <= 0) return errorValue("INVALID_RANGE", `loanRepayment: principal must be positive`);
2578
- if (years <= 0) return errorValue("INVALID_RANGE", `loanRepayment: years must be positive`);
2579
- if (rate < 0) return errorValue("INVALID_RATE", `loanRepayment: rate must not be negative`);
2580
- if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanRepayment: periodsPerYear must not be negative`);
2581
- const { totalRepayment } = amortizeLoan(principal, rate, years);
2582
- const result = periodsPerYear === 0 ? totalRepayment : totalRepayment / (years * periodsPerYear);
2583
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2584
- },
2585
- // loanInterest(principal, rate, years, periodsPerYear), the interest
2586
- // portion of index 55's repayment, same periodsPerYear convention.
2587
- // Backs "daily/monthly/annual/total interest on $P over Y years at R%".
2588
- 56: (args) => {
2589
- const principal = args[0].toNumber();
2590
- const rate = args[1].toNumber();
2591
- const years = args[2].toNumber();
2592
- const periodsPerYear = args[3].toNumber();
2593
- if (principal <= 0) return errorValue("INVALID_RANGE", `loanInterest: principal must be positive`);
2594
- if (years <= 0) return errorValue("INVALID_RANGE", `loanInterest: years must be positive`);
2595
- if (rate < 0) return errorValue("INVALID_RATE", `loanInterest: rate must not be negative`);
2596
- if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanInterest: periodsPerYear must not be negative`);
2597
- const { totalInterest } = amortizeLoan(principal, rate, years);
2598
- const result = periodsPerYear === 0 ? totalInterest : totalInterest / (years * periodsPerYear);
2599
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2600
- },
2601
- // monthlyPayment(principal, rate, years), convenience 3-arg wrapper
2602
- // around index 55's monthly case, for direct function-call use without
2603
- // the periodsPerYear parameter (the task's minimum-ask function form).
2604
- 57: (args) => {
2605
- const principal = args[0].toNumber();
2606
- const rate = args[1].toNumber();
2607
- const years = args[2].toNumber();
2608
- if (principal <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: principal must be positive`);
2609
- if (years <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: years must be positive`);
2610
- if (rate < 0) return errorValue("INVALID_RATE", `monthlyPayment: rate must not be negative`);
2611
- const { monthlyPayment } = amortizeLoan(principal, rate, years);
2612
- return args[0].type === 6 /* Uom */ ? uomValue(monthlyPayment, args[0].unit) : numberValue(monthlyPayment);
2613
- },
2614
- // taxAdd(amount, rate) -> amount * (1 + rate), the tax-inclusive total.
2615
- // Backs the taxAdd() function-call form, whose name promises exactly this.
2616
- // The "tax on $X at R%" PHRASE does NOT use it, see index 86.
2617
- //
2618
- // No default rate is baked in anywhere, the caller always supplies one
2619
- // explicitly, since tax rates vary by region and change over time; this
2620
- // package makes no assumption about which rate applies.
2621
- 58: (args) => {
2622
- const amount = args[0].toNumber();
2623
- const rate = args[1].toNumber();
2624
- if (args[0].type === 6 /* Uom */) return scaleMoneyByPercent(args[0], args[0].unit, rate, 1);
2625
- return numberValue(amount * (1 + rate));
2626
- },
2627
- // taxRemove(amount, rate) -> amount / (1 + rate), extracts the
2628
- // pre-tax amount from a tax-INCLUSIVE total. Backs "tax off $X at R%" /
2629
- // "VAT off $X at R%".
2630
- 59: (args) => {
2631
- const amount = args[0].toNumber();
2632
- const rate = args[1].toNumber();
2633
- if (1 + rate <= 0) {
2634
- return errorValue("INVALID_RATE", `taxRemove: rate ${rate} makes (1 + rate) non-positive`);
2635
- }
2636
- if (args[0].type === 6 /* Uom */) {
2637
- return removeTaxExact(args[0], args[0].unit, rate) ?? uomValue(amount / (1 + rate), args[0].unit);
2638
- }
2639
- return numberValue(amount / (1 + rate));
2640
- },
2641
- // inflationAdjust(amount, fromYear, toYear) -- CPI-based inflation
2642
- // adjustment between two arbitrary years, using the bundled CPI-U
2643
- // table (packages/finance/data/CpiTable.ts -- see its doc comment for
2644
- // vintage/accuracy notes). Backs the function-call form
2645
- // inflationAdjust(...) (FunctionCallParselet's builtinNameToIndex map)
2646
- // and the "what is $X in fromYear worth in toYear" phrase form
2647
- // (InflationQueryParselet.ts). The two present-year-relative phrase
2648
- // forms ("what is $X from year" / "what was $X worth in year" / "$X
2649
- // in year dollars") and the flat-rate future-value projection ("value
2650
- // of $X in year assuming N% inflation") are collision-safe
2651
- // pluginFunctions instead, not indices here -- see
2652
- // packages/finance/parselets/InflationPluginFunctions.ts.
2653
- 60: (args) => {
2654
- const amount = args[0].toNumber();
2655
- const fromYear = args[1].toNumber();
2656
- const toYear = args[2].toNumber();
2657
- const ratio = inflationRatio(fromYear, toYear);
2658
- if (ratio === void 0) {
2659
- return errorValue(
2660
- "INFLATION_YEAR_OUT_OF_RANGE",
2661
- `inflationAdjust: fromYear ${fromYear} or toYear ${toYear} is outside the bundled CPI table's range (${CPI_MIN_YEAR}-${CPI_MAX_YEAR})`
2662
- );
2663
- }
2664
- const result = amount * ratio;
2665
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2666
- },
2667
- // root(n, x) -- the n-th root of x (Numi's `root n (x)` phrasing maps
2668
- // to this same call-style form; see FunctionCallParselet's name map).
2669
- // No native Math.root exists (unlike Math.cbrt for n=3 specifically),
2670
- // so this is Math.pow(x, 1/n) directly -- exact for n=2/n=3 modulo the
2671
- // usual floating-point pow() rounding, same precision class as every
2672
- // other builtin here.
2673
- 61: (args) => {
2674
- const n = args[0].toNumber();
2675
- const x = args[1].toNumber();
2676
- return numberValue(power(x, 1 / n));
2677
- },
2678
- // fact(n) / factorial(n) -- integer factorial. Deliberately rejects
2679
- // negative or non-integer input (factorial isn't defined for either
2680
- // without a gamma-function generalization this engine doesn't need) and
2681
- // caps at 170 -- Number.MAX_VALUE overflows to Infinity at 171!, so
2682
- // returning a silently-wrong (or silently-infinite) result past that
2683
- // point would be worse than a clear error.
2684
- 62: (args) => {
2685
- const n = args[0].toNumber();
2686
- if (!Number.isInteger(n) || n < 0) {
2687
- return errorValue("INVALID_FACTORIAL_INPUT", `fact: ${n} is not a non-negative integer`);
2688
- }
2689
- if (n > 170) {
2690
- return errorValue("FACTORIAL_OVERFLOW", `fact: ${n}! exceeds the maximum representable double (170! is the largest finite factorial)`);
2691
- }
2692
- let result = 1;
2693
- for (let i = 2; i <= n; i++) result *= i;
2694
- return numberValue(result);
2695
- },
2696
- // ── Matrix (packages/matrix/) ────────────────────────────────────────
2697
- // transpose(a)/det(a)/inv(a)/dot(a,b), reachable both via ordinary
2698
- // function-call syntax (this map) and via operator syntax (`^T`, `^-1`
2699
- //. See PrecedenceParser.ts's CARET special-casing, which emits these
2700
- // SAME indices) and `|a|` (abs()'s Matrix branch, index 1 above).
2701
- // Real linear-algebra work lives in vm/MatrixOps.ts, shared by both
2702
- // entry points rather than duplicated.
2703
- // transpose(a), for a Matrix, swaps rows/cols. A plain Number is its
2704
- // own transpose (a 1x1 "matrix" transposed is itself), matches this
2705
- // engine's existing convention of treating a scalar as a trivial 1x1
2706
- // matrix (see Value.ts's toNumber()/isNaN() 1x1 special case).
2707
- 63: (args) => args[0].type === 7 /* Matrix */ ? transpose(args[0].value) : args[0],
2708
- // det(a), determinant. A plain Number's "determinant" is itself (the
2709
- // determinant of a 1x1 matrix [x] is x).
2710
- 64: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : numberValue(args[0].toNumber()),
2711
- // inv(a), matrix inverse for a Matrix; for a plain Number, `1/x`
2712
- // (byte-identical to `Math.pow(x, -1)`, which is what `x^-1` computed
2713
- // before this feature existed. See PrecedenceParser.ts's `^-1`
2714
- // special-case doc comment for why this must stay exact).
2715
- 65: (args) => {
2716
- if (args[0].type === 7 /* Matrix */) return inverse(args[0].value);
2717
- return numberValue(1 / args[0].toNumber());
2718
- },
2719
- // dot(a, b), matrix product / scalar-broadcast, the SAME dispatch as
2720
- // the `*` operator between two matrices (vm/VM.ts's MUL case). Plain
2721
- // Number operands multiply directly; a Number mixed with a Matrix
2722
- // promotes the Number to a 1x1 Matrix first, so it broadcasts exactly
2723
- // like matrixMultiply()'s own 1x1-scalar case.
2724
- 66: (args) => {
2725
- const [a, b] = args;
2726
- if (a.type === 0 /* Number */ && b.type === 0 /* Number */) {
2727
- return numberValue(a.toNumber() * b.toNumber());
2728
- }
2729
- const toMatrix = (v) => v.type === 7 /* Matrix */ ? v.value : { rows: 1, cols: 1, data: [v.toNumber()], hasSymbolic: false };
2730
- return matrixMultiply(toMatrix(a), toMatrix(b));
2731
- },
2732
- // ── Symbolic algebra (packages/symbolic/) ──
2733
- // expand(expr), multiplying out every product and power. Reached only
2734
- // through its own parselet, never the builtinNameToIndex name map, so that
2735
- // `expand` keeps working as an ordinary variable name; see
2736
- // packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts.
2737
- //
2738
- // A non-symbolic argument has nothing to expand and is returned unchanged,
2739
- // which is why this does not go through the CALL_BUILTIN symbolic dispatch:
2740
- // `expand(2+3)` is simply 5.
2741
- 67: (args) => {
2742
- const [value] = args;
2743
- if (value.type !== 9 /* Symbolic */) return value;
2744
- return symbolicToValue(expandSymbolic(value.value));
2745
- },
2746
- // factor(expr), writing a polynomial as a product of irreducible factors
2747
- // over the RATIONALS. x^2-2 and x^2+1 come back unchanged, which is the
2748
- // correct answer over that field rather than a failure; see symbolic/Factor.ts.
2749
- 68: (args) => {
2750
- const [value] = args;
2751
- if (value.type !== 9 /* Symbolic */) return value;
2752
- return symbolicToValue(factorSymbolic(value.value));
2753
- },
2754
- // solve(equation, variable), emitted by its own parselet as three stack
2755
- // values: the two sides of the equation, then the variable NAME as a
2756
- // String. Reading the name as a string rather than compiling it as a
2757
- // variable read is what lets `solve(x^2-4=0, x)` work without `x` existing.
2758
- 69: (args) => {
2759
- const [lhsValue, rhsValue, variableValue] = args;
2760
- if (variableValue?.type !== 3 /* String */) {
2761
- return errorValue("SOLVE_REQUIRES_VARIABLE_NAME", "solve's second argument must be the name of the unknown.");
2762
- }
2763
- return solveEquationValues(lhsValue, rhsValue, variableValue.value);
2764
- },
2765
- // der(expr, variable, order), the symbolic derivative. Genuinely symbolic
2766
- // rather than a finite difference, so it is exact.
2767
- 70: (args) => {
2768
- const [target, variableValue, orderValue] = args;
2769
- const variable = symbolicVariableName(variableValue, "der");
2770
- if (typeof variable !== "string") return variable;
2771
- const expression = valueToSymbolic(target);
2772
- if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "der needs an expression with an exact value.");
2773
- return symbolicToValue(differentiate2(expression, variable, orderValue?.toNumber() ?? 1));
2774
- },
2775
- // integral(expr, variable), the indefinite integral without a constant of
2776
- // integration. Reports what it cannot do rather than approximating; see
2777
- // symbolic/Integral.ts.
2778
- 71: (args) => {
2779
- const [target, variableValue] = args;
2780
- const variable = symbolicVariableName(variableValue, "integral");
2781
- if (typeof variable !== "string") return variable;
2782
- const expression = valueToSymbolic(target);
2783
- if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "integral needs an expression with an exact value.");
2784
- const result = integrate(expression, variable);
2785
- if (!result.ok) return errorValue("SYMBOLIC_INTEGRAL_UNSUPPORTED", `Cannot integrate this: ${result.reason}.`);
2786
- return symbolicToValue(result.value);
2787
- },
2788
- // taylor(expr, variable = point, degree).
2789
- 72: (args) => {
2790
- const [target, variableValue, pointValue, degreeValue] = args;
2791
- const variable = symbolicVariableName(variableValue, "taylor");
2792
- if (typeof variable !== "string") return variable;
2793
- const expression = valueToSymbolic(target);
2794
- const point = valueToSymbolic(pointValue);
2795
- if (expression === null || point === null || point.kind !== "const") {
2796
- return errorValue("SYMBOLIC_NONFINITE_OPERAND", "taylor needs an expression and an exact expansion point.");
2797
- }
2798
- return symbolicToValue(taylorSeries(expression, variable, point.value, degreeValue.toNumber()));
2799
- },
2800
- // jacobian(f1, f2, ...), variadic. The variables are not named: they come
2801
- // from the union of the functions' own unknowns, sorted, matching Calca.
2802
- 73: (args) => {
2803
- const functions = [];
2804
- for (const arg of args) {
2805
- const node = valueToSymbolic(arg);
2806
- if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "jacobian needs expressions with exact values.");
2807
- functions.push(node);
2808
- }
2809
- const variables = /* @__PURE__ */ new Set();
2810
- for (const fn of functions) for (const name of freeVariables(fn)) variables.add(name);
2811
- const sorted = [...variables].sort();
2812
- if (sorted.length === 0) return errorValue("SYMBOLIC_JACOBIAN_NO_VARIABLES", "jacobian needs at least one unknown to differentiate against.");
2813
- const rows = jacobian(functions, sorted);
2814
- const rowMajor = [];
2815
- for (const row of rows) {
2816
- for (const cell of row) rowMajor.push(symbolicToEntry(cell));
2817
- }
2818
- return matrixValue(rows.length, sorted.length, rowMajorToColumnMajor(rows.length, sorted.length, rowMajor));
2819
- },
2820
- // An imaginary literal, 3i. The parselet pushes the numeric part and this
2821
- // turns it into an exact imaginary value.
2822
- 74: (args) => symbolicToValue(complexNode(complex(RATIONAL_ZERO, rationalFromNumber(args[0].toNumber())))),
2823
- // conj(z), re(z) and im(z). Each folds immediately for a literal and stays
2824
- // symbolic for anything still carrying an unknown.
2825
- 75: (args) => applyComplexAccessor("conj", args[0]),
2826
- 76: (args) => applyComplexAccessor("re", args[0]),
2827
- 77: (args) => applyComplexAccessor("im", args[0]),
2828
- // cancel(expr), reducing a quotient of polynomials to lowest terms.
2829
- 78: (args) => {
2830
- const value = args[0];
2831
- if (value.type !== 9 /* Symbolic */) return value;
2832
- return symbolicToValue(cancelSymbolic(value.value));
2833
- },
2834
- // apart(expr), the partial-fraction decomposition of a rational function.
2835
- 79: (args) => {
2836
- const value = args[0];
2837
- if (value.type !== 9 /* Symbolic */) return value;
2838
- return symbolicToValue(apartSymbolic(value.value));
2839
- },
2840
- // taxIn(amount, rate) -> amount - amount/(1 + rate), the tax already
2841
- // contained in a tax-INCLUSIVE total. Backs "tax in/of/from $X at R%".
2842
- // The complement of taxRemove (index 59): the two sum to the gross amount.
2843
- 85: (args) => {
2844
- const amount = args[0].toNumber();
2845
- const rate = args[1].toNumber();
2846
- if (1 + rate <= 0) {
2847
- return errorValue("INVALID_RATE", `taxIn: rate ${rate} makes (1 + rate) non-positive`);
2848
- }
2849
- const tax = amount - amount / (1 + rate);
2850
- if (args[0].type === 6 /* Uom */) {
2851
- return taxInExact(args[0], args[0].unit, rate) ?? uomValue(tax, args[0].unit);
2852
- }
2853
- return numberValue(tax);
2854
- },
2855
- // taxOn(amount, rate) -> amount * rate, the tax itself.
2856
- //
2857
- // The "tax on $X at R%" phrase used to compile to taxAdd (index 58) and
2858
- // answer $345.00 for "tax on $300 at 15%". Soulver answers $45.00, and
2859
- // "the tax on $300" is the tax, not the bill. The total is "$300 + 15%",
2860
- // which reads as a relative increase (see PercentParselet.ts), or
2861
- // taxAdd(300, 0.15) for the function form.
2862
- 86: (args) => {
2863
- const amount = args[0].toNumber();
2864
- const rate = args[1].toNumber();
2865
- if (args[0].type === 6 /* Uom */) return scaleMoneyExact(args[0], rate, args[0].unit);
2866
- return numberValue(amount * rate);
2867
- },
2868
- // ── Degree-taking trig (sind/cosd/tand and the inverses) ──────────────
2869
- // The "d" spellings take and return degrees rather than radians, which is
2870
- // the convention every scientific calculator uses. sin(90 degrees) is the
2871
- // other way to say the same thing; both exist because both get typed.
2872
- 87: (args) => numberValue(Math.sin(args[0].toNumber() * Math.PI / 180)),
2873
- 88: (args) => numberValue(Math.cos(args[0].toNumber() * Math.PI / 180)),
2874
- 89: (args) => numberValue(Math.tan(args[0].toNumber() * Math.PI / 180)),
2875
- 90: (args) => numberValue(Math.asin(args[0].toNumber()) * 180 / Math.PI),
2876
- 91: (args) => numberValue(Math.acos(args[0].toNumber()) * 180 / Math.PI),
2877
- 92: (args) => numberValue(Math.atan(args[0].toNumber()) * 180 / Math.PI),
2878
- // daysCount(n) -> n labelled as days. "days in Q3" is a count of days
2879
- // and should say so; a bare 92 loses what was being counted.
2880
- 93: (args) => uomValue(args[0].toNumber(), "days"),
2881
- // asTwoUnits(value, majorUnit, minorUnit) -> "12 min 30 s".
2882
- //
2883
- // "12.5 minutes in minutes and seconds" asks for one quantity split
2884
- // across two units, which every other conversion path cannot express:
2885
- // they each produce a single number in a single unit.
2886
- //
2887
- // The whole part goes to the major unit and the remainder to the minor,
2888
- // so nothing is lost. A pair that is not ordered major-then-minor, or
2889
- // that spans two different measures, reports rather than guessing.
2890
- 94: (args) => {
2891
- const major = typeof args[1]?.value === "string" ? args[1].value : void 0;
2892
- const minor = typeof args[2]?.value === "string" ? args[2].value : void 0;
2893
- if (major === void 0 || minor === void 0) {
2894
- return errorValue("UNKNOWN_UNIT", 'both units have to be named, as in "12.5 minutes in minutes and seconds"');
2895
- }
2896
- const majorEntry = UNIT_TABLE[major.toLowerCase()];
2897
- const minorEntry = UNIT_TABLE[minor.toLowerCase()];
2898
- if (majorEntry === void 0 || minorEntry === void 0) {
2899
- return errorValue("UNKNOWN_UNIT", `${major} and ${minor}: one of these is not a unit`);
2900
- }
2901
- if (majorEntry[0] !== minorEntry[0]) {
2902
- return errorValue("INCOMPATIBLE_UNITS", `${major} and ${minor} measure different things`);
2903
- }
2904
- if (minorEntry[1] >= majorEntry[1]) {
2905
- return errorValue("INCOMPATIBLE_UNITS", `${major} and ${minor}: name the larger unit first`);
2906
- }
2907
- const source = args[0];
2908
- const sourceEntry = source.type === 6 /* Uom */ && source.unit !== void 0 ? UNIT_TABLE[source.unit.toLowerCase()] : void 0;
2909
- const inBase = source.toNumber() * (sourceEntry?.[1] ?? majorEntry[1]);
2910
- const majorCount = Math.floor(inBase / majorEntry[1]);
2911
- const minorCount = Math.round((inBase - majorCount * majorEntry[1]) / minorEntry[1] * 1e3) / 1e3;
2912
- return stringValue(`${majorCount} ${major} ${minorCount} ${minor}`);
2913
- },
2914
- // makeRate(value, denominatorUnit) -> value per that unit.
2915
- //
2916
- // `3 hours / day` is a rate, `3 hours / 3 days` is a division. The
2917
- // difference is whether a number was written in the denominator, which
2918
- // is decided at parse time, so this only ever receives the rate case.
2919
- //
2920
- // Building the rate directly rather than dividing by an implied 1 is the
2921
- // whole point: a division makes same-measure units cancel, which turned
2922
- // `3 hours / day` into 0.125 when that shortcut was tried.
2923
- 95: (args) => {
2924
- const source = args[0];
2925
- const denominator = String(args[1].value);
2926
- const numerator = source.type === 6 /* Uom */ && source.unit !== void 0 ? source.unit : "";
2927
- if (numerator.includes("/")) {
2928
- return errorValue("INVALID_RATE_UNIT", `${numerator}/${denominator}: that is already a rate`);
2929
- }
2930
- return uomValue(source.toNumber(), `${numerator}/${denominator}`);
2931
- },
2932
- // atRate(quantity, rate) -> whichever of the two the question implies.
2933
- //
2934
- // 30 hours at $30/hour $900 a duration at a price per duration
2935
- // $500 at $20/hour 25 hours money at a price per duration
2936
- //
2937
- // Both are written with the same word and mean opposite operations. Which
2938
- // one applies is decided by which half of the rate the left side matches:
2939
- // match the denominator and you are buying that many, match the numerator
2940
- // and you are asking how many it buys.
2941
- 96: (args) => {
2942
- const left = args[0];
2943
- const rate = args[1];
2944
- if (rate.type !== 6 /* Uom */ || rate.unit === void 0 || !rate.unit.includes("/")) {
2945
- return errorValue("INVALID_RATE", 'at: the right-hand side has to be a rate, as in "$30/hour"');
2946
- }
2947
- const slash = rate.unit.indexOf("/");
2948
- const numerator = rate.unit.slice(0, slash);
2949
- const denominator = rate.unit.slice(slash + 1);
2950
- const leftUnit = left.type === 6 /* Uom */ ? left.unit : void 0;
2951
- const denominatorEntry = UNIT_TABLE[denominator.toLowerCase()];
2952
- const leftEntry = leftUnit === void 0 ? void 0 : UNIT_TABLE[leftUnit.toLowerCase()];
2953
- if (leftEntry !== void 0 && denominatorEntry !== void 0 && leftEntry[0] === denominatorEntry[0]) {
2954
- const inDenominator = left.toNumber() * leftEntry[1] / denominatorEntry[1];
2955
- const total = inDenominator * rate.toNumber();
2956
- return numerator === "" ? numberValue(total) : uomValue(total, numerator);
2957
- }
2958
- if (leftUnit !== void 0 && leftUnit === numerator) {
2959
- const count = left.toNumber() / rate.toNumber();
2960
- return uomValue(count, pluraliseUnit(denominator, count));
2961
- }
2962
- if (leftUnit === void 0) {
2963
- const total = left.toNumber() * rate.toNumber();
2964
- return numerator === "" ? numberValue(total) : uomValue(total, numerator);
2965
- }
2966
- return errorValue("INCOMPATIBLE_UNITS", `at: ${leftUnit} matches neither side of ${rate.unit}`);
2967
- },
2968
- // ── Investments (packages/finance/) ────────────────────────────────────
2969
- // compoundFutureValueEvery(principal, rate, years, periodsPerYear)
2970
- // FV = P(1 + r/n)^(n·y). Index 51 is the same formula with n fixed at 1;
2971
- // this one backs "compounding monthly"/"quarterly"/"daily"/"weekly".
2972
- // Kept separate rather than widening 51, because 51 is also the public
2973
- // compoundInterest(principal, rate, years) call and its arity is part of
2974
- // that contract.
2975
- 80: (args) => {
2976
- const principal = args[0].toNumber();
2977
- const rate = args[1].toNumber();
2978
- const years = args[2].toNumber();
2979
- const perYear = args[3].toNumber();
2980
- if (perYear <= 0) {
2981
- return errorValue("INVALID_RATE", `compounding: ${perYear} periods per year is not a period`);
2982
- }
2983
- if (1 + rate / perYear <= 0) {
2984
- return errorValue("INVALID_RATE", `compounding: rate ${rate} makes each period non-positive`);
2985
- }
2986
- const fv = principal * Math.pow(1 + rate / perYear, perYear * years);
2987
- return args[0].type === 6 /* Uom */ ? uomValue(fv, args[0].unit) : numberValue(fv);
2988
- },
2989
- // compoundInterestEarnedEvery(principal, rate, years, periodsPerYear)
2990
- // The interest-only portion of index 80, i.e. FV - P.
2991
- 81: (args) => {
2992
- const principal = args[0].toNumber();
2993
- const rate = args[1].toNumber();
2994
- const years = args[2].toNumber();
2995
- const perYear = args[3].toNumber();
2996
- if (perYear <= 0 || 1 + rate / perYear <= 0) {
2997
- return errorValue("INVALID_RATE", `compounding: rate ${rate} over ${perYear} periods per year is not usable`);
2998
- }
2999
- const interest = principal * (Math.pow(1 + rate / perYear, perYear * years) - 1);
3000
- return args[0].type === 6 /* Uom */ ? uomValue(interest, args[0].unit) : numberValue(interest);
3001
- },
3002
- // presentValue(futureValue, rate, years) -> FV / (1 + r)^y, what a sum
3003
- // promised in the future is worth today. The inverse of index 51.
3004
- 82: (args) => {
3005
- const future = args[0].toNumber();
3006
- const rate = args[1].toNumber();
3007
- const years = args[2].toNumber();
3008
- if (1 + rate <= 0) {
3009
- return errorValue("INVALID_RATE", `presentValue: rate ${rate} makes (1 + rate) non-positive`);
3010
- }
3011
- const pv = future / Math.pow(1 + rate, years);
3012
- return args[0].type === 6 /* Uom */ ? uomValue(pv, args[0].unit) : numberValue(pv);
3013
- },
3014
- // returnOnInvestment(invested, returned) -> (returned - invested) /
3015
- // invested, the gain as a multiple of what was put in. $500 in and $1,500
3016
- // out is 2x, not 3x: ROI conventionally measures the profit against the
3017
- // cost, so doubling your money is 1x return and tripling it is 2x. The
3018
- // money multiple (3x here) is a different figure; `$1,500 / $500` gives it.
3019
- 83: (args) => {
3020
- const invested = args[0].toNumber();
3021
- const returned = args[1].toNumber();
3022
- if (invested === 0) {
3023
- return errorValue("INVALID_RATE", "roi: nothing was invested, so there is no return on it");
3024
- }
3025
- return numberValue((returned - invested) / invested);
3026
- },
3027
- // annualisedReturn(invested, returned, years) -> CAGR, the constant
3028
- // yearly rate that turns `invested` into `returned` over `years`:
3029
- // (returned/invested)^(1/years) - 1. Returned as a Percentage so it
3030
- // renders "13.99%" rather than 0.1399.
3031
- 84: (args) => {
3032
- const invested = args[0].toNumber();
3033
- const returned = args[1].toNumber();
3034
- const years = args[2].toNumber();
3035
- if (invested <= 0) {
3036
- return errorValue("INVALID_RATE", "annual return: the amount invested must be positive");
3037
- }
3038
- if (years <= 0) {
3039
- return errorValue("INVALID_RATE", "annual return: the period must be longer than zero");
3040
- }
3041
- if (returned <= 0) {
3042
- return errorValue("INVALID_RATE", "annual return: nothing was returned, so there is no annual rate");
3043
- }
3044
- return percentageValue(Math.pow(returned / invested, 1 / years) - 1);
3045
- },
3046
- // roundToPlaces(value, places) -> value rounded to that many decimal
3047
- // places, backing `<value> to <n> dp` (converters/parselets/
3048
- // RoundingParselets.ts).
3049
- //
3050
- // It exists because the obvious bytecode for it, "multiply by 10^p, round,
3051
- // divide by 10^p", is only safe for values small enough that the multiply
3052
- // is exact. `1e21 to 2 dp` came back as 999999999999999900000: 1e21 has no
3053
- // fractional part to round at all, and the round trip through 1e23 was
3054
- // pure loss. Asking for fewer decimal places than a number has cannot
3055
- // change it, so a value that is already whole is returned untouched.
3056
- 97: (args) => roundToPlaces(args[0], args[1].toNumber()),
3057
- // splitEach(amount, n): a per-person bill split, `split $180 between 4` and
3058
- // `$120 + 18% split 3 ways`. Backs both split spellings (see
3059
- // BillSplitParselets.ts). Money stays exact and the shares add back to the
3060
- // total to the cent (see splitEachExact in MoneyExact.ts). A bare number
3061
- // splits to a bare number; the odd penny is named, not rounded away.
3062
- 98: (args) => {
3063
- const n = args[1].toNumber();
3064
- if (!Number.isInteger(n) || n < 1) {
3065
- return errorValue("INVALID_RANGE", `split: the number of shares must be a whole number of at least 1, not ${args[1].toNumber()}.`);
3066
- }
3067
- return splitValue(splitEachExact(args[0], n));
3068
- },
3069
- // ── Savings goals ──────────────────────────────────────────────
3070
- // savingsGoalPayment(target, duration, annualRate): the level contribution
3071
- // per month that reaches `target` over `duration` (months or years), at an
3072
- // optional annual rate compounded monthly. Backs "how much per month to
3073
- // save/reach <target> in <duration> [at <rate>]".
3074
- 99: (args) => {
3075
- const target = args[0].toNumber();
3076
- const months = monthsOfDuration(args[1]);
3077
- const annualRate = args[2].toNumber();
3078
- if (months === null) return errorValue("INVALID_RANGE", `savings goal: the duration must be in months or years, e.g. "in 2 years".`);
3079
- if (target <= 0) return errorValue("INVALID_RANGE", `savings goal: the target must be positive.`);
3080
- if (months <= 0) return errorValue("INVALID_RANGE", `savings goal: the duration must be positive.`);
3081
- if (annualRate < 0) return errorValue("INVALID_RATE", `savings goal: the rate must not be negative.`);
3082
- const payment = annuityPayment(target, annualRate / 12, months);
3083
- return args[0].type === 6 /* Uom */ ? uomValue(payment, args[0].unit) : numberValue(payment);
3084
- },
3085
- // savingsGoalPeriods(target, contribution, periodsPerYear, annualRate,
3086
- // periodUnit): how many whole periods of `contribution` reach `target`,
3087
- // rounded UP, since a part period has not yet reached the goal. Backs
3088
- // "how long to save <target> at <amount> <period> [at <rate>]".
3089
- 100: (args) => {
3090
- const target = args[0].toNumber();
3091
- const contribution = args[1].toNumber();
3092
- const periodsPerYear = args[2].toNumber();
3093
- const annualRate = args[3].toNumber();
3094
- const unit = typeof args[4]?.value === "string" ? args[4].value : "periods";
3095
- if (target <= 0) return errorValue("INVALID_RANGE", `savings goal: the target must be positive.`);
3096
- if (contribution <= 0) return errorValue("INVALID_RANGE", `savings goal: the contribution must be positive.`);
3097
- if (annualRate < 0) return errorValue("INVALID_RATE", `savings goal: the rate must not be negative.`);
3098
- const periods = annuityPeriods(target, contribution, annualRate / periodsPerYear);
3099
- return uomValue(periods, unit);
3100
- }
3101
- };
3102
- function monthsOfDuration(duration) {
3103
- if (duration.type !== 6 /* Uom */) return null;
3104
- const unit = duration.unit;
3105
- if (unit === "months" || unit === "month") return duration.toNumber();
3106
- if (unit === "years" || unit === "year") return duration.toNumber() * 12;
3107
- return null;
3108
- }
3109
- function annuityPayment(target, i, months) {
3110
- return i === 0 ? target / months : target * i / (Math.pow(1 + i, months) - 1);
3111
- }
3112
- function annuityPeriods(target, contribution, i) {
3113
- const raw = i === 0 ? target / contribution : Math.log(1 + target * i / contribution) / Math.log(1 + i);
3114
- return Math.ceil(raw - 1e-9);
3115
- }
3116
- function applyComplexAccessor(name, value) {
3117
- const node = valueToSymbolic(value);
3118
- if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", name + " needs a value with an exact number.");
3119
- return symbolicToValue(callNode(name, [node]));
3120
- }
3121
- function symbolicVariableName(value, verb) {
3122
- if (value?.type !== 3 /* String */) {
3123
- return errorValue("SYMBOLIC_REQUIRES_VARIABLE_NAME", `${verb} needs the name of an unknown.`);
3124
- }
3125
- return value.value;
3126
- }
3127
- function amortizeLoan(principal, annualRate, years) {
3128
- const n = years * 12;
3129
- const rMonthly = annualRate / 12;
3130
- const monthlyPayment = rMonthly === 0 ? principal / n : principal * rMonthly / (1 - Math.pow(1 + rMonthly, -n));
3131
- const totalRepayment = monthlyPayment * n;
3132
- const totalInterest = totalRepayment - principal;
3133
- return { monthlyPayment, totalRepayment, totalInterest };
3134
- }
3135
- var pluginFunctionRegistry = defaultEngineContext.pluginFunctions;
3136
- var MAX_PLUGIN_FUNCTION_INDEX = 255;
3137
- var nextPluginFunctionIndex = 0;
3138
- function allocatePluginFunctionIndex() {
3139
- if (nextPluginFunctionIndex > MAX_PLUGIN_FUNCTION_INDEX) {
3140
- throw ErrorFactory.config(
3141
- "PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",
3142
- `allocatePluginFunctionIndex: pool exhausted (max ${MAX_PLUGIN_FUNCTION_INDEX + 1} allocations).`
3143
- );
3144
- }
3145
- return nextPluginFunctionIndex++;
3146
- }
3147
- var asConverterRegistry = /* @__PURE__ */ new Map();
3148
- function registerAsConverter(name, handler) {
3149
- const key = name.toLowerCase();
3150
- const existing = asConverterRegistry.get(key);
3151
- if (existing && existing !== handler) {
3152
- console.warn(`[asConverterRegistry] Converter name "${key}" is already registered \u2014 overwriting.`);
3153
- }
3154
- asConverterRegistry.set(key, handler);
3155
- }
3156
- function unregisterAsConverter(name) {
3157
- asConverterRegistry.delete(name.toLowerCase());
3158
- }
3159
-
3160
- // src/vm/GlobalVariableStore.ts
3161
- var _GlobalVariableStore = class _GlobalVariableStore {
3162
- constructor() {
3163
- this.values = /* @__PURE__ */ new Map();
3164
- this.listeners = /* @__PURE__ */ new Set();
3165
- this.notifyDepth = 0;
3166
- }
3167
- get(name) {
3168
- return this.values.get(name);
3169
- }
3170
- has(name) {
3171
- return this.values.has(name);
3172
- }
3173
- /**
3174
- * Last-write-wins: any document may call this for any name at any time.
3175
- * Notifies listeners synchronously, within the same call, before
3176
- * returning, so that ThreeTierEvaluator's dirty-marking (a listener)
3177
- * and GlobalVariableAsyncResolver's first-write promise (also a
3178
- * listener) both observe the new value immediately, no microtask delay.
3179
- *
3180
- * A write that does not CHANGE the stored value notifies nobody. This
3181
- * is not just an optimisation, it is what stops a re-evaluation cycle
3182
- * from sustaining itself. Every listener re-runs work in response to a
3183
- * write (ThreeTierEvaluator marks dependent lines dirty; the playground
3184
- * worker refreshes other documents), and those re-runs re-execute the
3185
- * very STORE_GLOBAL_VAR opcode that produced this write. Re-evaluating
3186
- * an unchanged `global :x = 5` line therefore used to re-notify, which
3187
- * re-triggered the listeners, which re-evaluated... bounded only by
3188
- * MAX_NOTIFY_DEPTH below, and only in DEPTH, so with more than one
3189
- * writer the work per keystroke grew exponentially. Nothing observable
3190
- * changed, so there is nothing for a listener to react to.
3191
- */
3192
- set(name, value) {
3193
- const previous = this.values.get(name);
3194
- this.values.set(name, value);
3195
- if (previous !== void 0 && sameValue(previous, value)) return;
3196
- this.notify(name, value);
3197
- }
3198
- notify(name, value) {
3199
- if (this.notifyDepth >= _GlobalVariableStore.MAX_NOTIFY_DEPTH) return;
3200
- this.notifyDepth++;
3201
- try {
3202
- for (const listener of this.listeners) listener(name, value);
3203
- } finally {
3204
- this.notifyDepth--;
3205
- }
3206
- }
3207
- /**
3208
- * Subscribe to every global-variable write (all names, callers filter
3209
- * for the name(s) they care about). Returns an unsubscribe function;
3210
- * callers MUST invoke it when disposing (e.g. ThreeTierEvaluator's
3211
- * terminateWorker()) to avoid leaking listeners for closed documents.
3212
- */
3213
- subscribe(listener) {
3214
- this.listeners.add(listener);
3215
- return () => {
3216
- this.listeners.delete(listener);
3217
- };
3218
- }
3219
- /**
3220
- * Full reset, test-only. Never called from production code paths;
3221
- * globals must outlive any single engine's own clear()/dispose cycle.
3222
- * Tests MUST call this in beforeEach/afterEach since this is a
3223
- * module-level singleton whose state and listeners otherwise leak
3224
- * across test cases and files.
3225
- */
3226
- clear() {
3227
- this.values.clear();
3228
- this.listeners.clear();
3229
- this.notifyDepth = 0;
3230
- }
3231
- };
3232
- /**
3233
- * Guards against runaway cross-document write cycles: doc A's write
3234
- * notifies doc B, whose dirty line, once evaluated, writes a global
3235
- * that notifies doc C, ... eventually back to A. Same philosophy as the
3236
- * VM's own instruction-limit safety net: stop propagating past the
3237
- * limit rather than let a genuine cycle recurse unboundedly. The store
3238
- * itself is left in a well-defined state either way. This only bounds
3239
- * *notification* depth, never the value actually stored.
3240
- */
3241
- _GlobalVariableStore.MAX_NOTIFY_DEPTH = 64;
3242
- var GlobalVariableStore = _GlobalVariableStore;
3243
- function sameValue(a, b) {
3244
- if (a.type !== b.type) return false;
3245
- if (a.unit !== b.unit) return false;
3246
- if ((a.timedOut ?? false) !== (b.timedOut ?? false)) return false;
3247
- const av = a.value;
3248
- const bv = b.value;
3249
- if (Array.isArray(av) || Array.isArray(bv)) {
3250
- if (!Array.isArray(av) || !Array.isArray(bv)) return false;
3251
- if (av.length !== bv.length) return false;
3252
- for (let i = 0; i < av.length; i++) {
3253
- if (!Object.is(av[i], bv[i])) return false;
3254
- }
3255
- return true;
3256
- }
3257
- return Object.is(av, bv);
3258
- }
3259
- var sharedGlobalVariableStore = new GlobalVariableStore();
3260
- function globalDagKey(name) {
3261
- return `global:${name}`;
3262
- }
3263
-
3264
- export { CPI_MAX_YEAR, CPI_MIN_YEAR, OpRegistry, SYMBOLIC_NATIVE_BUILTINS, adjustForInflation, allocatePluginFunctionIndex, asConverterRegistry, bigIntDivisionByZero, binaryOp, builtinFunctions, compareBigIntOperands, compareRationalOperands, compareUom, createEngineContext, defaultEngineContext, describeConversionMismatch, exactRationalOp, globalDagKey, incomparableUnitsError, moneyExactMagnitude, pluginFunctionRegistry, power, registerAsConverter, scaleMoneyByPercent, scaleMoneyExact, sharedGlobalVariableStore, sharedOpRegistry, solveEquationValues, solveForVariable, symbolicBuiltin, symbolicNeg, symbolicPow, toBigIntOperand, uncertainOp, unifyUom, unregisterAsConverter };
3265
- //# sourceMappingURL=chunk-WMQRJTAO.js.map
3266
- //# sourceMappingURL=chunk-WMQRJTAO.js.map