subunit-money 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,22 +1,416 @@
1
1
  /**
2
- * subunit-money - A type-safe value object for monetary amounts
2
+ * Money - An immutable value object for monetary amounts.
3
3
  *
4
- * @example
5
- * import { Money, ExchangeRateService, MoneyConverter } from '@cbrunnkvist/subunit-money'
4
+ * Design principles:
5
+ * - Immutable: all operations return new instances
6
+ * - Type-safe: currency mismatches are caught at compile time (when possible) and runtime
7
+ * - Precise: uses BigInt internally to avoid floating-point errors
8
+ * - String-based API: amounts are strings to preserve precision in JSON/DB round-trips
9
+ */
10
+ /**
11
+ * Serialized form of a Money object, safe for JSON.
12
+ */
13
+ interface MoneyObject<C extends string = string> {
14
+ currency: C;
15
+ amount: string;
16
+ }
17
+ /**
18
+ * Money class - represents a monetary amount in a specific currency.
19
+ *
20
+ * @typeParam C - The currency code type (enables compile-time currency checking)
6
21
  *
7
- * // Basic usage
22
+ * @example
8
23
  * const price = new Money('USD', '19.99')
9
24
  * const tax = price.multiply(0.08)
10
25
  * const total = price.add(tax)
26
+ * console.log(total.amount) // "21.59"
27
+ */
28
+ declare class Money<C extends string = string> {
29
+ #private;
30
+ readonly currency: C;
31
+ readonly amount: string;
32
+ readonly displayAmount: string;
33
+ /**
34
+ * Create a new Money instance.
35
+ *
36
+ * @param currency - ISO 4217 currency code (must be registered)
37
+ * @param amount - The amount as a number or string
38
+ * @throws {CurrencyUnknownError} If the currency is not registered
39
+ * @throws {AmountError} If the amount is not a valid number
40
+ * @throws {SubunitError} If the amount has more decimals than the currency allows
41
+ */
42
+ constructor(currency: C, amount: number | string);
43
+ /**
44
+ * Add another Money amount.
45
+ * @throws {CurrencyMismatchError} If currencies don't match
46
+ */
47
+ add(other: Money<C>): Money<C>;
48
+ /**
49
+ * Subtract another Money amount.
50
+ * @throws {CurrencyMismatchError} If currencies don't match
51
+ */
52
+ subtract(other: Money<C>): Money<C>;
53
+ /**
54
+ * Multiply by a factor.
55
+ *
56
+ * DESIGN: Rounds immediately after multiplication using banker's rounding
57
+ * (round half-to-even). This prevents the "split penny problem".
58
+ */
59
+ multiply(factor: number): Money<C>;
60
+ /**
61
+ * Allocate this amount proportionally.
62
+ * Handles remainder distribution to avoid losing pennies.
63
+ *
64
+ * @param proportions - Array of proportions (e.g., [1, 1, 1] for three-way split)
65
+ * @returns Array of Money objects that sum to the original amount
66
+ */
67
+ allocate(proportions: number[]): Money<C>[];
68
+ /**
69
+ * Check if this amount equals another.
70
+ * @throws {CurrencyMismatchError} If currencies don't match
71
+ */
72
+ equalTo(other: Money<C>): boolean;
73
+ /**
74
+ * Check if this amount is greater than another.
75
+ * @throws {CurrencyMismatchError} If currencies don't match
76
+ */
77
+ greaterThan(other: Money<C>): boolean;
78
+ /**
79
+ * Check if this amount is less than another.
80
+ * @throws {CurrencyMismatchError} If currencies don't match
81
+ */
82
+ lessThan(other: Money<C>): boolean;
83
+ /**
84
+ * Check if this amount is greater than or equal to another.
85
+ * @throws {CurrencyMismatchError} If currencies don't match
86
+ */
87
+ greaterThanOrEqual(other: Money<C>): boolean;
88
+ /**
89
+ * Check if this amount is less than or equal to another.
90
+ * @throws {CurrencyMismatchError} If currencies don't match
91
+ */
92
+ lessThanOrEqual(other: Money<C>): boolean;
93
+ /**
94
+ * Check if this amount is zero.
95
+ */
96
+ isZero(): boolean;
97
+ /**
98
+ * Check if this amount is positive (greater than zero).
99
+ */
100
+ isPositive(): boolean;
101
+ /**
102
+ * Check if this amount is negative (less than zero).
103
+ */
104
+ isNegative(): boolean;
105
+ /**
106
+ * Convert to a plain object (safe for JSON).
107
+ */
108
+ toJSON(): MoneyObject<C>;
109
+ /**
110
+ * Convert to string representation.
111
+ */
112
+ toString(): string;
113
+ /**
114
+ * Get the amount as a number (may lose precision for large values).
115
+ * Use with caution - prefer string-based operations.
116
+ */
117
+ toNumber(): number;
118
+ /**
119
+ * Get the amount in subunits (e.g., cents for USD).
120
+ * Useful for database storage (Stripe-style integer storage).
121
+ */
122
+ toSubunits(): bigint;
123
+ /**
124
+ * Create a Money instance from a plain object.
125
+ */
126
+ static fromObject<C extends string>(obj: MoneyObject<C>): Money<C>;
127
+ /**
128
+ * Create a Money instance from subunits (e.g., cents).
129
+ * Useful for loading from database (Stripe-style integer storage).
130
+ */
131
+ static fromSubunits<C extends string>(subunits: bigint | number, currency: C): Money<C>;
132
+ /**
133
+ * Compare two Money objects (for use with Array.sort).
134
+ * @throws {CurrencyMismatchError} If currencies don't match
135
+ */
136
+ static compare<C extends string>(a: Money<C>, b: Money<C>): -1 | 0 | 1;
137
+ /**
138
+ * Create a zero amount in the specified currency.
139
+ */
140
+ static zero<C extends string>(currency: C): Money<C>;
141
+ }
142
+
143
+ /**
144
+ * Exchange Rate Service - Central authority for currency conversion rates.
11
145
  *
12
- * // Currency conversion
146
+ * Design principles:
147
+ * - Rates are stored as strings to preserve precision
148
+ * - Timestamps track when rates were set
149
+ * - Optional source tracking for audit trails
150
+ * - Inverse rates can be auto-generated or explicitly set
151
+ */
152
+ interface ExchangeRate {
153
+ from: string;
154
+ to: string;
155
+ rate: string;
156
+ timestamp: Date;
157
+ source?: string;
158
+ }
159
+ interface RatePair {
160
+ forward: ExchangeRate;
161
+ reverse: ExchangeRate;
162
+ /** Relative discrepancy between forward and 1/reverse rates */
163
+ discrepancy: number;
164
+ }
165
+ /**
166
+ * Service for managing exchange rates between currencies.
167
+ *
168
+ * @example
169
+ * const rates = new ExchangeRateService()
170
+ * rates.setRate('USD', 'EUR', 0.92, 'ECB')
171
+ * rates.getRate('USD', 'EUR') // { from: 'USD', to: 'EUR', rate: '0.92', ... }
172
+ */
173
+ declare class ExchangeRateService {
174
+ #private;
175
+ /**
176
+ * Set an exchange rate.
177
+ *
178
+ * @param from - Source currency code
179
+ * @param to - Target currency code
180
+ * @param rate - Exchange rate (1 unit of 'from' = rate units of 'to')
181
+ * @param source - Optional source identifier (e.g., 'ECB', 'Coinbase')
182
+ * @param autoInverse - If true, automatically create inverse rate (default: true)
183
+ */
184
+ setRate(from: string, to: string, rate: number | string, source?: string, autoInverse?: boolean): void;
185
+ /**
186
+ * Get an exchange rate.
187
+ *
188
+ * @param from - Source currency code
189
+ * @param to - Target currency code
190
+ * @returns The exchange rate, or undefined if not set
191
+ */
192
+ getRate(from: string, to: string): ExchangeRate | undefined;
193
+ /**
194
+ * Check if a rate exists.
195
+ */
196
+ hasRate(from: string, to: string): boolean;
197
+ /**
198
+ * Remove a rate.
199
+ */
200
+ removeRate(from: string, to: string): boolean;
201
+ /**
202
+ * Get both forward and reverse rates, with discrepancy analysis.
203
+ * Useful for detecting rate inconsistencies.
204
+ *
205
+ * @param currencyA - First currency
206
+ * @param currencyB - Second currency
207
+ * @returns Rate pair with discrepancy, or undefined if either rate is missing
208
+ */
209
+ getRatePair(currencyA: string, currencyB: string): RatePair | undefined;
210
+ /**
211
+ * Get all rates for a specific base currency.
212
+ *
213
+ * @param base - The base currency code
214
+ * @returns Array of rates from this currency
215
+ */
216
+ getRatesFrom(base: string): ExchangeRate[];
217
+ /**
218
+ * Get all registered rates.
219
+ */
220
+ getAllRates(): ExchangeRate[];
221
+ /**
222
+ * Clear all rates.
223
+ */
224
+ clear(): void;
225
+ /**
226
+ * Load rates from a simple object.
227
+ *
228
+ * @param rates - Object where keys are "FROM:TO" and values are rates
229
+ * @param source - Optional source identifier
230
+ *
231
+ * @example
232
+ * service.loadRates({
233
+ * 'USD:EUR': 0.92,
234
+ * 'USD:GBP': 0.79,
235
+ * }, 'daily-update')
236
+ */
237
+ loadRates(rates: Record<string, number | string>, source?: string): void;
238
+ }
239
+
240
+ /**
241
+ * Money Converter - Safe cross-currency operations.
242
+ *
243
+ * Bridges Money objects with ExchangeRateService to enable:
244
+ * - Currency conversion
245
+ * - Multi-currency arithmetic
246
+ * - Percentage calculations across currencies
247
+ */
248
+
249
+ /**
250
+ * Converter for performing operations between different currencies.
251
+ *
252
+ * @example
13
253
  * const rates = new ExchangeRateService()
14
254
  * rates.setRate('USD', 'EUR', 0.92)
255
+ *
15
256
  * const converter = new MoneyConverter(rates)
16
- * const euros = converter.convert(total, 'EUR')
257
+ * const euros = converter.convert(new Money('USD', '100'), 'EUR')
258
+ * console.log(euros.toString()) // "92.00 EUR"
259
+ */
260
+ declare class MoneyConverter {
261
+ #private;
262
+ constructor(rateService: ExchangeRateService);
263
+ /**
264
+ * Convert a Money amount to another currency.
265
+ *
266
+ * @param money - The amount to convert
267
+ * @param targetCurrency - The target currency code
268
+ * @returns A new Money in the target currency
269
+ * @throws {ExchangeRateError} If no rate is available
270
+ */
271
+ convert<From extends string, To extends string>(money: Money<From>, targetCurrency: To): Money<To>;
272
+ /**
273
+ * Add two Money amounts, converting as needed.
274
+ *
275
+ * @param a - First amount
276
+ * @param b - Second amount
277
+ * @param resultCurrency - Currency for the result (must be one of the input currencies)
278
+ * @returns Sum in the result currency
279
+ */
280
+ add<A extends string, B extends string, R extends A | B>(a: Money<A>, b: Money<B>, resultCurrency: R): Money<R>;
281
+ /**
282
+ * Subtract two Money amounts, converting as needed.
283
+ *
284
+ * @param a - Amount to subtract from
285
+ * @param b - Amount to subtract
286
+ * @param resultCurrency - Currency for the result
287
+ * @returns Difference in the result currency
288
+ */
289
+ subtract<A extends string, B extends string, R extends A | B>(a: Money<A>, b: Money<B>, resultCurrency: R): Money<R>;
290
+ /**
291
+ * Calculate what percentage one amount is of another.
292
+ * Converts both to the same currency before comparison.
293
+ *
294
+ * @param part - The partial amount
295
+ * @param whole - The whole amount
296
+ * @returns Percentage as a number (e.g., 25 for 25%)
297
+ */
298
+ percentageOf<A extends string, B extends string>(part: Money<A>, whole: Money<B>): number;
299
+ /**
300
+ * Sum multiple Money amounts, converting all to a target currency.
301
+ *
302
+ * @param amounts - Array of Money objects (can be different currencies)
303
+ * @param targetCurrency - Currency for the result
304
+ * @returns Total in the target currency
305
+ */
306
+ sum<C extends string>(amounts: Money<string>[], targetCurrency: C): Money<C>;
307
+ /**
308
+ * Compare two Money amounts across currencies.
309
+ * Returns negative if a < b, zero if equal, positive if a > b.
310
+ *
311
+ * @param a - First amount
312
+ * @param b - Second amount
313
+ * @returns Comparison result
314
+ */
315
+ compare<A extends string, B extends string>(a: Money<A>, b: Money<B>): -1 | 0 | 1;
316
+ /**
317
+ * Get the exchange rate service (for direct rate access).
318
+ */
319
+ get rateService(): ExchangeRateService;
320
+ }
321
+
322
+ /**
323
+ * Custom error types for Money operations.
324
+ * All errors extend built-in Error types for proper instanceof checks.
325
+ */
326
+ /**
327
+ * Thrown when attempting operations between different currencies.
328
+ * @example
329
+ * new Money('USD', 10).add(new Money('EUR', 5)) // throws CurrencyMismatchError
330
+ */
331
+ declare class CurrencyMismatchError extends TypeError {
332
+ readonly fromCurrency: string;
333
+ readonly toCurrency: string;
334
+ constructor(fromCurrency: string, toCurrency: string);
335
+ }
336
+ /**
337
+ * Thrown when using an unregistered currency code.
338
+ * @example
339
+ * new Money('FAKE', 10) // throws CurrencyUnknownError
340
+ */
341
+ declare class CurrencyUnknownError extends TypeError {
342
+ readonly currency: string;
343
+ constructor(currency: string);
344
+ }
345
+ /**
346
+ * Thrown when an amount has more decimal places than the currency allows.
347
+ * @example
348
+ * new Money('USD', '1.234') // throws SubunitError (USD only allows 2 decimals)
349
+ */
350
+ declare class SubunitError extends RangeError {
351
+ readonly currency: string;
352
+ readonly maxDecimals: number;
353
+ constructor(currency: string, maxDecimals: number);
354
+ }
355
+ /**
356
+ * Thrown when an amount cannot be parsed as a valid number.
357
+ * @example
358
+ * new Money('USD', 'abc') // throws AmountError
359
+ */
360
+ declare class AmountError extends TypeError {
361
+ readonly amount: unknown;
362
+ constructor(amount: unknown);
363
+ }
364
+ /**
365
+ * Thrown when an exchange rate is not available.
366
+ * @example
367
+ * converter.convert(usdMoney, 'XYZ') // throws ExchangeRateError if no USD->XYZ rate
368
+ */
369
+ declare class ExchangeRateError extends Error {
370
+ readonly fromCurrency: string;
371
+ readonly toCurrency: string;
372
+ constructor(fromCurrency: string, toCurrency: string);
373
+ }
374
+
375
+ /**
376
+ * Currency registry and types.
377
+ * Manages ISO 4217 currency definitions and custom currencies.
378
+ */
379
+ interface CurrencyDefinition {
380
+ code: string;
381
+ decimalDigits: number;
382
+ displayDecimals?: number;
383
+ }
384
+ /**
385
+ * Register a new currency or update an existing one.
386
+ * @param code - ISO 4217 currency code (e.g., 'USD', 'EUR', 'BTC')
387
+ * @param decimalDigits - Number of decimal places (e.g., 2 for USD, 8 for BTC)
388
+ * @param displayDecimals - Optional number of decimal places to use for display/formatting (defaults to decimalDigits)
389
+ */
390
+ declare function registerCurrency(code: string, decimalDigits: number, displayDecimals?: number): void;
391
+ /**
392
+ * Get a currency definition by code.
393
+ * @returns The currency definition, or undefined if not registered
394
+ */
395
+ declare function getCurrency(code: string): CurrencyDefinition | undefined;
396
+ /**
397
+ * Check if a currency is registered.
398
+ */
399
+ declare function hasCurrency(code: string): boolean;
400
+ /**
401
+ * Get all registered currencies, sorted by code.
402
+ */
403
+ declare function getAllCurrencies(): CurrencyDefinition[];
404
+ /**
405
+ * Load currencies from the legacy currencymap.json format.
406
+ * @param map - Object with currency codes as keys and {decimal_digits: number} as values
407
+ */
408
+ declare function loadCurrencyMap(map: Record<string, {
409
+ decimal_digits: number;
410
+ }>): void;
411
+ /**
412
+ * Clear all registered currencies. Useful for testing.
17
413
  */
18
- export { Money, type MoneyObject } from './money.js';
19
- export { ExchangeRateService, type ExchangeRate, type RatePair } from './exchange-rate-service.js';
20
- export { MoneyConverter } from './money-converter.js';
21
- export { CurrencyMismatchError, CurrencyUnknownError, SubunitError, AmountError, ExchangeRateError, } from './errors.js';
22
- export { registerCurrency, getCurrency, hasCurrency, getAllCurrencies, loadCurrencyMap, clearCurrencies, type CurrencyDefinition, } from './currency.js';
414
+ declare function clearCurrencies(): void;
415
+
416
+ export { AmountError, type CurrencyDefinition, CurrencyMismatchError, CurrencyUnknownError, type ExchangeRate, ExchangeRateError, ExchangeRateService, Money, MoneyConverter, type MoneyObject, type RatePair, SubunitError, clearCurrencies, getAllCurrencies, getCurrency, hasCurrency, loadCurrencyMap, registerCurrency };