@jdsalasc/solvejs-money 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # @jdsalasc/solvejs-money
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@jdsalasc/solvejs-money)](https://www.npmjs.com/package/@jdsalasc/solvejs-money)
4
+ [![node](https://img.shields.io/node/v/@jdsalasc/solvejs-money)](https://www.npmjs.com/package/@jdsalasc/solvejs-money)
5
+
6
+ Zero-dependency money utilities that keep every amount in integer minor units, so arithmetic, percentages and splits are exact.
7
+
8
+ ## Utilities
9
+
10
+ - `fromDecimal`
11
+ - `toDecimal`
12
+ - `addMoney`
13
+ - `subtractMoney`
14
+ - `sumMoney`
15
+ - `multiplyMoney`
16
+ - `percentageOf`
17
+ - `applyPercentage`
18
+ - `allocateAmount`
19
+ - `formatMoney`
20
+ - `MoneyError`
21
+
22
+ ## When to use this package
23
+
24
+ Use it for anything that adds up and has to reconcile: invoices, order totals, split payments,
25
+ percentage discounts, tax. Money in a float loses cents silently, and the loss shows up as a
26
+ dispute rather than a bug report.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm i @jdsalasc/solvejs-money
32
+ ```
33
+
34
+ ## Why integer minor units
35
+
36
+ ```ts
37
+ 0.1 + 0.2 === 0.30000000000000004; // the float problem
38
+
39
+ fromDecimal("0.1") + fromDecimal("0.2"); // 30, exactly
40
+ ```
41
+
42
+ Every function here takes and returns an integer count of minor units: cents for USD, yen for JPY,
43
+ nothing at all for a zero-decimal currency.
44
+
45
+ ## Quick example
46
+
47
+ ```ts
48
+ import { fromDecimal, toDecimal, multiplyMoney, applyPercentage, allocateAmount, formatMoney } from "@jdsalasc/solvejs-money";
49
+
50
+ const unit = fromDecimal("19.99"); // 1999
51
+ const subtotal = multiplyMoney(unit, 3); // 5997
52
+ const discounted = applyPercentage(subtotal, -10); // 5397, a 10% discount
53
+ const taxed = applyPercentage(discounted, 21); // 6530
54
+
55
+ toDecimal(taxed); // "65.30"
56
+ formatMoney(taxed); // "$65.30"
57
+
58
+ allocateAmount(taxed, [1, 1, 1]); // [2180, 2175, 2175], sums back exactly
59
+ ```
60
+
61
+ Compare with the float path: `((19.99 * 3) * 0.9 * 1.21).toFixed(2)` is `"65.31"`, one cent off.
62
+
63
+ ## Allocation never loses a unit
64
+
65
+ `allocateAmount` uses the largest-remainder method, so the parts always sum back to the total. The
66
+ leftover units go to the largest fractional shares first, earliest part winning a tie, which makes
67
+ the result deterministic:
68
+
69
+ ```ts
70
+ allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
71
+ allocateAmount(100, [3, 1]); // [75, 25]
72
+ ```
73
+
74
+ ## Rounding is explicit
75
+
76
+ Any fractional result is settled by a mode you choose. The default is `half-away-from-zero`, which is
77
+ what invoices and tax tables expect.
78
+
79
+ | Mode | `52.5` becomes | `-52.5` becomes |
80
+ |---|---:|---:|
81
+ | `half-away-from-zero` (default) | 53 | -53 |
82
+ | `half-up` | 53 | -52 |
83
+ | `floor` | 52 | -53 |
84
+ | `ceil` | 53 | -52 |
85
+ | `down` | 52 | -52 |
86
+
87
+ `floor` and `ceil` follow the maths definitions, so they are asymmetric on negatives. Use `down` when
88
+ you want truncation toward zero.
89
+
90
+ ## Limitations and Constraints
91
+
92
+ ### Input precision is refused, not rounded
93
+
94
+ `fromDecimal` converts exactly or throws. `"2.675"` for a two-digit currency is an error, not `268`:
95
+
96
+ ```ts
97
+ fromDecimal("2.675"); // throws
98
+ fromDecimal("1.5000"); // 150, trailing zeros are not precision
99
+ fromDecimal("0.006", { fractionDigits: 3 }); // 6
100
+ ```
101
+
102
+ Silently rounding an input amount is how an invoice dispute starts. Round deliberately, at a step you
103
+ choose, with `multiplyMoney` and its `rounding` option.
104
+
105
+ ### Minor units are safe integers only
106
+
107
+ `Number.MAX_SAFE_INTEGER` is the ceiling, which is about 90 trillion USD. Beyond that, use a bigint
108
+ pipeline or a database decimal type.
109
+
110
+ ### formatMoney asks Intl for the fraction digits
111
+
112
+ A currency's own digits decide the rendering, so JPY shows no fraction and BHD shows three. It passes
113
+ the amount through `Number`, so it is a display helper only. Never parse the output back into an
114
+ amount.
115
+
116
+ ### A malformed locale or currency throws
117
+
118
+ `formatMoney(1234, { locale: "not a locale" })` throws a `RangeError` from `Intl`. That is a
119
+ configuration mistake, and guessing a locale would hide it. `MoneyError` covers the amount arguments,
120
+ `RangeError` covers the locale and currency.
121
+
122
+ ### Weights must be non-negative whole numbers
123
+
124
+ `allocateAmount` refuses negative, fractional and all-zero weights, because there is no sensible way
125
+ to split an amount among them. Pass a percentage as an integer like `20` for twenty percent.
@@ -0,0 +1,339 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MoneyError = void 0;
4
+ exports.fromDecimal = fromDecimal;
5
+ exports.toDecimal = toDecimal;
6
+ exports.addMoney = addMoney;
7
+ exports.subtractMoney = subtractMoney;
8
+ exports.sumMoney = sumMoney;
9
+ exports.multiplyMoney = multiplyMoney;
10
+ exports.percentageOf = percentageOf;
11
+ exports.applyPercentage = applyPercentage;
12
+ exports.allocateAmount = allocateAmount;
13
+ exports.formatMoney = formatMoney;
14
+ /**
15
+ * Error thrown by the money utilities.
16
+ *
17
+ * Carries a stable machine-readable `code` and a `details` context object.
18
+ */
19
+ class MoneyError extends Error {
20
+ constructor(code, message, details = {}) {
21
+ super(message);
22
+ this.name = "MoneyError";
23
+ this.code = code;
24
+ this.details = details;
25
+ Object.setPrototypeOf(this, MoneyError.prototype);
26
+ }
27
+ }
28
+ exports.MoneyError = MoneyError;
29
+ function fail(code, message, details = {}) {
30
+ throw new MoneyError(code, message, details);
31
+ }
32
+ const ROUNDING_MODES = ["half-away-from-zero", "half-up", "floor", "ceil", "down"];
33
+ // A plain decimal string. Deliberately narrow: no exponent, no currency symbol, no separators.
34
+ const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?$/;
35
+ function assertFractionDigits(value) {
36
+ if (!Number.isInteger(value) || value < 0) {
37
+ fail("MONEY_INVALID_FRACTION_DIGITS", "Expected fractionDigits to be a non-negative integer.", {
38
+ received: value
39
+ });
40
+ }
41
+ }
42
+ function assertMinorUnits(value, label = "minor units") {
43
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
44
+ fail("MONEY_INVALID_MINOR_UNITS", `Expected ${label} to be a safe integer.`, { received: value });
45
+ }
46
+ }
47
+ function assertFactor(value, label = "factor") {
48
+ if (typeof value !== "number" || !Number.isFinite(value)) {
49
+ fail("MONEY_INVALID_FACTOR", `Expected ${label} to be a finite number.`, { received: value });
50
+ }
51
+ }
52
+ function round(value, mode) {
53
+ switch (mode) {
54
+ case "floor":
55
+ return Math.floor(value);
56
+ case "ceil":
57
+ return Math.ceil(value);
58
+ case "down":
59
+ // Toward zero, unlike floor on a negative result.
60
+ return value < 0 ? Math.ceil(value) : Math.floor(value);
61
+ case "half-up":
62
+ // Ties go toward positive infinity, so -0.5 settles to 0.
63
+ return Math.round(value);
64
+ default:
65
+ // Half away from zero, which is what invoices and tax tables expect.
66
+ return value < 0 ? -Math.round(-value) : Math.round(value);
67
+ }
68
+ }
69
+ /**
70
+ * Converts a decimal amount into integer minor units.
71
+ *
72
+ * Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
73
+ * for a two-digit currency rather than inheriting the float `2.674999...`.
74
+ *
75
+ * @param value - Decimal amount as a string, or a number you already trust.
76
+ * @param options - Conversion options.
77
+ * @param options.fractionDigits - Digits the currency supports. Defaults to 2.
78
+ * @returns Amount in minor units.
79
+ * @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
80
+ *
81
+ * @example
82
+ * fromDecimal("19.99"); // 1999
83
+ * fromDecimal("0.07"); // 7
84
+ */
85
+ function fromDecimal(value, options = {}) {
86
+ const fractionDigits = options.fractionDigits ?? 2;
87
+ assertFractionDigits(fractionDigits);
88
+ const raw = typeof value === "number" ? value.toString() : value;
89
+ if (typeof raw !== "string") {
90
+ fail("MONEY_INVALID_DECIMAL", "Expected a decimal string or a number.", { received: typeof value });
91
+ }
92
+ const match = raw.trim().match(DECIMAL);
93
+ if (!match) {
94
+ fail("MONEY_INVALID_DECIMAL", `Expected a plain decimal amount, received ${JSON.stringify(value)}.`, {
95
+ received: value
96
+ });
97
+ }
98
+ const [, sign, whole, fraction = ""] = match;
99
+ const discarded = fraction.slice(fractionDigits);
100
+ // Conversion is exact or refused. Rounding an input amount silently is how an invoice dispute
101
+ // starts, so anything beyond the currency's own precision is an error rather than a rounded value.
102
+ if (/[^0]/.test(discarded)) {
103
+ fail("MONEY_INVALID_DECIMAL", `Expected at most ${fractionDigits} fraction digits.`, {
104
+ received: value,
105
+ fractionDigits
106
+ });
107
+ }
108
+ const kept = fraction.padEnd(fractionDigits, "0").slice(0, fractionDigits);
109
+ const scaled = Number(`${whole}${kept}`);
110
+ if (!Number.isSafeInteger(scaled)) {
111
+ fail("MONEY_INVALID_DECIMAL", "Expected an amount within the safe integer range.", { received: value });
112
+ }
113
+ return (sign === "-" ? -1 : 1) * scaled;
114
+ }
115
+ /**
116
+ * Converts integer minor units into a decimal string.
117
+ *
118
+ * @param minorUnits - Amount in minor units.
119
+ * @param options - Conversion options.
120
+ * @param options.fractionDigits - Digits to render. Defaults to 2.
121
+ * @returns The decimal amount, with exactly `fractionDigits` digits.
122
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
123
+ *
124
+ * @example
125
+ * toDecimal(1999); // "19.99"
126
+ */
127
+ function toDecimal(minorUnits, options = {}) {
128
+ assertMinorUnits(minorUnits);
129
+ const fractionDigits = options.fractionDigits ?? 2;
130
+ assertFractionDigits(fractionDigits);
131
+ const negative = minorUnits < 0;
132
+ const digits = String(Math.abs(minorUnits)).padStart(fractionDigits + 1, "0");
133
+ const whole = digits.slice(0, digits.length - fractionDigits);
134
+ const fraction = fractionDigits === 0 ? "" : `.${digits.slice(digits.length - fractionDigits)}`;
135
+ return `${negative ? "-" : ""}${whole}${fraction}`;
136
+ }
137
+ /**
138
+ * Adds two amounts in minor units.
139
+ *
140
+ * @param left - First amount.
141
+ * @param right - Second amount.
142
+ * @returns The sum.
143
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
144
+ */
145
+ function addMoney(left, right) {
146
+ assertMinorUnits(left, "left");
147
+ assertMinorUnits(right, "right");
148
+ const sum = left + right;
149
+ assertMinorUnits(sum, "the sum");
150
+ return sum;
151
+ }
152
+ /**
153
+ * Subtracts two amounts in minor units.
154
+ *
155
+ * @param left - Amount to subtract from.
156
+ * @param right - Amount to subtract.
157
+ * @returns The difference.
158
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
159
+ */
160
+ function subtractMoney(left, right) {
161
+ assertMinorUnits(left, "left");
162
+ assertMinorUnits(right, "right");
163
+ const difference = left - right;
164
+ assertMinorUnits(difference, "the difference");
165
+ return difference;
166
+ }
167
+ /**
168
+ * Adds a list of amounts in minor units.
169
+ *
170
+ * @param amounts - Amounts to add.
171
+ * @returns The sum, or `0` for an empty list.
172
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
173
+ */
174
+ function sumMoney(amounts) {
175
+ if (!Array.isArray(amounts)) {
176
+ fail("MONEY_INVALID_MINOR_UNITS", "Expected amounts to be an array.", { received: typeof amounts });
177
+ }
178
+ return amounts.reduce((total, amount) => addMoney(total, amount), 0);
179
+ }
180
+ /**
181
+ * Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
182
+ *
183
+ * @param minorUnits - Amount in minor units.
184
+ * @param factor - Multiplier.
185
+ * @param options - Rounding options.
186
+ * @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
187
+ * @returns The product in minor units.
188
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
189
+ *
190
+ * @example
191
+ * multiplyMoney(1999, 3); // 5997
192
+ */
193
+ function multiplyMoney(minorUnits, factor, options = {}) {
194
+ assertMinorUnits(minorUnits);
195
+ assertFactor(factor);
196
+ const rounding = options.rounding ?? "half-away-from-zero";
197
+ if (!ROUNDING_MODES.includes(rounding)) {
198
+ fail("MONEY_INVALID_FACTOR", `Expected rounding to be one of: ${ROUNDING_MODES.join(", ")}.`, {
199
+ received: rounding
200
+ });
201
+ }
202
+ // Reduce the factor to an integer ratio so the product stays in integer space.
203
+ const scale = 10 ** countDecimals(factor);
204
+ const numerator = Math.round(factor * scale);
205
+ const result = round((minorUnits * numerator) / scale, rounding);
206
+ assertMinorUnits(result, "the product");
207
+ return result;
208
+ }
209
+ function countDecimals(value) {
210
+ const text = String(value);
211
+ const dot = text.indexOf(".");
212
+ if (dot === -1)
213
+ return 0;
214
+ return Math.min(text.length - dot - 1, 12);
215
+ }
216
+ /**
217
+ * Returns the percentage of an amount, in minor units.
218
+ *
219
+ * @param minorUnits - Amount in minor units.
220
+ * @param percent - Percentage, for example `19` for 19%.
221
+ * @param options - Rounding options.
222
+ * @returns The percentage amount.
223
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
224
+ *
225
+ * @example
226
+ * percentageOf(10000, 19); // 1900
227
+ */
228
+ function percentageOf(minorUnits, percent, options = {}) {
229
+ assertMinorUnits(minorUnits);
230
+ assertFactor(percent, "percent");
231
+ return multiplyMoney(minorUnits, percent / 100, options);
232
+ }
233
+ /**
234
+ * Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
235
+ *
236
+ * @param minorUnits - Amount in minor units.
237
+ * @param percent - Percentage. `-10` applies a 10% discount.
238
+ * @param options - Rounding options.
239
+ * @returns The adjusted amount.
240
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
241
+ *
242
+ * @example
243
+ * applyPercentage(10000, 21); // 12100
244
+ * applyPercentage(10000, -10); // 9000
245
+ */
246
+ function applyPercentage(minorUnits, percent, options = {}) {
247
+ return addMoney(minorUnits, percentageOf(minorUnits, percent, options));
248
+ }
249
+ /**
250
+ * Splits an amount across weights without losing or inventing a single minor unit.
251
+ *
252
+ * Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
253
+ * minor unit goes to the earliest parts, which keeps the result deterministic.
254
+ *
255
+ * @param total - Amount in minor units.
256
+ * @param weights - Non-negative whole-number weights, one per part.
257
+ * @returns One amount per weight, summing exactly to `total`.
258
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
259
+ *
260
+ * @example
261
+ * allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
262
+ */
263
+ function allocateAmount(total, weights) {
264
+ assertMinorUnits(total, "total");
265
+ if (!Array.isArray(weights) || weights.length === 0) {
266
+ fail("MONEY_INVALID_WEIGHTS", "Expected a non-empty array of weights.", { received: weights });
267
+ }
268
+ for (const weight of weights) {
269
+ if (typeof weight !== "number" || !Number.isFinite(weight) || weight < 0 || !Number.isInteger(weight)) {
270
+ fail("MONEY_INVALID_WEIGHTS", "Expected every weight to be a non-negative integer.", { received: weight });
271
+ }
272
+ }
273
+ const weightSum = weights.reduce((sum, weight) => sum + weight, 0);
274
+ if (weightSum === 0) {
275
+ fail("MONEY_INVALID_WEIGHTS", "Expected the weights to sum above zero.", { weights });
276
+ }
277
+ const sign = total < 0 ? -1 : 1;
278
+ const magnitude = Math.abs(total);
279
+ // Exact share times the weight, kept as a numerator so no precision is lost.
280
+ const scale = 10 ** 9;
281
+ const shares = weights.map((weight) => (weight * magnitude * scale) / weightSum);
282
+ const floors = shares.map((share) => Math.floor(share / scale));
283
+ let remainder = magnitude - floors.reduce((sum, value) => sum + value, 0);
284
+ const result = [...floors];
285
+ // Hand the leftover units to the largest fractional shares first, earliest part winning a tie.
286
+ const order = shares
287
+ .map((share, index) => ({ index, fraction: (share / scale) % 1 }))
288
+ .sort((a, b) => b.fraction - a.fraction || a.index - b.index);
289
+ for (const { index } of order) {
290
+ if (remainder <= 0)
291
+ break;
292
+ result[index] += 1;
293
+ remainder -= 1;
294
+ }
295
+ return result.map((value) => sign * value);
296
+ }
297
+ /**
298
+ * Formats an amount for display.
299
+ *
300
+ * @param minorUnits - Amount in minor units.
301
+ * @param options - Formatting options.
302
+ * @param options.currency - ISO 4217 code, defaults to `USD`.
303
+ * @param options.locale - BCP 47 tag, defaults to `en-US`.
304
+ * @param options.showCurrency - Omit the symbol or code, defaults to `true`.
305
+ * @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
306
+ * @returns The formatted string.
307
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
308
+ *
309
+ * @example
310
+ * formatMoney(123456); // "$1,234.56"
311
+ */
312
+ function formatMoney(minorUnits, options = {}) {
313
+ assertMinorUnits(minorUnits);
314
+ const currency = options.currency ?? "USD";
315
+ const locale = options.locale ?? "en-US";
316
+ const fractionDigits = resolveFractionDigits(currency, locale);
317
+ // Intl decides the fraction digits for a currency, so ask it, then hand the count back so the
318
+ // decimal style keeps its trailing zeros instead of defaulting to Intl's maximum of 3.
319
+ const formatter = new Intl.NumberFormat(locale, {
320
+ style: options.showCurrency === false ? "decimal" : "currency",
321
+ ...(options.showCurrency === false ? {} : { currency }),
322
+ minimumFractionDigits: fractionDigits,
323
+ maximumFractionDigits: fractionDigits,
324
+ signDisplay: options.signed ? "exceptZero" : "auto"
325
+ });
326
+ return formatter.format(Number(toDecimal(minorUnits, { fractionDigits })));
327
+ }
328
+ function resolveFractionDigits(currency, locale) {
329
+ try {
330
+ const parts = new Intl.NumberFormat(locale, { style: "currency", currency }).formatToParts(1);
331
+ const fraction = parts.find((part) => part.type === "fraction")?.value ?? "";
332
+ return fraction.replace(/\D/g, "").length;
333
+ }
334
+ catch {
335
+ // An unusable currency or locale falls back to the common two digits.
336
+ return 2;
337
+ }
338
+ }
339
+ //# sourceMappingURL=index.js.map
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Stable money error codes. */
2
+ export type MoneyErrorCode = "MONEY_INVALID_DECIMAL" | "MONEY_INVALID_MINOR_UNITS" | "MONEY_INVALID_FACTOR" | "MONEY_INVALID_WEIGHTS" | "MONEY_INVALID_FRACTION_DIGITS";
3
+ /**
4
+ * Error thrown by the money utilities.
5
+ *
6
+ * Carries a stable machine-readable `code` and a `details` context object.
7
+ */
8
+ export declare class MoneyError extends Error {
9
+ readonly code: MoneyErrorCode;
10
+ readonly details: Record<string, unknown>;
11
+ constructor(code: MoneyErrorCode, message: string, details?: Record<string, unknown>);
12
+ }
13
+ /** Rounding behaviour for a fractional result. */
14
+ export type RoundingMode = "half-away-from-zero" | "half-up" | "floor" | "ceil" | "down";
15
+ /** Options for {@link fromDecimal}. */
16
+ export type FromDecimalOptions = {
17
+ /** Digits the currency supports. Defaults to 2. More than this is refused. */
18
+ fractionDigits?: number;
19
+ };
20
+ /** Options for {@link toDecimal}. */
21
+ export type ToDecimalOptions = {
22
+ /** Digits to render. Defaults to 2. */
23
+ fractionDigits?: number;
24
+ };
25
+ /** Options for {@link multiplyMoney}, {@link percentageOf} and {@link applyPercentage}. */
26
+ export type MultiplyOptions = {
27
+ /** How to settle a fractional minor unit. Defaults to `half-away-from-zero`. */
28
+ rounding?: RoundingMode;
29
+ };
30
+ /** Options for {@link formatMoney}. */
31
+ export type FormatMoneyOptions = {
32
+ /** ISO 4217 currency code. */
33
+ currency?: string;
34
+ /** BCP 47 locale tag. */
35
+ locale?: string;
36
+ /** Omit the currency symbol or code. */
37
+ showCurrency?: boolean;
38
+ /** Force an explicit `+` on a positive amount. */
39
+ signed?: boolean;
40
+ };
41
+ /**
42
+ * Converts a decimal amount into integer minor units.
43
+ *
44
+ * Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
45
+ * for a two-digit currency rather than inheriting the float `2.674999...`.
46
+ *
47
+ * @param value - Decimal amount as a string, or a number you already trust.
48
+ * @param options - Conversion options.
49
+ * @param options.fractionDigits - Digits the currency supports. Defaults to 2.
50
+ * @returns Amount in minor units.
51
+ * @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
52
+ *
53
+ * @example
54
+ * fromDecimal("19.99"); // 1999
55
+ * fromDecimal("0.07"); // 7
56
+ */
57
+ export declare function fromDecimal(value: string | number, options?: FromDecimalOptions): number;
58
+ /**
59
+ * Converts integer minor units into a decimal string.
60
+ *
61
+ * @param minorUnits - Amount in minor units.
62
+ * @param options - Conversion options.
63
+ * @param options.fractionDigits - Digits to render. Defaults to 2.
64
+ * @returns The decimal amount, with exactly `fractionDigits` digits.
65
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
66
+ *
67
+ * @example
68
+ * toDecimal(1999); // "19.99"
69
+ */
70
+ export declare function toDecimal(minorUnits: number, options?: ToDecimalOptions): string;
71
+ /**
72
+ * Adds two amounts in minor units.
73
+ *
74
+ * @param left - First amount.
75
+ * @param right - Second amount.
76
+ * @returns The sum.
77
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
78
+ */
79
+ export declare function addMoney(left: number, right: number): number;
80
+ /**
81
+ * Subtracts two amounts in minor units.
82
+ *
83
+ * @param left - Amount to subtract from.
84
+ * @param right - Amount to subtract.
85
+ * @returns The difference.
86
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
87
+ */
88
+ export declare function subtractMoney(left: number, right: number): number;
89
+ /**
90
+ * Adds a list of amounts in minor units.
91
+ *
92
+ * @param amounts - Amounts to add.
93
+ * @returns The sum, or `0` for an empty list.
94
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
95
+ */
96
+ export declare function sumMoney(amounts: readonly number[]): number;
97
+ /**
98
+ * Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
99
+ *
100
+ * @param minorUnits - Amount in minor units.
101
+ * @param factor - Multiplier.
102
+ * @param options - Rounding options.
103
+ * @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
104
+ * @returns The product in minor units.
105
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
106
+ *
107
+ * @example
108
+ * multiplyMoney(1999, 3); // 5997
109
+ */
110
+ export declare function multiplyMoney(minorUnits: number, factor: number, options?: MultiplyOptions): number;
111
+ /**
112
+ * Returns the percentage of an amount, in minor units.
113
+ *
114
+ * @param minorUnits - Amount in minor units.
115
+ * @param percent - Percentage, for example `19` for 19%.
116
+ * @param options - Rounding options.
117
+ * @returns The percentage amount.
118
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
119
+ *
120
+ * @example
121
+ * percentageOf(10000, 19); // 1900
122
+ */
123
+ export declare function percentageOf(minorUnits: number, percent: number, options?: MultiplyOptions): number;
124
+ /**
125
+ * Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
126
+ *
127
+ * @param minorUnits - Amount in minor units.
128
+ * @param percent - Percentage. `-10` applies a 10% discount.
129
+ * @param options - Rounding options.
130
+ * @returns The adjusted amount.
131
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
132
+ *
133
+ * @example
134
+ * applyPercentage(10000, 21); // 12100
135
+ * applyPercentage(10000, -10); // 9000
136
+ */
137
+ export declare function applyPercentage(minorUnits: number, percent: number, options?: MultiplyOptions): number;
138
+ /**
139
+ * Splits an amount across weights without losing or inventing a single minor unit.
140
+ *
141
+ * Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
142
+ * minor unit goes to the earliest parts, which keeps the result deterministic.
143
+ *
144
+ * @param total - Amount in minor units.
145
+ * @param weights - Non-negative whole-number weights, one per part.
146
+ * @returns One amount per weight, summing exactly to `total`.
147
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
148
+ *
149
+ * @example
150
+ * allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
151
+ */
152
+ export declare function allocateAmount(total: number, weights: readonly number[]): number[];
153
+ /**
154
+ * Formats an amount for display.
155
+ *
156
+ * @param minorUnits - Amount in minor units.
157
+ * @param options - Formatting options.
158
+ * @param options.currency - ISO 4217 code, defaults to `USD`.
159
+ * @param options.locale - BCP 47 tag, defaults to `en-US`.
160
+ * @param options.showCurrency - Omit the symbol or code, defaults to `true`.
161
+ * @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
162
+ * @returns The formatted string.
163
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
164
+ *
165
+ * @example
166
+ * formatMoney(123456); // "$1,234.56"
167
+ */
168
+ export declare function formatMoney(minorUnits: number, options?: FormatMoneyOptions): string;
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Error thrown by the money utilities.
3
+ *
4
+ * Carries a stable machine-readable `code` and a `details` context object.
5
+ */
6
+ export class MoneyError extends Error {
7
+ constructor(code, message, details = {}) {
8
+ super(message);
9
+ this.name = "MoneyError";
10
+ this.code = code;
11
+ this.details = details;
12
+ Object.setPrototypeOf(this, MoneyError.prototype);
13
+ }
14
+ }
15
+ function fail(code, message, details = {}) {
16
+ throw new MoneyError(code, message, details);
17
+ }
18
+ const ROUNDING_MODES = ["half-away-from-zero", "half-up", "floor", "ceil", "down"];
19
+ // A plain decimal string. Deliberately narrow: no exponent, no currency symbol, no separators.
20
+ const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?$/;
21
+ function assertFractionDigits(value) {
22
+ if (!Number.isInteger(value) || value < 0) {
23
+ fail("MONEY_INVALID_FRACTION_DIGITS", "Expected fractionDigits to be a non-negative integer.", {
24
+ received: value
25
+ });
26
+ }
27
+ }
28
+ function assertMinorUnits(value, label = "minor units") {
29
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
30
+ fail("MONEY_INVALID_MINOR_UNITS", `Expected ${label} to be a safe integer.`, { received: value });
31
+ }
32
+ }
33
+ function assertFactor(value, label = "factor") {
34
+ if (typeof value !== "number" || !Number.isFinite(value)) {
35
+ fail("MONEY_INVALID_FACTOR", `Expected ${label} to be a finite number.`, { received: value });
36
+ }
37
+ }
38
+ function round(value, mode) {
39
+ switch (mode) {
40
+ case "floor":
41
+ return Math.floor(value);
42
+ case "ceil":
43
+ return Math.ceil(value);
44
+ case "down":
45
+ // Toward zero, unlike floor on a negative result.
46
+ return value < 0 ? Math.ceil(value) : Math.floor(value);
47
+ case "half-up":
48
+ // Ties go toward positive infinity, so -0.5 settles to 0.
49
+ return Math.round(value);
50
+ default:
51
+ // Half away from zero, which is what invoices and tax tables expect.
52
+ return value < 0 ? -Math.round(-value) : Math.round(value);
53
+ }
54
+ }
55
+ /**
56
+ * Converts a decimal amount into integer minor units.
57
+ *
58
+ * Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
59
+ * for a two-digit currency rather than inheriting the float `2.674999...`.
60
+ *
61
+ * @param value - Decimal amount as a string, or a number you already trust.
62
+ * @param options - Conversion options.
63
+ * @param options.fractionDigits - Digits the currency supports. Defaults to 2.
64
+ * @returns Amount in minor units.
65
+ * @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
66
+ *
67
+ * @example
68
+ * fromDecimal("19.99"); // 1999
69
+ * fromDecimal("0.07"); // 7
70
+ */
71
+ export function fromDecimal(value, options = {}) {
72
+ const fractionDigits = options.fractionDigits ?? 2;
73
+ assertFractionDigits(fractionDigits);
74
+ const raw = typeof value === "number" ? value.toString() : value;
75
+ if (typeof raw !== "string") {
76
+ fail("MONEY_INVALID_DECIMAL", "Expected a decimal string or a number.", { received: typeof value });
77
+ }
78
+ const match = raw.trim().match(DECIMAL);
79
+ if (!match) {
80
+ fail("MONEY_INVALID_DECIMAL", `Expected a plain decimal amount, received ${JSON.stringify(value)}.`, {
81
+ received: value
82
+ });
83
+ }
84
+ const [, sign, whole, fraction = ""] = match;
85
+ const discarded = fraction.slice(fractionDigits);
86
+ // Conversion is exact or refused. Rounding an input amount silently is how an invoice dispute
87
+ // starts, so anything beyond the currency's own precision is an error rather than a rounded value.
88
+ if (/[^0]/.test(discarded)) {
89
+ fail("MONEY_INVALID_DECIMAL", `Expected at most ${fractionDigits} fraction digits.`, {
90
+ received: value,
91
+ fractionDigits
92
+ });
93
+ }
94
+ const kept = fraction.padEnd(fractionDigits, "0").slice(0, fractionDigits);
95
+ const scaled = Number(`${whole}${kept}`);
96
+ if (!Number.isSafeInteger(scaled)) {
97
+ fail("MONEY_INVALID_DECIMAL", "Expected an amount within the safe integer range.", { received: value });
98
+ }
99
+ return (sign === "-" ? -1 : 1) * scaled;
100
+ }
101
+ /**
102
+ * Converts integer minor units into a decimal string.
103
+ *
104
+ * @param minorUnits - Amount in minor units.
105
+ * @param options - Conversion options.
106
+ * @param options.fractionDigits - Digits to render. Defaults to 2.
107
+ * @returns The decimal amount, with exactly `fractionDigits` digits.
108
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
109
+ *
110
+ * @example
111
+ * toDecimal(1999); // "19.99"
112
+ */
113
+ export function toDecimal(minorUnits, options = {}) {
114
+ assertMinorUnits(minorUnits);
115
+ const fractionDigits = options.fractionDigits ?? 2;
116
+ assertFractionDigits(fractionDigits);
117
+ const negative = minorUnits < 0;
118
+ const digits = String(Math.abs(minorUnits)).padStart(fractionDigits + 1, "0");
119
+ const whole = digits.slice(0, digits.length - fractionDigits);
120
+ const fraction = fractionDigits === 0 ? "" : `.${digits.slice(digits.length - fractionDigits)}`;
121
+ return `${negative ? "-" : ""}${whole}${fraction}`;
122
+ }
123
+ /**
124
+ * Adds two amounts in minor units.
125
+ *
126
+ * @param left - First amount.
127
+ * @param right - Second amount.
128
+ * @returns The sum.
129
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
130
+ */
131
+ export function addMoney(left, right) {
132
+ assertMinorUnits(left, "left");
133
+ assertMinorUnits(right, "right");
134
+ const sum = left + right;
135
+ assertMinorUnits(sum, "the sum");
136
+ return sum;
137
+ }
138
+ /**
139
+ * Subtracts two amounts in minor units.
140
+ *
141
+ * @param left - Amount to subtract from.
142
+ * @param right - Amount to subtract.
143
+ * @returns The difference.
144
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
145
+ */
146
+ export function subtractMoney(left, right) {
147
+ assertMinorUnits(left, "left");
148
+ assertMinorUnits(right, "right");
149
+ const difference = left - right;
150
+ assertMinorUnits(difference, "the difference");
151
+ return difference;
152
+ }
153
+ /**
154
+ * Adds a list of amounts in minor units.
155
+ *
156
+ * @param amounts - Amounts to add.
157
+ * @returns The sum, or `0` for an empty list.
158
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
159
+ */
160
+ export function sumMoney(amounts) {
161
+ if (!Array.isArray(amounts)) {
162
+ fail("MONEY_INVALID_MINOR_UNITS", "Expected amounts to be an array.", { received: typeof amounts });
163
+ }
164
+ return amounts.reduce((total, amount) => addMoney(total, amount), 0);
165
+ }
166
+ /**
167
+ * Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
168
+ *
169
+ * @param minorUnits - Amount in minor units.
170
+ * @param factor - Multiplier.
171
+ * @param options - Rounding options.
172
+ * @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
173
+ * @returns The product in minor units.
174
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
175
+ *
176
+ * @example
177
+ * multiplyMoney(1999, 3); // 5997
178
+ */
179
+ export function multiplyMoney(minorUnits, factor, options = {}) {
180
+ assertMinorUnits(minorUnits);
181
+ assertFactor(factor);
182
+ const rounding = options.rounding ?? "half-away-from-zero";
183
+ if (!ROUNDING_MODES.includes(rounding)) {
184
+ fail("MONEY_INVALID_FACTOR", `Expected rounding to be one of: ${ROUNDING_MODES.join(", ")}.`, {
185
+ received: rounding
186
+ });
187
+ }
188
+ // Reduce the factor to an integer ratio so the product stays in integer space.
189
+ const scale = 10 ** countDecimals(factor);
190
+ const numerator = Math.round(factor * scale);
191
+ const result = round((minorUnits * numerator) / scale, rounding);
192
+ assertMinorUnits(result, "the product");
193
+ return result;
194
+ }
195
+ function countDecimals(value) {
196
+ const text = String(value);
197
+ const dot = text.indexOf(".");
198
+ if (dot === -1)
199
+ return 0;
200
+ return Math.min(text.length - dot - 1, 12);
201
+ }
202
+ /**
203
+ * Returns the percentage of an amount, in minor units.
204
+ *
205
+ * @param minorUnits - Amount in minor units.
206
+ * @param percent - Percentage, for example `19` for 19%.
207
+ * @param options - Rounding options.
208
+ * @returns The percentage amount.
209
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
210
+ *
211
+ * @example
212
+ * percentageOf(10000, 19); // 1900
213
+ */
214
+ export function percentageOf(minorUnits, percent, options = {}) {
215
+ assertMinorUnits(minorUnits);
216
+ assertFactor(percent, "percent");
217
+ return multiplyMoney(minorUnits, percent / 100, options);
218
+ }
219
+ /**
220
+ * Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
221
+ *
222
+ * @param minorUnits - Amount in minor units.
223
+ * @param percent - Percentage. `-10` applies a 10% discount.
224
+ * @param options - Rounding options.
225
+ * @returns The adjusted amount.
226
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
227
+ *
228
+ * @example
229
+ * applyPercentage(10000, 21); // 12100
230
+ * applyPercentage(10000, -10); // 9000
231
+ */
232
+ export function applyPercentage(minorUnits, percent, options = {}) {
233
+ return addMoney(minorUnits, percentageOf(minorUnits, percent, options));
234
+ }
235
+ /**
236
+ * Splits an amount across weights without losing or inventing a single minor unit.
237
+ *
238
+ * Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
239
+ * minor unit goes to the earliest parts, which keeps the result deterministic.
240
+ *
241
+ * @param total - Amount in minor units.
242
+ * @param weights - Non-negative whole-number weights, one per part.
243
+ * @returns One amount per weight, summing exactly to `total`.
244
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
245
+ *
246
+ * @example
247
+ * allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
248
+ */
249
+ export function allocateAmount(total, weights) {
250
+ assertMinorUnits(total, "total");
251
+ if (!Array.isArray(weights) || weights.length === 0) {
252
+ fail("MONEY_INVALID_WEIGHTS", "Expected a non-empty array of weights.", { received: weights });
253
+ }
254
+ for (const weight of weights) {
255
+ if (typeof weight !== "number" || !Number.isFinite(weight) || weight < 0 || !Number.isInteger(weight)) {
256
+ fail("MONEY_INVALID_WEIGHTS", "Expected every weight to be a non-negative integer.", { received: weight });
257
+ }
258
+ }
259
+ const weightSum = weights.reduce((sum, weight) => sum + weight, 0);
260
+ if (weightSum === 0) {
261
+ fail("MONEY_INVALID_WEIGHTS", "Expected the weights to sum above zero.", { weights });
262
+ }
263
+ const sign = total < 0 ? -1 : 1;
264
+ const magnitude = Math.abs(total);
265
+ // Exact share times the weight, kept as a numerator so no precision is lost.
266
+ const scale = 10 ** 9;
267
+ const shares = weights.map((weight) => (weight * magnitude * scale) / weightSum);
268
+ const floors = shares.map((share) => Math.floor(share / scale));
269
+ let remainder = magnitude - floors.reduce((sum, value) => sum + value, 0);
270
+ const result = [...floors];
271
+ // Hand the leftover units to the largest fractional shares first, earliest part winning a tie.
272
+ const order = shares
273
+ .map((share, index) => ({ index, fraction: (share / scale) % 1 }))
274
+ .sort((a, b) => b.fraction - a.fraction || a.index - b.index);
275
+ for (const { index } of order) {
276
+ if (remainder <= 0)
277
+ break;
278
+ result[index] += 1;
279
+ remainder -= 1;
280
+ }
281
+ return result.map((value) => sign * value);
282
+ }
283
+ /**
284
+ * Formats an amount for display.
285
+ *
286
+ * @param minorUnits - Amount in minor units.
287
+ * @param options - Formatting options.
288
+ * @param options.currency - ISO 4217 code, defaults to `USD`.
289
+ * @param options.locale - BCP 47 tag, defaults to `en-US`.
290
+ * @param options.showCurrency - Omit the symbol or code, defaults to `true`.
291
+ * @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
292
+ * @returns The formatted string.
293
+ * @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
294
+ *
295
+ * @example
296
+ * formatMoney(123456); // "$1,234.56"
297
+ */
298
+ export function formatMoney(minorUnits, options = {}) {
299
+ assertMinorUnits(minorUnits);
300
+ const currency = options.currency ?? "USD";
301
+ const locale = options.locale ?? "en-US";
302
+ const fractionDigits = resolveFractionDigits(currency, locale);
303
+ // Intl decides the fraction digits for a currency, so ask it, then hand the count back so the
304
+ // decimal style keeps its trailing zeros instead of defaulting to Intl's maximum of 3.
305
+ const formatter = new Intl.NumberFormat(locale, {
306
+ style: options.showCurrency === false ? "decimal" : "currency",
307
+ ...(options.showCurrency === false ? {} : { currency }),
308
+ minimumFractionDigits: fractionDigits,
309
+ maximumFractionDigits: fractionDigits,
310
+ signDisplay: options.signed ? "exceptZero" : "auto"
311
+ });
312
+ return formatter.format(Number(toDecimal(minorUnits, { fractionDigits })));
313
+ }
314
+ function resolveFractionDigits(currency, locale) {
315
+ try {
316
+ const parts = new Intl.NumberFormat(locale, { style: "currency", currency }).formatToParts(1);
317
+ const fraction = parts.find((part) => part.type === "fraction")?.value ?? "";
318
+ return fraction.replace(/\D/g, "").length;
319
+ }
320
+ catch {
321
+ // An unusable currency or locale falls back to the common two digits.
322
+ return 2;
323
+ }
324
+ }
325
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAQA;;;;GAIG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAInC,YAAY,IAAoB,EAAE,OAAe,EAAE,UAAmC,EAAE;QACtF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC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C,CAAC,MAAM;KACpD,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAgB,EAAE,MAAc;IAC7D,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;QAC9F,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC;QAC7E,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,sEAAsE;QACtE,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@jdsalasc/solvejs-money",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "TypeScript money utilities using integer minor units for lossless arithmetic, exact percentage application, largest-remainder allocation, and formatting, with no floating point rounding.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/cjs/index.cjs",
9
+ "module": "./dist/esm/index.js",
10
+ "types": "./dist/esm/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/esm/index.d.ts",
14
+ "import": "./dist/esm/index.js",
15
+ "require": "./dist/cjs/index.cjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "build": "npm run clean && npm run build:esm && npm run build:cjs",
24
+ "build:esm": "tsc -p tsconfig.esm.json",
25
+ "build:cjs": "tsc -p tsconfig.cjs.json && node ./scripts/rename-cjs.mjs",
26
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
27
+ "test": "npm run build && node --test test/*.test.mjs",
28
+ "lint": "tsc -p tsconfig.esm.json --noEmit"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "author": "jdsalasc",
34
+ "homepage": "https://github.com/jdsalasca/solvejs#readme",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/jdsalasca/solvejs.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/jdsalasca/solvejs/issues"
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "dependencies": {},
46
+ "keywords": [
47
+ "money",
48
+ "currency",
49
+ "minor units",
50
+ "cents",
51
+ "allocate",
52
+ "percentage",
53
+ "invoice",
54
+ "rounding",
55
+ "typescript",
56
+ "javascript",
57
+ "zero dependency",
58
+ "solvejs"
59
+ ]
60
+ }