@open-mercato/shared 0.10.1-develop.8289.1.9a25111d49 → 0.10.1-develop.8292.1.59f204debc

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.
@@ -1,3 +1,3 @@
1
1
  [generate-countries] up to date (259 countries)
2
- [build:shared] found 336 entry points
2
+ [build:shared] found 340 entry points
3
3
  [build:shared] built successfully
package/AGENTS.md CHANGED
@@ -46,6 +46,7 @@ yarn workspace @open-mercato/shared build
46
46
  | `custom-fields/` | When handling custom field payloads | `@open-mercato/shared/lib/custom-fields` |
47
47
  | `data/` | When you need `DataEngine` or `QueryEngine` types | `@open-mercato/shared/lib/data/engine` |
48
48
  | `db/` | When resolving the ORM/connection-pool config (`resolvePoolConfig`, pool/timeout env knobs); when serializing a bounded write across processes under a Postgres transaction advisory lock (`withAdvisoryXactLock` — pass the request EntityManager; `fn` does all DB I/O on `txEm`, flushes its own writes, makes at most one external call, never nests `transactional` or forks; `maxConcurrentHolders` caps holders per process) | `@open-mercato/shared/lib/db/mikro`, `@open-mercato/shared/lib/db/advisoryLock` |
49
+ | `decimal.ts` | When doing ANY money or FX arithmetic - exact add/subtract/multiply, division that keeps at least 17 significant digits, half-up rounding, and `decimalStringSchema` (accepts number or string, outputs a canonical decimal string). MUST NOT do money math on JS `number`; round amounts with `resolveAmountDecimalPlaces(currency.decimalPlaces)` | `@open-mercato/shared/lib/decimal` |
49
50
  | `delivery/` | When scheduling delivery/retry attempts — exponential backoff with jitter for delivery pipelines (currently the push delivery worker) | `@open-mercato/shared/lib/delivery/retry` (`calculateBackoffDelayMs`) |
50
51
  | `di/` | When setting up dependency injection (Awilix). The app-level hook (`src/di.ts` → `register`) is wired explicitly in BOTH bootstrap paths — `src/bootstrap.ts` for the Next.js runtime, `bootstrapFromAppRoot()` for worker/scheduler/CLI processes. Never rely on the legacy `import('@/di')` fallback: the alias does not exist outside the app bundler | `@open-mercato/shared/lib/di` |
51
52
  | `encryption/` | When querying encrypted entities (MUST use instead of raw `em.find`) | `@open-mercato/shared/lib/encryption/find` |
@@ -53,7 +54,7 @@ yarn workspace @open-mercato/shared build
53
54
  | `indexers/` | When building query index helpers | `@open-mercato/shared/lib/indexers` |
54
55
  | `logger/` | When emitting diagnostics — `createLogger(namespace)` instead of raw `console.*` (migrate incrementally, Boy Scout rule). Message-first with structured fields (`logger.warn('Payload too large', { event, maxBytes })`), errors under `err`, `child(bindings)` for context, `getLogLevel()`/`isLevelEnabled()` to gate expensive fields; level via `OM_LOG_LEVEL`. Never log credentials, PII, or payload bodies | `@open-mercato/shared/lib/logger` |
55
56
  | `modules/` | When registering or listing modules; `onModulesRegistered(listener)` subscribes to (re-)registrations so a cache derived from the module list can drop what it built from an incomplete one — bootstrap may register an i18n-only set before the full module list merges in, and listeners fire only when the registered set actually changed, so nothing is added to the request path. Its governing contract — notification timing, fail-soft handling of a throwing or rejecting listener, snapshot-based change detection, listener lifetime under HMR, and the globals a test MUST clear — is [`.ai/specs/2026-08-12-module-registry-registration-listeners.md`](../../.ai/specs/2026-08-12-module-registry-registration-listeners.md); `surfaceFingerprint` gives a deploy-time hash of the enabled modules, their declared ACL features, and the backend route manifest — mix it into any cache key whose payload is derived from those (no DB write exists to tag-invalidate on, so an omitted fingerprint serves the pre-deploy payload forever). It cannot see React-element fields such as a route `icon`, so callers MUST still pass a `ttl` | `@open-mercato/shared/lib/modules/registry`, `@open-mercato/shared/lib/modules/surfaceFingerprint` |
56
- | `number.ts` | When parsing numeric strings from env/query params with a fallback and optional min/integer constraint (`parseNumberWithDefault`), or when parsing a number a USER TYPED, which carries the application locale's decimal/group separators (`parseLocaleNumber`, returns `null` — never a silent `0` — on unparseable input). MUST NOT run API/DB values through `parseLocaleNumber`; those are already numbers. When an input REDISPLAYS a stored number (blur, reload, post-save), render it with `formatLocaleNumberInput(value, locale)`, never `String(value)`, which always emits a dot | `@open-mercato/shared/lib/number` |
57
+ | `number.ts` | When parsing numeric strings from env/query params with a fallback and optional min/integer constraint (`parseNumberWithDefault`), or when parsing a number a USER TYPED, which carries the application locale's decimal/group separators (`parseLocaleNumber`, returns `null` — never a silent `0` — on unparseable input). MUST NOT run API/DB values through `parseLocaleNumber`; those are already numbers. When an input REDISPLAYS a stored number (blur, reload, post-save), render it with `formatLocaleNumberInput(value, locale)` (`formatLocaleDecimalInput` for exact decimal strings; `parseLocaleDecimal` parses them back), never `String(value)`, which always emits a dot | `@open-mercato/shared/lib/number` |
57
58
  | `openapi/` | When generating CRUD OpenAPI specs | `@open-mercato/shared/lib/openapi/crud` |
58
59
  | `profiler/` | When profiling with `OM_PROFILE` env flag | `@open-mercato/shared/lib/profiler` |
59
60
  | `search/` | When resolving record ids from the `search_tokens` index — MUST use instead of hand-rolling the Kysely lookup, for raw ORM/Kysely encrypted-column filters; QueryEngine owns this rewrite automatically | `@open-mercato/shared/lib/search/tokenLookup` |
@@ -0,0 +1,51 @@
1
+ import {
2
+ countDecimalPlaces,
3
+ decimalToString,
4
+ parseDecimal,
5
+ resolveAmountDecimalPlaces,
6
+ resolveIsoCurrencyDecimalPlaces
7
+ } from "./decimal.js";
8
+ import { getTelemetryRuntime } from "./telemetry/runtime.js";
9
+ function findCurrencyAmountPrecisionError(input) {
10
+ const amount = parseDecimal(input.amount);
11
+ const currencyCode = input.currencyCode?.trim().toUpperCase();
12
+ if (amount === null || !currencyCode) return null;
13
+ const isoDecimalPlaces = resolveIsoCurrencyDecimalPlaces(currencyCode);
14
+ const decimalPlaces = input.decimalPlaces !== null && isoDecimalPlaces !== null ? Math.min(input.decimalPlaces, isoDecimalPlaces) : input.decimalPlaces;
15
+ if (decimalPlaces === null || countDecimalPlaces(amount) <= decimalPlaces) return null;
16
+ return { amount: decimalToString(amount), currencyCode, decimalPlaces };
17
+ }
18
+ async function resolveCurrencyDecimalPlaces(container, lookup) {
19
+ if (!lookup.code) return null;
20
+ let resolver = null;
21
+ try {
22
+ resolver = container.resolve("currencyPrecisionService");
23
+ } catch {
24
+ resolver = null;
25
+ }
26
+ let decimalPlaces = null;
27
+ if (resolver) {
28
+ try {
29
+ decimalPlaces = await resolver.getDecimalPlaces(lookup);
30
+ } catch (error) {
31
+ try {
32
+ getTelemetryRuntime()?.reportError(error, {
33
+ module: "currencies",
34
+ code: "currencies.precision_lookup_failed"
35
+ });
36
+ } catch {
37
+ }
38
+ decimalPlaces = null;
39
+ }
40
+ }
41
+ return decimalPlaces ?? resolveIsoCurrencyDecimalPlaces(lookup.code);
42
+ }
43
+ async function resolveCurrencyAmountDecimalPlaces(container, lookup) {
44
+ return resolveAmountDecimalPlaces(await resolveCurrencyDecimalPlaces(container, lookup));
45
+ }
46
+ export {
47
+ findCurrencyAmountPrecisionError,
48
+ resolveCurrencyAmountDecimalPlaces,
49
+ resolveCurrencyDecimalPlaces
50
+ };
51
+ //# sourceMappingURL=currencyPrecision.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/currencyPrecision.ts"],
4
+ "sourcesContent": ["import {\n countDecimalPlaces,\n decimalToString,\n parseDecimal,\n resolveAmountDecimalPlaces,\n resolveIsoCurrencyDecimalPlaces,\n} from './decimal'\nimport { getTelemetryRuntime } from './telemetry/runtime'\n\nexport function findCurrencyAmountPrecisionError(input: {\n amount: number | string | null | undefined\n currencyCode: string | null | undefined\n decimalPlaces: number | null\n}): { amount: string; currencyCode: string; decimalPlaces: number } | null {\n const amount = parseDecimal(input.amount)\n const currencyCode = input.currencyCode?.trim().toUpperCase()\n if (amount === null || !currencyCode) return null\n const isoDecimalPlaces = resolveIsoCurrencyDecimalPlaces(currencyCode)\n const decimalPlaces = input.decimalPlaces !== null && isoDecimalPlaces !== null\n ? Math.min(input.decimalPlaces, isoDecimalPlaces)\n : input.decimalPlaces\n if (decimalPlaces === null || countDecimalPlaces(amount) <= decimalPlaces) return null\n return { amount: decimalToString(amount), currencyCode, decimalPlaces }\n}\n\nexport type CurrencyPrecisionLookup = {\n code: string\n tenantId: string\n organizationId?: string | null\n}\n\nexport type CurrencyPrecisionResolver = {\n getDecimalPlaces(lookup: CurrencyPrecisionLookup): Promise<number | null>\n}\n\ntype ServiceContainer = {\n resolve<T = unknown>(name: string): T\n}\n\n/**\n * The currency's own decimal places: the tenant's currency precision (via the\n * optional `currencyPrecisionService`), else the ISO 4217 digits, else `null`.\n */\nexport async function resolveCurrencyDecimalPlaces(\n container: ServiceContainer,\n lookup: CurrencyPrecisionLookup,\n): Promise<number | null> {\n if (!lookup.code) return null\n let resolver: CurrencyPrecisionResolver | null = null\n try {\n resolver = container.resolve<CurrencyPrecisionResolver>('currencyPrecisionService')\n } catch {\n resolver = null\n }\n let decimalPlaces: number | null = null\n if (resolver) {\n try {\n decimalPlaces = await resolver.getDecimalPlaces(lookup)\n } catch (error) {\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'currencies',\n code: 'currencies.precision_lookup_failed',\n })\n } catch {}\n decimalPlaces = null\n }\n }\n return decimalPlaces ?? resolveIsoCurrencyDecimalPlaces(lookup.code)\n}\n\n/**\n * Decimal places money amounts in `code` are rounded to after a division:\n * the tenant's currency precision (via the optional `currencyPrecisionService`),\n * else the ISO 4217 digits, never fewer than DEFAULT_AMOUNT_DECIMAL_PLACES.\n */\nexport async function resolveCurrencyAmountDecimalPlaces(\n container: ServiceContainer,\n lookup: CurrencyPrecisionLookup,\n): Promise<number> {\n return resolveAmountDecimalPlaces(await resolveCurrencyDecimalPlaces(container, lookup))\n}\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AAE7B,SAAS,iCAAiC,OAI0B;AACzE,QAAM,SAAS,aAAa,MAAM,MAAM;AACxC,QAAM,eAAe,MAAM,cAAc,KAAK,EAAE,YAAY;AAC5D,MAAI,WAAW,QAAQ,CAAC,aAAc,QAAO;AAC7C,QAAM,mBAAmB,gCAAgC,YAAY;AACrE,QAAM,gBAAgB,MAAM,kBAAkB,QAAQ,qBAAqB,OACvE,KAAK,IAAI,MAAM,eAAe,gBAAgB,IAC9C,MAAM;AACV,MAAI,kBAAkB,QAAQ,mBAAmB,MAAM,KAAK,cAAe,QAAO;AAClF,SAAO,EAAE,QAAQ,gBAAgB,MAAM,GAAG,cAAc,cAAc;AACxE;AAoBA,eAAsB,6BACpB,WACA,QACwB;AACxB,MAAI,CAAC,OAAO,KAAM,QAAO;AACzB,MAAI,WAA6C;AACjD,MAAI;AACF,eAAW,UAAU,QAAmC,0BAA0B;AAAA,EACpF,QAAQ;AACN,eAAW;AAAA,EACb;AACA,MAAI,gBAA+B;AACnC,MAAI,UAAU;AACZ,QAAI;AACF,sBAAgB,MAAM,SAAS,iBAAiB,MAAM;AAAA,IACxD,SAAS,OAAO;AACd,UAAI;AACF,4BAAoB,GAAG,YAAY,OAAO;AAAA,UACxC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH,QAAQ;AAAA,MAAC;AACT,sBAAgB;AAAA,IAClB;AAAA,EACF;AACA,SAAO,iBAAiB,gCAAgC,OAAO,IAAI;AACrE;AAOA,eAAsB,mCACpB,WACA,QACiB;AACjB,SAAO,2BAA2B,MAAM,6BAA6B,WAAW,MAAM,CAAC;AACzF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,20 @@
1
+ import { DecimalType } from "@mikro-orm/core";
2
+ import { parseDecimal } from "../decimal.js";
3
+ class ExactDecimalType extends DecimalType {
4
+ constructor() {
5
+ super("string");
6
+ }
7
+ getColumnType(_property, _platform) {
8
+ return "numeric";
9
+ }
10
+ compareValues(left, right) {
11
+ const leftDecimal = parseDecimal(left);
12
+ const rightDecimal = parseDecimal(right);
13
+ if (!leftDecimal || !rightDecimal) return left === right;
14
+ return leftDecimal.eq(rightDecimal);
15
+ }
16
+ }
17
+ export {
18
+ ExactDecimalType
19
+ };
20
+ //# sourceMappingURL=exactDecimalType.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/db/exactDecimalType.ts"],
4
+ "sourcesContent": ["import { DecimalType, type EntityProperty, type Platform } from '@mikro-orm/core'\nimport { parseDecimal } from '../decimal'\n\n/**\n * Unconstrained `numeric` mapped to a decimal string. MikroORM's `DecimalType`\n * detects changes by comparing `+value`, so an edit beyond float precision\n * (`1.123456789012345678` -> `...679`) is never flushed. This type compares the\n * exact decimal values instead.\n */\nexport class ExactDecimalType extends DecimalType {\n constructor() {\n super('string')\n }\n\n getColumnType(_property: EntityProperty, _platform: Platform): string {\n return 'numeric'\n }\n\n compareValues(left: unknown, right: unknown): boolean {\n const leftDecimal = parseDecimal(left)\n const rightDecimal = parseDecimal(right)\n if (!leftDecimal || !rightDecimal) return left === right\n return leftDecimal.eq(rightDecimal)\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,mBAAuD;AAChE,SAAS,oBAAoB;AAQtB,MAAM,yBAAyB,YAAY;AAAA,EAChD,cAAc;AACZ,UAAM,QAAQ;AAAA,EAChB;AAAA,EAEA,cAAc,WAA2B,WAA6B;AACpE,WAAO;AAAA,EACT;AAAA,EAEA,cAAc,MAAe,OAAyB;AACpD,UAAM,cAAc,aAAa,IAAI;AACrC,UAAM,eAAe,aAAa,KAAK;AACvC,QAAI,CAAC,eAAe,CAAC,aAAc,QAAO,SAAS;AACnD,WAAO,YAAY,GAAG,YAAY;AAAA,EACpC;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,289 @@
1
+ import BigConstructor from "big.js";
2
+ import { z } from "zod";
3
+ import { ISO_4217_MINOR_UNITS } from "./isoCurrencyMinorUnits.js";
4
+ const FX_DECIMAL_PLACES = 50;
5
+ const MIN_SIGNIFICANT_DIGITS = 17;
6
+ const DEFAULT_AMOUNT_DECIMAL_PLACES = 4;
7
+ const ROUND_HALF_UP = 1;
8
+ const Decimal = BigConstructor();
9
+ Decimal.DP = FX_DECIMAL_PLACES;
10
+ Decimal.RM = ROUND_HALF_UP;
11
+ const MAX_DECIMAL_EXPONENT = 1e3;
12
+ const MAX_DECIMAL_SIGNIFICANT_DIGITS = 1e3;
13
+ const MAX_DECIMAL_INTEGER_DIGITS = 300;
14
+ const MAX_DECIMAL_INPUT_LENGTH = 2048;
15
+ const DECIMAL_STRING_PATTERN = /^[+-]?(\d+(\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i;
16
+ const NON_ZERO_DIGIT_PATTERN = /[1-9]/;
17
+ function isDecimalString(value) {
18
+ if (value.length > MAX_DECIMAL_INPUT_LENGTH) return false;
19
+ const match = DECIMAL_STRING_PATTERN.exec(value);
20
+ if (!match) return false;
21
+ const exponent = match[3] === void 0 ? 0 : Number(match[3]);
22
+ if (Math.abs(exponent) > MAX_DECIMAL_EXPONENT) return false;
23
+ const [integerPart, fractionPart = ""] = match[1].split(".");
24
+ const digits = `${integerPart}${fractionPart}`;
25
+ const firstSignificant = digits.search(NON_ZERO_DIGIT_PATTERN);
26
+ if (firstSignificant === -1) return true;
27
+ let lastSignificant = digits.length - 1;
28
+ while (digits[lastSignificant] === "0") lastSignificant -= 1;
29
+ const unitsIndex = integerPart.length - 1 + exponent;
30
+ return lastSignificant - firstSignificant < MAX_DECIMAL_SIGNIFICANT_DIGITS && unitsIndex - firstSignificant < MAX_DECIMAL_INTEGER_DIGITS && unitsIndex - lastSignificant >= -MAX_DECIMAL_EXPONENT;
31
+ }
32
+ function isDecimalNumber(value) {
33
+ return Number.isFinite(value) && isDecimalString(String(value));
34
+ }
35
+ function isBigLike(value) {
36
+ if (typeof value !== "object" || value === null) return false;
37
+ const candidate = value;
38
+ return Array.isArray(candidate.c) && typeof candidate.e === "number" && typeof candidate.s === "number";
39
+ }
40
+ function isZeroBig(value) {
41
+ return value.c.length === 1 && value.c[0] === 0;
42
+ }
43
+ function invalidDecimalPlaces(decimalPlaces) {
44
+ return new Error(`[internal] Invalid decimal places: ${decimalPlaces}`);
45
+ }
46
+ function assertDecimalPlaces(decimalPlaces) {
47
+ if (!Number.isInteger(decimalPlaces) || decimalPlaces < 0 || decimalPlaces > MAX_DECIMAL_EXPONENT) {
48
+ throw invalidDecimalPlaces(decimalPlaces);
49
+ }
50
+ }
51
+ function withinCaps(value) {
52
+ if (isZeroBig(value)) return value;
53
+ const decimalPlaces = value.c.length - 1 - value.e;
54
+ const allowedDecimalPlaces = Math.min(MAX_DECIMAL_EXPONENT, MAX_DECIMAL_SIGNIFICANT_DIGITS - 1 - value.e);
55
+ const capped = decimalPlaces > allowedDecimalPlaces ? value.round(allowedDecimalPlaces, ROUND_HALF_UP) : value;
56
+ if (!isZeroBig(capped) && capped.e >= MAX_DECIMAL_INTEGER_DIGITS) {
57
+ throw new Error("[internal] Decimal result out of range");
58
+ }
59
+ return capped;
60
+ }
61
+ function isDecimalInput(value) {
62
+ if (typeof value === "number") return isDecimalNumber(value);
63
+ if (typeof value === "string") return isDecimalString(value.trim());
64
+ return isBigLike(value) && (isZeroBig(value) || value.e < MAX_DECIMAL_INTEGER_DIGITS);
65
+ }
66
+ function toDecimal(value) {
67
+ if (typeof value === "number") {
68
+ if (!isDecimalNumber(value)) throw new Error(`[internal] Invalid decimal value: ${value}`);
69
+ return new Decimal(value);
70
+ }
71
+ if (typeof value === "string") {
72
+ const trimmed = value.trim();
73
+ if (!isDecimalString(trimmed)) throw new Error(`[internal] Invalid decimal value: ${value.slice(0, 50)}`);
74
+ return new Decimal(trimmed.startsWith("+") ? trimmed.slice(1) : trimmed);
75
+ }
76
+ if (!isBigLike(value)) throw new Error("[internal] Invalid decimal value");
77
+ return withinCaps(new Decimal(value));
78
+ }
79
+ function parseDecimal(value) {
80
+ if (value === null || value === void 0 || value === "") return null;
81
+ if (!isDecimalInput(value)) return null;
82
+ return toDecimal(value);
83
+ }
84
+ function decimalToString(value) {
85
+ return toDecimal(value).toFixed();
86
+ }
87
+ function addDecimals(left, right) {
88
+ return withinCaps(toDecimal(left).plus(toDecimal(right)));
89
+ }
90
+ function subtractDecimals(left, right) {
91
+ return withinCaps(toDecimal(left).minus(toDecimal(right)));
92
+ }
93
+ function multiplyDecimals(left, right) {
94
+ return withinCaps(toDecimal(left).times(toDecimal(right)));
95
+ }
96
+ function sumDecimals(values) {
97
+ return withinCaps(values.reduce((total, value) => total.plus(toDecimal(value)), new Decimal(0)));
98
+ }
99
+ function divideDecimals(dividend, divisor, decimalPlaces = FX_DECIMAL_PLACES) {
100
+ assertDecimalPlaces(decimalPlaces);
101
+ const left = toDecimal(dividend);
102
+ const right = toDecimal(divisor);
103
+ if (right.eq(0)) throw new Error("[internal] Division by zero");
104
+ if (left.eq(0)) return new Decimal(0);
105
+ const significantDecimalPlaces = MIN_SIGNIFICANT_DIGITS - (left.e - right.e);
106
+ const previousDecimalPlaces = Decimal.DP;
107
+ Decimal.DP = Math.max(decimalPlaces, significantDecimalPlaces, 0);
108
+ try {
109
+ return withinCaps(left.div(right));
110
+ } finally {
111
+ Decimal.DP = previousDecimalPlaces;
112
+ }
113
+ }
114
+ function roundDecimal(value, decimalPlaces) {
115
+ assertDecimalPlaces(decimalPlaces);
116
+ return toDecimal(value).round(decimalPlaces, ROUND_HALF_UP);
117
+ }
118
+ function compareDecimals(left, right) {
119
+ return toDecimal(left).cmp(toDecimal(right));
120
+ }
121
+ function decimalsEqual(left, right) {
122
+ return compareDecimals(left, right) === 0;
123
+ }
124
+ function isZeroDecimal(value) {
125
+ return toDecimal(value).eq(0);
126
+ }
127
+ function isNegativeDecimal(value) {
128
+ return toDecimal(value).lt(0);
129
+ }
130
+ function absDecimal(value) {
131
+ return toDecimal(value).abs();
132
+ }
133
+ function negateDecimal(value) {
134
+ return toDecimal(value).neg();
135
+ }
136
+ function minDecimal(...values) {
137
+ if (values.length === 0) throw new Error("[internal] minDecimal requires at least one value");
138
+ return values.map(toDecimal).reduce((lowest, value) => value.lt(lowest) ? value : lowest);
139
+ }
140
+ function maxDecimal(...values) {
141
+ if (values.length === 0) throw new Error("[internal] maxDecimal requires at least one value");
142
+ return values.map(toDecimal).reduce((highest, value) => value.gt(highest) ? value : highest);
143
+ }
144
+ function countDecimalPlaces(value) {
145
+ const fraction = decimalToString(value).split(".")[1];
146
+ return fraction ? fraction.length : 0;
147
+ }
148
+ function padDecimalPlaces(value, minDecimalPlaces) {
149
+ assertDecimalPlaces(minDecimalPlaces);
150
+ const decimal = toDecimal(value);
151
+ return decimal.toFixed(Math.max(minDecimalPlaces, countDecimalPlaces(decimal)));
152
+ }
153
+ function decimalToNumber(value) {
154
+ return Number(decimalToString(value));
155
+ }
156
+ function matchesLegacyNumber(exact, legacy) {
157
+ if (decimalToNumber(exact) !== legacy) return false;
158
+ return legacy !== 0 || exact.eq(0);
159
+ }
160
+ function resolveExactDecimal(exact, legacy) {
161
+ const exactDecimal = parseDecimal(exact);
162
+ const legacyDecimal = parseDecimal(legacy);
163
+ if (exactDecimal && (typeof legacy !== "number" || matchesLegacyNumber(exactDecimal, legacy))) {
164
+ return decimalToString(exactDecimal);
165
+ }
166
+ return legacyDecimal ? decimalToString(legacyDecimal) : null;
167
+ }
168
+ function exactCandidate(source, field, value) {
169
+ if (typeof value !== "number") return value;
170
+ const rawValue = source[field];
171
+ return typeof rawValue === "number" ? source[`${field}Exact`] ?? rawValue : rawValue;
172
+ }
173
+ function withExactAmounts(parsed, raw, fields) {
174
+ const source = raw && typeof raw === "object" ? raw : {};
175
+ const values = parsed;
176
+ const exact = {};
177
+ for (const field of fields) {
178
+ const value = values[field];
179
+ if (value === void 0) continue;
180
+ exact[`${field}Exact`] = resolveExactDecimal(exactCandidate(source, field, value), value);
181
+ }
182
+ return { ...parsed, ...exact };
183
+ }
184
+ function withExactListAmounts(parsedItems, raw, key, fields) {
185
+ if (!parsedItems) return void 0;
186
+ const source = raw && typeof raw === "object" ? raw[key] : void 0;
187
+ const rawItems = Array.isArray(source) ? source : [];
188
+ return parsedItems.map((item, index) => withExactAmounts(item, rawItems[index], fields));
189
+ }
190
+ function amountComparisonTolerance(decimalPlaces = DEFAULT_AMOUNT_DECIMAL_PLACES) {
191
+ assertDecimalPlaces(decimalPlaces);
192
+ return toDecimal(`5e-${Math.max(decimalPlaces, DEFAULT_AMOUNT_DECIMAL_PLACES) - 1}`);
193
+ }
194
+ function resolveAmountDecimalPlaces(currencyDecimalPlaces) {
195
+ if (typeof currencyDecimalPlaces !== "number" || !Number.isInteger(currencyDecimalPlaces) || currencyDecimalPlaces < 0) {
196
+ return DEFAULT_AMOUNT_DECIMAL_PLACES;
197
+ }
198
+ return Math.max(DEFAULT_AMOUNT_DECIMAL_PLACES, currencyDecimalPlaces);
199
+ }
200
+ let isoCurrencyCodes;
201
+ function resolveIsoCurrencyCodes() {
202
+ if (isoCurrencyCodes !== void 0) return isoCurrencyCodes;
203
+ try {
204
+ isoCurrencyCodes = typeof Intl.supportedValuesOf === "function" ? new Set(Intl.supportedValuesOf("currency")) : null;
205
+ } catch {
206
+ isoCurrencyCodes = null;
207
+ }
208
+ return isoCurrencyCodes;
209
+ }
210
+ function resolveCurrencyDisplayDecimalPlaces(currencyCode) {
211
+ if (!currencyCode) return null;
212
+ const code = currencyCode.toUpperCase();
213
+ const knownCodes = resolveIsoCurrencyCodes();
214
+ if (knownCodes && !knownCodes.has(code)) return null;
215
+ try {
216
+ return new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? null;
217
+ } catch {
218
+ return null;
219
+ }
220
+ }
221
+ function resolveIsoCurrencyDecimalPlaces(currencyCode) {
222
+ if (!currencyCode) return null;
223
+ const code = currencyCode.toUpperCase();
224
+ if (Object.hasOwn(ISO_4217_MINOR_UNITS, code)) return ISO_4217_MINOR_UNITS[code];
225
+ return resolveCurrencyDisplayDecimalPlaces(code);
226
+ }
227
+ function isWithinDecimalCaps(value) {
228
+ if (typeof value === "string" && value.trim().length === 0) return true;
229
+ if (typeof value !== "string" && typeof value !== "number") return true;
230
+ return isDecimalInput(value);
231
+ }
232
+ function withDecimalCaps(schema, message) {
233
+ return z.unknown().refine(isWithinDecimalCaps, message === void 0 ? void 0 : { message }).pipe(schema);
234
+ }
235
+ const decimalInputSchema = z.union([z.string(), z.number()]).refine(isDecimalInput, {
236
+ message: "invalidDecimal"
237
+ });
238
+ const decimalStringSchema = decimalInputSchema.transform((value) => decimalToString(value));
239
+ const nonNegativeDecimalStringSchema = decimalStringSchema.refine(
240
+ (value) => !isNegativeDecimal(value),
241
+ { message: "decimalMustBeNonNegative" }
242
+ );
243
+ const positiveDecimalStringSchema = decimalStringSchema.refine(
244
+ (value) => toDecimal(value).gt(0),
245
+ { message: "decimalMustBePositive" }
246
+ );
247
+ export {
248
+ DEFAULT_AMOUNT_DECIMAL_PLACES,
249
+ FX_DECIMAL_PLACES,
250
+ MAX_DECIMAL_EXPONENT,
251
+ MAX_DECIMAL_INPUT_LENGTH,
252
+ MAX_DECIMAL_INTEGER_DIGITS,
253
+ MAX_DECIMAL_SIGNIFICANT_DIGITS,
254
+ MIN_SIGNIFICANT_DIGITS,
255
+ absDecimal,
256
+ addDecimals,
257
+ amountComparisonTolerance,
258
+ compareDecimals,
259
+ countDecimalPlaces,
260
+ decimalStringSchema,
261
+ decimalToNumber,
262
+ decimalToString,
263
+ decimalsEqual,
264
+ divideDecimals,
265
+ isDecimalInput,
266
+ isNegativeDecimal,
267
+ isWithinDecimalCaps,
268
+ isZeroDecimal,
269
+ maxDecimal,
270
+ minDecimal,
271
+ multiplyDecimals,
272
+ negateDecimal,
273
+ nonNegativeDecimalStringSchema,
274
+ padDecimalPlaces,
275
+ parseDecimal,
276
+ positiveDecimalStringSchema,
277
+ resolveAmountDecimalPlaces,
278
+ resolveCurrencyDisplayDecimalPlaces,
279
+ resolveExactDecimal,
280
+ resolveIsoCurrencyDecimalPlaces,
281
+ roundDecimal,
282
+ subtractDecimals,
283
+ sumDecimals,
284
+ toDecimal,
285
+ withDecimalCaps,
286
+ withExactAmounts,
287
+ withExactListAmounts
288
+ };
289
+ //# sourceMappingURL=decimal.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/decimal.ts"],
4
+ "sourcesContent": ["import BigConstructor from 'big.js'\nimport type { Big, BigSource } from 'big.js'\nimport { z } from 'zod'\nimport { ISO_4217_MINOR_UNITS } from './isoCurrencyMinorUnits'\n\nexport type DecimalValue = Big\nexport type DecimalInput = string | number | Big\n\nexport const FX_DECIMAL_PLACES = 50\nexport const MIN_SIGNIFICANT_DIGITS = 17\nexport const DEFAULT_AMOUNT_DECIMAL_PLACES = 4\n\nconst ROUND_HALF_UP = 1\n\nconst Decimal = BigConstructor()\nDecimal.DP = FX_DECIMAL_PLACES\nDecimal.RM = ROUND_HALF_UP\n\n/**\n * Largest exponent accepted in a decimal string, and the lowest decimal position\n * a digit may sit at (`1e-1000`). Expanding `1e-100000000` to plain notation\n * would allocate a 100M-character string, so anything beyond this bound (far\n * past any real money or FX value) is rejected as invalid input.\n */\nexport const MAX_DECIMAL_EXPONENT = 1000\n\n/**\n * Most significant digits a decimal input may carry. Arithmetic cost grows with\n * the digit count, so longer inputs are rejected as invalid.\n */\nexport const MAX_DECIMAL_SIGNIFICANT_DIGITS = 1000\n\n/**\n * Most integer digits a decimal input may carry (`|value| < 1e300`), so the\n * legacy float copy of an accepted value is always finite.\n */\nexport const MAX_DECIMAL_INTEGER_DIGITS = 300\n\n/**\n * Longest decimal string accepted, so a value padded with millions of zeros is\n * rejected before it is scanned. The longest plain value within the other caps\n * (300 integer and 1000 fractional digits) is about 1300 characters.\n */\nexport const MAX_DECIMAL_INPUT_LENGTH = 2048\n\nconst DECIMAL_STRING_PATTERN = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)(?:e([+-]?\\d+))?$/i\nconst NON_ZERO_DIGIT_PATTERN = /[1-9]/\n\nfunction isDecimalString(value: string): boolean {\n if (value.length > MAX_DECIMAL_INPUT_LENGTH) return false\n const match = DECIMAL_STRING_PATTERN.exec(value)\n if (!match) return false\n const exponent = match[3] === undefined ? 0 : Number(match[3])\n if (Math.abs(exponent) > MAX_DECIMAL_EXPONENT) return false\n const [integerPart, fractionPart = ''] = match[1].split('.')\n const digits = `${integerPart}${fractionPart}`\n const firstSignificant = digits.search(NON_ZERO_DIGIT_PATTERN)\n if (firstSignificant === -1) return true\n let lastSignificant = digits.length - 1\n while (digits[lastSignificant] === '0') lastSignificant -= 1\n const unitsIndex = integerPart.length - 1 + exponent\n return (\n lastSignificant - firstSignificant < MAX_DECIMAL_SIGNIFICANT_DIGITS &&\n unitsIndex - firstSignificant < MAX_DECIMAL_INTEGER_DIGITS &&\n unitsIndex - lastSignificant >= -MAX_DECIMAL_EXPONENT\n )\n}\n\nfunction isDecimalNumber(value: number): boolean {\n return Number.isFinite(value) && isDecimalString(String(value))\n}\n\n/**\n * Duck-typed so a `Big` from another copy of big.js (CommonJS and ES module\n * builds, or two installed versions) is still recognised.\n */\nfunction isBigLike(value: unknown): value is Big {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as { c?: unknown; e?: unknown; s?: unknown }\n return Array.isArray(candidate.c) && typeof candidate.e === 'number' && typeof candidate.s === 'number'\n}\n\nfunction isZeroBig(value: Big): boolean {\n return value.c.length === 1 && value.c[0] === 0\n}\n\nfunction invalidDecimalPlaces(decimalPlaces: number): Error {\n return new Error(`[internal] Invalid decimal places: ${decimalPlaces}`)\n}\n\nfunction assertDecimalPlaces(decimalPlaces: number): void {\n if (!Number.isInteger(decimalPlaces) || decimalPlaces < 0 || decimalPlaces > MAX_DECIMAL_EXPONENT) {\n throw invalidDecimalPlaces(decimalPlaces)\n }\n}\n\n/**\n * Keeps a computed value within the input caps, so every result can be stored\n * and parsed back. Digits beyond 1000 significant digits or below `1e-1000`\n * (chained FX products grow their decimals with every multiplication) are\n * rounded half-up; a value with more than 300 integer digits throws instead of\n * turning into an unparseable string or an infinite float copy.\n */\nfunction withinCaps(value: Big): Big {\n if (isZeroBig(value)) return value\n const decimalPlaces = value.c.length - 1 - value.e\n const allowedDecimalPlaces = Math.min(MAX_DECIMAL_EXPONENT, MAX_DECIMAL_SIGNIFICANT_DIGITS - 1 - value.e)\n const capped = decimalPlaces > allowedDecimalPlaces ? value.round(allowedDecimalPlaces, ROUND_HALF_UP) : value\n if (!isZeroBig(capped) && capped.e >= MAX_DECIMAL_INTEGER_DIGITS) {\n throw new Error('[internal] Decimal result out of range')\n }\n return capped\n}\n\nexport function isDecimalInput(value: unknown): value is DecimalInput {\n if (typeof value === 'number') return isDecimalNumber(value)\n if (typeof value === 'string') return isDecimalString(value.trim())\n return isBigLike(value) && (isZeroBig(value) || value.e < MAX_DECIMAL_INTEGER_DIGITS)\n}\n\n/**\n * A JS number is read as its shortest round-trip decimal form, so `0.1 + 0.2`\n * becomes `0.30000000000000004`; pass the raw string to keep the entered digits.\n * A `Big` is copied and brought within the caps (see `withinCaps`).\n */\nexport function toDecimal(value: DecimalInput): DecimalValue {\n if (typeof value === 'number') {\n if (!isDecimalNumber(value)) throw new Error(`[internal] Invalid decimal value: ${value}`)\n return new Decimal(value)\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!isDecimalString(trimmed)) throw new Error(`[internal] Invalid decimal value: ${value.slice(0, 50)}`)\n return new Decimal(trimmed.startsWith('+') ? trimmed.slice(1) : trimmed)\n }\n if (!isBigLike(value)) throw new Error('[internal] Invalid decimal value')\n return withinCaps(new Decimal(value as BigSource))\n}\n\nexport function parseDecimal(value: unknown): DecimalValue | null {\n if (value === null || value === undefined || value === '') return null\n if (!isDecimalInput(value)) return null\n return toDecimal(value)\n}\n\nexport function decimalToString(value: DecimalInput): string {\n return toDecimal(value).toFixed()\n}\n\nexport function addDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {\n return withinCaps(toDecimal(left).plus(toDecimal(right)))\n}\n\nexport function subtractDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {\n return withinCaps(toDecimal(left).minus(toDecimal(right)))\n}\n\nexport function multiplyDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {\n return withinCaps(toDecimal(left).times(toDecimal(right)))\n}\n\nexport function sumDecimals(values: DecimalInput[]): DecimalValue {\n return withinCaps(values.reduce<DecimalValue>((total, value) => total.plus(toDecimal(value)), new Decimal(0)))\n}\n\n/**\n * Divides with at least `decimalPlaces` decimals and never fewer than\n * MIN_SIGNIFICANT_DIGITS significant digits, so a quotient is never less\n * precise than the same division done on a JS `number`. The quotient is cut,\n * not exact: `1 / 3 * 3` is `0.999...9`, so round before comparing or storing.\n */\nexport function divideDecimals(\n dividend: DecimalInput,\n divisor: DecimalInput,\n decimalPlaces: number = FX_DECIMAL_PLACES,\n): DecimalValue {\n assertDecimalPlaces(decimalPlaces)\n const left = toDecimal(dividend)\n const right = toDecimal(divisor)\n if (right.eq(0)) throw new Error('[internal] Division by zero')\n if (left.eq(0)) return new Decimal(0)\n const significantDecimalPlaces = MIN_SIGNIFICANT_DIGITS - (left.e - right.e)\n const previousDecimalPlaces = Decimal.DP\n Decimal.DP = Math.max(decimalPlaces, significantDecimalPlaces, 0)\n try {\n return withinCaps(left.div(right))\n } finally {\n Decimal.DP = previousDecimalPlaces\n }\n}\n\n/**\n * Rounds half away from zero (commercial rounding): `2.5` -> `3`, `-2.5` -> `-3`.\n * There is no banker's rounding mode.\n */\nexport function roundDecimal(value: DecimalInput, decimalPlaces: number): DecimalValue {\n assertDecimalPlaces(decimalPlaces)\n return toDecimal(value).round(decimalPlaces, ROUND_HALF_UP)\n}\n\nexport function compareDecimals(left: DecimalInput, right: DecimalInput): -1 | 0 | 1 {\n return toDecimal(left).cmp(toDecimal(right)) as -1 | 0 | 1\n}\n\nexport function decimalsEqual(left: DecimalInput, right: DecimalInput): boolean {\n return compareDecimals(left, right) === 0\n}\n\nexport function isZeroDecimal(value: DecimalInput): boolean {\n return toDecimal(value).eq(0)\n}\n\nexport function isNegativeDecimal(value: DecimalInput): boolean {\n return toDecimal(value).lt(0)\n}\n\nexport function absDecimal(value: DecimalInput): DecimalValue {\n return toDecimal(value).abs()\n}\n\nexport function negateDecimal(value: DecimalInput): DecimalValue {\n return toDecimal(value).neg()\n}\n\nexport function minDecimal(...values: DecimalInput[]): DecimalValue {\n if (values.length === 0) throw new Error('[internal] minDecimal requires at least one value')\n return values.map(toDecimal).reduce((lowest, value) => (value.lt(lowest) ? value : lowest))\n}\n\nexport function maxDecimal(...values: DecimalInput[]): DecimalValue {\n if (values.length === 0) throw new Error('[internal] maxDecimal requires at least one value')\n return values.map(toDecimal).reduce((highest, value) => (value.gt(highest) ? value : highest))\n}\n\nexport function countDecimalPlaces(value: DecimalInput): number {\n const fraction = decimalToString(value).split('.')[1]\n return fraction ? fraction.length : 0\n}\n\n/** Plain decimal string with at least `minDecimalPlaces` decimals (`12.5` -> `12.50`), never cut. */\nexport function padDecimalPlaces(value: DecimalInput, minDecimalPlaces: number): string {\n assertDecimalPlaces(minDecimalPlaces)\n const decimal = toDecimal(value)\n return decimal.toFixed(Math.max(minDecimalPlaces, countDecimalPlaces(decimal)))\n}\n\nexport function decimalToNumber(value: DecimalInput): number {\n return Number(decimalToString(value))\n}\n\n/**\n * Whether `exact` is the decimal the validated `legacy` number stands for. A value\n * that underflows to zero (`-1e-400`) must itself be zero, so it cannot slip past\n * a sign or range check made on the number.\n */\nfunction matchesLegacyNumber(exact: DecimalValue, legacy: number): boolean {\n if (decimalToNumber(exact) !== legacy) return false\n return legacy !== 0 || exact.eq(0)\n}\n\n/**\n * Picks the exact decimal string for a dual `number` + `<field>Exact` pair.\n * The exact value wins unless the legacy `number` was changed on its own\n * (e.g. by a hook unaware of the exact field) - then the number is used.\n */\nexport function resolveExactDecimal(exact: unknown, legacy: unknown): string | null {\n const exactDecimal = parseDecimal(exact)\n const legacyDecimal = parseDecimal(legacy)\n if (exactDecimal && (typeof legacy !== 'number' || matchesLegacyNumber(exactDecimal, legacy))) {\n return decimalToString(exactDecimal)\n }\n return legacyDecimal ? decimalToString(legacyDecimal) : null\n}\n\nexport type WithExactAmounts<T, K extends string> = T & { [P in K as `${P}Exact`]?: string | null }\n\nfunction exactCandidate(source: Record<string, unknown>, field: string, value: unknown): unknown {\n if (typeof value !== 'number') return value\n const rawValue = source[field]\n return typeof rawValue === 'number' ? source[`${field}Exact`] ?? rawValue : rawValue\n}\n\n/**\n * Adds `<field>Exact` strings next to number fields a zod schema coerced, taken\n * from the raw input so digits beyond float precision survive the parse. When the\n * raw field is already a number (an API route parsed the body before the command),\n * the `<field>Exact` string that route attached is used instead, and only while it\n * matches that number. A parsed `null` (or a parsed non-number) is never paired\n * with a raw value, so it cannot smuggle unvalidated input past the schema.\n *\n * Only the number was validated, so the exact string may carry digits below float\n * precision that a `max`, `int` or `multipleOf` rule never saw (`100.00000000000000000001`\n * passes `max(100)`); a raw `<field>Exact` sent next to a JSON number is accepted on the\n * same terms. Sign checks hold. Use it only for fields whose rules are sign checks, or\n * re-check the exact value with decimal-aware rules.\n */\nexport function withExactAmounts<T extends object, K extends string>(\n parsed: T,\n raw: unknown,\n fields: readonly K[],\n): WithExactAmounts<T, K> {\n const source = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n const values = parsed as Record<string, unknown>\n const exact: Record<string, string | null> = {}\n for (const field of fields) {\n const value = values[field]\n if (value === undefined) continue\n exact[`${field}Exact`] = resolveExactDecimal(exactCandidate(source, field, value), value)\n }\n return { ...parsed, ...exact } as WithExactAmounts<T, K>\n}\n\n/**\n * Applies `withExactAmounts` to each item of the `key` list, pairing parsed and raw\n * items by index. Lets an API route keep exact digits for nested lines. The list\n * schema must not filter or reorder items, or exact strings pair with the wrong item\n * (the float-equality check limits this to items whose floats are equal).\n */\nexport function withExactListAmounts<T extends object, K extends string>(\n parsedItems: readonly T[] | null | undefined,\n raw: unknown,\n key: string,\n fields: readonly K[],\n): WithExactAmounts<T, K>[] | undefined {\n if (!parsedItems) return undefined\n const source = raw && typeof raw === 'object' ? (raw as Record<string, unknown>)[key] : undefined\n const rawItems = Array.isArray(source) ? source : []\n return parsedItems.map((item, index) => withExactAmounts(item, rawItems[index], fields))\n}\n\n/**\n * Tolerance for comparing money amounts rounded to `decimalPlaces`: half a\n * minor unit of a 2-decimal currency at the default 4 places (0.005), scaled\n * down with higher precision and never wider than that default.\n */\nexport function amountComparisonTolerance(decimalPlaces: number = DEFAULT_AMOUNT_DECIMAL_PLACES): DecimalValue {\n assertDecimalPlaces(decimalPlaces)\n return toDecimal(`5e-${Math.max(decimalPlaces, DEFAULT_AMOUNT_DECIMAL_PLACES) - 1}`)\n}\n\nexport function resolveAmountDecimalPlaces(currencyDecimalPlaces?: number | null): number {\n if (typeof currencyDecimalPlaces !== 'number' || !Number.isInteger(currencyDecimalPlaces) || currencyDecimalPlaces < 0) {\n return DEFAULT_AMOUNT_DECIMAL_PLACES\n }\n return Math.max(DEFAULT_AMOUNT_DECIMAL_PLACES, currencyDecimalPlaces)\n}\n\nlet isoCurrencyCodes: Set<string> | null | undefined\n\nfunction resolveIsoCurrencyCodes(): Set<string> | null {\n if (isoCurrencyCodes !== undefined) return isoCurrencyCodes\n try {\n isoCurrencyCodes = typeof Intl.supportedValuesOf === 'function' ? new Set(Intl.supportedValuesOf('currency')) : null\n } catch {\n isoCurrencyCodes = null\n }\n return isoCurrencyCodes\n}\n\n/**\n * Decimal places `Intl.NumberFormat` displays for `currencyCode`, or `null` when\n * the runtime does not know the code. These are CLDR display digits, not ISO 4217\n * minor units (HUF, COP and IDR display 0 digits but have 2 minor units), and may\n * change with the ICU version, so use them to format amounts, never to validate\n * or round stored ones. `Intl.NumberFormat` accepts any well-formed code (ETH,\n * XYZ) and reports 2 digits for it, so only codes listed by\n * `Intl.supportedValuesOf` count.\n */\nexport function resolveCurrencyDisplayDecimalPlaces(currencyCode?: string | null): number | null {\n if (!currencyCode) return null\n const code = currencyCode.toUpperCase()\n const knownCodes = resolveIsoCurrencyCodes()\n if (knownCodes && !knownCodes.has(code)) return null\n try {\n return new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions()\n .maximumFractionDigits ?? null\n } catch {\n return null\n }\n}\n\n/**\n * ISO 4217 minor units (decimal places) of `currencyCode`, read from a static table\n * of every ISO 4217 code so the result does not depend on the ICU version. `null`\n * when ISO defines no minor unit (N.A. or withdrawn codes) or the code is not ISO\n * 4217; a non-ISO code the runtime supports falls back to its `Intl` digits.\n */\nexport function resolveIsoCurrencyDecimalPlaces(currencyCode?: string | null): number | null {\n if (!currencyCode) return null\n const code = currencyCode.toUpperCase()\n if (Object.hasOwn(ISO_4217_MINOR_UNITS, code)) return ISO_4217_MINOR_UNITS[code]\n return resolveCurrencyDisplayDecimalPlaces(code)\n}\n\n/**\n * Whether a raw money input may reach a number-coercing schema: blank strings and\n * non-numeric values are left to that schema, numbers and strings must be decimals\n * within the size caps, so an oversized value is rejected instead of turning into 0.\n * The wrapped schema decides what a blank string means: `z.coerce.number()` turns\n * `''` into `0`, as it did before this wrapper; preprocess blanks to `null` or\n * `undefined` where an empty field must not mean zero.\n */\nexport function isWithinDecimalCaps(value: unknown): boolean {\n if (typeof value === 'string' && value.trim().length === 0) return true\n if (typeof value !== 'string' && typeof value !== 'number') return true\n return isDecimalInput(value)\n}\n\nexport function withDecimalCaps<T extends z.ZodType>(schema: T, message?: string) {\n return z.unknown().refine(isWithinDecimalCaps, message === undefined ? undefined : { message }).pipe(schema)\n}\n\nconst decimalInputSchema = z.union([z.string(), z.number()]).refine(isDecimalInput, {\n message: 'invalidDecimal',\n})\n\nexport const decimalStringSchema = decimalInputSchema.transform((value) => decimalToString(value))\n\nexport const nonNegativeDecimalStringSchema = decimalStringSchema.refine(\n (value) => !isNegativeDecimal(value),\n { message: 'decimalMustBeNonNegative' },\n)\n\nexport const positiveDecimalStringSchema = decimalStringSchema.refine(\n (value) => toDecimal(value).gt(0),\n { message: 'decimalMustBePositive' },\n)\n"],
5
+ "mappings": "AAAA,OAAO,oBAAoB;AAE3B,SAAS,SAAS;AAClB,SAAS,4BAA4B;AAK9B,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,gCAAgC;AAE7C,MAAM,gBAAgB;AAEtB,MAAM,UAAU,eAAe;AAC/B,QAAQ,KAAK;AACb,QAAQ,KAAK;AAQN,MAAM,uBAAuB;AAM7B,MAAM,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