@stripe/extensibility-sdk 0.26.0 → 1.0.0

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