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