@ducatjs/money 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +51 -0
  3. package/README.md +1034 -3
  4. package/assets/CREDITS.md +12 -0
  5. package/data/adyen-fx.json +19 -0
  6. package/data/adyen.json +171 -0
  7. package/data/braintree.json +223 -0
  8. package/data/cash-rounding.json +520 -0
  9. package/data/checkout.json +230 -0
  10. package/data/cldr-cash.json +101 -0
  11. package/data/historic.json +78 -0
  12. package/data/iso4217-list-one.xml +1956 -0
  13. package/data/iso4217-list-three.xml +1185 -0
  14. package/data/klarna.json +95 -0
  15. package/data/paypal.json +65 -0
  16. package/data/stripe-fx.json +17 -0
  17. package/data/stripe.json +285 -0
  18. package/dist/adyen-fx.d.ts +25 -0
  19. package/dist/adyen-fx.d.ts.map +1 -0
  20. package/dist/adyen-fx.js +140 -0
  21. package/dist/adyen-fx.js.map +1 -0
  22. package/dist/adyen.d.ts +25 -0
  23. package/dist/adyen.d.ts.map +1 -0
  24. package/dist/adyen.js +34 -0
  25. package/dist/adyen.js.map +1 -0
  26. package/dist/allocate.d.ts +72 -0
  27. package/dist/allocate.d.ts.map +1 -0
  28. package/dist/allocate.js +314 -0
  29. package/dist/allocate.js.map +1 -0
  30. package/dist/bag.d.ts +58 -0
  31. package/dist/bag.d.ts.map +1 -0
  32. package/dist/bag.js +122 -0
  33. package/dist/bag.js.map +1 -0
  34. package/dist/boc.d.ts +31 -0
  35. package/dist/boc.d.ts.map +1 -0
  36. package/dist/boc.js +114 -0
  37. package/dist/boc.js.map +1 -0
  38. package/dist/boe.d.ts +33 -0
  39. package/dist/boe.d.ts.map +1 -0
  40. package/dist/boe.js +114 -0
  41. package/dist/boe.js.map +1 -0
  42. package/dist/braintree.d.ts +34 -0
  43. package/dist/braintree.d.ts.map +1 -0
  44. package/dist/braintree.js +45 -0
  45. package/dist/braintree.js.map +1 -0
  46. package/dist/cash.d.ts +64 -0
  47. package/dist/cash.d.ts.map +1 -0
  48. package/dist/cash.js +134 -0
  49. package/dist/cash.js.map +1 -0
  50. package/dist/checkout.d.ts +42 -0
  51. package/dist/checkout.d.ts.map +1 -0
  52. package/dist/checkout.js +52 -0
  53. package/dist/checkout.js.map +1 -0
  54. package/dist/convert.d.ts +52 -0
  55. package/dist/convert.d.ts.map +1 -0
  56. package/dist/convert.js +65 -0
  57. package/dist/convert.js.map +1 -0
  58. package/dist/currency.d.ts +22 -0
  59. package/dist/currency.d.ts.map +1 -0
  60. package/dist/currency.js +38 -0
  61. package/dist/currency.js.map +1 -0
  62. package/dist/decimal.d.ts +52 -0
  63. package/dist/decimal.d.ts.map +1 -0
  64. package/dist/decimal.js +251 -0
  65. package/dist/decimal.js.map +1 -0
  66. package/dist/drizzle/mysql.d.ts +105 -0
  67. package/dist/drizzle/mysql.d.ts.map +1 -0
  68. package/dist/drizzle/mysql.js +60 -0
  69. package/dist/drizzle/mysql.js.map +1 -0
  70. package/dist/drizzle/pg.d.ts +103 -0
  71. package/dist/drizzle/pg.d.ts.map +1 -0
  72. package/dist/drizzle/pg.js +60 -0
  73. package/dist/drizzle/pg.js.map +1 -0
  74. package/dist/drizzle/sqlite.d.ts +102 -0
  75. package/dist/drizzle/sqlite.d.ts.map +1 -0
  76. package/dist/drizzle/sqlite.js +59 -0
  77. package/dist/drizzle/sqlite.js.map +1 -0
  78. package/dist/ecb.d.ts +52 -0
  79. package/dist/ecb.d.ts.map +1 -0
  80. package/dist/ecb.js +285 -0
  81. package/dist/ecb.js.map +1 -0
  82. package/dist/exact.d.ts +62 -0
  83. package/dist/exact.d.ts.map +1 -0
  84. package/dist/exact.js +147 -0
  85. package/dist/exact.js.map +1 -0
  86. package/dist/fed.d.ts +35 -0
  87. package/dist/fed.d.ts.map +1 -0
  88. package/dist/fed.js +134 -0
  89. package/dist/fed.js.map +1 -0
  90. package/dist/fetch.d.ts +103 -0
  91. package/dist/fetch.d.ts.map +1 -0
  92. package/dist/fetch.js +222 -0
  93. package/dist/fetch.js.map +1 -0
  94. package/dist/fixed.d.ts +121 -0
  95. package/dist/fixed.d.ts.map +1 -0
  96. package/dist/fixed.js +420 -0
  97. package/dist/fixed.js.map +1 -0
  98. package/dist/fn.d.ts +34 -0
  99. package/dist/fn.d.ts.map +1 -0
  100. package/dist/fn.js +37 -0
  101. package/dist/fn.js.map +1 -0
  102. package/dist/format.d.ts +13 -0
  103. package/dist/format.d.ts.map +1 -0
  104. package/dist/format.js +90 -0
  105. package/dist/format.js.map +1 -0
  106. package/dist/generated/adyen.d.ts +3 -0
  107. package/dist/generated/adyen.d.ts.map +1 -0
  108. package/dist/generated/adyen.js +144 -0
  109. package/dist/generated/adyen.js.map +1 -0
  110. package/dist/generated/braintree.d.ts +3 -0
  111. package/dist/generated/braintree.d.ts.map +1 -0
  112. package/dist/generated/braintree.js +140 -0
  113. package/dist/generated/braintree.js.map +1 -0
  114. package/dist/generated/cash.d.ts +14 -0
  115. package/dist/generated/cash.d.ts.map +1 -0
  116. package/dist/generated/cash.js +465 -0
  117. package/dist/generated/cash.js.map +1 -0
  118. package/dist/generated/checkout.d.ts +3 -0
  119. package/dist/generated/checkout.d.ts.map +1 -0
  120. package/dist/generated/checkout.js +151 -0
  121. package/dist/generated/checkout.js.map +1 -0
  122. package/dist/generated/historic.d.ts +337 -0
  123. package/dist/generated/historic.d.ts.map +1 -0
  124. package/dist/generated/historic.js +66 -0
  125. package/dist/generated/historic.js.map +1 -0
  126. package/dist/generated/iso4217.d.ts +174 -0
  127. package/dist/generated/iso4217.d.ts.map +1 -0
  128. package/dist/generated/iso4217.js +175 -0
  129. package/dist/generated/iso4217.js.map +1 -0
  130. package/dist/generated/kernel.d.ts +17 -0
  131. package/dist/generated/kernel.d.ts.map +1 -0
  132. package/dist/generated/kernel.js +208 -0
  133. package/dist/generated/kernel.js.map +1 -0
  134. package/dist/generated/klarna.d.ts +3 -0
  135. package/dist/generated/klarna.d.ts.map +1 -0
  136. package/dist/generated/klarna.js +21 -0
  137. package/dist/generated/klarna.js.map +1 -0
  138. package/dist/generated/paypal.d.ts +3 -0
  139. package/dist/generated/paypal.d.ts.map +1 -0
  140. package/dist/generated/paypal.js +31 -0
  141. package/dist/generated/paypal.js.map +1 -0
  142. package/dist/generated/stripe.d.ts +8 -0
  143. package/dist/generated/stripe.d.ts.map +1 -0
  144. package/dist/generated/stripe.js +150 -0
  145. package/dist/generated/stripe.js.map +1 -0
  146. package/dist/historic.d.ts +40 -0
  147. package/dist/historic.d.ts.map +1 -0
  148. package/dist/historic.js +43 -0
  149. package/dist/historic.js.map +1 -0
  150. package/dist/history.d.ts +96 -0
  151. package/dist/history.d.ts.map +1 -0
  152. package/dist/history.js +213 -0
  153. package/dist/history.js.map +1 -0
  154. package/dist/hmrc.d.ts +28 -0
  155. package/dist/hmrc.d.ts.map +1 -0
  156. package/dist/hmrc.js +108 -0
  157. package/dist/hmrc.js.map +1 -0
  158. package/dist/index.d.ts +11 -0
  159. package/dist/index.d.ts.map +1 -0
  160. package/dist/index.js +11 -0
  161. package/dist/index.js.map +1 -0
  162. package/dist/klarna.d.ts +31 -0
  163. package/dist/klarna.d.ts.map +1 -0
  164. package/dist/klarna.js +38 -0
  165. package/dist/klarna.js.map +1 -0
  166. package/dist/kysely.d.ts +120 -0
  167. package/dist/kysely.d.ts.map +1 -0
  168. package/dist/kysely.js +309 -0
  169. package/dist/kysely.js.map +1 -0
  170. package/dist/money.d.ts +302 -0
  171. package/dist/money.d.ts.map +1 -0
  172. package/dist/money.js +703 -0
  173. package/dist/money.js.map +1 -0
  174. package/dist/parse.d.ts +55 -0
  175. package/dist/parse.d.ts.map +1 -0
  176. package/dist/parse.js +419 -0
  177. package/dist/parse.js.map +1 -0
  178. package/dist/paypal.d.ts +41 -0
  179. package/dist/paypal.d.ts.map +1 -0
  180. package/dist/paypal.js +58 -0
  181. package/dist/paypal.js.map +1 -0
  182. package/dist/pg.d.ts +100 -0
  183. package/dist/pg.d.ts.map +1 -0
  184. package/dist/pg.js +343 -0
  185. package/dist/pg.js.map +1 -0
  186. package/dist/plugins/adyen.d.ts +15 -0
  187. package/dist/plugins/adyen.d.ts.map +1 -0
  188. package/dist/plugins/adyen.js +10 -0
  189. package/dist/plugins/adyen.js.map +1 -0
  190. package/dist/plugins/all.d.ts +29 -0
  191. package/dist/plugins/all.d.ts.map +1 -0
  192. package/dist/plugins/all.js +30 -0
  193. package/dist/plugins/all.js.map +1 -0
  194. package/dist/plugins/allocate.d.ts +20 -0
  195. package/dist/plugins/allocate.d.ts.map +1 -0
  196. package/dist/plugins/allocate.js +26 -0
  197. package/dist/plugins/allocate.js.map +1 -0
  198. package/dist/plugins/braintree.d.ts +12 -0
  199. package/dist/plugins/braintree.d.ts.map +1 -0
  200. package/dist/plugins/braintree.js +12 -0
  201. package/dist/plugins/braintree.js.map +1 -0
  202. package/dist/plugins/cash.d.ts +19 -0
  203. package/dist/plugins/cash.d.ts.map +1 -0
  204. package/dist/plugins/cash.js +16 -0
  205. package/dist/plugins/cash.js.map +1 -0
  206. package/dist/plugins/checkout.d.ts +21 -0
  207. package/dist/plugins/checkout.d.ts.map +1 -0
  208. package/dist/plugins/checkout.js +16 -0
  209. package/dist/plugins/checkout.js.map +1 -0
  210. package/dist/plugins/convert.d.ts +19 -0
  211. package/dist/plugins/convert.d.ts.map +1 -0
  212. package/dist/plugins/convert.js +13 -0
  213. package/dist/plugins/convert.js.map +1 -0
  214. package/dist/plugins/exact.d.ts +15 -0
  215. package/dist/plugins/exact.d.ts.map +1 -0
  216. package/dist/plugins/exact.js +13 -0
  217. package/dist/plugins/exact.js.map +1 -0
  218. package/dist/plugins/fixed.d.ts +17 -0
  219. package/dist/plugins/fixed.d.ts.map +1 -0
  220. package/dist/plugins/fixed.js +13 -0
  221. package/dist/plugins/fixed.js.map +1 -0
  222. package/dist/plugins/format.d.ts +9 -0
  223. package/dist/plugins/format.d.ts.map +1 -0
  224. package/dist/plugins/format.js +16 -0
  225. package/dist/plugins/format.js.map +1 -0
  226. package/dist/plugins/klarna.d.ts +10 -0
  227. package/dist/plugins/klarna.d.ts.map +1 -0
  228. package/dist/plugins/klarna.js +10 -0
  229. package/dist/plugins/klarna.js.map +1 -0
  230. package/dist/plugins/paypal.d.ts +14 -0
  231. package/dist/plugins/paypal.d.ts.map +1 -0
  232. package/dist/plugins/paypal.js +16 -0
  233. package/dist/plugins/paypal.js.map +1 -0
  234. package/dist/plugins/prisma.d.ts +8 -0
  235. package/dist/plugins/prisma.d.ts.map +1 -0
  236. package/dist/plugins/prisma.js +13 -0
  237. package/dist/plugins/prisma.js.map +1 -0
  238. package/dist/plugins/stripe.d.ts +14 -0
  239. package/dist/plugins/stripe.d.ts.map +1 -0
  240. package/dist/plugins/stripe.js +16 -0
  241. package/dist/plugins/stripe.js.map +1 -0
  242. package/dist/plugins/tax.d.ts +20 -0
  243. package/dist/plugins/tax.d.ts.map +1 -0
  244. package/dist/plugins/tax.js +18 -0
  245. package/dist/plugins/tax.js.map +1 -0
  246. package/dist/policy.d.ts +34 -0
  247. package/dist/policy.d.ts.map +1 -0
  248. package/dist/policy.js +90 -0
  249. package/dist/policy.js.map +1 -0
  250. package/dist/prisma.d.ts +77 -0
  251. package/dist/prisma.d.ts.map +1 -0
  252. package/dist/prisma.js +76 -0
  253. package/dist/prisma.js.map +1 -0
  254. package/dist/processor.d.ts +28 -0
  255. package/dist/processor.d.ts.map +1 -0
  256. package/dist/processor.js +118 -0
  257. package/dist/processor.js.map +1 -0
  258. package/dist/provider.d.ts +103 -0
  259. package/dist/provider.d.ts.map +1 -0
  260. package/dist/provider.js +280 -0
  261. package/dist/provider.js.map +1 -0
  262. package/dist/rate-text.d.ts +38 -0
  263. package/dist/rate-text.d.ts.map +1 -0
  264. package/dist/rate-text.js +143 -0
  265. package/dist/rate-text.js.map +1 -0
  266. package/dist/rate.d.ts +175 -0
  267. package/dist/rate.d.ts.map +1 -0
  268. package/dist/rate.js +371 -0
  269. package/dist/rate.js.map +1 -0
  270. package/dist/rounding-error.d.ts +9 -0
  271. package/dist/rounding-error.d.ts.map +1 -0
  272. package/dist/rounding-error.js +9 -0
  273. package/dist/rounding-error.js.map +1 -0
  274. package/dist/rounding.d.ts +50 -0
  275. package/dist/rounding.d.ts.map +1 -0
  276. package/dist/rounding.js +87 -0
  277. package/dist/rounding.js.map +1 -0
  278. package/dist/schema.d.ts +43 -0
  279. package/dist/schema.d.ts.map +1 -0
  280. package/dist/schema.js +77 -0
  281. package/dist/schema.js.map +1 -0
  282. package/dist/sql.d.ts +54 -0
  283. package/dist/sql.d.ts.map +1 -0
  284. package/dist/sql.js +131 -0
  285. package/dist/sql.js.map +1 -0
  286. package/dist/stripe-fx.d.ts +22 -0
  287. package/dist/stripe-fx.d.ts.map +1 -0
  288. package/dist/stripe-fx.js +30 -0
  289. package/dist/stripe-fx.js.map +1 -0
  290. package/dist/stripe.d.ts +36 -0
  291. package/dist/stripe.d.ts.map +1 -0
  292. package/dist/stripe.js +39 -0
  293. package/dist/stripe.js.map +1 -0
  294. package/dist/tax.d.ts +33 -0
  295. package/dist/tax.d.ts.map +1 -0
  296. package/dist/tax.js +55 -0
  297. package/dist/tax.js.map +1 -0
  298. package/dist/testing/arbitraries.d.ts +43 -0
  299. package/dist/testing/arbitraries.d.ts.map +1 -0
  300. package/dist/testing/arbitraries.js +98 -0
  301. package/dist/testing/arbitraries.js.map +1 -0
  302. package/dist/testing/index.d.ts +67 -0
  303. package/dist/testing/index.d.ts.map +1 -0
  304. package/dist/testing/index.js +159 -0
  305. package/dist/testing/index.js.map +1 -0
  306. package/dist/testing/jest.d.ts +2 -0
  307. package/dist/testing/jest.d.ts.map +1 -0
  308. package/dist/testing/jest.js +15 -0
  309. package/dist/testing/jest.js.map +1 -0
  310. package/dist/testing/vitest.d.ts +7 -0
  311. package/dist/testing/vitest.d.ts.map +1 -0
  312. package/dist/testing/vitest.js +12 -0
  313. package/dist/testing/vitest.js.map +1 -0
  314. package/dist/valibot.d.ts +33 -0
  315. package/dist/valibot.d.ts.map +1 -0
  316. package/dist/valibot.js +61 -0
  317. package/dist/valibot.js.map +1 -0
  318. package/dist/zod.d.ts +36 -0
  319. package/dist/zod.d.ts.map +1 -0
  320. package/dist/zod.js +58 -0
  321. package/dist/zod.js.map +1 -0
  322. package/package.json +280 -5
  323. package/src/adyen-fx.ts +175 -0
  324. package/src/adyen.ts +46 -0
  325. package/src/allocate.ts +393 -0
  326. package/src/bag.ts +170 -0
  327. package/src/boc.ts +136 -0
  328. package/src/boe.ts +131 -0
  329. package/src/braintree.ts +71 -0
  330. package/src/cash.ts +183 -0
  331. package/src/checkout.ts +77 -0
  332. package/src/convert.ts +177 -0
  333. package/src/currency.ts +61 -0
  334. package/src/decimal.ts +283 -0
  335. package/src/drizzle/mysql.ts +78 -0
  336. package/src/drizzle/pg.ts +78 -0
  337. package/src/drizzle/sqlite.ts +70 -0
  338. package/src/ecb.ts +328 -0
  339. package/src/exact.ts +182 -0
  340. package/src/fed.ts +146 -0
  341. package/src/fetch.ts +306 -0
  342. package/src/fixed.ts +558 -0
  343. package/src/fn.ts +94 -0
  344. package/src/format.ts +106 -0
  345. package/src/generated/adyen.ts +144 -0
  346. package/src/generated/braintree.ts +140 -0
  347. package/src/generated/cash.ts +478 -0
  348. package/src/generated/checkout.ts +151 -0
  349. package/src/generated/historic.ts +67 -0
  350. package/src/generated/iso4217.ts +179 -0
  351. package/src/generated/kernel.ts +230 -0
  352. package/src/generated/klarna.ts +21 -0
  353. package/src/generated/paypal.ts +31 -0
  354. package/src/generated/stripe.ts +150 -0
  355. package/src/historic.ts +77 -0
  356. package/src/history.ts +333 -0
  357. package/src/hmrc.ts +125 -0
  358. package/src/index.ts +41 -0
  359. package/src/klarna.ts +54 -0
  360. package/src/kysely.ts +588 -0
  361. package/src/money.ts +979 -0
  362. package/src/parse.ts +511 -0
  363. package/src/paypal.ts +93 -0
  364. package/src/pg.ts +410 -0
  365. package/src/plugins/adyen.ts +25 -0
  366. package/src/plugins/all.ts +57 -0
  367. package/src/plugins/allocate.ts +53 -0
  368. package/src/plugins/braintree.ts +23 -0
  369. package/src/plugins/cash.ts +33 -0
  370. package/src/plugins/checkout.ts +32 -0
  371. package/src/plugins/convert.ts +49 -0
  372. package/src/plugins/exact.ts +23 -0
  373. package/src/plugins/fixed.ts +28 -0
  374. package/src/plugins/format.ts +28 -0
  375. package/src/plugins/klarna.ts +21 -0
  376. package/src/plugins/paypal.ts +29 -0
  377. package/src/plugins/prisma.ts +24 -0
  378. package/src/plugins/stripe.ts +29 -0
  379. package/src/plugins/tax.ts +40 -0
  380. package/src/policy.ts +124 -0
  381. package/src/prisma.ts +199 -0
  382. package/src/processor.ts +181 -0
  383. package/src/provider.ts +389 -0
  384. package/src/rate-text.ts +151 -0
  385. package/src/rate.ts +546 -0
  386. package/src/rounding-error.ts +8 -0
  387. package/src/rounding.ts +122 -0
  388. package/src/schema.ts +119 -0
  389. package/src/sql.ts +178 -0
  390. package/src/stripe-fx.ts +49 -0
  391. package/src/stripe.ts +69 -0
  392. package/src/tax.ts +102 -0
  393. package/src/testing/arbitraries.ts +134 -0
  394. package/src/testing/index.ts +247 -0
  395. package/src/testing/jest.ts +18 -0
  396. package/src/testing/vitest.ts +18 -0
  397. package/src/valibot.ts +87 -0
  398. package/src/zod.ts +78 -0
package/dist/money.js ADDED
@@ -0,0 +1,703 @@
1
+ import { currencyExponent } from './currency.js';
2
+ import { formatScaled, parseDecimal, parsePlainDecimal, POW10, pow10n, ratio, normalizeMinor, } from './decimal.js';
3
+ import { DEFAULT_ROUNDING, divideAndRound, divideAndRoundBigint, RoundingError, } from './rounding.js';
4
+ // A module-local constant, not an import: the hot loops (sum, add) read it on every iteration, and
5
+ // V8 reads an imported binding through an extra indirection.
6
+ const MAX_SAFE_MINOR = Number.MAX_SAFE_INTEGER;
7
+ /**
8
+ * @internal The key a policy's rounding function is stored under. Module-private, so only
9
+ * `roundingPolicy` from this copy of the package makes values the core accepts as policies: a
10
+ * lookalike function, or a policy from a second installed copy (whose results would be that copy's
11
+ * Money), is rejected with a TypeError, as `isMoney` rejects the other copy's Money.
12
+ */
13
+ export const ROUND_PRODUCT = Symbol();
14
+ /**
15
+ * @internal money × factor rounded by a policy. Anything not built by `roundingPolicy` lacks the
16
+ * private key, so calling it throws a TypeError; that is the whole check, kept this small because
17
+ * it is in every bundle.
18
+ */
19
+ export const roundWithPolicy = (money, factor, policy) => policy[ROUND_PRODUCT](money, factor);
20
+ /** Thrown when two amounts in different currencies are combined. */
21
+ export class CurrencyMismatchError extends TypeError {
22
+ name = 'CurrencyMismatchError';
23
+ constructor(expected, actual) {
24
+ super(`Currency mismatch: ${expected} vs ${actual}`);
25
+ this.expected = expected;
26
+ this.actual = actual;
27
+ }
28
+ }
29
+ /**
30
+ * An immutable amount of money: an integer number of 10^-scale units of `currency`.
31
+ *
32
+ * `minor` is a JS number whenever it is a safe integer (|v| <= 2^53 - 1) and a bigint otherwise, so
33
+ * ordinary amounts never allocate a bigint, and huge or high-precision amounts never lose a digit.
34
+ * `scale` is normally the currency's ISO exponent (2 for EUR) but can be larger for sub-minor
35
+ * precision (unit prices, FX intermediates); `round()` brings it back.
36
+ *
37
+ * Instances are not frozen (Object.freeze costs 5-8x on construction in V8 and JSC; see bench/),
38
+ * but every field is readonly and no operation mutates. Create values with `money()` /
39
+ * `fromMinor()`.
40
+ *
41
+ * The class carries the core methods only. Opt-in modules (`@ducatjs/money/allocate`,
42
+ * `@ducatjs/money/tax`, `@ducatjs/money/format`, ...) add theirs when imported; see `extendMoney`.
43
+ */
44
+ class Money {
45
+ /** @internal */
46
+ constructor(currency, minor, scale) {
47
+ this.currency = currency;
48
+ this.minor = minor;
49
+ this.scale = scale;
50
+ }
51
+ /** "12.34 EUR" */
52
+ toString() {
53
+ return `${formatScaled(this.minor, this.scale)} ${this.currency}`;
54
+ }
55
+ toJSON() {
56
+ return { amount: formatScaled(this.minor, this.scale), currency: this.currency };
57
+ }
58
+ /** Blocks `a + b`, `a > b`, `+a`: arithmetic and comparison must go through the library. */
59
+ [Symbol.toPrimitive](hint) {
60
+ if (hint === 'string') {
61
+ return this.toString();
62
+ }
63
+ throw new TypeError('Money cannot be converted to a number; use add(), compare(), toDecimal() etc.');
64
+ }
65
+ // Methods. Each one is a thin wrapper over the free function of the same name (also exported), so
66
+ // `a.add(b)` and `add(a, b)` are the same code. Operands are Money only: a bare number is never
67
+ // guessed to mean major or minor units.
68
+ // arithmetic
69
+ /** this + other (same currency; any scale) */
70
+ add(other) {
71
+ return add(this, other);
72
+ }
73
+ /** this - other */
74
+ subtract(other) {
75
+ return subtract(this, other);
76
+ }
77
+ /**
78
+ * this * factor, rounded to this scale. `factor` is exact: integer, decimal string ('1.075'),
79
+ * bigint or ratio().
80
+ */
81
+ multiply(factor, rounding) {
82
+ return multiply(this, factor, rounding);
83
+ }
84
+ /** this / divisor, rounded to this scale (or to a policy's scale and increment) */
85
+ divide(divisor, rounding) {
86
+ return divide(this, divisor, rounding);
87
+ }
88
+ negate() {
89
+ return negate(this);
90
+ }
91
+ abs() {
92
+ return abs(this);
93
+ }
94
+ round(rounding, scale) {
95
+ // the free function handles both; the cast only picks its implementation signature
96
+ return round(this, rounding, scale);
97
+ }
98
+ /** Changes the scale; decreasing it rounds (default 'halfExpand'). */
99
+ toScale(scale, rounding) {
100
+ return toScale(this, scale, rounding);
101
+ }
102
+ // comparison
103
+ /** -1, 0 or 1; throws on currency mismatch */
104
+ compare(other) {
105
+ return compare(this, other);
106
+ }
107
+ /** same currency and value; a different currency is simply not equal */
108
+ equals(other) {
109
+ return equals(this, other);
110
+ }
111
+ lessThan(other) {
112
+ return compare(this, other) < 0;
113
+ }
114
+ lessThanOrEqual(other) {
115
+ return compare(this, other) <= 0;
116
+ }
117
+ greaterThan(other) {
118
+ return compare(this, other) > 0;
119
+ }
120
+ greaterThanOrEqual(other) {
121
+ return compare(this, other) >= 0;
122
+ }
123
+ isZero() {
124
+ return this.minor == 0;
125
+ }
126
+ isPositive() {
127
+ return this.minor > 0;
128
+ }
129
+ isNegative() {
130
+ return this.minor < 0;
131
+ }
132
+ sign() {
133
+ return sign(this);
134
+ }
135
+ min(...others) {
136
+ return min(this, ...others);
137
+ }
138
+ max(...others) {
139
+ return max(this, ...others);
140
+ }
141
+ clamp(lo, hi) {
142
+ return clamp(this, lo, hi);
143
+ }
144
+ /** Same currency, value and scale: 1.0 EUR is not identical to 1.00 EUR. */
145
+ identical(other) {
146
+ return identical(this, other);
147
+ }
148
+ /**
149
+ * Applies `operation` to this amount and returns its result, so a rounding policy or a
150
+ * conversion reads as one step in a chain: `price.multiply('1.075').with(toCash)`.
151
+ */
152
+ with(operation) {
153
+ return operation(this);
154
+ }
155
+ // output
156
+ /** The whole major units, truncated toward zero: 12 for 12.34 EUR, -12 for -12.34 EUR. */
157
+ majorPart() {
158
+ return majorPart(this);
159
+ }
160
+ /** The rest in 10^-scale units, with the amount's sign: 34 for 12.34 EUR, -34 for -12.34. */
161
+ minorPart() {
162
+ return minorPart(this);
163
+ }
164
+ /** Exact decimal string in major units: "12.34" */
165
+ toDecimal() {
166
+ return formatScaled(this.minor, this.scale);
167
+ }
168
+ /** Minor units as a bigint (BIGINT columns) */
169
+ toMinor() {
170
+ return toBigInt(this.minor);
171
+ }
172
+ /** Minor units as a number; throws beyond 2^53 */
173
+ toMinorNumber() {
174
+ return toMinorNumber(this);
175
+ }
176
+ }
177
+ /** Whether a value is a Money from this package. */
178
+ export function isMoney(value) {
179
+ return value instanceof Money;
180
+ }
181
+ /**
182
+ * Whether a value is a Money in `currency`. It narrows a currency known only at run time
183
+ * (`Money<string>`, or `unknown`) to the literal type:
184
+ *
185
+ * if (isMoneyIn(price, 'EUR')) { price.add(money('1', 'EUR')) }
186
+ */
187
+ export function isMoneyIn(value, currency) {
188
+ return value instanceof Money && value.currency === currency;
189
+ }
190
+ /**
191
+ * Narrows `money` to `Money<C>`, or throws a `CurrencyMismatchError` if it is in another
192
+ * currency. Use it where a different currency is a bug rather than a branch.
193
+ */
194
+ export function assertCurrency(money, currency) {
195
+ // A non-Money would otherwise pass when it happens to have a matching `currency` field.
196
+ if (!(money instanceof Money)) {
197
+ throw new TypeError(`Expected Money, got ${typeof money}`);
198
+ }
199
+ if (money.currency !== currency) {
200
+ throw new CurrencyMismatchError(currency, money.currency);
201
+ }
202
+ }
203
+ /**
204
+ * Which module installed each added method, so a second copy of the same module can replace its
205
+ * own.
206
+ */
207
+ const methodOwners = new Map();
208
+ /**
209
+ * Names `extendMoney` refuses: the ones every object inherits, whose meaning other code relies on.
210
+ * `toLocaleString` is allowed, since a formatting module may want to provide it.
211
+ */
212
+ const RESERVED_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype).filter((name) => name !== 'toLocaleString'));
213
+ /**
214
+ * Adds methods to every Money (this is how `@ducatjs/money/allocate`, `@ducatjs/money/format`, ...
215
+ * install theirs). Declare their types with `declare module '@ducatjs/money' { interface Money<C
216
+ * extends string> { ... } }`. The methods are non-enumerable, like class methods. A name that Money
217
+ * already has (one of its own methods, or one added by a different owner) throws, so two modules
218
+ * cannot silently fight over it.
219
+ */
220
+ export function extendMoney(methods, options) {
221
+ const prototype = Money.prototype;
222
+ const owner = options?.owner;
223
+ for (const name of Object.keys(methods)) {
224
+ const method = methods[name];
225
+ if (RESERVED_NAMES.has(name)) {
226
+ throw new TypeError(`Money#${name} is reserved`);
227
+ }
228
+ // Replacing an existing method would silently change behaviour for every caller, unless it is
229
+ // the same function or the same owner installing its own methods again.
230
+ const previousOwner = methodOwners.get(name);
231
+ const isOwnReinstall = owner !== undefined && previousOwner === owner;
232
+ if (Object.hasOwn(prototype, name) && prototype[name] !== method && !isOwnReinstall) {
233
+ throw new TypeError(`Money#${name} is already defined`);
234
+ }
235
+ // Non-enumerable, like the class's own methods, so Object.keys and spreads see only the fields.
236
+ Object.defineProperty(prototype, name, {
237
+ value: method,
238
+ writable: true,
239
+ configurable: true,
240
+ enumerable: false,
241
+ });
242
+ if (owner !== undefined) {
243
+ methodOwners.set(name, owner);
244
+ }
245
+ }
246
+ }
247
+ /** @internal construct from a value that may be an unsafe bigint */
248
+ export function make(currency, minor, scale) {
249
+ return new Money(currency, typeof minor === 'bigint' ? normalizeMinor(minor) : minor, scale);
250
+ }
251
+ const toBigInt = (minor) => (typeof minor === 'bigint' ? minor : BigInt(minor));
252
+ /** v * 10^e exactly (e >= 0) */
253
+ export function scaleUp(minor, exponent) {
254
+ if (exponent === 0) {
255
+ return minor;
256
+ }
257
+ if (typeof minor === 'number' && exponent <= 15) {
258
+ const scaled = minor * POW10[exponent];
259
+ if (scaled <= MAX_SAFE_MINOR && scaled >= -MAX_SAFE_MINOR) {
260
+ return scaled;
261
+ }
262
+ }
263
+ return normalizeMinor(toBigInt(minor) * pow10n(exponent));
264
+ }
265
+ /** v / 10^e rounded (e >= 0) */
266
+ export function scaleDown(minor, exponent, mode) {
267
+ if (exponent === 0) {
268
+ return minor;
269
+ }
270
+ if (typeof minor === 'number' && exponent <= 15) {
271
+ return divideAndRound(minor, POW10[exponent], mode);
272
+ }
273
+ return normalizeMinor(divideAndRoundBigint(toBigInt(minor), pow10n(exponent), mode));
274
+ }
275
+ /**
276
+ * Creates money from an amount in major units.
277
+ *
278
+ * money('12.34', 'EUR') // exact decimal string: the recommended form
279
+ * money(12, 'EUR') // integers are major units: 12.00 EUR
280
+ * money(12.34, 'EUR') // non-integer numbers are read at their shortest decimal form ("12.34")
281
+ * money(10n ** 30n, 'USD')
282
+ *
283
+ * Throws if the amount has more decimals than the currency (or `scale`) unless `rounding` is given,
284
+ * so `money(0.1 + 0.2, 'EUR')` throws rather than silently becoming 0.30.
285
+ */
286
+ export function money(amount, currency, options) {
287
+ const scale = options?.scale ?? currencyExponent(currency);
288
+ if (typeof amount === 'string') {
289
+ const parsed = parsePlainDecimal(amount) ?? parseDecimal(amount);
290
+ return fromScaled(currency, parsed.digits, parsed.scale, scale, options?.rounding ?? 'unnecessary', amount);
291
+ }
292
+ if (typeof amount === 'number') {
293
+ if (Number.isSafeInteger(amount)) {
294
+ return make(currency, scaleUp(amount, scale), scale);
295
+ }
296
+ if (!Number.isFinite(amount)) {
297
+ throw new RangeError(`Invalid amount ${amount}`);
298
+ }
299
+ const parsed = parseDecimal(String(amount));
300
+ return fromScaled(currency, parsed.digits, parsed.scale, scale, options?.rounding ?? 'unnecessary', amount);
301
+ }
302
+ if (typeof amount === 'bigint') {
303
+ return make(currency, scaleUp(normalizeMinor(amount), scale), scale);
304
+ }
305
+ throw new TypeError(`Invalid amount ${String(amount)}`);
306
+ }
307
+ function fromScaled(currency, digits, from, to, mode, input) {
308
+ if (typeof digits === 'bigint') {
309
+ digits = normalizeMinor(digits);
310
+ }
311
+ if (from === to) {
312
+ return new Money(currency, digits, to);
313
+ }
314
+ if (from < to) {
315
+ return make(currency, scaleUp(digits, to - from), to);
316
+ }
317
+ try {
318
+ return make(currency, scaleDown(digits, from - to, mode), to);
319
+ }
320
+ catch (error) {
321
+ if (error instanceof RoundingError) {
322
+ throw new RoundingError(`${String(input)} has more than ${to} decimal places for ${currency}; pass { rounding } or { scale }`);
323
+ }
324
+ throw error;
325
+ }
326
+ }
327
+ /**
328
+ * Creates money from an integer count of minor units (cents): `fromMinor(1234, 'EUR')` is 12.34
329
+ * EUR. This is the form to read from a BIGINT column or a payment processor (but see
330
+ * `stripe`/`adyen` for processors whose exponent differs from ISO).
331
+ */
332
+ export function fromMinor(minor, currency, scale) {
333
+ const resolvedScale = scale ?? currencyExponent(currency);
334
+ if (typeof minor === 'number') {
335
+ if (!Number.isSafeInteger(minor)) {
336
+ throw new RangeError(`Minor units must be a safe integer, got ${minor}; pass a bigint`);
337
+ }
338
+ return new Money(currency, minor + 0, resolvedScale);
339
+ }
340
+ if (typeof minor !== 'bigint') {
341
+ throw new TypeError(`Invalid minor units ${String(minor)}`);
342
+ }
343
+ return make(currency, minor, resolvedScale);
344
+ }
345
+ /** Zero in a currency, at its exponent (or `scale`). */
346
+ export function zero(currency, scale) {
347
+ return new Money(currency, 0, scale ?? currencyExponent(currency));
348
+ }
349
+ // ---------------------------------------------------------------------------------------------
350
+ // Arithmetic
351
+ // ---------------------------------------------------------------------------------------------
352
+ function mismatch(money, other) {
353
+ throw new CurrencyMismatchError(money.currency, other.currency);
354
+ }
355
+ function addUsingBigInt(money, other, sign) {
356
+ const scale = Math.max(money.scale, other.scale);
357
+ const left = toBigInt(scaleUp(money.minor, scale - money.scale));
358
+ const right = toBigInt(scaleUp(other.minor, scale - other.scale));
359
+ return make(money.currency, sign === 1 ? left + right : left - right, scale);
360
+ }
361
+ /**
362
+ * a + b. Mixing currencies is a type error for literal currency types and a runtime error
363
+ * otherwise.
364
+ */
365
+ export function add(money, other) {
366
+ if (money.currency !== other.currency) {
367
+ mismatch(money, other);
368
+ }
369
+ const left = money.minor;
370
+ const right = other.minor;
371
+ if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
372
+ // exact whenever |sum| <= MAX_SAFE_MINOR: both inputs are safe integers
373
+ const sum = left + right;
374
+ if (sum <= MAX_SAFE_MINOR && sum >= -MAX_SAFE_MINOR) {
375
+ return new Money(money.currency, sum, money.scale);
376
+ }
377
+ }
378
+ return addUsingBigInt(money, other, 1);
379
+ }
380
+ /** a - b */
381
+ export function subtract(money, other) {
382
+ if (money.currency !== other.currency) {
383
+ mismatch(money, other);
384
+ }
385
+ const left = money.minor;
386
+ const right = other.minor;
387
+ if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
388
+ const difference = left - right;
389
+ if (difference <= MAX_SAFE_MINOR && difference >= -MAX_SAFE_MINOR) {
390
+ return new Money(money.currency, difference + 0, money.scale);
391
+ }
392
+ }
393
+ return addUsingBigInt(money, other, -1);
394
+ }
395
+ /** Sum of a list (same currency; any scale). An empty list needs `currency` and returns zero. */
396
+ export function sum(items, currency) {
397
+ const count = items.length;
398
+ if (count === 0) {
399
+ if (currency === undefined) {
400
+ throw new RangeError('sum() of an empty list needs a currency');
401
+ }
402
+ return zero(currency);
403
+ }
404
+ let total = items[0];
405
+ if (currency !== undefined && total.currency !== currency) {
406
+ throw new CurrencyMismatchError(currency, total.currency);
407
+ }
408
+ const itemCurrency = total.currency;
409
+ const scale = total.scale;
410
+ // Fast loop on plain numbers: each partial sum of safe integers is exact while it stays within
411
+ // MAX_SAFE_MINOR. It falls back to add() at the first bigint, scale change or overflow. NaN marks
412
+ // "no fast total".
413
+ let fastTotal = typeof total.minor === 'number' ? total.minor : NaN;
414
+ let i = 1;
415
+ for (; i < count && fastTotal === fastTotal; i++) {
416
+ const item = items[i];
417
+ if (item.currency !== itemCurrency) {
418
+ mismatch(total, item);
419
+ }
420
+ if (typeof item.minor !== 'number' || item.scale !== scale) {
421
+ break;
422
+ }
423
+ const next = fastTotal + item.minor;
424
+ if (!(next <= MAX_SAFE_MINOR && next >= -MAX_SAFE_MINOR)) {
425
+ break;
426
+ }
427
+ fastTotal = next;
428
+ }
429
+ if (fastTotal === fastTotal) {
430
+ total = new Money(itemCurrency, fastTotal, scale);
431
+ }
432
+ for (; i < count; i++) {
433
+ total = add(total, items[i]);
434
+ }
435
+ return total;
436
+ }
437
+ /** -money */
438
+ export function negate(money) {
439
+ const minor = money.minor;
440
+ return new Money(money.currency, typeof minor === 'number' ? 0 - minor : normalizeMinor(-minor), money.scale);
441
+ }
442
+ /** |money| */
443
+ export function abs(money) {
444
+ return money.minor < 0 ? negate(money) : money;
445
+ }
446
+ /**
447
+ * m * factor, rounded to m's scale. `factor` is exact: an integer, a decimal string ('1.075'), a
448
+ * bigint, or a `ratio()`. Rounding defaults to 'halfExpand' (ties away from zero); pass
449
+ * 'unnecessary' to throw instead.
450
+ */
451
+ export function multiply(money, factor, rounding = DEFAULT_ROUNDING) {
452
+ const minor = money.minor;
453
+ // An integer product is exact at this scale, but a policy may ask for another scale or increment.
454
+ if (typeof factor === 'number' &&
455
+ Number.isSafeInteger(factor) &&
456
+ typeof minor === 'number' &&
457
+ typeof rounding === 'string') {
458
+ const product = minor * factor;
459
+ if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
460
+ return new Money(money.currency, product + 0, money.scale);
461
+ }
462
+ }
463
+ return multiplyByRatio(money, ratio(factor), rounding);
464
+ }
465
+ /** @internal m * r, rounded with a mode (at `scale`) or with a policy (at the policy's scale) */
466
+ export function multiplyByRatio(money, factor, rounding, scale = money.scale) {
467
+ if (typeof rounding === 'function') {
468
+ return roundWithPolicy(money, factor, rounding);
469
+ }
470
+ const minor = money.minor;
471
+ if (typeof minor === 'number' &&
472
+ scale === money.scale &&
473
+ factor.n === factor.n &&
474
+ factor.d === factor.d) {
475
+ // exact when |product| <= MAX_SAFE_MINOR (both factors are safe integers)
476
+ const product = minor * factor.n;
477
+ if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
478
+ return new Money(money.currency, divideAndRound(product, factor.d, rounding), scale);
479
+ }
480
+ }
481
+ let numerator = toBigInt(minor) * factor.num;
482
+ let denominator = factor.den;
483
+ if (scale > money.scale) {
484
+ numerator *= pow10n(scale - money.scale);
485
+ }
486
+ else if (scale < money.scale) {
487
+ denominator *= pow10n(money.scale - scale);
488
+ }
489
+ return make(money.currency, divideAndRoundBigint(numerator, denominator, rounding), scale);
490
+ }
491
+ /** m / divisor, rounded to m's scale (default 'halfExpand'), or with a rounding policy. */
492
+ export function divide(money, divisor, rounding = DEFAULT_ROUNDING) {
493
+ const divisorRatio = ratio(divisor);
494
+ if (divisorRatio.num === 0n) {
495
+ throw new RangeError('Division by zero');
496
+ }
497
+ // Fast path: m / (n/d) = m·d / n, rounded once by the same kernel the ratio path uses. Building
498
+ // the inverse ratio d/n would cost bigint arithmetic and a gcd on every call; the divisor's own
499
+ // ratio is cached for small integers and strings. Why it is exact:
500
+ // - makeRatio guarantees d > 0 and n/d in lowest terms, so m·d / n is the same fraction the
501
+ // inverse ratio d/n would give, and only n's sign needs handling;
502
+ // - `x === x` is false only for NaN, which is how a Ratio marks a part that is not a safe
503
+ // integer, so both parts are safe integers here;
504
+ // - m and d are safe integers, so a float product beyond 2^53 - 1 cannot round back down into
505
+ // the safe range: the bound check below rejects every inexact product;
506
+ // - divideAndRound corrects its float quotient exactly (and takes the bigint kernel itself when
507
+ // dividend + divisor exceeds the safe range).
508
+ // A rounding policy (a function, not a mode string) must not take this path: it rounds to its own
509
+ // scale and increment.
510
+ const minor = money.minor;
511
+ const numerator = divisorRatio.n;
512
+ const denominator = divisorRatio.d;
513
+ if (typeof minor === 'number' &&
514
+ typeof rounding === 'string' &&
515
+ numerator === numerator &&
516
+ denominator === denominator) {
517
+ let dividend = minor * denominator;
518
+ if (dividend <= MAX_SAFE_MINOR && dividend >= -MAX_SAFE_MINOR) {
519
+ // divideAndRound needs a positive divisor: (−p)/(−n) is the same quotient
520
+ let positiveDivisor = numerator;
521
+ if (numerator < 0) {
522
+ dividend = 0 - dividend;
523
+ positiveDivisor = 0 - numerator;
524
+ }
525
+ return new Money(money.currency, divideAndRound(dividend, positiveDivisor, rounding), money.scale);
526
+ }
527
+ }
528
+ return multiplyByRatio(money, ratio(divisorRatio.den, divisorRatio.num), rounding);
529
+ }
530
+ export function round(money, rounding, scale) {
531
+ if (typeof rounding === 'function') {
532
+ return roundWithPolicy(money, ratio(1), rounding);
533
+ }
534
+ return toScale(money, scale ?? currencyExponent(money.currency), rounding);
535
+ }
536
+ /**
537
+ * Changes the scale; increasing it is always exact, decreasing it rounds (default 'halfExpand').
538
+ */
539
+ export function toScale(money, scale, rounding = DEFAULT_ROUNDING) {
540
+ if (!Number.isInteger(scale) || scale < 0) {
541
+ throw new RangeError(`Invalid scale ${scale}`);
542
+ }
543
+ if (scale === money.scale) {
544
+ return money;
545
+ }
546
+ if (scale > money.scale) {
547
+ return make(money.currency, scaleUp(money.minor, scale - money.scale), scale);
548
+ }
549
+ return make(money.currency, scaleDown(money.minor, money.scale - scale, rounding), scale);
550
+ }
551
+ // ---------------------------------------------------------------------------------------------
552
+ // Comparison
553
+ // ---------------------------------------------------------------------------------------------
554
+ /** -1, 0 or 1. Throws on currency mismatch. Works across scales and number/bigint. */
555
+ export function compare(money, other) {
556
+ if (money.currency !== other.currency) {
557
+ mismatch(money, other);
558
+ }
559
+ let left = money.minor;
560
+ let right = other.minor;
561
+ if (money.scale !== other.scale) {
562
+ const scale = Math.max(money.scale, other.scale);
563
+ left = scaleUp(left, scale - money.scale);
564
+ right = scaleUp(right, scale - other.scale);
565
+ }
566
+ // number < bigint comparisons are exact in JS
567
+ if (left < right) {
568
+ return -1;
569
+ }
570
+ return left > right ? 1 : 0;
571
+ }
572
+ /**
573
+ * Same currency and same value (1.0 EUR at scale 1 equals 1.00 EUR). Different currencies: false.
574
+ */
575
+ export function equals(money, other) {
576
+ if (money.currency !== other.currency) {
577
+ return false;
578
+ }
579
+ if (money.scale === other.scale) {
580
+ // == compares number and bigint exactly
581
+ return money.minor == other.minor;
582
+ }
583
+ return compare(money, other) === 0;
584
+ }
585
+ /**
586
+ * Same currency, same value *and* same scale, with number and bigint minor units counted as equal.
587
+ * `equals` treats 1.0 EUR (scale 1) and 1.00 EUR as equal; `identical` does not. For round-trip
588
+ * tests, where the scale must survive too.
589
+ */
590
+ export function identical(money, other) {
591
+ return (money.currency === other.currency && money.scale === other.scale && money.minor == other.minor);
592
+ }
593
+ /** money < other (same currency; any scale). */
594
+ export const lessThan = (money, other) => compare(money, other) < 0;
595
+ /** money <= other */
596
+ export const lessThanOrEqual = (money, other) => compare(money, other) <= 0;
597
+ /** money > other */
598
+ export const greaterThan = (money, other) => compare(money, other) > 0;
599
+ /** money >= other */
600
+ export const greaterThanOrEqual = (money, other) => compare(money, other) >= 0;
601
+ /** Whether the amount is zero. */
602
+ export const isZero = (money) => money.minor == 0;
603
+ /** Whether the amount is greater than zero. */
604
+ export const isPositive = (money) => money.minor > 0;
605
+ /** Whether the amount is less than zero. */
606
+ export const isNegative = (money) => money.minor < 0;
607
+ /** 1, 0 or -1 for positive, zero and negative amounts. */
608
+ export const sign = (money) => {
609
+ if (money.minor > 0) {
610
+ return 1;
611
+ }
612
+ return money.minor < 0 ? -1 : 0;
613
+ };
614
+ /** The smallest of the amounts (same currency); the first one wins ties. */
615
+ export function min(first, ...rest) {
616
+ let smallest = first;
617
+ for (const candidate of rest) {
618
+ if (compare(candidate, smallest) < 0) {
619
+ smallest = candidate;
620
+ }
621
+ }
622
+ return smallest;
623
+ }
624
+ /** The largest of the amounts (same currency); the first one wins ties. */
625
+ export function max(first, ...rest) {
626
+ let largest = first;
627
+ for (const candidate of rest) {
628
+ if (compare(candidate, largest) > 0) {
629
+ largest = candidate;
630
+ }
631
+ }
632
+ return largest;
633
+ }
634
+ /** Limits m to [lo, hi]. */
635
+ export function clamp(money, lo, hi) {
636
+ if (compare(lo, hi) > 0) {
637
+ throw new RangeError('clamp(): lo > hi');
638
+ }
639
+ if (compare(money, lo) < 0) {
640
+ return lo;
641
+ }
642
+ return compare(money, hi) > 0 ? hi : money;
643
+ }
644
+ // ---------------------------------------------------------------------------------------------
645
+ // Serialisation primitives
646
+ // ---------------------------------------------------------------------------------------------
647
+ /**
648
+ * Exact decimal string in major units: "12.34", "-0.05", "1000" (JPY). For NUMERIC/DECIMAL columns.
649
+ */
650
+ export function toDecimal(money) {
651
+ return formatScaled(money.minor, money.scale);
652
+ }
653
+ /**
654
+ * The whole major units, truncated toward zero: 12 for 12.34 EUR and -12 for -12.34 EUR. A number
655
+ * while it is a safe integer, a bigint beyond, like `minor`.
656
+ */
657
+ export function majorPart(money) {
658
+ const minor = money.minor;
659
+ if (typeof minor === 'number' && money.scale <= 15) {
660
+ // Taking the remainder out first leaves an exact multiple, so the division is exact. `+ 0`
661
+ // turns -0 into 0.
662
+ const unit = POW10[money.scale];
663
+ return (minor - (minor % unit)) / unit + 0;
664
+ }
665
+ // bigint division truncates toward zero, like the fast path
666
+ return normalizeMinor(toBigInt(minor) / pow10n(money.scale));
667
+ }
668
+ /**
669
+ * What is left after `majorPart`, in 10^-scale units and with the amount's sign: 34 for 12.34
670
+ * EUR, -34 for -12.34 EUR, 5 for 1.005 EUR at scale 3.
671
+ */
672
+ export function minorPart(money) {
673
+ const minor = money.minor;
674
+ if (typeof minor === 'number' && money.scale <= 15) {
675
+ // % on safe integers is exact and keeps the dividend's sign; `+ 0` turns -0 into 0.
676
+ return (minor % POW10[money.scale]) + 0;
677
+ }
678
+ return normalizeMinor(toBigInt(minor) % pow10n(money.scale));
679
+ }
680
+ /** Minor units as a bigint (always safe; use for BIGINT columns). */
681
+ export function toMinor(money) {
682
+ return toBigInt(money.minor);
683
+ }
684
+ /** Minor units as a number; throws if not a safe integer. */
685
+ export function toMinorNumber(money) {
686
+ if (typeof money.minor === 'bigint') {
687
+ throw new RangeError(`${money} does not fit in a safe integer; use toMinor()`);
688
+ }
689
+ return money.minor;
690
+ }
691
+ /** Parses `{ amount: "12.34", currency: "EUR" }` (as produced by JSON.stringify(money)). */
692
+ export function fromJSON(json, options) {
693
+ const parsed = typeof json === 'string' ? JSON.parse(json) : json;
694
+ if (parsed === null ||
695
+ typeof parsed !== 'object' ||
696
+ typeof parsed.amount !== 'string' ||
697
+ typeof parsed.currency !== 'string') {
698
+ throw new TypeError('Expected { amount: string, currency: string }');
699
+ }
700
+ return money(parsed.amount, parsed.currency, options);
701
+ }
702
+ export { ratio } from './decimal.js';
703
+ //# sourceMappingURL=money.js.map