@vielzeug/coins 1.0.4 → 2.0.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 (80) hide show
  1. package/README.md +50 -222
  2. package/dist/aggregate.cjs +2 -0
  3. package/dist/aggregate.cjs.map +1 -0
  4. package/dist/aggregate.d.ts +11 -0
  5. package/dist/aggregate.d.ts.map +1 -0
  6. package/dist/aggregate.js +44 -0
  7. package/dist/aggregate.js.map +1 -0
  8. package/dist/coins.cjs +1 -1
  9. package/dist/coins.cjs.map +1 -1
  10. package/dist/coins.iife.js +1 -1
  11. package/dist/coins.iife.js.map +1 -1
  12. package/dist/coins.js +1 -1
  13. package/dist/coins.js.map +1 -1
  14. package/dist/currency.cjs +2 -0
  15. package/dist/currency.cjs.map +1 -0
  16. package/dist/currency.d.ts +38 -0
  17. package/dist/currency.d.ts.map +1 -0
  18. package/dist/currency.js +55 -0
  19. package/dist/currency.js.map +1 -0
  20. package/dist/decimal.cjs +2 -0
  21. package/dist/decimal.cjs.map +1 -0
  22. package/dist/decimal.d.ts +7 -0
  23. package/dist/decimal.d.ts.map +1 -0
  24. package/dist/decimal.js +52 -0
  25. package/dist/decimal.js.map +1 -0
  26. package/dist/errors.cjs +1 -1
  27. package/dist/errors.cjs.map +1 -1
  28. package/dist/errors.d.ts +6 -42
  29. package/dist/errors.d.ts.map +1 -1
  30. package/dist/errors.js +7 -6
  31. package/dist/errors.js.map +1 -1
  32. package/dist/exchange.cjs +1 -1
  33. package/dist/exchange.cjs.map +1 -1
  34. package/dist/exchange.d.ts +9 -27
  35. package/dist/exchange.d.ts.map +1 -1
  36. package/dist/exchange.js +24 -12
  37. package/dist/exchange.js.map +1 -1
  38. package/dist/format.cjs +1 -1
  39. package/dist/format.cjs.map +1 -1
  40. package/dist/format.d.ts +2 -39
  41. package/dist/format.d.ts.map +1 -1
  42. package/dist/format.js +57 -94
  43. package/dist/format.js.map +1 -1
  44. package/dist/index.cjs +1 -1
  45. package/dist/index.d.ts +8 -4
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +8 -5
  48. package/dist/money.cjs +1 -1
  49. package/dist/money.cjs.map +1 -1
  50. package/dist/money.d.ts +26 -245
  51. package/dist/money.d.ts.map +1 -1
  52. package/dist/money.js +71 -184
  53. package/dist/money.js.map +1 -1
  54. package/dist/serialization.cjs +2 -0
  55. package/dist/serialization.cjs.map +1 -0
  56. package/dist/serialization.d.ts +6 -0
  57. package/dist/serialization.d.ts.map +1 -0
  58. package/dist/serialization.js +45 -0
  59. package/dist/serialization.js.map +1 -0
  60. package/dist/types.d.ts +35 -52
  61. package/dist/types.d.ts.map +1 -1
  62. package/package.json +3 -3
  63. package/dist/_cache.cjs +0 -2
  64. package/dist/_cache.cjs.map +0 -1
  65. package/dist/_cache.d.ts +0 -6
  66. package/dist/_cache.d.ts.map +0 -1
  67. package/dist/_cache.js +0 -14
  68. package/dist/_cache.js.map +0 -1
  69. package/dist/_dev.cjs +0 -2
  70. package/dist/_dev.cjs.map +0 -1
  71. package/dist/_dev.d.ts +0 -2
  72. package/dist/_dev.d.ts.map +0 -1
  73. package/dist/_dev.js +0 -9
  74. package/dist/_dev.js.map +0 -1
  75. package/dist/utils.cjs +0 -2
  76. package/dist/utils.cjs.map +0 -1
  77. package/dist/utils.d.ts +0 -66
  78. package/dist/utils.d.ts.map +0 -1
  79. package/dist/utils.js +0 -66
  80. package/dist/utils.js.map +0 -1
package/dist/money.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs"),t=require("./utils.cjs"),n=require("./_dev.cjs");function r(e,r){let i=t.validateCurrencyCode(r);if(typeof e==`bigint`)return{amount:e,currency:i};if(typeof e==`number`){let r=t.getCurrencyDecimals(i),o=String(e),s=t.SCIENTIFIC_RE.test(o)?t.expandScientific(o):o,c=s.indexOf(`.`),l=c===-1?0:s.length-c-1;return l>r&&n.warn(`money(): number input "${e}" has more decimal places (${l}) than ${i} supports (${r}). Use a decimal string to avoid IEEE-754 precision loss.`),{amount:a(o,r),currency:i}}return{amount:a(String(e),t.getCurrencyDecimals(i)),currency:i}}function i(t,n){if(t.currency!==n.currency)throw new e.CurrencyMismatchError(t.currency,n.currency)}function a(e,n){let{denominator:r,negative:i,numerator:a}=t.parseRational(e),o=a*t.pow10(n),s=t.applyRounding(o/r,o%r,r,`half-away-from-zero`);return i?-s:s}function o(e,t){return{amount:t,currency:e.currency}}function s(e){if(typeof e!=`object`||!e)return!1;let t=e;return Object.hasOwn(t,`amount`)&&typeof t.amount==`bigint`&&Object.hasOwn(t,`currency`)&&typeof t.currency==`string`}function c(e,t){return i(e,t),{amount:e.amount+t.amount,currency:e.currency}}function l(e,t){return i(e,t),{amount:e.amount-t.amount,currency:e.currency}}function u(e,n,r=`half-away-from-zero`){let{denominator:i,negative:a,numerator:o}=t.parseRational(String(n)),s=e.amount<0n!==a,c=(e.amount<0n?-e.amount:e.amount)*o,l=t.applyRounding(c/i,c%i,i,r,s);return{amount:s?-l:l,currency:e.currency}}function d(n,r,i=`half-away-from-zero`){let{denominator:a,negative:o,numerator:s}=t.parseRational(String(r));if(s===0n)throw new e.CoinsError(`Division by zero`);let c=n.amount<0n!==o,l=(n.amount<0n?-n.amount:n.amount)*a,u=t.applyRounding(l/s,l%s,s,i,c);return{amount:c?-u:u,currency:n.currency}}function f(n,r){if(r.length===0)throw new e.CoinsError(`allocate requires at least one ratio`);let i=r.map(e=>t.parseRational(String(e)));if(i.some(e=>e.negative))throw new e.CoinsError(`All ratios must be non-negative`);if(!i.some(e=>e.numerator>0n))throw new e.CoinsError(`At least one ratio must be positive`);let a=n.amount<0n,o=a?-n.amount:n.amount,s=i.reduce((e,t)=>t.denominator>e?t.denominator:e,1n),c=i.map(e=>e.numerator*(s/e.denominator)),l=c.reduce((e,t)=>e+t,0n),u=[],d=[];for(let e of c){let t=o*e;u.push(t/l),d.push(t%l)}let f=r.map((e,t)=>t).sort((e,t)=>{let n=d[t]-d[e];return n>0n?1:n<0n?-1:0}),p=[...u],m=o-u.reduce((e,t)=>e+t,0n);for(let e=0;m>0n;e++,m--)p[f[e]]+=1n;return p.map(e=>({amount:a?-e:e,currency:n.currency}))}function p(t){if(t.length===0)throw new e.CoinsError(`sum requires at least one Money value`);let n=t[0].currency;for(let r=1;r<t.length;r++)if(t[r].currency!==n)throw new e.CurrencyMismatchError(n,t[r].currency);return{amount:t.reduce((e,t)=>e+t.amount,0n),currency:n}}function m(t){if(t.length===0)throw new e.CoinsError(`min requires at least one Money value`);let n=t[0];for(let e=1;e<t.length;e++)n=b(n,t[e])<=0?n:t[e];return n}function h(t){if(t.length===0)throw new e.CoinsError(`max requires at least one Money value`);let n=t[0];for(let e=1;e<t.length;e++)n=b(n,t[e])>=0?n:t[e];return n}function g(t,n){if(!Number.isInteger(n)||n<=0)throw new e.CoinsError(`splitEvenly requires a positive integer number of parts`);return f(t,Array.from({length:n},()=>1))}function _(t,n,r){if(t.currency!==n.currency||t.currency!==r.currency)throw new e.CurrencyMismatchError(t.currency,t.currency===n.currency?r.currency:n.currency);if(b(n,r)>0)throw new e.CoinsError(`clamp: lower (${N(n)} ${n.currency}) must be <= upper (${N(r)} ${r.currency})`);return h([n,m([t,r])])}function v(e){return{amount:e.amount<0n?-e.amount:e.amount,currency:e.currency}}function y(e){return{amount:-e.amount,currency:e.currency}}function b(e,t){return i(e,t),e.amount<t.amount?-1:+(e.amount>t.amount)}function x(e,t){return e.currency===t.currency&&e.amount===t.amount}function S(e,t){return b(e,t)>0}function C(e,t){return b(e,t)>=0}function w(e,t){return b(e,t)<0}function T(e,t){return b(e,t)<=0}function E(e){return e.amount===0n}function D(e){return e.amount>0n}function O(e){return e.amount<0n}function k(e){return e.amount>=0n}function A(e){return e.amount<=0n}function j(e){return{amount:String(e.amount),currency:e.currency}}function M(n){let r=t.validateCurrencyCode(n.currency);if(typeof n.amount!=`string`)throw new e.CoinsError(`Invalid money amount in JSON: ${String(n.amount)} (expected an integer string, e.g. '123456')`);let i;try{i=BigInt(n.amount)}catch{throw new e.CoinsError(`Invalid money amount in JSON: "${n.amount}" (expected an integer string, e.g. '123456')`)}return{amount:i,currency:r}}function N(e){let n=t.getCurrencyDecimals(e.currency);if(n===0)return String(e.amount);let r=e.amount<0n,i=r?-e.amount:e.amount,a=t.pow10(n),o=i/a,s=(i%a).toString().padStart(n,`0`);return`${r?`-`:``}${o}.${s}`}function P(e){let n=t.getCurrencyDecimals(e.currency);return Number(e.amount)/Number(t.pow10(n))}function F(n,r,i=`half-away-from-zero`){if(!Number.isInteger(r)||r<0)throw new e.CoinsError(`roundTo: places must be a non-negative integer, got ${r}`);let a=t.getCurrencyDecimals(n.currency);if(r>a)throw new e.CoinsError(`roundTo: places (${r}) exceeds the decimal places for ${n.currency} (${a})`);if(r===a)return n;let o=t.pow10(a-r),s=n.amount<0n,c=s?-n.amount:n.amount,l=t.applyRounding(c/o,c%o,o,i,s);return{amount:s?-l:l,currency:n.currency}}exports.abs=v,exports.add=c,exports.allocate=f,exports.clamp=_,exports.compare=b,exports.divide=d,exports.fromJSON=M,exports.greaterThan=S,exports.greaterThanOrEqual=C,exports.isEqual=x,exports.isMoney=s,exports.isNegative=O,exports.isNonNegative=k,exports.isNonPositive=A,exports.isPositive=D,exports.isZero=E,exports.lessThan=w,exports.lessThanOrEqual=T,exports.max=h,exports.min=m,exports.money=r,exports.multiply=u,exports.negate=y,exports.roundTo=F,exports.splitEvenly=g,exports.subtract=l,exports.sum=p,exports.toDecimal=N,exports.toJSON=j,exports.toNumber=P,exports.withAmount=o;
1
+ const e=require("./errors.cjs"),t=require("./decimal.cjs"),n=require("./currency.cjs");var r=`halfAwayFromZero`;function i(n,i,a){if(b(i),typeof n==`bigint`){if(!a||!(`unit`in a)||a.unit!==`minor`)throw new e.CoinsError(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return _(n,i)}if(a&&`unit`in a)throw new e.CoinsError(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let o=t.decimal(n),s=o.numerator*10n**BigInt(i.minorUnit);if(s%o.denominator!==0n&&!a)throw new e.CoinsError(`INVALID_MONEY`,`Amount "${n}" exceeds ${i.code} precision; provide rounding`);return _(t.roundDivision(s,o.denominator,a?.rounding??r),i)}function a(t){if(!x(t))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a plain data object`);let r=Object.getOwnPropertyDescriptors(t),i=r.amount,a=r.currency;if(!S(i)||!S(a))throw new e.CoinsError(`INVALID_MONEY`,`Money properties must be plain data values`);if(typeof i.value!=`bigint`||!n.isCurrency(a.value))throw new e.CoinsError(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency`);return _(i.value,a.value)}function o(e){try{return a(e),!0}catch{return!1}}function s(e,t){return y(e,t),_(e.amount+t.amount,e.currency)}function c(e,t){return y(e,t),_(e.amount-t.amount,e.currency)}function l(e,n,i={}){v(e);let a=t.decimal(n);return _(t.roundDivision(e.amount*a.numerator,a.denominator,i.rounding??r),e.currency)}function u(n,i,a={}){v(n);let o=t.decimal(i);if(o.numerator===0n)throw new e.CoinsError(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);return _(t.roundDivision(n.amount*o.denominator,o.numerator<0n?-o.numerator:o.numerator,a.rounding??r)*(o.numerator<0n?-1n:1n),n.currency)}function d(e,t){return y(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function f(e){return v(e),_(e.amount<0n?-e.amount:e.amount,e.currency)}function p(e){return v(e),_(-e.amount,e.currency)}function m(n,i){v(n);let{fractionDigits:a,rounding:o=r}=i;if(!Number.isInteger(a)||a<0||a>n.currency.minorUnit)throw new e.CoinsError(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${n.currency.minorUnit}`);let s=10n**BigInt(n.currency.minorUnit-a);return _(t.roundDivision(n.amount,s,o)*s,n.currency)}function h(e){return v(e),t.toDecimalString(e.amount,e.currency.minorUnit)}function g(e,t){return b(t),_(e,t)}function _(e,t){return Object.freeze({amount:e,currency:t})}function v(t){if(!Object.isFrozen(t)||!n.isCurrency(t.currency))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a canonical Coins value`)}function y(t,n){if(v(t),v(n),t.currency!==n.currency)throw new e.CurrencyMismatchError(t.currency.code,n.currency.code)}function b(t){if(!n.isCurrency(t))throw new e.CoinsError(`INVALID_CURRENCY`,`Money requires a registered currency`)}function x(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function S(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}exports.abs=f,exports.add=s,exports.compare=d,exports.divide=u,exports.isMoney=o,exports.money=i,exports.multiply=l,exports.negate=p,exports.parseMoney=a,exports.round=m,exports.subtract=c,exports.toDecimal=h,exports.withMinor=g;
2
2
  //# sourceMappingURL=money.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"money.cjs","names":[],"sources":["../src/money.ts"],"sourcesContent":["import type { CurrencyCode, Money, MoneyJSON, RoundingMode } from './types';\n\nimport { warn } from './_dev';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport {\n applyRounding,\n expandScientific,\n getCurrencyDecimals,\n parseRational,\n pow10,\n SCIENTIFIC_RE,\n validateCurrencyCode,\n} from './utils';\n\nexport { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';\n\n// ─── Factories ───────────────────────────────────────────────────────────────\n\n/**\n * Creates a `Money` value from a decimal string, number, or raw bigint minor units.\n * Validates the currency code — throws `InvalidCurrencyError` for unrecognised ISO 4217 codes.\n *\n * - **string** `'1234.56'` → parsed losslessly; respects the currency's decimal places.\n * - **number** `1234.56` → converted via `String()` first; inherits IEEE-754 limits.\n * Prefer strings when precision matters.\n * - **bigint** `123456n` → used as-is (already in minor units).\n *\n * @example\n * ```ts\n * money('1234.56', 'USD') // { amount: 123456n, currency: 'USD' }\n * money(1234, 'JPY') // { amount: 1234n, currency: 'JPY' }\n * money(123456n, 'USD') // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function money(amount: bigint | number | string, currency: CurrencyCode): Money {\n const validCurrency = validateCurrencyCode(currency);\n\n if (typeof amount === 'bigint') {\n return { amount, currency: validCurrency };\n }\n\n if (typeof amount === 'number') {\n const decimals = getCurrencyDecimals(validCurrency);\n const str = String(amount);\n // Expand scientific notation (e.g. String(1e-7) === '1e-7') before measuring fraction\n // length — otherwise inputs like 1e-7 report 0 fractional digits and skip the warning\n // below despite having far more precision than the currency supports.\n const normalized = SCIENTIFIC_RE.test(str) ? expandScientific(str) : str;\n const dotIndex = normalized.indexOf('.');\n const fracLen = dotIndex === -1 ? 0 : normalized.length - dotIndex - 1;\n\n if (fracLen > decimals) {\n warn(\n `money(): number input \"${amount}\" has more decimal places (${fracLen}) than ${validCurrency} supports (${decimals}). ` +\n `Use a decimal string to avoid IEEE-754 precision loss.`,\n );\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(str, decimals), currency: validCurrency };\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(String(amount), getCurrencyDecimals(validCurrency)), currency: validCurrency };\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nfunction assertSameCurrency(a: Money, b: Money): void {\n if (a.currency !== b.currency) {\n throw new CurrencyMismatchError(a.currency, b.currency);\n }\n}\n\n/**\n * Converts a decimal string to minor units for the given decimal precision.\n * Uses parseRational + applyRounding to share the single rounding implementation.\n */\nfunction parseToMinorUnits(str: string, decimals: number): bigint {\n const { denominator, negative, numerator } = parseRational(str);\n // numerator/denominator × 10^decimals = numerator × 10^decimals / denominator\n const scale = pow10(decimals);\n const raw = numerator * scale;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, 'half-away-from-zero');\n\n return negative ? -result : result;\n}\n\n/**\n * Creates a new `Money` value with the given `amount` and the same currency as `m`.\n * Useful when you compute a raw `bigint` amount externally and need to wrap it\n * back into a `Money` value without re-validating the currency.\n *\n * @example\n * ```ts\n * const price = money('9.99', 'USD');\n * withAmount(price, 1999n) // { amount: 1999n, currency: 'USD' }\n * ```\n */\nexport function withAmount(m: Money, amount: bigint): Money {\n return { amount, currency: m.currency };\n}\n\n/**\n * Type guard that returns `true` if `value` is a `Money`-shaped object\n * (has a `bigint` `amount` and a `string` `currency`).\n * Useful for narrowing unknown payloads from APIs or deserialized storage.\n *\n * Note: does **not** validate the currency code — use `money(0n, currency)` or\n * `validateCurrencyCode()` if you also need to confirm it is a recognized ISO 4217 code.\n *\n * @example\n * ```ts\n * isMoney({ amount: 100n, currency: 'USD' }) // true\n * isMoney({ amount: 1.5, currency: 'USD' }) // false\n * isMoney(null) // false\n * ```\n */\nexport function isMoney(value: unknown): value is Money {\n if (typeof value !== 'object' || value === null) return false;\n\n const v = value as Record<string, unknown>;\n\n return (\n Object.hasOwn(v, 'amount') &&\n typeof v.amount === 'bigint' &&\n Object.hasOwn(v, 'currency') &&\n typeof v.currency === 'string'\n );\n}\n\n// ─── Arithmetic ──────────────────────────────────────────────────────────────\n\n/** Adds two `Money` values. Throws if their currencies differ. */\nexport function add(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount + b.amount, currency: a.currency };\n}\n\n/** Subtracts `b` from `a`. Throws if their currencies differ. */\nexport function subtract(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount - b.amount, currency: a.currency };\n}\n\n/**\n * Multiplies a `Money` value by a scalar factor.\n * The factor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * multiply(money('100.00', 'USD'), '1.5') // $150.00\n * multiply(money('1.00', 'USD'), '0.339', 'floor') // $0.33\n * multiply(money('1.00', 'USD'), '0.339', 'ceiling') // $0.34\n * ```\n */\nexport function multiply(m: Money, factor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator, negative: factorNegative, numerator } = parseRational(String(factor));\n const negative = m.amount < 0n !== factorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n const raw = absAmount * numerator;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Divides a `Money` value by a scalar divisor.\n * The divisor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n * @throws {CoinsError} On division by zero.\n *\n * @example\n * ```ts\n * divide(money('100.00', 'USD'), 3) // $33.33\n * divide(money('100.00', 'USD'), 3, 'ceiling') // $33.34\n * ```\n */\nexport function divide(m: Money, divisor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator: parsedDenom, negative: divisorNegative, numerator } = parseRational(String(divisor));\n\n if (numerator === 0n) throw new CoinsError('Division by zero');\n\n const negative = m.amount < 0n !== divisorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n // Dividing by (numerator/parsedDenom) = multiplying by (parsedDenom/numerator).\n const raw = absAmount * parsedDenom;\n const quotient = raw / numerator;\n const result = applyRounding(quotient, raw % numerator, numerator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Distributes `money` across `ratios` without losing or gaining a single minor unit.\n * Accepts both number and string ratios — use strings for lossless decimal weights.\n *\n * Uses the Largest Remainder Method: each share gets its floor allocation first,\n * then any remainder units are assigned one-by-one to the shares with the largest\n * fractional parts, breaking ties by original index (stable, left-to-right).\n *\n * Throws if `ratios` is empty, contains negative values (including negative strings like `'-0.5'`), or sums to zero.\n *\n * @example\n * ```ts\n * allocate(money('10.00', 'USD'), [1, 1, 1])\n * // → [$3.34, $3.33, $3.33] (not three × $3.33 — that loses a penny)\n *\n * allocate(money('10.00', 'USD'), ['0.3', '0.7'])\n * // → [$3.00, $7.00]\n * ```\n */\nexport function allocate(m: Money, ratios: readonly (number | string)[]): [Money, ...Money[]] {\n if (ratios.length === 0) throw new CoinsError('allocate requires at least one ratio');\n\n const parsedRatios = ratios.map((r) => parseRational(String(r)));\n\n if (parsedRatios.some((p) => p.negative)) throw new CoinsError('All ratios must be non-negative');\n\n if (!parsedRatios.some((p) => p.numerator > 0n)) throw new CoinsError('At least one ratio must be positive');\n\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n\n // All denominators are powers of 10; the max is their LCM — use it to normalise weights to integers.\n const maxDenominator = parsedRatios.reduce((max, p) => (p.denominator > max ? p.denominator : max), 1n);\n const bigWeights = parsedRatios.map((p) => p.numerator * (maxDenominator / p.denominator));\n const bigTotal = bigWeights.reduce((a, b) => a + b, 0n);\n\n // Floor allocation + fractional remainders.\n const floors: bigint[] = [];\n const fracRemainders: bigint[] = [];\n\n for (const w of bigWeights) {\n const ideal = absAmount * w;\n\n floors.push(ideal / bigTotal);\n fracRemainders.push(ideal % bigTotal);\n }\n\n // Distribute leftover units to the shares with the largest fractional remainders.\n // Relies on V8/SpiderMonkey's stable sort (ECMAScript 2019+ spec-mandated): ties\n // in fractional remainders are broken by original index (left-to-right), ensuring\n // deterministic output for equal-weight ratios (e.g. [1, 1, 1]).\n const indices = ratios\n .map((_, i) => i)\n .sort((a, b) => {\n const diff = fracRemainders[b]! - fracRemainders[a]!;\n\n return diff > 0n ? 1 : diff < 0n ? -1 : 0;\n });\n\n const result = [...floors];\n // `remaining` is always < ratios.length (at most one unit per share), safe for this loop.\n let remaining = absAmount - floors.reduce((a, b) => a + b, 0n);\n\n for (let i = 0; remaining > 0n; i++, remaining--) {\n result[indices[i]!]! += 1n;\n }\n\n return result.map((amount) => ({ amount: negative ? -amount : amount, currency: m.currency })) as [Money, ...Money[]];\n}\n\n// ─── Aggregates ──────────────────────────────────────────────────────────────\n\n/**\n * Sums an array of `Money` values. Throws if the array is empty or currencies differ.\n *\n * @example\n * ```ts\n * sum([money('1.00', 'USD'), money('2.50', 'USD')]) // $3.50\n * ```\n */\nexport function sum(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('sum requires at least one Money value');\n\n const currency = moneys[0]!.currency;\n\n for (let i = 1; i < moneys.length; i++) {\n if (moneys[i]!.currency !== currency) {\n throw new CurrencyMismatchError(currency, moneys[i]!.currency);\n }\n }\n\n return { amount: moneys.reduce((acc, m) => acc + m.amount, 0n), currency };\n}\n\n/**\n * Returns the smallest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * min([money('3.00', 'USD'), money('1.00', 'USD'), money('2.00', 'USD')]) // $1.00\n * ```\n */\nexport function min(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('min requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) <= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Returns the largest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * max([money('1.00', 'USD'), money('3.00', 'USD'), money('2.00', 'USD')]) // $3.00\n * ```\n */\nexport function max(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('max requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) >= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Splits `money` into `parts` equal shares without losing or gaining a single minor unit.\n * Equivalent to `allocate(money, Array.from({ length: parts }, () => 1))`.\n *\n * @throws {CoinsError} If `parts` is not a positive integer (≥ 1).\n *\n * @example\n * ```ts\n * splitEvenly(money('10.00', 'USD'), 3)\n * // → [$3.34, $3.33, $3.33]\n * ```\n */\nexport function splitEvenly(m: Money, parts: number): [Money, ...Money[]] {\n if (!Number.isInteger(parts) || parts <= 0) {\n throw new CoinsError('splitEvenly requires a positive integer number of parts');\n }\n\n return allocate(\n m,\n Array.from({ length: parts }, () => 1),\n );\n}\n\n/**\n * Clamps `m` to the inclusive range `[lower, upper]`.\n *\n * @throws {CurrencyMismatchError} If `m`, `lower`, or `upper` have different currencies.\n * @throws {CoinsError} If `lower > upper`.\n *\n * @example\n * ```ts\n * clamp(money('5.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $5.00\n * clamp(money('0.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $1.00\n * clamp(money('15.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $10.00\n * ```\n */\nexport function clamp(m: Money, lower: Money, upper: Money): Money {\n // Validate currency consistency upfront so the error always names the mismatch,\n // rather than surfacing mid-computation from min() or max().\n if (m.currency !== lower.currency || m.currency !== upper.currency) {\n throw new CurrencyMismatchError(m.currency, m.currency !== lower.currency ? lower.currency : upper.currency);\n }\n\n if (compare(lower, upper) > 0) {\n throw new CoinsError(\n `clamp: lower (${toDecimal(lower)} ${lower.currency}) must be <= upper (${toDecimal(upper)} ${upper.currency})`,\n );\n }\n\n return max([lower, min([m, upper])]);\n}\n\n// ─── Unary ───────────────────────────────────────────────────────────────────\n\n/** Returns the absolute value of `money`. Negative amounts become positive. */\nexport function abs(m: Money): Money {\n return { amount: m.amount < 0n ? -m.amount : m.amount, currency: m.currency };\n}\n\n/** Returns `money` with its sign flipped. */\nexport function negate(m: Money): Money {\n return { amount: -m.amount, currency: m.currency };\n}\n\n// ─── Comparison ──────────────────────────────────────────────────────────────\n\n/**\n * Compares two `Money` values. Returns `-1`, `0`, or `1`.\n * Throws if their currencies differ.\n */\nexport function compare(a: Money, b: Money): -1 | 0 | 1 {\n assertSameCurrency(a, b);\n\n if (a.amount < b.amount) return -1;\n\n if (a.amount > b.amount) return 1;\n\n return 0;\n}\n\n/**\n * Returns `true` if both `Money` values have the same currency and amount.\n * Returns `false` if currencies differ — safe to use in `.filter()` and conditional chains.\n */\nexport function isEqual(a: Money, b: Money): boolean {\n return a.currency === b.currency && a.amount === b.amount;\n}\n\n/** Returns `true` if `a` is strictly greater than `b`. Throws on currency mismatch. */\nexport function greaterThan(a: Money, b: Money): boolean {\n return compare(a, b) > 0;\n}\n\n/** Returns `true` if `a` is greater than or equal to `b`. Throws on currency mismatch. */\nexport function greaterThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) >= 0;\n}\n\n/** Returns `true` if `a` is strictly less than `b`. Throws on currency mismatch. */\nexport function lessThan(a: Money, b: Money): boolean {\n return compare(a, b) < 0;\n}\n\n/** Returns `true` if `a` is less than or equal to `b`. Throws on currency mismatch. */\nexport function lessThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) <= 0;\n}\n\n// ─── Predicates ──────────────────────────────────────────────────────────────\n\n/** Returns `true` if the amount is exactly zero. */\nexport function isZero(m: Money): boolean {\n return m.amount === 0n;\n}\n\n/** Returns `true` if the amount is strictly positive (> 0). */\nexport function isPositive(m: Money): boolean {\n return m.amount > 0n;\n}\n\n/** Returns `true` if the amount is strictly negative (< 0). */\nexport function isNegative(m: Money): boolean {\n return m.amount < 0n;\n}\n\n/** Returns `true` if the amount is zero or positive (>= 0). */\nexport function isNonNegative(m: Money): boolean {\n return m.amount >= 0n;\n}\n\n/** Returns `true` if the amount is zero or negative (<= 0). */\nexport function isNonPositive(m: Money): boolean {\n return m.amount <= 0n;\n}\n\n// ─── Serialization ───────────────────────────────────────────────────────────\n\n/**\n * Serializes a `Money` value to a plain-object JSON-safe form.\n * `amount` is a bigint string (e.g. `'123456'`) to avoid `JSON.stringify` throwing.\n *\n * @example\n * ```ts\n * toJSON(money('1234.56', 'USD')) // { amount: '123456', currency: 'USD' }\n * JSON.stringify(toJSON(price)) // '{\"amount\":\"123456\",\"currency\":\"USD\"}'\n * ```\n */\nexport function toJSON(m: Money): MoneyJSON {\n return { amount: String(m.amount), currency: m.currency };\n}\n\n/**\n * Deserializes a `MoneyJSON` object back into a `Money` value.\n * Validates the currency code and the amount string.\n *\n * @example\n * ```ts\n * fromJSON({ amount: '123456', currency: 'USD' }) // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function fromJSON(json: MoneyJSON): Money {\n const validCurrency = validateCurrencyCode(json.currency);\n\n if (typeof json.amount !== 'string') {\n throw new CoinsError(\n `Invalid money amount in JSON: ${String(json.amount)} (expected an integer string, e.g. '123456')`,\n );\n }\n\n let amount: bigint;\n\n try {\n amount = BigInt(json.amount);\n } catch {\n throw new CoinsError(`Invalid money amount in JSON: \"${json.amount}\" (expected an integer string, e.g. '123456')`);\n }\n\n return { amount, currency: validCurrency };\n}\n\n/**\n * Serializes a `Money` value to a decimal string (e.g. `'1234.56'`).\n * Round-trips losslessly with `money()`.\n *\n * @example\n * ```ts\n * toDecimal(money('1234.56', 'USD')) // '1234.56'\n * toDecimal(money(5n, 'USD')) // '0.05'\n * toDecimal(money(1234n, 'JPY')) // '1234'\n * ```\n */\nexport function toDecimal(m: Money): string {\n const decimals = getCurrencyDecimals(m.currency);\n\n if (decimals === 0) return String(m.amount);\n\n const negative = m.amount < 0n;\n const abs = negative ? -m.amount : m.amount;\n const scale = pow10(decimals);\n const whole = abs / scale;\n const frac = (abs % scale).toString().padStart(decimals, '0');\n\n return `${negative ? '-' : ''}${whole}.${frac}`;\n}\n\n/**\n * Converts a `Money` value to a floating-point number.\n * Useful for charting and display; **not** for arithmetic (lossy).\n *\n * @example\n * ```ts\n * toNumber(money('1234.56', 'USD')) // 1234.56\n * ```\n */\nexport function toNumber(m: Money): number {\n const decimals = getCurrencyDecimals(m.currency);\n\n return Number(m.amount) / Number(pow10(decimals));\n}\n\n// ─── Rounding ─────────────────────────────────────────────────────────────────\n\n/**\n * Rounds a `Money` value to fewer decimal places than the currency's default.\n * `places` must be a non-negative integer in the range `0..currencyDecimals`.\n *\n * Useful for display purposes (e.g. rounding USD to whole dollars).\n * @throws {CoinsError} If `places` is out of the allowed range.\n *\n * @param mode Rounding mode. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * roundTo(money('1234.56', 'USD'), 0) // $1235 (whole dollars)\n * roundTo(money('1234.56', 'USD'), 1) // $1234.6\n * roundTo(money('1234.56', 'USD'), 1, 'floor') // $1234.5\n * roundTo(money('1234', 'JPY'), 0) // ¥1234 (no-op: JPY is already 0-decimal)\n * ```\n */\nexport function roundTo(m: Money, places: number, mode: RoundingMode = 'half-away-from-zero'): Money {\n if (!Number.isInteger(places) || places < 0) {\n throw new CoinsError(`roundTo: places must be a non-negative integer, got ${places}`);\n }\n\n const currencyDecimals = getCurrencyDecimals(m.currency);\n\n if (places > currencyDecimals) {\n throw new CoinsError(\n `roundTo: places (${places}) exceeds the decimal places for ${m.currency} (${currencyDecimals})`,\n );\n }\n\n if (places === currencyDecimals) return m;\n\n const drop = currencyDecimals - places;\n const divisor = pow10(drop);\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n const quotient = absAmount / divisor;\n const remainder = absAmount % divisor;\n const rounded = applyRounding(quotient, remainder, divisor, mode, negative);\n\n return { amount: negative ? -rounded : rounded, currency: m.currency };\n}\n"],"mappings":"iFAkCA,SAAgB,EAAM,EAAkC,EAA+B,CACrF,IAAM,EAAgB,EAAA,qBAAqB,CAAQ,EAEnD,GAAI,OAAO,GAAW,SACpB,MAAO,CAAE,SAAQ,SAAU,CAAc,EAG3C,GAAI,OAAO,GAAW,SAAU,CAC9B,IAAM,EAAW,EAAA,oBAAoB,CAAa,EAC5C,EAAM,OAAO,CAAM,EAInB,EAAa,EAAA,cAAc,KAAK,CAAG,EAAI,EAAA,iBAAiB,CAAG,EAAI,EAC/D,EAAW,EAAW,QAAQ,GAAG,EACjC,EAAU,IAAa,GAAK,EAAI,EAAW,OAAS,EAAW,EAUrE,OARI,EAAU,GACZ,EAAA,KACE,0BAA0B,EAAO,6BAA6B,EAAQ,SAAS,EAAc,aAAa,EAAS,0DAErH,EAIK,CAAE,OAAQ,EAAkB,EAAK,CAAQ,EAAG,SAAU,CAAc,CAC7E,CAGA,MAAO,CAAE,OAAQ,EAAkB,OAAO,CAAM,EAAG,EAAA,oBAAoB,CAAa,CAAC,EAAG,SAAU,CAAc,CAClH,CAIA,SAAS,EAAmB,EAAU,EAAgB,CACpD,GAAI,EAAE,WAAa,EAAE,SACnB,MAAM,IAAI,EAAA,sBAAsB,EAAE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AAM,KAAK,EAAM,GAAG,GAC3C,CAWA,SAAgB,EAAS,EAAkB,CACzC,IAAM,EAAW,EAAA,oBAAoB,EAAE,QAAQ,EAE/C,OAAO,OAAO,EAAE,MAAM,EAAI,OAAO,EAAA,MAAM,CAAQ,CAAC,CAClD,CAqBA,SAAgB,EAAQ,EAAU,EAAgB,EAAqB,sBAA8B,CACnG,GAAI,CAAC,OAAO,UAAU,CAAM,GAAK,EAAS,EACxC,MAAM,IAAI,EAAA,WAAW,uDAAuD,GAAQ,EAGtF,IAAM,EAAmB,EAAA,oBAAoB,EAAE,QAAQ,EAEvD,GAAI,EAAS,EACX,MAAM,IAAI,EAAA,WACR,oBAAoB,EAAO,mCAAmC,EAAE,SAAS,IAAI,EAAiB,EAChG,EAGF,GAAI,IAAW,EAAkB,OAAO,EAGxC,IAAM,EAAU,EAAA,MADH,EAAmB,CACN,EACpB,EAAW,EAAE,OAAS,GACtB,EAAY,EAAW,CAAC,EAAE,OAAS,EAAE,OAGrC,EAAU,EAAA,cAFC,EAAY,EACX,EAAY,EACqB,EAAS,EAAM,CAAQ,EAE1E,MAAO,CAAE,OAAQ,EAAW,CAAC,EAAU,EAAS,SAAU,EAAE,QAAS,CACvE"}
1
+ {"version":3,"file":"money.cjs","names":[],"sources":["../src/money.ts"],"sourcesContent":["import type { Currency, Money, RoundingMode } from './types';\n\nimport { isCurrency } from './currency';\nimport { decimal, roundDivision, toDecimalString } from './decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nexport function money<C extends Currency>(amount: string, currency: C): Money<C>;\nexport function money<C extends Currency>(amount: string, currency: C, options: { rounding: RoundingMode }): Money<C>;\nexport function money<C extends Currency>(amount: bigint, currency: C, options: { unit: 'minor' }): Money<C>;\nexport function money<C extends Currency>(\n amount: bigint | string,\n currency: C,\n options?: { rounding: RoundingMode } | { unit: 'minor' },\n): Money<C> {\n assertCurrency(currency);\n\n if (typeof amount === 'bigint') {\n if (!options || !('unit' in options) || options.unit !== 'minor') {\n throw new CoinsError('INVALID_MONEY', \"Bigint amounts require { unit: 'minor' }\");\n }\n\n return createMoney(amount, currency);\n }\n\n if (options && 'unit' in options)\n throw new CoinsError('INVALID_MONEY', 'Decimal strings do not accept a unit option');\n\n const value = decimal(amount);\n const scaled = value.numerator * 10n ** BigInt(currency.minorUnit);\n const remainder = scaled % value.denominator;\n\n if (remainder !== 0n && !options) {\n throw new CoinsError('INVALID_MONEY', `Amount \"${amount}\" exceeds ${currency.code} precision; provide rounding`);\n }\n\n return createMoney(roundDivision(scaled, value.denominator, options?.rounding ?? defaultRounding), currency);\n}\n\nexport function parseMoney(value: unknown): Money {\n if (!isPlainDataObject(value)) throw new CoinsError('INVALID_MONEY', 'Money must be a plain data object');\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const amountDescriptor = descriptors.amount;\n const currencyDescriptor = descriptors.currency;\n\n if (!isDataProperty(amountDescriptor) || !isDataProperty(currencyDescriptor)) {\n throw new CoinsError('INVALID_MONEY', 'Money properties must be plain data values');\n }\n\n if (typeof amountDescriptor.value !== 'bigint' || !isCurrency(currencyDescriptor.value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must contain bigint amount and a registered currency');\n }\n\n return createMoney(amountDescriptor.value, currencyDescriptor.value);\n}\n\nexport function isMoney(value: unknown): value is Money {\n try {\n parseMoney(value);\n\n return true;\n } catch {\n return false;\n }\n}\n\nexport function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount + right.amount, left.currency);\n}\n\nexport function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount - right.amount, left.currency);\n}\n\nexport function multiply<C extends Currency>(\n value: Money<C>,\n factor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(factor);\n\n return createMoney(\n roundDivision(value.amount * scalar.numerator, scalar.denominator, options.rounding ?? defaultRounding),\n value.currency,\n );\n}\n\nexport function divide<C extends Currency>(\n value: Money<C>,\n divisor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(divisor);\n\n if (scalar.numerator === 0n) throw new CoinsError('DIVISION_BY_ZERO', 'Cannot divide money by zero');\n\n return createMoney(\n roundDivision(\n value.amount * scalar.denominator,\n scalar.numerator < 0n ? -scalar.numerator : scalar.numerator,\n options.rounding ?? defaultRounding,\n ) * (scalar.numerator < 0n ? -1n : 1n),\n value.currency,\n );\n}\n\nexport function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1 {\n assertSameCurrency(left, right);\n\n return left.amount === right.amount ? 0 : left.amount < right.amount ? -1 : 1;\n}\n\nexport function abs<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(value.amount < 0n ? -value.amount : value.amount, value.currency);\n}\n\nexport function negate<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(-value.amount, value.currency);\n}\n\nexport function round<C extends Currency>(\n value: Money<C>,\n options: { fractionDigits: number; rounding?: RoundingMode },\n): Money<C> {\n assertMoney(value);\n\n const { fractionDigits, rounding = defaultRounding } = options;\n\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0 || fractionDigits > value.currency.minorUnit) {\n throw new CoinsError('INVALID_ROUNDING', `fractionDigits must be an integer from 0 to ${value.currency.minorUnit}`);\n }\n\n const factor = 10n ** BigInt(value.currency.minorUnit - fractionDigits);\n\n return createMoney(roundDivision(value.amount, factor, rounding) * factor, value.currency);\n}\n\nexport function toDecimal(value: Money): string {\n assertMoney(value);\n\n return toDecimalString(value.amount, value.currency.minorUnit);\n}\n\nexport function withMinor<C extends Currency>(amount: bigint, currency: C): Money<C> {\n assertCurrency(currency);\n\n return createMoney(amount, currency);\n}\n\nfunction createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n return Object.freeze({ amount, currency }) as Money<C>;\n}\n\nfunction assertMoney(value: Money): void {\n if (!Object.isFrozen(value) || !isCurrency(value.currency)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical Coins value');\n }\n}\n\nfunction assertSameCurrency(left: Money, right: Money): void {\n assertMoney(left);\n assertMoney(right);\n\n if (left.currency !== right.currency) {\n throw new CurrencyMismatchError(left.currency.code, right.currency.code);\n }\n}\n\nfunction assertCurrency(value: Currency): void {\n if (!isCurrency(value)) throw new CoinsError('INVALID_CURRENCY', 'Money requires a registered currency');\n}\n\nfunction isPlainDataObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDataProperty(\n descriptor: PropertyDescriptor | undefined,\n): descriptor is PropertyDescriptor & { value: unknown } {\n return (\n descriptor !== undefined && 'value' in descriptor && descriptor.get === undefined && descriptor.set === undefined\n );\n}\n"],"mappings":"uFAMA,IAAM,EAAgC,mBAKtC,SAAgB,EACd,EACA,EACA,EACU,CAGV,GAFA,EAAe,CAAQ,EAEnB,OAAO,GAAW,SAAU,CAC9B,GAAI,CAAC,GAAW,EAAE,SAAU,IAAY,EAAQ,OAAS,QACvD,MAAM,IAAI,EAAA,WAAW,gBAAiB,0CAA0C,EAGlF,OAAO,EAAY,EAAQ,CAAQ,CACrC,CAEA,GAAI,GAAW,SAAU,EACvB,MAAM,IAAI,EAAA,WAAW,gBAAiB,6CAA6C,EAErF,IAAM,EAAQ,EAAA,QAAQ,CAAM,EACtB,EAAS,EAAM,UAAY,KAAO,OAAO,EAAS,SAAS,EAGjE,GAFkB,EAAS,EAAM,cAEf,IAAM,CAAC,EACvB,MAAM,IAAI,EAAA,WAAW,gBAAiB,WAAW,EAAO,YAAY,EAAS,KAAK,6BAA6B,EAGjH,OAAO,EAAY,EAAA,cAAc,EAAQ,EAAM,YAAa,GAAS,UAAY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,EAAY,EAAoB,CACvC,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,CAAC,EAAA,WAAW,EAAM,QAAQ,EACvD,MAAM,IAAI,EAAA,WAAW,gBAAiB,uCAAuC,CAEjF,CAEA,SAAS,EAAmB,EAAa,EAAoB,CAI3D,GAHA,EAAY,CAAI,EAChB,EAAY,CAAK,EAEb,EAAK,WAAa,EAAM,SAC1B,MAAM,IAAI,EAAA,sBAAsB,EAAK,SAAS,KAAM,EAAM,SAAS,IAAI,CAE3E,CAEA,SAAS,EAAe,EAAuB,CAC7C,GAAI,CAAC,EAAA,WAAW,CAAK,EAAG,MAAM,IAAI,EAAA,WAAW,mBAAoB,sCAAsC,CACzG,CAEA,SAAS,EAAkB,EAAuD,CAChF,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GAExD,IAAM,EAAY,OAAO,eAAe,CAAK,EAE7C,OAAO,IAAc,OAAO,WAAa,IAAc,IACzD,CAEA,SAAS,EACP,EACuD,CACvD,OACE,IAAe,IAAA,IAAa,UAAW,GAAc,EAAW,MAAQ,IAAA,IAAa,EAAW,MAAQ,IAAA,EAE5G"}
package/dist/money.d.ts CHANGED
@@ -1,247 +1,28 @@
1
- import type { CurrencyCode, Money, MoneyJSON, RoundingMode } from './types';
2
- export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';
3
- /**
4
- * Creates a `Money` value from a decimal string, number, or raw bigint minor units.
5
- * Validates the currency code — throws `InvalidCurrencyError` for unrecognised ISO 4217 codes.
6
- *
7
- * - **string** `'1234.56'` → parsed losslessly; respects the currency's decimal places.
8
- * - **number** `1234.56` → converted via `String()` first; inherits IEEE-754 limits.
9
- * Prefer strings when precision matters.
10
- * - **bigint** `123456n` → used as-is (already in minor units).
11
- *
12
- * @example
13
- * ```ts
14
- * money('1234.56', 'USD') // { amount: 123456n, currency: 'USD' }
15
- * money(1234, 'JPY') // { amount: 1234n, currency: 'JPY' }
16
- * money(123456n, 'USD') // { amount: 123456n, currency: 'USD' }
17
- * ```
18
- */
19
- export declare function money(amount: bigint | number | string, currency: CurrencyCode): Money;
20
- /**
21
- * Creates a new `Money` value with the given `amount` and the same currency as `m`.
22
- * Useful when you compute a raw `bigint` amount externally and need to wrap it
23
- * back into a `Money` value without re-validating the currency.
24
- *
25
- * @example
26
- * ```ts
27
- * const price = money('9.99', 'USD');
28
- * withAmount(price, 1999n) // { amount: 1999n, currency: 'USD' }
29
- * ```
30
- */
31
- export declare function withAmount(m: Money, amount: bigint): Money;
32
- /**
33
- * Type guard that returns `true` if `value` is a `Money`-shaped object
34
- * (has a `bigint` `amount` and a `string` `currency`).
35
- * Useful for narrowing unknown payloads from APIs or deserialized storage.
36
- *
37
- * Note: does **not** validate the currency code — use `money(0n, currency)` or
38
- * `validateCurrencyCode()` if you also need to confirm it is a recognized ISO 4217 code.
39
- *
40
- * @example
41
- * ```ts
42
- * isMoney({ amount: 100n, currency: 'USD' }) // true
43
- * isMoney({ amount: 1.5, currency: 'USD' }) // false
44
- * isMoney(null) // false
45
- * ```
46
- */
1
+ import type { Currency, Money, RoundingMode } from './types';
2
+ export declare function money<C extends Currency>(amount: string, currency: C): Money<C>;
3
+ export declare function money<C extends Currency>(amount: string, currency: C, options: {
4
+ rounding: RoundingMode;
5
+ }): Money<C>;
6
+ export declare function money<C extends Currency>(amount: bigint, currency: C, options: {
7
+ unit: 'minor';
8
+ }): Money<C>;
9
+ export declare function parseMoney(value: unknown): Money;
47
10
  export declare function isMoney(value: unknown): value is Money;
48
- /** Adds two `Money` values. Throws if their currencies differ. */
49
- export declare function add(a: Money, b: Money): Money;
50
- /** Subtracts `b` from `a`. Throws if their currencies differ. */
51
- export declare function subtract(a: Money, b: Money): Money;
52
- /**
53
- * Multiplies a `Money` value by a scalar factor.
54
- * The factor can be a decimal string (lossless) or a number.
55
- *
56
- * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.
57
- *
58
- * @example
59
- * ```ts
60
- * multiply(money('100.00', 'USD'), '1.5') // $150.00
61
- * multiply(money('1.00', 'USD'), '0.339', 'floor') // $0.33
62
- * multiply(money('1.00', 'USD'), '0.339', 'ceiling') // $0.34
63
- * ```
64
- */
65
- export declare function multiply(m: Money, factor: number | string, mode?: RoundingMode): Money;
66
- /**
67
- * Divides a `Money` value by a scalar divisor.
68
- * The divisor can be a decimal string (lossless) or a number.
69
- *
70
- * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.
71
- * @throws {CoinsError} On division by zero.
72
- *
73
- * @example
74
- * ```ts
75
- * divide(money('100.00', 'USD'), 3) // $33.33
76
- * divide(money('100.00', 'USD'), 3, 'ceiling') // $33.34
77
- * ```
78
- */
79
- export declare function divide(m: Money, divisor: number | string, mode?: RoundingMode): Money;
80
- /**
81
- * Distributes `money` across `ratios` without losing or gaining a single minor unit.
82
- * Accepts both number and string ratios — use strings for lossless decimal weights.
83
- *
84
- * Uses the Largest Remainder Method: each share gets its floor allocation first,
85
- * then any remainder units are assigned one-by-one to the shares with the largest
86
- * fractional parts, breaking ties by original index (stable, left-to-right).
87
- *
88
- * Throws if `ratios` is empty, contains negative values (including negative strings like `'-0.5'`), or sums to zero.
89
- *
90
- * @example
91
- * ```ts
92
- * allocate(money('10.00', 'USD'), [1, 1, 1])
93
- * // → [$3.34, $3.33, $3.33] (not three × $3.33 — that loses a penny)
94
- *
95
- * allocate(money('10.00', 'USD'), ['0.3', '0.7'])
96
- * // → [$3.00, $7.00]
97
- * ```
98
- */
99
- export declare function allocate(m: Money, ratios: readonly (number | string)[]): [Money, ...Money[]];
100
- /**
101
- * Sums an array of `Money` values. Throws if the array is empty or currencies differ.
102
- *
103
- * @example
104
- * ```ts
105
- * sum([money('1.00', 'USD'), money('2.50', 'USD')]) // $3.50
106
- * ```
107
- */
108
- export declare function sum(moneys: readonly Money[]): Money;
109
- /**
110
- * Returns the smallest `Money` value from a non-empty array. Throws if currencies differ.
111
- *
112
- * @example
113
- * ```ts
114
- * min([money('3.00', 'USD'), money('1.00', 'USD'), money('2.00', 'USD')]) // $1.00
115
- * ```
116
- */
117
- export declare function min(moneys: readonly Money[]): Money;
118
- /**
119
- * Returns the largest `Money` value from a non-empty array. Throws if currencies differ.
120
- *
121
- * @example
122
- * ```ts
123
- * max([money('1.00', 'USD'), money('3.00', 'USD'), money('2.00', 'USD')]) // $3.00
124
- * ```
125
- */
126
- export declare function max(moneys: readonly Money[]): Money;
127
- /**
128
- * Splits `money` into `parts` equal shares without losing or gaining a single minor unit.
129
- * Equivalent to `allocate(money, Array.from({ length: parts }, () => 1))`.
130
- *
131
- * @throws {CoinsError} If `parts` is not a positive integer (≥ 1).
132
- *
133
- * @example
134
- * ```ts
135
- * splitEvenly(money('10.00', 'USD'), 3)
136
- * // → [$3.34, $3.33, $3.33]
137
- * ```
138
- */
139
- export declare function splitEvenly(m: Money, parts: number): [Money, ...Money[]];
140
- /**
141
- * Clamps `m` to the inclusive range `[lower, upper]`.
142
- *
143
- * @throws {CurrencyMismatchError} If `m`, `lower`, or `upper` have different currencies.
144
- * @throws {CoinsError} If `lower > upper`.
145
- *
146
- * @example
147
- * ```ts
148
- * clamp(money('5.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $5.00
149
- * clamp(money('0.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $1.00
150
- * clamp(money('15.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $10.00
151
- * ```
152
- */
153
- export declare function clamp(m: Money, lower: Money, upper: Money): Money;
154
- /** Returns the absolute value of `money`. Negative amounts become positive. */
155
- export declare function abs(m: Money): Money;
156
- /** Returns `money` with its sign flipped. */
157
- export declare function negate(m: Money): Money;
158
- /**
159
- * Compares two `Money` values. Returns `-1`, `0`, or `1`.
160
- * Throws if their currencies differ.
161
- */
162
- export declare function compare(a: Money, b: Money): -1 | 0 | 1;
163
- /**
164
- * Returns `true` if both `Money` values have the same currency and amount.
165
- * Returns `false` if currencies differ — safe to use in `.filter()` and conditional chains.
166
- */
167
- export declare function isEqual(a: Money, b: Money): boolean;
168
- /** Returns `true` if `a` is strictly greater than `b`. Throws on currency mismatch. */
169
- export declare function greaterThan(a: Money, b: Money): boolean;
170
- /** Returns `true` if `a` is greater than or equal to `b`. Throws on currency mismatch. */
171
- export declare function greaterThanOrEqual(a: Money, b: Money): boolean;
172
- /** Returns `true` if `a` is strictly less than `b`. Throws on currency mismatch. */
173
- export declare function lessThan(a: Money, b: Money): boolean;
174
- /** Returns `true` if `a` is less than or equal to `b`. Throws on currency mismatch. */
175
- export declare function lessThanOrEqual(a: Money, b: Money): boolean;
176
- /** Returns `true` if the amount is exactly zero. */
177
- export declare function isZero(m: Money): boolean;
178
- /** Returns `true` if the amount is strictly positive (> 0). */
179
- export declare function isPositive(m: Money): boolean;
180
- /** Returns `true` if the amount is strictly negative (< 0). */
181
- export declare function isNegative(m: Money): boolean;
182
- /** Returns `true` if the amount is zero or positive (>= 0). */
183
- export declare function isNonNegative(m: Money): boolean;
184
- /** Returns `true` if the amount is zero or negative (<= 0). */
185
- export declare function isNonPositive(m: Money): boolean;
186
- /**
187
- * Serializes a `Money` value to a plain-object JSON-safe form.
188
- * `amount` is a bigint string (e.g. `'123456'`) to avoid `JSON.stringify` throwing.
189
- *
190
- * @example
191
- * ```ts
192
- * toJSON(money('1234.56', 'USD')) // { amount: '123456', currency: 'USD' }
193
- * JSON.stringify(toJSON(price)) // '{"amount":"123456","currency":"USD"}'
194
- * ```
195
- */
196
- export declare function toJSON(m: Money): MoneyJSON;
197
- /**
198
- * Deserializes a `MoneyJSON` object back into a `Money` value.
199
- * Validates the currency code and the amount string.
200
- *
201
- * @example
202
- * ```ts
203
- * fromJSON({ amount: '123456', currency: 'USD' }) // { amount: 123456n, currency: 'USD' }
204
- * ```
205
- */
206
- export declare function fromJSON(json: MoneyJSON): Money;
207
- /**
208
- * Serializes a `Money` value to a decimal string (e.g. `'1234.56'`).
209
- * Round-trips losslessly with `money()`.
210
- *
211
- * @example
212
- * ```ts
213
- * toDecimal(money('1234.56', 'USD')) // '1234.56'
214
- * toDecimal(money(5n, 'USD')) // '0.05'
215
- * toDecimal(money(1234n, 'JPY')) // '1234'
216
- * ```
217
- */
218
- export declare function toDecimal(m: Money): string;
219
- /**
220
- * Converts a `Money` value to a floating-point number.
221
- * Useful for charting and display; **not** for arithmetic (lossy).
222
- *
223
- * @example
224
- * ```ts
225
- * toNumber(money('1234.56', 'USD')) // 1234.56
226
- * ```
227
- */
228
- export declare function toNumber(m: Money): number;
229
- /**
230
- * Rounds a `Money` value to fewer decimal places than the currency's default.
231
- * `places` must be a non-negative integer in the range `0..currencyDecimals`.
232
- *
233
- * Useful for display purposes (e.g. rounding USD to whole dollars).
234
- * @throws {CoinsError} If `places` is out of the allowed range.
235
- *
236
- * @param mode Rounding mode. Defaults to `'half-away-from-zero'`.
237
- *
238
- * @example
239
- * ```ts
240
- * roundTo(money('1234.56', 'USD'), 0) // $1235 (whole dollars)
241
- * roundTo(money('1234.56', 'USD'), 1) // $1234.6
242
- * roundTo(money('1234.56', 'USD'), 1, 'floor') // $1234.5
243
- * roundTo(money('1234', 'JPY'), 0) // ¥1234 (no-op: JPY is already 0-decimal)
244
- * ```
245
- */
246
- export declare function roundTo(m: Money, places: number, mode?: RoundingMode): Money;
11
+ export declare function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C>;
12
+ export declare function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C>;
13
+ export declare function multiply<C extends Currency>(value: Money<C>, factor: string, options?: {
14
+ rounding?: RoundingMode;
15
+ }): Money<C>;
16
+ export declare function divide<C extends Currency>(value: Money<C>, divisor: string, options?: {
17
+ rounding?: RoundingMode;
18
+ }): Money<C>;
19
+ export declare function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1;
20
+ export declare function abs<C extends Currency>(value: Money<C>): Money<C>;
21
+ export declare function negate<C extends Currency>(value: Money<C>): Money<C>;
22
+ export declare function round<C extends Currency>(value: Money<C>, options: {
23
+ fractionDigits: number;
24
+ rounding?: RoundingMode;
25
+ }): Money<C>;
26
+ export declare function toDecimal(value: Money): string;
27
+ export declare function withMinor<C extends Currency>(amount: bigint, currency: C): Money<C>;
247
28
  //# sourceMappingURL=money.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"money.d.ts","sourceRoot":"","sources":["../src/money.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAc5E,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAInF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,KAAK,CA8BrF;AAyBD;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAE1D;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,KAAK,CAWtD;AAID,kEAAkE;AAClE,wBAAgB,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,CAI7C;AAED,iEAAiE;AACjE,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,CAIlD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,GAAE,YAAoC,GAAG,KAAK,CAS7G;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,GAAE,YAA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