@stripe/extensibility-sdk 0.25.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +7 -9
  2. package/dist/config-values/generate.cjs +1 -1
  3. package/dist/config-values/generate.js +1 -1
  4. package/dist/extensibility-sdk-alpha.d.ts +85 -119
  5. package/dist/extensibility-sdk-beta.d.ts +85 -119
  6. package/dist/extensibility-sdk-extensions-alpha.d.ts +82 -54
  7. package/dist/extensibility-sdk-extensions-beta.d.ts +82 -54
  8. package/dist/extensibility-sdk-extensions-internal.d.ts +83 -55
  9. package/dist/extensibility-sdk-extensions-public.d.ts +82 -54
  10. package/dist/extensibility-sdk-internal.d.ts +89 -101
  11. package/dist/extensibility-sdk-public.d.ts +85 -119
  12. package/dist/extensions/billing/index.d.ts +1 -1
  13. package/dist/extensions/billing/invoice_collection_options.d.ts +111 -0
  14. package/dist/extensions/billing/invoice_collection_options.d.ts.map +1 -0
  15. package/dist/extensions/billing/recurring_billing_item_handling.d.ts +43 -0
  16. package/dist/extensions/billing/recurring_billing_item_handling.d.ts.map +1 -1
  17. package/dist/extensions/index.cjs +111 -52
  18. package/dist/extensions/index.js +111 -52
  19. package/dist/index.cjs +128 -97
  20. package/dist/index.js +126 -91
  21. package/dist/internal.cjs +7 -7
  22. package/dist/internal.js +7 -7
  23. package/dist/stdlib/decimal.d.ts +2 -2
  24. package/dist/stdlib/index.d.ts +4 -8
  25. package/dist/stdlib/index.d.ts.map +1 -1
  26. package/dist/stdlib/refs.d.ts +1 -31
  27. package/dist/stdlib/refs.d.ts.map +1 -1
  28. package/dist/stdlib/scalars.d.ts +0 -22
  29. package/dist/stdlib/scalars.d.ts.map +1 -1
  30. package/dist/stdlib/to-const.d.ts +1 -1
  31. package/dist/stdlib/transforms.d.ts +1 -1
  32. package/dist/stdlib/types.d.ts +5 -5
  33. package/dist/stdlib/types.d.ts.map +1 -1
  34. package/dist/tsconfig.build.tsbuildinfo +1 -1
  35. package/package.json +2 -10
  36. package/dist/extensibility-sdk-stdlib-alpha.d.ts +0 -638
  37. package/dist/extensibility-sdk-stdlib-beta.d.ts +0 -638
  38. package/dist/extensibility-sdk-stdlib-internal.d.ts +0 -1008
  39. package/dist/extensibility-sdk-stdlib-public.d.ts +0 -638
  40. package/dist/extensions/billing/invoice_collection_setting.d.ts +0 -117
  41. package/dist/extensions/billing/invoice_collection_setting.d.ts.map +0 -1
  42. package/dist/stdlib/index.cjs +0 -1770
  43. package/dist/stdlib/index.js +0 -1710
@@ -1,1770 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/stdlib/index.ts
21
- var stdlib_exports = {};
22
- __export(stdlib_exports, {
23
- DEFAULT_DIV_PRECISION: () => DEFAULT_DIV_PRECISION,
24
- Decimal: () => Decimal,
25
- DecimalRoundingPresets: () => DecimalRoundingPresets,
26
- Integer: () => Integer,
27
- PositiveInteger: () => PositiveInteger,
28
- Ref: () => Ref,
29
- StreetAddress: () => StreetAddress,
30
- Timestamp: () => Timestamp,
31
- WireReadError: () => WireReadError,
32
- WireWriteError: () => WireWriteError,
33
- _ConfigEnum: () => _ConfigEnum,
34
- _JsonWireToType: () => _JsonWireToType,
35
- _ProtoEnum: () => _ProtoEnum,
36
- _ProtoWireToType: () => _ProtoWireToType,
37
- _ShapeDescriptor: () => _ShapeDescriptor,
38
- _TypeToProtoWire: () => _TypeToProtoWire,
39
- _UnionDescriptor: () => _UnionDescriptor,
40
- _apply: () => _apply,
41
- _applyConfig: () => _applyConfig,
42
- _applyIncoming: () => _applyIncoming,
43
- _applyOutgoing: () => _applyOutgoing,
44
- _configAppContextFromContext: () => _configAppContextFromContext,
45
- _identity: () => _identity,
46
- _isPromiseLike: () => _isPromiseLike,
47
- _required: () => _required,
48
- _translateArray: () => _translateArray,
49
- _translateDateTime: () => _translateDateTime,
50
- _translateDecimal: () => _translateDecimal,
51
- _translateEnum: () => _translateEnum,
52
- _translateMap: () => _translateMap,
53
- _translateShape: () => _translateShape,
54
- _translateUnion: () => _translateUnion,
55
- isDecimal: () => isDecimal,
56
- toConst: () => toConst
57
- });
58
- module.exports = __toCommonJS(stdlib_exports);
59
-
60
- // src/stdlib/scalars.ts
61
- var import_core = require("@formspec/core");
62
-
63
- // src/stdlib/decimal.ts
64
- var PLAIN_NOTATION_DIGIT_LIMIT = 30;
65
- var DecimalRoundingPresets = Object.freeze({
66
- "ubb-usage-count": Object.freeze({
67
- mode: "significant-figures",
68
- value: 15
69
- }),
70
- "v1-api": Object.freeze({
71
- mode: "decimal-places",
72
- value: 12
73
- })
74
- });
75
- var DEFAULT_DIV_PRECISION = 34;
76
- var IMPLICIT_DECIMAL_COERCION_ERROR = "Implicit Decimal coercion is not allowed; use .add(), .sub(), .mul(), .div(), .toString(), or .toNumber() explicitly.";
77
- var MAX_EXPONENT = Number.MAX_SAFE_INTEGER;
78
- function normalizeZero(value) {
79
- return Object.is(value, -0) ? 0 : value;
80
- }
81
- var DECIMAL_BRAND = /* @__PURE__ */ Symbol.for(
82
- "stripe.apps-extensibility-sdk.Decimal"
83
- );
84
- var DecimalImpl = class _DecimalImpl {
85
- /** @internal */
86
- [DECIMAL_BRAND] = true;
87
- /** @internal */
88
- #coefficient;
89
- /** @internal */
90
- #exponent;
91
- /**
92
- * Construct and normalise a decimal value.
93
- *
94
- * @param coefficient - The unscaled integer value.
95
- * @param exponent - The power-of-ten scale factor.
96
- *
97
- * @internal
98
- */
99
- constructor(coefficient, exponent) {
100
- const [normalizedCoef, normalizedExp] = _DecimalImpl.normalize(coefficient, exponent);
101
- this.#coefficient = normalizedCoef;
102
- this.#exponent = normalizedExp;
103
- Object.freeze(this);
104
- }
105
- /**
106
- * Strip trailing zeros from `coefficient`, incrementing `exponent`
107
- * for each zero removed. Zero always normalises to `(0n, 0)`.
108
- *
109
- * @param coefficient - Raw coefficient before normalisation.
110
- * @param exponent - Raw exponent before normalisation.
111
- * @returns A `[coefficient, exponent]` tuple with trailing zeros removed.
112
- *
113
- * @internal
114
- */
115
- static normalize(coefficient, exponent) {
116
- if (coefficient === 0n) {
117
- return [0n, 0];
118
- }
119
- let coef = coefficient;
120
- let exp = exponent;
121
- while (coef !== 0n && coef % 10n === 0n) {
122
- coef = coef / 10n;
123
- exp++;
124
- }
125
- return [coef, exp];
126
- }
127
- /**
128
- * Apply rounding to the result of an integer division.
129
- *
130
- * @remarks
131
- * BigInt division truncates toward zero. This helper inspects the
132
- * `remainder` to decide whether to adjust the truncated `quotient`
133
- * by ±1 according to the chosen {@link RoundDirection}.
134
- *
135
- * The rounding direction is derived from the signs of `remainder`
136
- * and `divisor`: when they agree the exact fractional part is
137
- * positive (the truncation point is below the true value, so +1
138
- * rounds to nearest); when they disagree the fractional part is
139
- * negative (−1 rounds to nearest).
140
- *
141
- * @param quotient - Truncated integer quotient (`dividend / divisor`).
142
- * @param remainder - Division remainder (`dividend % divisor`).
143
- * @param divisor - The divisor used in the division.
144
- * @param direction - The rounding strategy to apply.
145
- * @returns The rounded quotient.
146
- *
147
- * @internal
148
- */
149
- static roundDivision(quotient, remainder, divisor, direction) {
150
- if (remainder === 0n) {
151
- return quotient;
152
- }
153
- if (direction === "round-down") {
154
- return quotient;
155
- }
156
- const roundDir = remainder > 0n === divisor > 0n ? 1n : -1n;
157
- if (direction === "round-up") {
158
- return quotient + roundDir;
159
- }
160
- if (direction === "ceil") {
161
- return roundDir === 1n ? quotient + 1n : quotient;
162
- }
163
- if (direction === "floor") {
164
- return roundDir === -1n ? quotient - 1n : quotient;
165
- }
166
- const absRemainder = remainder < 0n ? -remainder : remainder;
167
- const absDivisor = divisor < 0n ? -divisor : divisor;
168
- const doubled = absRemainder * 2n;
169
- const cmp = doubled === absDivisor ? 0 : doubled < absDivisor ? -1 : 1;
170
- if (cmp < 0) {
171
- return quotient;
172
- }
173
- if (cmp > 0) {
174
- return quotient + roundDir;
175
- }
176
- if (direction === "half-up") {
177
- return quotient + roundDir;
178
- }
179
- if (direction === "half-down") {
180
- return quotient;
181
- }
182
- if (quotient % 2n === 0n) {
183
- return quotient;
184
- } else {
185
- return quotient + roundDir;
186
- }
187
- }
188
- // -------------------------------------------------------------------
189
- // Arithmetic
190
- // -------------------------------------------------------------------
191
- /**
192
- * Return the sum of this value and `other`.
193
- *
194
- * @param other - The addend. Accepts any {@link DecimalLike} value.
195
- * @returns A new {@link Decimal} equal to `this + other`.
196
- *
197
- * @public
198
- */
199
- add(other) {
200
- const otherImpl = coerceToImpl(other);
201
- if (this.#exponent === otherImpl.#exponent) {
202
- return toDecimal(
203
- new _DecimalImpl(this.#coefficient + otherImpl.#coefficient, this.#exponent)
204
- );
205
- }
206
- if (this.#exponent < otherImpl.#exponent) {
207
- const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
208
- return toDecimal(
209
- new _DecimalImpl(
210
- this.#coefficient + otherImpl.#coefficient * scale,
211
- this.#exponent
212
- )
213
- );
214
- } else {
215
- const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
216
- return toDecimal(
217
- new _DecimalImpl(
218
- this.#coefficient * scale + otherImpl.#coefficient,
219
- otherImpl.#exponent
220
- )
221
- );
222
- }
223
- }
224
- /**
225
- * Return the difference of this value and `other`.
226
- *
227
- * @param other - The subtrahend. Accepts any {@link DecimalLike} value.
228
- * @returns A new {@link Decimal} equal to `this - other`.
229
- *
230
- * @public
231
- */
232
- sub(other) {
233
- const otherImpl = coerceToImpl(other);
234
- if (this.#exponent === otherImpl.#exponent) {
235
- return toDecimal(
236
- new _DecimalImpl(this.#coefficient - otherImpl.#coefficient, this.#exponent)
237
- );
238
- }
239
- if (this.#exponent < otherImpl.#exponent) {
240
- const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
241
- return toDecimal(
242
- new _DecimalImpl(
243
- this.#coefficient - otherImpl.#coefficient * scale,
244
- this.#exponent
245
- )
246
- );
247
- } else {
248
- const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
249
- return toDecimal(
250
- new _DecimalImpl(
251
- this.#coefficient * scale - otherImpl.#coefficient,
252
- otherImpl.#exponent
253
- )
254
- );
255
- }
256
- }
257
- /**
258
- * Return the product of this value and `other`.
259
- *
260
- * @param other - The multiplicand. Accepts any {@link DecimalLike} value.
261
- * @returns A new {@link Decimal} equal to `this × other`.
262
- *
263
- * @public
264
- */
265
- mul(other) {
266
- const otherImpl = coerceToImpl(other);
267
- return toDecimal(
268
- new _DecimalImpl(
269
- this.#coefficient * otherImpl.#coefficient,
270
- this.#exponent + otherImpl.#exponent
271
- )
272
- );
273
- }
274
- /**
275
- * Return the quotient of this value divided by `other`.
276
- *
277
- * @remarks
278
- * Division scales the dividend to produce `precision` decimal digits
279
- * in the result, then applies integer division and rounds the
280
- * remainder according to `direction`.
281
- *
282
- * Division requires explicit rounding control — no invisible defaults
283
- * in financial code. For full precision use {@link DEFAULT_DIV_PRECISION}
284
- * (34, matching the IEEE 754 decimal128 coefficient size).
285
- *
286
- * @example
287
- * ```ts
288
- * Decimal.from('1').div(Decimal.from('3'), 5, 'half-up'); // "0.33333"
289
- * Decimal.from('5').div(Decimal.from('2'), 0, 'half-up'); // "3"
290
- * Decimal.from('5').div(Decimal.from('2'), 0, 'half-even'); // "2"
291
- * ```
292
- *
293
- * @param other - The divisor. Must not be zero. Accepts any {@link DecimalLike} value.
294
- * @param precision - Maximum number of decimal digits in the result.
295
- * @param direction - How to round when the exact quotient cannot
296
- * be represented at the requested precision.
297
- * @returns A new {@link Decimal} equal to `this ÷ other`, rounded to
298
- * `precision` decimal places.
299
- * @throws Error if `other` is zero.
300
- * @throws Error if `precision` is negative or non-integer.
301
- *
302
- * @public
303
- */
304
- div(other, precision, direction) {
305
- if (precision < 0 || !Number.isInteger(precision)) {
306
- throw new Error("precision must be a non-negative integer");
307
- }
308
- const otherImpl = coerceToImpl(other);
309
- if (otherImpl.#coefficient === 0n) {
310
- throw new Error("Division by zero");
311
- }
312
- const scale = this.#exponent - otherImpl.#exponent + precision;
313
- let quotient;
314
- let remainder;
315
- let roundingDivisor;
316
- if (scale >= 0) {
317
- const scaledDividend = this.#coefficient * 10n ** BigInt(scale);
318
- quotient = scaledDividend / otherImpl.#coefficient;
319
- remainder = scaledDividend % otherImpl.#coefficient;
320
- roundingDivisor = otherImpl.#coefficient;
321
- } else {
322
- const scaledDivisor = otherImpl.#coefficient * 10n ** BigInt(-scale);
323
- quotient = this.#coefficient / scaledDivisor;
324
- remainder = this.#coefficient % scaledDivisor;
325
- roundingDivisor = scaledDivisor;
326
- }
327
- const roundedQuotient = _DecimalImpl.roundDivision(
328
- quotient,
329
- remainder,
330
- roundingDivisor,
331
- direction
332
- );
333
- return toDecimal(new _DecimalImpl(roundedQuotient, -precision));
334
- }
335
- // -------------------------------------------------------------------
336
- // Comparison
337
- // -------------------------------------------------------------------
338
- /**
339
- * Three-way comparison of this value with `other`.
340
- *
341
- * @example
342
- * ```ts
343
- * const a = Decimal.from('1.5');
344
- * const b = Decimal.from('2');
345
- * a.cmp(b); // -1
346
- * b.cmp(a); // 1
347
- * a.cmp(a); // 0
348
- * ```
349
- *
350
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
351
- * @returns `-1` if `this < other`, `0` if equal, `1` if `this > other`.
352
- *
353
- * @public
354
- */
355
- cmp(other) {
356
- const otherImpl = coerceToImpl(other);
357
- if (this.#exponent === otherImpl.#exponent) {
358
- if (this.#coefficient < otherImpl.#coefficient) return -1;
359
- if (this.#coefficient > otherImpl.#coefficient) return 1;
360
- return 0;
361
- }
362
- if (this.#exponent < otherImpl.#exponent) {
363
- const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
364
- const scaledOther = otherImpl.#coefficient * scale;
365
- if (this.#coefficient < scaledOther) return -1;
366
- if (this.#coefficient > scaledOther) return 1;
367
- return 0;
368
- } else {
369
- const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
370
- const scaledThis = this.#coefficient * scale;
371
- if (scaledThis < otherImpl.#coefficient) return -1;
372
- if (scaledThis > otherImpl.#coefficient) return 1;
373
- return 0;
374
- }
375
- }
376
- /**
377
- * Return `true` if this value is numerically equal to `other`.
378
- *
379
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
380
- * @returns `true` if `this === other` in value, `false` otherwise.
381
- *
382
- * @public
383
- */
384
- eq(other) {
385
- return this.cmp(other) === 0;
386
- }
387
- /**
388
- * Return `true` if this value is strictly less than `other`.
389
- *
390
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
391
- * @returns `true` if `this < other`, `false` otherwise.
392
- *
393
- * @public
394
- */
395
- lt(other) {
396
- return this.cmp(other) === -1;
397
- }
398
- /**
399
- * Return `true` if this value is less than or equal to `other`.
400
- *
401
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
402
- * @returns `true` if `this ≤ other`, `false` otherwise.
403
- *
404
- * @public
405
- */
406
- lte(other) {
407
- return this.cmp(other) <= 0;
408
- }
409
- /**
410
- * Return `true` if this value is strictly greater than `other`.
411
- *
412
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
413
- * @returns `true` if `this > other`, `false` otherwise.
414
- *
415
- * @public
416
- */
417
- gt(other) {
418
- return this.cmp(other) === 1;
419
- }
420
- /**
421
- * Return `true` if this value is greater than or equal to `other`.
422
- *
423
- * @param other - The value to compare against. Accepts any {@link DecimalLike} value.
424
- * @returns `true` if `this ≥ other`, `false` otherwise.
425
- *
426
- * @public
427
- */
428
- gte(other) {
429
- return this.cmp(other) >= 0;
430
- }
431
- // -------------------------------------------------------------------
432
- // Predicates
433
- // -------------------------------------------------------------------
434
- /**
435
- * Return `true` if this value is exactly zero.
436
- *
437
- * @returns `true` if the value is zero, `false` otherwise.
438
- *
439
- * @public
440
- */
441
- isZero() {
442
- return this.#coefficient === 0n;
443
- }
444
- /**
445
- * Return `true` if this value is strictly less than zero.
446
- *
447
- * @returns `true` if negative, `false` if zero or positive.
448
- *
449
- * @public
450
- */
451
- isNegative() {
452
- return this.#coefficient < 0n;
453
- }
454
- /**
455
- * Return `true` if this value is strictly greater than zero.
456
- *
457
- * @returns `true` if positive, `false` if zero or negative.
458
- *
459
- * @public
460
- */
461
- isPositive() {
462
- return this.#coefficient > 0n;
463
- }
464
- // -------------------------------------------------------------------
465
- // Unary operations
466
- // -------------------------------------------------------------------
467
- /**
468
- * Return the additive inverse of this value.
469
- *
470
- * @returns A new {@link Decimal} equal to `-this`.
471
- *
472
- * @public
473
- */
474
- neg() {
475
- return toDecimal(new _DecimalImpl(-this.#coefficient, this.#exponent));
476
- }
477
- /**
478
- * Return the absolute value.
479
- *
480
- * @returns A new {@link Decimal} equal to `|this|`. If this value is
481
- * already non-negative, returns `this` (no allocation).
482
- *
483
- * @public
484
- */
485
- abs() {
486
- if (this.#coefficient < 0n) {
487
- return toDecimal(new _DecimalImpl(-this.#coefficient, this.#exponent));
488
- }
489
- return toDecimal(this);
490
- }
491
- // -------------------------------------------------------------------
492
- // Rounding
493
- // -------------------------------------------------------------------
494
- /**
495
- * Round this value to a specified precision.
496
- *
497
- * @remarks
498
- * **Rounding directions** (IEEE 754-2019 §4.3):
499
- *
500
- * | Direction | Behavior |
501
- * | -------------- | ---------------------------------------------- |
502
- * | `'ceil'` | 1.1→2, -1.1→-1, 1.0→1 (toward +∞) |
503
- * | `'floor'` | 1.9→1, -1.1→-2, 1.0→1 (toward -∞) |
504
- * | `'round-down'` | 1.9→1, -1.9→-1 (toward zero / truncate) |
505
- * | `'round-up'` | 1.1→2, -1.1→-2 (away from zero) |
506
- * | `'half-up'` | 0.5→1, 1.5→2, -0.5→-1 (ties away from zero) |
507
- * | `'half-down'` | 0.5→0, 1.5→1, -0.5→0 (ties toward zero) |
508
- * | `'half-even'` | 0.5→0, 1.5→2, 2.5→2, 3.5→4 (ties to even) |
509
- *
510
- * **Precision** is specified as a {@link DecimalRoundingOptions} object
511
- * or a built-in preset name from {@link DecimalRoundingPresets}:
512
- *
513
- * @example
514
- * ```ts
515
- * // Using a preset
516
- * amount.round('half-even', 'v1-api');
517
- *
518
- * // Using explicit options
519
- * amount.round('half-even', { mode: 'decimal-places', value: 2 });
520
- * amount.round('half-up', { mode: 'significant-figures', value: 4 });
521
- * ```
522
- *
523
- * @param direction - How to round.
524
- * @param options - A {@link DecimalRoundingOptions} object or key of `typeof DecimalRoundingPresets`.
525
- * @returns A new {@link Decimal} rounded to the specified precision.
526
- * @throws Error if `options.value` is negative or non-integer.
527
- * @throws Error if the preset name is not recognized.
528
- *
529
- * @public
530
- */
531
- round(direction, options) {
532
- if (typeof options === "string") {
533
- if (!Object.hasOwn(DecimalRoundingPresets, options)) {
534
- throw new Error(`Unknown rounding preset: "${options}"`);
535
- }
536
- return this.#roundWithOptions(direction, DecimalRoundingPresets[options]);
537
- }
538
- return this.#roundWithOptions(direction, options);
539
- }
540
- /**
541
- * Apply resolved {@link DecimalRoundingOptions} to this value.
542
- *
543
- * @param direction - How to round.
544
- * @param resolved - Already-resolved options (never a preset name).
545
- * @returns A new {@link Decimal} rounded to the specified precision.
546
- *
547
- * @internal
548
- */
549
- #roundWithOptions(direction, resolved) {
550
- if (resolved.value < 0 || !Number.isInteger(resolved.value)) {
551
- throw new Error("DecimalRoundingOptions.value must be a non-negative integer");
552
- }
553
- if (resolved.mode === "decimal-places") {
554
- const fixed = this.toFixed(resolved.value, direction);
555
- return Decimal.from(fixed);
556
- }
557
- if (this.#coefficient === 0n) {
558
- return toDecimal(this);
559
- }
560
- const coeffStr = this.#coefficient < 0n ? (-this.#coefficient).toString() : this.#coefficient.toString();
561
- const currentSigFigs = coeffStr.length;
562
- if (resolved.value === 0) {
563
- return Decimal.zero;
564
- }
565
- if (currentSigFigs <= resolved.value) {
566
- return toDecimal(this);
567
- }
568
- const digitsToTrim = currentSigFigs - resolved.value;
569
- const divisor = 10n ** BigInt(digitsToTrim);
570
- const quotient = this.#coefficient / divisor;
571
- const remainder = this.#coefficient % divisor;
572
- const rounded = _DecimalImpl.roundDivision(quotient, remainder, divisor, direction);
573
- return toDecimal(new _DecimalImpl(rounded, this.#exponent + digitsToTrim));
574
- }
575
- // -------------------------------------------------------------------
576
- // Conversion / serialisation
577
- // -------------------------------------------------------------------
578
- /**
579
- * Return a human-readable string representation.
580
- *
581
- * @remarks
582
- * Plain notation for values whose digit count is at most 30, and
583
- * scientific notation (`1.23E+40`) for larger values. Trailing zeros
584
- * are never present because the internal representation is normalised.
585
- *
586
- * @public
587
- */
588
- toString() {
589
- if (this.#coefficient === 0n) {
590
- return "0";
591
- }
592
- const coeffStr = this.#coefficient.toString();
593
- const isNeg = coeffStr.startsWith("-");
594
- const absCoeffStr = isNeg ? coeffStr.slice(1) : coeffStr;
595
- if (this.#exponent < 0) {
596
- const decimalPlaces = -this.#exponent;
597
- const leadingZeroCount = decimalPlaces >= absCoeffStr.length ? decimalPlaces - absCoeffStr.length : 0;
598
- if (leadingZeroCount > PLAIN_NOTATION_DIGIT_LIMIT) {
599
- if (absCoeffStr.length === 1) {
600
- return `${coeffStr}E${String(this.#exponent)}`;
601
- }
602
- const intPart = absCoeffStr[0] ?? "";
603
- const fracPart = absCoeffStr.slice(1);
604
- const adjustedExp = this.#exponent + absCoeffStr.length - 1;
605
- return `${isNeg ? "-" : ""}${intPart}.${fracPart}E${String(adjustedExp)}`;
606
- }
607
- if (decimalPlaces >= absCoeffStr.length) {
608
- const leadingZeros = "0".repeat(decimalPlaces - absCoeffStr.length);
609
- return `${isNeg ? "-" : ""}0.${leadingZeros}${absCoeffStr}`;
610
- } else {
611
- const integerPart = absCoeffStr.slice(0, absCoeffStr.length - decimalPlaces);
612
- const fractionalPart = absCoeffStr.slice(absCoeffStr.length - decimalPlaces);
613
- return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}`;
614
- }
615
- }
616
- const plainLength = absCoeffStr.length + this.#exponent;
617
- if (plainLength <= PLAIN_NOTATION_DIGIT_LIMIT) {
618
- if (this.#exponent === 0) {
619
- return coeffStr;
620
- }
621
- const trailingZeros = "0".repeat(this.#exponent);
622
- return `${isNeg ? "-" : ""}${absCoeffStr}${trailingZeros}`;
623
- } else {
624
- if (absCoeffStr.length === 1) {
625
- return `${coeffStr}E+${String(this.#exponent)}`;
626
- }
627
- const integerPart = absCoeffStr[0] ?? "";
628
- const fractionalPart = absCoeffStr.slice(1);
629
- const adjustedExponent = this.#exponent + absCoeffStr.length - 1;
630
- return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}E+${String(adjustedExponent)}`;
631
- }
632
- }
633
- /**
634
- * Return the JSON-serialisable representation.
635
- *
636
- * @remarks
637
- * Returns a plain string matching the Stripe API convention where
638
- * decimal values are serialised as strings in JSON. Called
639
- * automatically by `JSON.stringify`.
640
- *
641
- * @public
642
- */
643
- toJSON() {
644
- return this.toString();
645
- }
646
- /**
647
- * Convert to a JavaScript `number`.
648
- *
649
- * @remarks
650
- * This is an explicit, intentionally lossy conversion. Use it only
651
- * when you need a numeric value for display or interop with APIs
652
- * that require `number`. Prefer {@link Decimal.toString | toString}
653
- * or {@link Decimal.toFixed | toFixed} for lossless output.
654
- *
655
- * @public
656
- */
657
- toNumber() {
658
- return Number(this.toString());
659
- }
660
- /**
661
- * Format this value as a fixed-point string with exactly
662
- * `decimalPlaces` digits after the decimal point.
663
- *
664
- * @remarks
665
- * Values are rounded according to `direction` when the internal
666
- * precision exceeds the requested number of decimal places.
667
- * The rounding direction is always required — no invisible defaults
668
- * in financial code.
669
- *
670
- * @example
671
- * ```ts
672
- * Decimal.from('1.235').toFixed(2, 'half-up'); // "1.24"
673
- * Decimal.from('1.225').toFixed(2, 'half-even'); // "1.22"
674
- * Decimal.from('42').toFixed(3, 'half-up'); // "42.000"
675
- * ```
676
- *
677
- * @param decimalPlaces - Number of digits after the decimal point.
678
- * Must be a non-negative integer.
679
- * @param direction - How to round when truncating excess digits.
680
- * @returns A string with exactly `decimalPlaces` fractional digits.
681
- * @throws Error if `decimalPlaces` is negative or non-integer.
682
- *
683
- * @public
684
- */
685
- toFixed(decimalPlaces, direction) {
686
- if (decimalPlaces < 0 || !Number.isInteger(decimalPlaces)) {
687
- throw new Error("decimalPlaces must be a non-negative integer");
688
- }
689
- const formatFixed = (coef) => {
690
- const coeffStr = coef.toString();
691
- const isNeg = coeffStr.startsWith("-");
692
- const absCoeffStr = isNeg ? coeffStr.slice(1) : coeffStr;
693
- if (decimalPlaces === 0) {
694
- return coeffStr;
695
- }
696
- if (decimalPlaces >= absCoeffStr.length) {
697
- const leadingZeros = "0".repeat(decimalPlaces - absCoeffStr.length);
698
- return `${isNeg ? "-" : ""}0.${leadingZeros}${absCoeffStr}`;
699
- } else {
700
- const integerPart = absCoeffStr.slice(0, absCoeffStr.length - decimalPlaces);
701
- const fractionalPart = absCoeffStr.slice(absCoeffStr.length - decimalPlaces);
702
- return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}`;
703
- }
704
- };
705
- const targetExponent = -decimalPlaces;
706
- if (this.#exponent === targetExponent) {
707
- return formatFixed(this.#coefficient);
708
- }
709
- if (this.#exponent < targetExponent) {
710
- const scaleDiff = targetExponent - this.#exponent;
711
- const divisor = 10n ** BigInt(scaleDiff);
712
- const quotient = this.#coefficient / divisor;
713
- const remainder = this.#coefficient % divisor;
714
- const rounded = _DecimalImpl.roundDivision(quotient, remainder, divisor, direction);
715
- return formatFixed(rounded);
716
- } else {
717
- const scaleDiff = this.#exponent - targetExponent;
718
- const scaled = this.#coefficient * 10n ** BigInt(scaleDiff);
719
- return formatFixed(scaled);
720
- }
721
- }
722
- /**
723
- * Convert this value to an {@link (Integer:type)} by rounding.
724
- *
725
- * @remarks
726
- * The rounding direction is always required — no invisible defaults
727
- * in financial code.
728
- *
729
- * @example
730
- * ```ts
731
- * Decimal.from('2.7').toInteger('floor'); // 2
732
- * Decimal.from('2.5').toInteger('half-up'); // 3
733
- * Decimal.from('2.5').toInteger('half-even'); // 2
734
- * ```
735
- *
736
- * @param direction - How to round when the value is not a whole number.
737
- * @returns A branded {@link (Integer:type)} value.
738
- * @throws Error if the rounded value is too large to represent as
739
- * a JavaScript `number`.
740
- *
741
- * @public
742
- */
743
- toInteger(direction) {
744
- const fixed = this.toFixed(0, direction);
745
- const num = Number(fixed);
746
- if (!Number.isFinite(num) || !Number.isSafeInteger(num)) {
747
- throw new Error(
748
- `Decimal value ${fixed} cannot be exactly represented as a JavaScript integer`
749
- );
750
- }
751
- const normalized = normalizeZero(num);
752
- return normalized;
753
- }
754
- /**
755
- * Reject implicit arithmetic-style coercion while preserving explicit
756
- * stringification.
757
- *
758
- * @remarks
759
- * JavaScript cannot overload `+` to perform exact decimal arithmetic.
760
- * The runtime only allows coercion hooks to return primitive values,
761
- * which would either concatenate strings or lose precision by forcing
762
- * the Decimal through IEEE 754 `number`. In financial code, that is
763
- * less safe than rejecting the operation outright.
764
- *
765
- * `String(decimal)` and template-string interpolation still work
766
- * because the string hint returns the canonical decimal string.
767
- *
768
- * @public
769
- */
770
- [Symbol.toPrimitive](hint) {
771
- if (hint === "string") {
772
- return this.toString();
773
- }
774
- throw new Error(IMPLICIT_DECIMAL_COERCION_ERROR);
775
- }
776
- /**
777
- * Return the canonical string representation when called directly.
778
- *
779
- * @remarks
780
- * JavaScript implicit coercion uses
781
- * {@link Decimal.[Symbol.toPrimitive] | [Symbol.toPrimitive]} first, so
782
- * this method is only reached via explicit direct calls such as
783
- * `decimal.valueOf()`.
784
- *
785
- * @public
786
- */
787
- valueOf() {
788
- return this.toString();
789
- }
790
- };
791
- function toImpl(d) {
792
- return d;
793
- }
794
- function coerceToImpl(value) {
795
- if (isDecimal(value)) {
796
- return toImpl(value);
797
- }
798
- return toImpl(Decimal.from(value));
799
- }
800
- function toDecimal(impl) {
801
- return impl;
802
- }
803
- function isDecimal(value) {
804
- return typeof value === "object" && value !== null && DECIMAL_BRAND in value && // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- symbol key access requires cast
805
- value[DECIMAL_BRAND] === true;
806
- }
807
- function assertIsDecimal(value) {
808
- if (!isDecimal(value)) {
809
- throw new Error(`Expected a Decimal, got ${typeof value}`);
810
- }
811
- }
812
- var Decimal = {
813
- /**
814
- * Type guard that narrows an unknown value to {@link (Decimal:type)}.
815
- *
816
- * @example
817
- * ```ts
818
- * if (Decimal.is(value)) {
819
- * value.add(1); // value is Decimal
820
- * }
821
- * ```
822
- * @public
823
- */
824
- is: isDecimal,
825
- /**
826
- * Assertion guard that throws if the value is not a {@link (Decimal:type)}.
827
- *
828
- * @example
829
- * ```ts
830
- * Decimal.assert(value);
831
- * value.add(1); // value is Decimal
832
- * ```
833
- * @public
834
- */
835
- assert: assertIsDecimal,
836
- /**
837
- * Create a `Decimal` from a string, number, bigint, Integer, or Decimal.
838
- *
839
- * @remarks
840
- * - **Decimal**: returned as-is (immutable passthrough).
841
- * - **string**: Parsed as a decimal literal. Accepts an optional sign,
842
- * integer digits, an optional fractional part, and an optional `e`/`E`
843
- * exponent. Leading/trailing whitespace is trimmed.
844
- * - **number** (including Integer): Must be finite. Converted via
845
- * `Number.prototype.toString()` then parsed, so `Decimal.from(0.1)`
846
- * produces `"0.1"` (not the 53-bit binary approximation).
847
- * - **bigint**: Treated as an integer with exponent 0.
848
- *
849
- * @example
850
- * ```ts
851
- * Decimal.from('1.23'); // string
852
- * Decimal.from(42); // number
853
- * Decimal.from(100n); // bigint
854
- * Decimal.from('1.5e3'); // scientific notation → 1500
855
- * Decimal.from(d); // Decimal passthrough
856
- * ```
857
- *
858
- * @param value - The value to convert.
859
- * @returns A new frozen `Decimal` instance (or the same instance if
860
- * already a Decimal).
861
- * @throws Error if `value` is a non-finite number, an empty
862
- * string, or a string that does not match the decimal literal grammar.
863
- *
864
- * @public
865
- */
866
- from(value) {
867
- if (isDecimal(value)) {
868
- return value;
869
- }
870
- if (typeof value === "bigint") {
871
- return toDecimal(new DecimalImpl(value, 0));
872
- }
873
- if (typeof value === "number") {
874
- if (!Number.isFinite(value)) {
875
- throw new Error("Number must be finite");
876
- }
877
- return Decimal.from(value.toString());
878
- }
879
- const trimmed = value.trim();
880
- if (trimmed === "") {
881
- throw new Error("Cannot parse empty string as Decimal");
882
- }
883
- const match = /^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(trimmed);
884
- if (!match) {
885
- throw new Error(`Invalid decimal string: ${value}`);
886
- }
887
- const sign = match[1] === "-" ? -1n : 1n;
888
- const integerPart = match[2] ?? "";
889
- const fractionalPart = match[3] ?? "";
890
- const exponentPart = match[4] ? Number(match[4]) : 0;
891
- if (!Number.isSafeInteger(exponentPart) || exponentPart > MAX_EXPONENT || exponentPart < -MAX_EXPONENT) {
892
- throw new Error(
893
- `Exponent out of range: ${String(match[4])} exceeds safe integer bounds`
894
- );
895
- }
896
- const coefficientStr = integerPart + fractionalPart;
897
- const coefficient = sign * BigInt(coefficientStr);
898
- const exponent = exponentPart - fractionalPart.length;
899
- if (!Number.isSafeInteger(exponent) || exponent > MAX_EXPONENT || exponent < -MAX_EXPONENT) {
900
- throw new Error(
901
- `Computed exponent out of range: ${String(exponent)} exceeds safe integer bounds`
902
- );
903
- }
904
- return toDecimal(new DecimalImpl(coefficient, exponent));
905
- },
906
- /**
907
- * The `Decimal` value representing zero.
908
- *
909
- * @remarks
910
- * Pre-allocated singleton — prefer `Decimal.zero` over
911
- * `Decimal.from(0)` to avoid an unnecessary allocation.
912
- *
913
- * @public
914
- */
915
- zero: toDecimal(new DecimalImpl(0n, 0))
916
- };
917
-
918
- // src/stdlib/scalars.ts
919
- function roundToInteger(value, direction) {
920
- switch (direction) {
921
- case "ceil":
922
- return Math.ceil(value);
923
- case "floor":
924
- return Math.floor(value);
925
- case "round-down":
926
- return Math.trunc(value);
927
- case "round-up":
928
- return value >= 0 ? Math.ceil(value) : Math.floor(value);
929
- case "half-up":
930
- return value >= 0 ? Math.floor(value + 0.5) : Math.ceil(value - 0.5);
931
- default: {
932
- const _exhaustive = direction;
933
- throw new Error(`Unknown rounding direction: ${String(_exhaustive)}`);
934
- }
935
- }
936
- }
937
- function normalizeZero2(value) {
938
- return Object.is(value, -0) ? 0 : value;
939
- }
940
- function assertIsInteger(value) {
941
- if (!(typeof value === "number" && Number.isInteger(value))) {
942
- throw new Error(
943
- `Expected an integer, got ${typeof value === "number" ? String(value) : typeof value}`
944
- );
945
- }
946
- }
947
- function assertIsPositiveInteger(value) {
948
- if (!(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
949
- throw new Error(
950
- `Expected a non-negative integer, got ${typeof value === "number" ? String(value) : typeof value}`
951
- );
952
- }
953
- }
954
- function assertIntegerIsPositive(value) {
955
- if (value < 0) {
956
- throw new Error(`Expected a non-negative integer, got ${String(value)}`);
957
- }
958
- }
959
- var Integer = {
960
- /**
961
- * The `Integer` value representing zero.
962
- *
963
- * @remarks
964
- * Pre-allocated singleton — prefer `Integer.zero` over
965
- * `Integer.from(0, 'floor')` to avoid an unnecessary call.
966
- *
967
- * @public
968
- */
969
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- branded type construction: 0 is trivially an integer
970
- zero: 0,
971
- /**
972
- * Type guard that narrows an unknown value to {@link (Integer:type)}.
973
- *
974
- * @example
975
- * ```ts
976
- * const n: unknown = getCount();
977
- * if (Integer.is(n)) {
978
- * // n is Integer here
979
- * config.retryCount = n;
980
- * }
981
- * ```
982
- * @public
983
- */
984
- is: (value) => typeof value === "number" && Number.isInteger(value),
985
- /**
986
- * Assertion guard that throws if the value is not an {@link (Integer:type)}.
987
- *
988
- * @example
989
- * ```ts
990
- * const n: unknown = getCount();
991
- * Integer.assert(n);
992
- * // n is Integer here
993
- * ```
994
- * @public
995
- */
996
- assert: assertIsInteger,
997
- /**
998
- * Coerces a value to an {@link (Integer:type)} by rounding.
999
- *
1000
- * @remarks
1001
- * Accepts `number`, `string`, `Decimal`, or `Integer`. The rounding
1002
- * direction is always required — no invisible defaults.
1003
- *
1004
- * - **number** (including Integer): must be finite and round to a
1005
- * safe integer (`Number.isSafeInteger`). IEEE 754 negative zero is
1006
- * normalized to positive zero.
1007
- * - **string**: must be a valid numeric literal (not empty/whitespace).
1008
- * Parsed via `Number()`, then rounded. The result must be a safe integer.
1009
- * - **Decimal**: delegated to {@link Decimal.toInteger | Decimal.toInteger()}.
1010
- *
1011
- * @example
1012
- * ```ts
1013
- * Integer.from(9.99, 'floor'); // 9
1014
- * Integer.from('1.5', 'ceil'); // 2
1015
- * Integer.from(Decimal.from('2.7'), 'half-up'); // 3
1016
- * ```
1017
- *
1018
- * @throws Error if the value is non-finite, an empty string, an
1019
- * unparseable string, or rounds to a value outside the safe integer range.
1020
- *
1021
- * @public
1022
- */
1023
- from(value, rounding) {
1024
- if (typeof value === "number") {
1025
- if (!Number.isFinite(value)) {
1026
- throw new Error(`Cannot round non-finite value ${String(value)} to an integer`);
1027
- }
1028
- const rounded = normalizeZero2(roundToInteger(value, rounding));
1029
- if (!Number.isSafeInteger(rounded)) {
1030
- throw new Error(
1031
- `Value ${String(value)} rounds to ${String(rounded)}, which is outside the safe integer range`
1032
- );
1033
- }
1034
- return rounded;
1035
- }
1036
- if (typeof value === "string") {
1037
- if (value.trim() === "") {
1038
- throw new Error("Cannot parse empty string as an integer");
1039
- }
1040
- const num = Number(value);
1041
- if (!Number.isFinite(num)) {
1042
- throw new Error(
1043
- `Cannot parse "${value}" as a finite number for integer conversion`
1044
- );
1045
- }
1046
- const rounded = normalizeZero2(roundToInteger(num, rounding));
1047
- if (!Number.isSafeInteger(rounded)) {
1048
- throw new Error(
1049
- `Value "${value}" rounds to ${String(rounded)}, which is outside the safe integer range`
1050
- );
1051
- }
1052
- return rounded;
1053
- }
1054
- if (isDecimal(value)) {
1055
- return value.toInteger(rounding);
1056
- }
1057
- throw new Error(
1058
- `Cannot convert ${typeof value} to Integer; expected string, number, or Decimal`
1059
- );
1060
- },
1061
- /**
1062
- * Convert an {@link (Integer:type)} to a {@link (Decimal:type)}.
1063
- *
1064
- * @remarks
1065
- * This conversion is lossless — every JavaScript integer is exactly
1066
- * representable as a Decimal.
1067
- *
1068
- * @example
1069
- * ```ts
1070
- * const dec = Integer.toDecimal(Integer.from(42, 'floor'));
1071
- * dec.add(Decimal.from('0.5')); // 42.5
1072
- * ```
1073
- * @public
1074
- */
1075
- toDecimal(value) {
1076
- return Decimal.from(value);
1077
- },
1078
- /**
1079
- * Type guard that narrows an {@link (Integer:type)} to {@link (PositiveInteger:type)}.
1080
- *
1081
- * @example
1082
- * ```ts
1083
- * const n = Integer.from(count, 'floor');
1084
- * if (Integer.isPositive(n)) {
1085
- * // n is PositiveInteger here
1086
- * }
1087
- * ```
1088
- * @public
1089
- */
1090
- isPositive: (value) => value >= 0,
1091
- /**
1092
- * Assertion guard that throws if an {@link (Integer:type)} is not a {@link (PositiveInteger:type)}.
1093
- *
1094
- * @example
1095
- * ```ts
1096
- * const n = Integer.from(count, 'floor');
1097
- * Integer.assertIsPositive(n);
1098
- * // n is PositiveInteger here
1099
- * ```
1100
- * @public
1101
- */
1102
- assertIsPositive: assertIntegerIsPositive
1103
- };
1104
- var PositiveInteger = {
1105
- /**
1106
- * Type guard that narrows an unknown value to {@link (PositiveInteger:type)}.
1107
- *
1108
- * @example
1109
- * ```ts
1110
- * const n: unknown = getRetryCount();
1111
- * if (PositiveInteger.is(n)) {
1112
- * // n is PositiveInteger here
1113
- * config.maxRetries = n;
1114
- * }
1115
- * ```
1116
- * @public
1117
- */
1118
- is: (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
1119
- /**
1120
- * Assertion guard that throws if the value is not a {@link (PositiveInteger:type)}.
1121
- *
1122
- * @example
1123
- * ```ts
1124
- * const n: unknown = getRetryCount();
1125
- * PositiveInteger.assert(n);
1126
- * // n is PositiveInteger here
1127
- * ```
1128
- * @public
1129
- */
1130
- assert: assertIsPositiveInteger,
1131
- /**
1132
- * Coerces a value to a {@link (PositiveInteger:type)} by rounding.
1133
- *
1134
- * @remarks
1135
- * Delegates to {@link (Integer:variable).from | Integer.from()} for
1136
- * rounding, then checks the result is non-negative. All error
1137
- * conditions from `Integer.from()` apply (non-finite, empty string,
1138
- * unsafe integer range), plus an additional check that the rounded
1139
- * result is ≥ 0. IEEE 754 negative zero is normalized to positive zero.
1140
- *
1141
- * @example
1142
- * ```ts
1143
- * PositiveInteger.from(2.7, 'floor'); // 2
1144
- * PositiveInteger.from('1.5', 'ceil'); // 2
1145
- * PositiveInteger.from(Decimal.from('3.2'), 'half-up'); // 3
1146
- * ```
1147
- *
1148
- * @throws Error if the value is non-finite, unparseable, outside the
1149
- * safe integer range, or rounds to a negative number.
1150
- *
1151
- * @public
1152
- */
1153
- from(value, rounding) {
1154
- const rounded = Integer.from(value, rounding);
1155
- const normalized = normalizeZero2(rounded);
1156
- if (normalized < 0) {
1157
- throw new Error(
1158
- `Value ${String(value)} rounds to ${String(normalized)}, which is negative`
1159
- );
1160
- }
1161
- return normalized;
1162
- }
1163
- };
1164
- var StreetAddress = {
1165
- create: (address) => {
1166
- return address;
1167
- }
1168
- };
1169
- var Timestamp = {
1170
- create: (value) => {
1171
- return value;
1172
- }
1173
- };
1174
-
1175
- // src/stdlib/refs.ts
1176
- var Ref = {
1177
- create: (step) => {
1178
- return {
1179
- type: step.object,
1180
- id: step.id
1181
- };
1182
- }
1183
- };
1184
-
1185
- // src/stdlib/types.ts
1186
- var WireReadError = class extends Error {
1187
- /**
1188
- * Error class name for `instanceof`-free identification.
1189
- * @internal
1190
- */
1191
- name = "WireReadError";
1192
- };
1193
- var WireWriteError = class extends Error {
1194
- /**
1195
- * Error class name for `instanceof`-free identification.
1196
- * @internal
1197
- */
1198
- name = "WireWriteError";
1199
- };
1200
- var WireParseError = class extends Error {
1201
- name = "WireParseError";
1202
- };
1203
- var _ProtoEnum = class {
1204
- _from;
1205
- _to;
1206
- constructor(fromProto) {
1207
- this._from = new Map(Object.entries(fromProto));
1208
- const to = /* @__PURE__ */ new Map();
1209
- for (const [wire, sdk] of this._from) {
1210
- if (to.has(sdk)) {
1211
- throw new Error(`_ProtoEnum: duplicate SDK value '${sdk}' in fromProto map`);
1212
- }
1213
- to.set(sdk, wire);
1214
- }
1215
- this._to = to;
1216
- }
1217
- /**
1218
- * Convert a proto wire value to an SDK value, or `null` if unknown.
1219
- * @internal
1220
- */
1221
- fromWire(value) {
1222
- return this._from.get(value) ?? null;
1223
- }
1224
- /**
1225
- * Convert an SDK value to a proto wire value, or `null` if unknown.
1226
- * @internal
1227
- */
1228
- toWire(value) {
1229
- return this._to.get(value) ?? null;
1230
- }
1231
- };
1232
- var _ConfigEnum = class {
1233
- _values;
1234
- constructor(values) {
1235
- this._values = new Set(values);
1236
- }
1237
- /**
1238
- * Validate and return the wire value unchanged, or `null` if unknown.
1239
- * @internal
1240
- */
1241
- fromWire(value) {
1242
- return this._values.has(value) ? value : null;
1243
- }
1244
- /**
1245
- * Validate and return the SDK value unchanged, or `null` if unknown.
1246
- * @internal
1247
- */
1248
- toWire(value) {
1249
- return this._values.has(value) ? value : null;
1250
- }
1251
- };
1252
- var _ShapeDescriptor = class {
1253
- /** The type name, used in error messages. */
1254
- typeName;
1255
- /** The field descriptors for this shape. */
1256
- fields;
1257
- /** Optional oneof field descriptors (mixed messages with regular + oneof fields). */
1258
- oneofFields;
1259
- constructor(typeName, fields, oneofFields) {
1260
- this.typeName = typeName;
1261
- this.fields = fields;
1262
- if (oneofFields) {
1263
- this.oneofFields = oneofFields;
1264
- }
1265
- }
1266
- };
1267
- var _UnionDescriptor = class {
1268
- /** The type name, used in error messages. */
1269
- typeName;
1270
- /** The SDK-side discriminant field name (e.g. `'value'`, `'kind'`). */
1271
- discriminantFieldName;
1272
- /** The branch descriptors for this union. */
1273
- branches;
1274
- constructor(typeName, discriminantFieldName, branches) {
1275
- this.typeName = typeName;
1276
- this.discriminantFieldName = discriminantFieldName;
1277
- this.branches = branches;
1278
- }
1279
- };
1280
- function otherFieldNameFor(discriminantFieldName) {
1281
- return "other" + discriminantFieldName.charAt(0).toUpperCase() + discriminantFieldName.slice(1);
1282
- }
1283
- function _isPromiseLike(value) {
1284
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
1285
- if ("then" in value) {
1286
- return typeof value.then === "function";
1287
- }
1288
- }
1289
- return false;
1290
- }
1291
-
1292
- // src/stdlib/transforms.ts
1293
- function _apply(descriptor, strategy, inputObject, typeName = descriptor.typeName) {
1294
- if (inputObject === null || inputObject === void 0) {
1295
- const loc = typeName || "object";
1296
- const received = inputObject === null ? "null" : "undefined";
1297
- throw strategy.createNotObjectError(loc, received);
1298
- }
1299
- if (typeof inputObject !== "object") {
1300
- const loc = typeName || "object";
1301
- throw strategy.createNotObjectError(loc, typeof inputObject);
1302
- }
1303
- const input = inputObject;
1304
- const result = {};
1305
- for (const desc of descriptor.fields) {
1306
- const [key, value] = strategy.applyField(typeName, desc, input, strategy);
1307
- if (value !== void 0) result[key] = value;
1308
- }
1309
- if (descriptor.oneofFields) {
1310
- const regularWireKeys = descriptor.fields.map((f) => f.wire ?? f.type);
1311
- const allOneofBranchKeys = descriptor.oneofFields.flatMap(
1312
- (o) => o.branches.map((b) => b.wireKey)
1313
- );
1314
- const excludeKeys = /* @__PURE__ */ new Set([...regularWireKeys, ...allOneofBranchKeys]);
1315
- for (const oneof of descriptor.oneofFields) {
1316
- strategy.applyOneofField(typeName, oneof, input, strategy, result, excludeKeys);
1317
- const otherField = otherFieldNameFor(oneof.discriminant);
1318
- if (result[oneof.discriminant] === "other" && typeof result[otherField] === "string") {
1319
- excludeKeys.add(result[otherField]);
1320
- }
1321
- }
1322
- }
1323
- return result;
1324
- }
1325
- var _identity = (_strategy, value) => value;
1326
- function _required(fn = _identity) {
1327
- return (strategy, value) => {
1328
- const result = fn(strategy, value);
1329
- if (result === null || result === void 0) {
1330
- throw new WireParseError("Required field is missing");
1331
- }
1332
- return result;
1333
- };
1334
- }
1335
- var _translateDecimal = (strategy, value) => strategy.translateDecimal(value);
1336
- var _translateDateTime = (strategy, value) => strategy.translateDateTime(value);
1337
- function _translateEnum(spec) {
1338
- return (strategy, value) => strategy.translateEnum(spec, value);
1339
- }
1340
- function _translateShape(getDesc) {
1341
- return (strategy, value) => {
1342
- if (value === null || value === void 0) return void 0;
1343
- return _apply(getDesc(), strategy, value);
1344
- };
1345
- }
1346
- function _translateUnion(getDesc) {
1347
- return (strategy, value) => {
1348
- if (value === null || value === void 0) return void 0;
1349
- return strategy.applyUnion(getDesc(), value);
1350
- };
1351
- }
1352
- function _translateArray(elementFn) {
1353
- return (strategy, value) => {
1354
- if (value === null || value === void 0) return void 0;
1355
- if (!Array.isArray(value)) {
1356
- throw new WireParseError(`Expected array but received: ${typeof value}`);
1357
- }
1358
- return value.map((v) => elementFn(strategy, v));
1359
- };
1360
- }
1361
- function _translateMap(keyFn, valueFn) {
1362
- return (strategy, value) => {
1363
- if (value === null || value === void 0) return void 0;
1364
- if (typeof value !== "object" || Array.isArray(value)) {
1365
- throw new WireParseError(
1366
- `Expected object for translateMap but received: ${typeof value}`
1367
- );
1368
- }
1369
- const entries = Object.entries(value);
1370
- return Object.fromEntries(
1371
- entries.map(([k, v]) => {
1372
- const mappedKey = keyFn(strategy, k);
1373
- if (typeof mappedKey !== "string") {
1374
- throw new WireParseError(
1375
- `translateMap: key transform returned ${typeof mappedKey} instead of string`
1376
- );
1377
- }
1378
- return [mappedKey, valueFn(strategy, v)];
1379
- })
1380
- );
1381
- };
1382
- }
1383
-
1384
- // src/stdlib/transform-strategies.ts
1385
- function parseDateString(value) {
1386
- const date = new Date(value);
1387
- if (isNaN(date.getTime())) {
1388
- throw new WireParseError(`Cannot parse '${value}' as Date`);
1389
- }
1390
- return date;
1391
- }
1392
- function enumLookup(spec, value, direction) {
1393
- if (typeof value !== "string") {
1394
- throw new WireParseError(`Expected string enum value but received ${typeof value}`);
1395
- }
1396
- const result = spec[direction](value);
1397
- if (result === null) {
1398
- throw new WireParseError(`Unknown enum value '${value}'`);
1399
- }
1400
- return result;
1401
- }
1402
- var _ProtoWireToType = {
1403
- _brand: "ProtoWireToType",
1404
- createNotObjectError(loc, received) {
1405
- return new WireReadError(`${loc}: Expected an object but received ${received}`);
1406
- },
1407
- applyField(typeName, desc, input, strategy) {
1408
- const from = desc.wire ?? desc.type;
1409
- const to = desc.type;
1410
- const raw = Object.hasOwn(input, from) ? input[from] : void 0;
1411
- try {
1412
- return [to, (desc.transform ?? _identity)(strategy, raw)];
1413
- } catch (e) {
1414
- if (e instanceof WireParseError)
1415
- throw new WireReadError(`${typeName}.${desc.type}: ${e.message}`);
1416
- throw e;
1417
- }
1418
- },
1419
- translateDecimal(value) {
1420
- if (value === null || value === void 0) return void 0;
1421
- if (typeof value !== "object" || !("value" in value)) {
1422
- throw new WireParseError(
1423
- `Cannot parse ${typeof value} as Decimal \u2014 expected {value: string}`
1424
- );
1425
- }
1426
- const raw = String(value.value);
1427
- try {
1428
- return Decimal.from(raw);
1429
- } catch {
1430
- throw new WireParseError(`Cannot parse '${raw}' as Decimal`);
1431
- }
1432
- },
1433
- translateDateTime(value) {
1434
- if (value === null || value === void 0) return void 0;
1435
- if (typeof value !== "string") {
1436
- throw new WireParseError(`Cannot parse ${typeof value} as Date \u2014 expected string`);
1437
- }
1438
- return parseDateString(value);
1439
- },
1440
- translateEnum(spec, value) {
1441
- if (value === null || value === void 0) return void 0;
1442
- return enumLookup(spec, value, "fromWire");
1443
- },
1444
- applyUnion(descriptor, input) {
1445
- if (input === null || input === void 0) {
1446
- throw this.createNotObjectError(descriptor.typeName || "union", String(input));
1447
- }
1448
- if (typeof input !== "object") {
1449
- throw this.createNotObjectError(descriptor.typeName || "union", typeof input);
1450
- }
1451
- const wire = input;
1452
- for (const branch of descriptor.branches) {
1453
- if (Object.hasOwn(wire, branch.wireKey) && wire[branch.wireKey] !== null && wire[branch.wireKey] !== void 0) {
1454
- const branchData = _apply(
1455
- new _ShapeDescriptor(descriptor.typeName, branch.shape),
1456
- this,
1457
- wire[branch.wireKey]
1458
- );
1459
- return { [descriptor.discriminantFieldName]: branch.typeKey, ...branchData };
1460
- }
1461
- }
1462
- const knownWireKeys = new Set(descriptor.branches.map((b) => b.wireKey));
1463
- for (const key of Object.keys(wire)) {
1464
- if (!knownWireKeys.has(key) && wire[key] !== null && wire[key] !== void 0) {
1465
- const otherFieldName = otherFieldNameFor(descriptor.discriminantFieldName);
1466
- return { [descriptor.discriminantFieldName]: "other", [otherFieldName]: key };
1467
- }
1468
- }
1469
- const loc = descriptor.typeName || "union";
1470
- throw new WireReadError(`${loc}: No variant set`);
1471
- },
1472
- applyOneofField(typeName, oneof, input, strategy, result, excludeWireKeys) {
1473
- applyOneofFieldIncoming(typeName, oneof, input, strategy, result, excludeWireKeys);
1474
- }
1475
- };
1476
- var _TypeToProtoWire = {
1477
- _brand: "TypeToProtoWire",
1478
- createNotObjectError(loc, received) {
1479
- return new WireWriteError(`${loc}: Expected an object but received ${received}`);
1480
- },
1481
- applyField(typeName, desc, input, strategy) {
1482
- const from = desc.type;
1483
- const to = desc.wire ?? desc.type;
1484
- const raw = Object.hasOwn(input, from) ? input[from] : void 0;
1485
- try {
1486
- return [to, (desc.transform ?? _identity)(strategy, raw)];
1487
- } catch (e) {
1488
- if (e instanceof WireParseError)
1489
- throw new WireWriteError(`${typeName}.${desc.type}: ${e.message}`);
1490
- throw e;
1491
- }
1492
- },
1493
- translateDecimal(value) {
1494
- if (value === null || value === void 0) return void 0;
1495
- if (!isDecimal(value)) {
1496
- throw new WireParseError(
1497
- `Cannot serialize ${typeof value} as Decimal \u2014 expected Decimal instance`
1498
- );
1499
- }
1500
- return { value: value.toString() };
1501
- },
1502
- translateDateTime(value) {
1503
- if (value === null || value === void 0) return void 0;
1504
- if (!(value instanceof Date)) {
1505
- throw new WireParseError(
1506
- `Cannot serialize ${typeof value} as Date \u2014 expected Date instance`
1507
- );
1508
- }
1509
- if (isNaN(value.getTime())) {
1510
- throw new WireParseError(`Cannot serialize invalid Date (NaN time value)`);
1511
- }
1512
- return value.toISOString();
1513
- },
1514
- translateEnum(spec, value) {
1515
- if (value === null || value === void 0) return void 0;
1516
- return enumLookup(spec, value, "toWire");
1517
- },
1518
- applyUnion(descriptor, input) {
1519
- if (input === null || input === void 0) {
1520
- throw this.createNotObjectError(descriptor.typeName || "union", String(input));
1521
- }
1522
- if (typeof input !== "object") {
1523
- throw this.createNotObjectError(descriptor.typeName || "union", typeof input);
1524
- }
1525
- const sdk = input;
1526
- const discriminant = sdk[descriptor.discriminantFieldName];
1527
- if (typeof discriminant !== "string") {
1528
- const loc = descriptor.typeName || "union";
1529
- throw new WireWriteError(
1530
- `${loc}: Expected a string '${descriptor.discriminantFieldName}' discriminant but received ${discriminant === void 0 ? "undefined" : typeof discriminant}`
1531
- );
1532
- }
1533
- if (discriminant === "other") {
1534
- const loc = descriptor.typeName || "union";
1535
- throw new WireWriteError(
1536
- `${loc}: Cannot serialize 'other' variant back to wire format`
1537
- );
1538
- }
1539
- const branch = descriptor.branches.find((b) => b.typeKey === discriminant);
1540
- if (!branch) {
1541
- const loc = descriptor.typeName || "union";
1542
- throw new WireWriteError(`${loc}: Unknown variant '${discriminant}'`);
1543
- }
1544
- const branchData = _apply(
1545
- new _ShapeDescriptor(descriptor.typeName, branch.shape),
1546
- this,
1547
- sdk
1548
- );
1549
- return { [branch.wireKey]: branchData };
1550
- },
1551
- applyOneofField(typeName, oneof, input, strategy, result, _excludeWireKeys) {
1552
- applyOneofFieldOutgoing(typeName, oneof, input, strategy, result);
1553
- }
1554
- };
1555
- function _configAppContextFromContext(ctx) {
1556
- if (typeof ctx !== "object" || ctx === null || !("clockTime" in ctx)) {
1557
- return {};
1558
- }
1559
- const raw = ctx.clockTime;
1560
- if (raw === void 0 || raw === null) return {};
1561
- if (typeof raw !== "string") {
1562
- throw new WireParseError(
1563
- `Expected clockTime to be a string but received ${typeof raw}`
1564
- );
1565
- }
1566
- return { clockTime: raw };
1567
- }
1568
- var _JsonWireToType = {
1569
- _brand: "JsonWireToType",
1570
- createNotObjectError(loc, received) {
1571
- return new WireReadError(`${loc}: Expected an object but received ${received}`);
1572
- },
1573
- applyField(typeName, desc, input, strategy) {
1574
- const key = desc.type;
1575
- const raw = Object.hasOwn(input, key) ? input[key] : void 0;
1576
- try {
1577
- return [key, (desc.transform ?? _identity)(strategy, raw)];
1578
- } catch (e) {
1579
- if (e instanceof WireParseError)
1580
- throw new WireReadError(`${typeName}.${desc.type}: ${e.message}`);
1581
- throw e;
1582
- }
1583
- },
1584
- translateDecimal(value) {
1585
- if (value === null || value === void 0) return void 0;
1586
- if (typeof value === "string") {
1587
- try {
1588
- return Decimal.from(value);
1589
- } catch {
1590
- throw new WireParseError(`Cannot parse '${value}' as Decimal`);
1591
- }
1592
- }
1593
- if (typeof value === "number") {
1594
- if (!isFinite(value)) {
1595
- throw new WireParseError(
1596
- `Expected a string or finite number but received ${typeof value}`
1597
- );
1598
- }
1599
- return Decimal.from(value);
1600
- }
1601
- throw new WireParseError(
1602
- `Expected a string or finite number but received ${typeof value}`
1603
- );
1604
- },
1605
- translateDateTime(value) {
1606
- if (value === null || value === void 0) return void 0;
1607
- if (typeof value !== "string") {
1608
- throw new WireParseError(`Cannot parse ${typeof value} as Date \u2014 expected string`);
1609
- }
1610
- return parseDateString(value);
1611
- },
1612
- translateEnum(spec, value) {
1613
- if (value === null || value === void 0) return void 0;
1614
- return enumLookup(spec, value, "fromWire");
1615
- },
1616
- applyUnion() {
1617
- throw new Error("applyUnion is not supported for JsonWireToType");
1618
- },
1619
- applyOneofField() {
1620
- throw new Error("applyOneofField is not supported for JsonWireToType");
1621
- }
1622
- };
1623
- function applyOneofFieldIncoming(typeName, oneof, input, strategy, result, excludeWireKeys) {
1624
- for (const branch of oneof.branches) {
1625
- const raw = Object.hasOwn(input, branch.wireKey) ? input[branch.wireKey] : void 0;
1626
- if (raw !== null && raw !== void 0) {
1627
- result[oneof.discriminant] = branch.typeKey;
1628
- try {
1629
- const transformed = branch.transform ? branch.transform(strategy, raw) : raw;
1630
- if (transformed !== void 0) {
1631
- result[branch.typeKey] = transformed;
1632
- }
1633
- } catch (e) {
1634
- if (e instanceof WireParseError) {
1635
- throw new WireReadError(
1636
- `${typeName}.${oneof.discriminant}(${branch.typeKey}): ${e.message}`
1637
- );
1638
- }
1639
- throw e;
1640
- }
1641
- return;
1642
- }
1643
- }
1644
- const knownWireKeys = new Set(oneof.branches.map((b) => b.wireKey));
1645
- for (const key of Object.keys(input)) {
1646
- if (!knownWireKeys.has(key) && !excludeWireKeys.has(key) && input[key] !== null && input[key] !== void 0) {
1647
- result[oneof.discriminant] = "other";
1648
- result[otherFieldNameFor(oneof.discriminant)] = key;
1649
- return;
1650
- }
1651
- }
1652
- if (!oneof.optional) {
1653
- throw new WireReadError(`${typeName}.${oneof.discriminant}: no variant set`);
1654
- }
1655
- }
1656
- function applyOneofFieldOutgoing(typeName, oneof, input, strategy, result) {
1657
- const discriminant = Object.hasOwn(input, oneof.discriminant) ? input[oneof.discriminant] : void 0;
1658
- if (discriminant === void 0 || discriminant === null) {
1659
- if (!oneof.optional) {
1660
- throw new WireWriteError(`${typeName}.${oneof.discriminant}: no variant set`);
1661
- }
1662
- return;
1663
- }
1664
- if (typeof discriminant !== "string") {
1665
- throw new WireWriteError(
1666
- `${typeName}.${oneof.discriminant}: expected string discriminant but received ${typeof discriminant}`
1667
- );
1668
- }
1669
- if (discriminant === "other") {
1670
- throw new WireWriteError(
1671
- `${typeName}.${oneof.discriminant}: cannot serialize 'other' variant back to wire format`
1672
- );
1673
- }
1674
- const branch = oneof.branches.find((b) => b.typeKey === discriminant);
1675
- if (!branch) {
1676
- throw new WireWriteError(
1677
- `${typeName}.${oneof.discriminant}: unknown variant '${discriminant}'`
1678
- );
1679
- }
1680
- const raw = Object.hasOwn(input, branch.typeKey) ? input[branch.typeKey] : void 0;
1681
- try {
1682
- const transformed = branch.transform ? branch.transform(strategy, raw) : raw;
1683
- result[branch.wireKey] = transformed ?? {};
1684
- } catch (e) {
1685
- if (e instanceof WireParseError) {
1686
- throw new WireWriteError(
1687
- `${typeName}.${oneof.discriminant}(${branch.typeKey}): ${e.message}`
1688
- );
1689
- }
1690
- throw e;
1691
- }
1692
- }
1693
- function createJsonWireToType(appCtx) {
1694
- return {
1695
- ..._JsonWireToType,
1696
- translateDateTime(value) {
1697
- if (value === null || value === void 0) {
1698
- if (appCtx.clockTime !== void 0) {
1699
- return parseDateString(appCtx.clockTime);
1700
- }
1701
- return void 0;
1702
- }
1703
- return _JsonWireToType.translateDateTime(value);
1704
- }
1705
- };
1706
- }
1707
- function _applyIncoming(descriptor, inputObject) {
1708
- return _apply(descriptor, _ProtoWireToType, inputObject);
1709
- }
1710
- function _applyOutgoing(descriptor, inputObject) {
1711
- return _apply(descriptor, _TypeToProtoWire, inputObject);
1712
- }
1713
- function _applyConfig(descriptor, inputObject, appCtx) {
1714
- const strategy = appCtx?.clockTime !== void 0 ? createJsonWireToType(appCtx) : _JsonWireToType;
1715
- return _apply(descriptor, strategy, inputObject);
1716
- }
1717
-
1718
- // src/stdlib/to-const.ts
1719
- function toConst(value) {
1720
- if (value === null || typeof value !== "object") {
1721
- return value;
1722
- }
1723
- if (Array.isArray(value)) {
1724
- for (const item of value) {
1725
- toConst(item);
1726
- }
1727
- return Object.freeze(value);
1728
- }
1729
- for (const key of Object.keys(value)) {
1730
- toConst(value[key]);
1731
- }
1732
- return Object.freeze(value);
1733
- }
1734
- // Annotate the CommonJS export names for ESM import in node:
1735
- 0 && (module.exports = {
1736
- DEFAULT_DIV_PRECISION,
1737
- Decimal,
1738
- DecimalRoundingPresets,
1739
- Integer,
1740
- PositiveInteger,
1741
- Ref,
1742
- StreetAddress,
1743
- Timestamp,
1744
- WireReadError,
1745
- WireWriteError,
1746
- _ConfigEnum,
1747
- _JsonWireToType,
1748
- _ProtoEnum,
1749
- _ProtoWireToType,
1750
- _ShapeDescriptor,
1751
- _TypeToProtoWire,
1752
- _UnionDescriptor,
1753
- _apply,
1754
- _applyConfig,
1755
- _applyIncoming,
1756
- _applyOutgoing,
1757
- _configAppContextFromContext,
1758
- _identity,
1759
- _isPromiseLike,
1760
- _required,
1761
- _translateArray,
1762
- _translateDateTime,
1763
- _translateDecimal,
1764
- _translateEnum,
1765
- _translateMap,
1766
- _translateShape,
1767
- _translateUnion,
1768
- isDecimal,
1769
- toConst
1770
- });