@dodopayments/nextjs 0.2.2 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -2324,6 +2324,7 @@ function requireReact_production () {
2324
2324
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
2325
2325
  REACT_MEMO_TYPE = Symbol.for("react.memo"),
2326
2326
  REACT_LAZY_TYPE = Symbol.for("react.lazy"),
2327
+ REACT_ACTIVITY_TYPE = Symbol.for("react.activity"),
2327
2328
  MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
2328
2329
  function getIteratorFn(maybeIterable) {
2329
2330
  if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
@@ -2375,28 +2376,22 @@ function requireReact_production () {
2375
2376
  pureComponentPrototype.constructor = PureComponent;
2376
2377
  assign(pureComponentPrototype, Component.prototype);
2377
2378
  pureComponentPrototype.isPureReactComponent = true;
2378
- var isArrayImpl = Array.isArray,
2379
- ReactSharedInternals = { H: null, A: null, T: null, S: null, V: null },
2379
+ var isArrayImpl = Array.isArray;
2380
+ function noop() {}
2381
+ var ReactSharedInternals = { H: null, A: null, T: null, S: null },
2380
2382
  hasOwnProperty = Object.prototype.hasOwnProperty;
2381
- function ReactElement(type, key, self, source, owner, props) {
2382
- self = props.ref;
2383
+ function ReactElement(type, key, props) {
2384
+ var refProp = props.ref;
2383
2385
  return {
2384
2386
  $$typeof: REACT_ELEMENT_TYPE,
2385
2387
  type: type,
2386
2388
  key: key,
2387
- ref: void 0 !== self ? self : null,
2389
+ ref: void 0 !== refProp ? refProp : null,
2388
2390
  props: props
2389
2391
  };
2390
2392
  }
2391
2393
  function cloneAndReplaceKey(oldElement, newKey) {
2392
- return ReactElement(
2393
- oldElement.type,
2394
- newKey,
2395
- void 0,
2396
- void 0,
2397
- void 0,
2398
- oldElement.props
2399
- );
2394
+ return ReactElement(oldElement.type, newKey, oldElement.props);
2400
2395
  }
2401
2396
  function isValidElement(object) {
2402
2397
  return (
@@ -2420,7 +2415,6 @@ function requireReact_production () {
2420
2415
  ? escape("" + element.key)
2421
2416
  : index.toString(36);
2422
2417
  }
2423
- function noop$1() {}
2424
2418
  function resolveThenable(thenable) {
2425
2419
  switch (thenable.status) {
2426
2420
  case "fulfilled":
@@ -2430,7 +2424,7 @@ function requireReact_production () {
2430
2424
  default:
2431
2425
  switch (
2432
2426
  ("string" === typeof thenable.status
2433
- ? thenable.then(noop$1, noop$1)
2427
+ ? thenable.then(noop, noop)
2434
2428
  : ((thenable.status = "pending"),
2435
2429
  thenable.then(
2436
2430
  function (fulfilledValue) {
@@ -2591,68 +2585,69 @@ function requireReact_production () {
2591
2585
  throw payload._result;
2592
2586
  }
2593
2587
  var reportGlobalError =
2594
- "function" === typeof reportError
2595
- ? reportError
2596
- : function (error) {
2597
- if (
2598
- "object" === typeof window &&
2599
- "function" === typeof window.ErrorEvent
2600
- ) {
2601
- var event = new window.ErrorEvent("error", {
2602
- bubbles: true,
2603
- cancelable: true,
2604
- message:
2605
- "object" === typeof error &&
2606
- null !== error &&
2607
- "string" === typeof error.message
2608
- ? String(error.message)
2609
- : String(error),
2610
- error: error
2611
- });
2612
- if (!window.dispatchEvent(event)) return;
2613
- } else if (
2614
- "object" === typeof process &&
2615
- "function" === typeof process.emit
2616
- ) {
2617
- process.emit("uncaughtException", error);
2618
- return;
2619
- }
2620
- console.error(error);
2621
- };
2622
- function noop() {}
2623
- react_production.Children = {
2624
- map: mapChildren,
2625
- forEach: function (children, forEachFunc, forEachContext) {
2626
- mapChildren(
2627
- children,
2628
- function () {
2629
- forEachFunc.apply(this, arguments);
2630
- },
2631
- forEachContext
2632
- );
2633
- },
2634
- count: function (children) {
2635
- var n = 0;
2636
- mapChildren(children, function () {
2637
- n++;
2638
- });
2639
- return n;
2640
- },
2641
- toArray: function (children) {
2642
- return (
2643
- mapChildren(children, function (child) {
2644
- return child;
2645
- }) || []
2646
- );
2647
- },
2648
- only: function (children) {
2649
- if (!isValidElement(children))
2650
- throw Error(
2651
- "React.Children.only expected to receive a single React element child."
2588
+ "function" === typeof reportError
2589
+ ? reportError
2590
+ : function (error) {
2591
+ if (
2592
+ "object" === typeof window &&
2593
+ "function" === typeof window.ErrorEvent
2594
+ ) {
2595
+ var event = new window.ErrorEvent("error", {
2596
+ bubbles: true,
2597
+ cancelable: true,
2598
+ message:
2599
+ "object" === typeof error &&
2600
+ null !== error &&
2601
+ "string" === typeof error.message
2602
+ ? String(error.message)
2603
+ : String(error),
2604
+ error: error
2605
+ });
2606
+ if (!window.dispatchEvent(event)) return;
2607
+ } else if (
2608
+ "object" === typeof process &&
2609
+ "function" === typeof process.emit
2610
+ ) {
2611
+ process.emit("uncaughtException", error);
2612
+ return;
2613
+ }
2614
+ console.error(error);
2615
+ },
2616
+ Children = {
2617
+ map: mapChildren,
2618
+ forEach: function (children, forEachFunc, forEachContext) {
2619
+ mapChildren(
2620
+ children,
2621
+ function () {
2622
+ forEachFunc.apply(this, arguments);
2623
+ },
2624
+ forEachContext
2652
2625
  );
2653
- return children;
2654
- }
2655
- };
2626
+ },
2627
+ count: function (children) {
2628
+ var n = 0;
2629
+ mapChildren(children, function () {
2630
+ n++;
2631
+ });
2632
+ return n;
2633
+ },
2634
+ toArray: function (children) {
2635
+ return (
2636
+ mapChildren(children, function (child) {
2637
+ return child;
2638
+ }) || []
2639
+ );
2640
+ },
2641
+ only: function (children) {
2642
+ if (!isValidElement(children))
2643
+ throw Error(
2644
+ "React.Children.only expected to receive a single React element child."
2645
+ );
2646
+ return children;
2647
+ }
2648
+ };
2649
+ react_production.Activity = REACT_ACTIVITY_TYPE;
2650
+ react_production.Children = Children;
2656
2651
  react_production.Component = Component;
2657
2652
  react_production.Fragment = REACT_FRAGMENT_TYPE;
2658
2653
  react_production.Profiler = REACT_PROFILER_TYPE;
@@ -2672,18 +2667,18 @@ function requireReact_production () {
2672
2667
  return fn.apply(null, arguments);
2673
2668
  };
2674
2669
  };
2670
+ react_production.cacheSignal = function () {
2671
+ return null;
2672
+ };
2675
2673
  react_production.cloneElement = function (element, config, children) {
2676
2674
  if (null === element || void 0 === element)
2677
2675
  throw Error(
2678
2676
  "The argument must be a React element, but you passed " + element + "."
2679
2677
  );
2680
2678
  var props = assign({}, element.props),
2681
- key = element.key,
2682
- owner = void 0;
2679
+ key = element.key;
2683
2680
  if (null != config)
2684
- for (propName in (void 0 !== config.ref && (owner = void 0),
2685
- void 0 !== config.key && (key = "" + config.key),
2686
- config))
2681
+ for (propName in (void 0 !== config.key && (key = "" + config.key), config))
2687
2682
  !hasOwnProperty.call(config, propName) ||
2688
2683
  "key" === propName ||
2689
2684
  "__self" === propName ||
@@ -2697,7 +2692,7 @@ function requireReact_production () {
2697
2692
  childArray[i] = arguments[i + 2];
2698
2693
  props.children = childArray;
2699
2694
  }
2700
- return ReactElement(element.type, key, void 0, void 0, owner, props);
2695
+ return ReactElement(element.type, key, props);
2701
2696
  };
2702
2697
  react_production.createContext = function (defaultValue) {
2703
2698
  defaultValue = {
@@ -2737,7 +2732,7 @@ function requireReact_production () {
2737
2732
  for (propName in ((childrenLength = type.defaultProps), childrenLength))
2738
2733
  void 0 === props[propName] &&
2739
2734
  (props[propName] = childrenLength[propName]);
2740
- return ReactElement(type, key, void 0, void 0, null, props);
2735
+ return ReactElement(type, key, props);
2741
2736
  };
2742
2737
  react_production.createRef = function () {
2743
2738
  return { current: null };
@@ -2776,7 +2771,10 @@ function requireReact_production () {
2776
2771
  } catch (error) {
2777
2772
  reportGlobalError(error);
2778
2773
  } finally {
2779
- ReactSharedInternals.T = prevTransition;
2774
+ null !== prevTransition &&
2775
+ null !== currentTransition.types &&
2776
+ (prevTransition.types = currentTransition.types),
2777
+ (ReactSharedInternals.T = prevTransition);
2780
2778
  }
2781
2779
  };
2782
2780
  react_production.unstable_useCacheRefresh = function () {
@@ -2798,13 +2796,11 @@ function requireReact_production () {
2798
2796
  react_production.useDeferredValue = function (value, initialValue) {
2799
2797
  return ReactSharedInternals.H.useDeferredValue(value, initialValue);
2800
2798
  };
2801
- react_production.useEffect = function (create, createDeps, update) {
2802
- var dispatcher = ReactSharedInternals.H;
2803
- if ("function" === typeof update)
2804
- throw Error(
2805
- "useEffect CRUD overload is not enabled in this build of React."
2806
- );
2807
- return dispatcher.useEffect(create, createDeps);
2799
+ react_production.useEffect = function (create, deps) {
2800
+ return ReactSharedInternals.H.useEffect(create, deps);
2801
+ };
2802
+ react_production.useEffectEvent = function (callback) {
2803
+ return ReactSharedInternals.H.useEffectEvent(callback);
2808
2804
  };
2809
2805
  react_production.useId = function () {
2810
2806
  return ReactSharedInternals.H.useId();
@@ -2847,7 +2843,7 @@ function requireReact_production () {
2847
2843
  react_production.useTransition = function () {
2848
2844
  return ReactSharedInternals.H.useTransition();
2849
2845
  };
2850
- react_production.version = "19.1.0";
2846
+ react_production.version = "19.2.0";
2851
2847
  return react_production;
2852
2848
  }
2853
2849
 
@@ -2918,6 +2914,7 @@ function requireReact_development () {
2918
2914
  this.refs = emptyObject;
2919
2915
  this.updater = updater || ReactNoopUpdateQueue;
2920
2916
  }
2917
+ function noop() {}
2921
2918
  function testStringCoercion(value) {
2922
2919
  return "" + value;
2923
2920
  }
@@ -2977,7 +2974,7 @@ function requireReact_development () {
2977
2974
  case REACT_PORTAL_TYPE:
2978
2975
  return "Portal";
2979
2976
  case REACT_CONTEXT_TYPE:
2980
- return (type.displayName || "Context") + ".Provider";
2977
+ return type.displayName || "Context";
2981
2978
  case REACT_CONSUMER_TYPE:
2982
2979
  return (type._context.displayName || "Context") + ".Consumer";
2983
2980
  case REACT_FORWARD_REF_TYPE:
@@ -3057,17 +3054,8 @@ function requireReact_development () {
3057
3054
  componentName = this.props.ref;
3058
3055
  return void 0 !== componentName ? componentName : null;
3059
3056
  }
3060
- function ReactElement(
3061
- type,
3062
- key,
3063
- self,
3064
- source,
3065
- owner,
3066
- props,
3067
- debugStack,
3068
- debugTask
3069
- ) {
3070
- self = props.ref;
3057
+ function ReactElement(type, key, props, owner, debugStack, debugTask) {
3058
+ var refProp = props.ref;
3071
3059
  type = {
3072
3060
  $$typeof: REACT_ELEMENT_TYPE,
3073
3061
  type: type,
@@ -3075,7 +3063,7 @@ function requireReact_development () {
3075
3063
  props: props,
3076
3064
  _owner: owner
3077
3065
  };
3078
- null !== (void 0 !== self ? self : null)
3066
+ null !== (void 0 !== refProp ? refProp : null)
3079
3067
  ? Object.defineProperty(type, "ref", {
3080
3068
  enumerable: false,
3081
3069
  get: elementRefGetterWithDeprecationWarning
@@ -3113,10 +3101,8 @@ function requireReact_development () {
3113
3101
  newKey = ReactElement(
3114
3102
  oldElement.type,
3115
3103
  newKey,
3116
- void 0,
3117
- void 0,
3118
- oldElement._owner,
3119
3104
  oldElement.props,
3105
+ oldElement._owner,
3120
3106
  oldElement._debugStack,
3121
3107
  oldElement._debugTask
3122
3108
  );
@@ -3124,6 +3110,18 @@ function requireReact_development () {
3124
3110
  (newKey._store.validated = oldElement._store.validated);
3125
3111
  return newKey;
3126
3112
  }
3113
+ function validateChildKeys(node) {
3114
+ isValidElement(node)
3115
+ ? node._store && (node._store.validated = 1)
3116
+ : "object" === typeof node &&
3117
+ null !== node &&
3118
+ node.$$typeof === REACT_LAZY_TYPE &&
3119
+ ("fulfilled" === node._payload.status
3120
+ ? isValidElement(node._payload.value) &&
3121
+ node._payload.value._store &&
3122
+ (node._payload.value._store.validated = 1)
3123
+ : node._store && (node._store.validated = 1));
3124
+ }
3127
3125
  function isValidElement(object) {
3128
3126
  return (
3129
3127
  "object" === typeof object &&
@@ -3147,7 +3145,6 @@ function requireReact_development () {
3147
3145
  ? (checkKeyStringCoercion(element.key), escape("" + element.key))
3148
3146
  : index.toString(36);
3149
3147
  }
3150
- function noop$1() {}
3151
3148
  function resolveThenable(thenable) {
3152
3149
  switch (thenable.status) {
3153
3150
  case "fulfilled":
@@ -3157,7 +3154,7 @@ function requireReact_development () {
3157
3154
  default:
3158
3155
  switch (
3159
3156
  ("string" === typeof thenable.status
3160
- ? thenable.then(noop$1, noop$1)
3157
+ ? thenable.then(noop, noop)
3161
3158
  : ((thenable.status = "pending"),
3162
3159
  thenable.then(
3163
3160
  function (fulfilledValue) {
@@ -3319,35 +3316,56 @@ function requireReact_development () {
3319
3316
  }
3320
3317
  function lazyInitializer(payload) {
3321
3318
  if (-1 === payload._status) {
3322
- var ctor = payload._result;
3323
- ctor = ctor();
3324
- ctor.then(
3319
+ var ioInfo = payload._ioInfo;
3320
+ null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
3321
+ ioInfo = payload._result;
3322
+ var thenable = ioInfo();
3323
+ thenable.then(
3325
3324
  function (moduleObject) {
3326
- if (0 === payload._status || -1 === payload._status)
3327
- (payload._status = 1), (payload._result = moduleObject);
3325
+ if (0 === payload._status || -1 === payload._status) {
3326
+ payload._status = 1;
3327
+ payload._result = moduleObject;
3328
+ var _ioInfo = payload._ioInfo;
3329
+ null != _ioInfo && (_ioInfo.end = performance.now());
3330
+ void 0 === thenable.status &&
3331
+ ((thenable.status = "fulfilled"),
3332
+ (thenable.value = moduleObject));
3333
+ }
3328
3334
  },
3329
3335
  function (error) {
3330
- if (0 === payload._status || -1 === payload._status)
3331
- (payload._status = 2), (payload._result = error);
3336
+ if (0 === payload._status || -1 === payload._status) {
3337
+ payload._status = 2;
3338
+ payload._result = error;
3339
+ var _ioInfo2 = payload._ioInfo;
3340
+ null != _ioInfo2 && (_ioInfo2.end = performance.now());
3341
+ void 0 === thenable.status &&
3342
+ ((thenable.status = "rejected"), (thenable.reason = error));
3343
+ }
3332
3344
  }
3333
3345
  );
3346
+ ioInfo = payload._ioInfo;
3347
+ if (null != ioInfo) {
3348
+ ioInfo.value = thenable;
3349
+ var displayName = thenable.displayName;
3350
+ "string" === typeof displayName && (ioInfo.name = displayName);
3351
+ }
3334
3352
  -1 === payload._status &&
3335
- ((payload._status = 0), (payload._result = ctor));
3353
+ ((payload._status = 0), (payload._result = thenable));
3336
3354
  }
3337
3355
  if (1 === payload._status)
3338
3356
  return (
3339
- (ctor = payload._result),
3340
- void 0 === ctor &&
3357
+ (ioInfo = payload._result),
3358
+ void 0 === ioInfo &&
3341
3359
  console.error(
3342
3360
  "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
3343
- ctor
3361
+ ioInfo
3344
3362
  ),
3345
- "default" in ctor ||
3363
+ "default" in ioInfo ||
3346
3364
  console.error(
3347
3365
  "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",
3348
- ctor
3366
+ ioInfo
3349
3367
  ),
3350
- ctor.default
3368
+ ioInfo.default
3351
3369
  );
3352
3370
  throw payload._result;
3353
3371
  }
@@ -3359,7 +3377,9 @@ function requireReact_development () {
3359
3377
  );
3360
3378
  return dispatcher;
3361
3379
  }
3362
- function noop() {}
3380
+ function releaseAsyncTransition() {
3381
+ ReactSharedInternals.asyncTransitions--;
3382
+ }
3363
3383
  function enqueueTask(task) {
3364
3384
  if (null === enqueueTaskImpl)
3365
3385
  try {
@@ -3451,8 +3471,8 @@ function requireReact_development () {
3451
3471
  REACT_PORTAL_TYPE = Symbol.for("react.portal"),
3452
3472
  REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
3453
3473
  REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
3454
- REACT_PROFILER_TYPE = Symbol.for("react.profiler");
3455
- var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
3474
+ REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
3475
+ REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
3456
3476
  REACT_CONTEXT_TYPE = Symbol.for("react.context"),
3457
3477
  REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
3458
3478
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
@@ -3495,16 +3515,15 @@ function requireReact_development () {
3495
3515
  this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
3496
3516
  };
3497
3517
  var deprecatedAPIs = {
3498
- isMounted: [
3499
- "isMounted",
3500
- "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
3501
- ],
3502
- replaceState: [
3503
- "replaceState",
3504
- "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
3505
- ]
3506
- },
3507
- fnName;
3518
+ isMounted: [
3519
+ "isMounted",
3520
+ "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
3521
+ ],
3522
+ replaceState: [
3523
+ "replaceState",
3524
+ "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
3525
+ ]
3526
+ };
3508
3527
  for (fnName in deprecatedAPIs)
3509
3528
  deprecatedAPIs.hasOwnProperty(fnName) &&
3510
3529
  defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
@@ -3520,8 +3539,8 @@ function requireReact_development () {
3520
3539
  A: null,
3521
3540
  T: null,
3522
3541
  S: null,
3523
- V: null,
3524
3542
  actQueue: null,
3543
+ asyncTransitions: 0,
3525
3544
  isBatchingLegacy: false,
3526
3545
  didScheduleLegacyUpdate: false,
3527
3546
  didUsePromise: false,
@@ -3536,15 +3555,16 @@ function requireReact_development () {
3536
3555
  return null;
3537
3556
  };
3538
3557
  deprecatedAPIs = {
3539
- "react-stack-bottom-frame": function (callStackForError) {
3558
+ react_stack_bottom_frame: function (callStackForError) {
3540
3559
  return callStackForError();
3541
3560
  }
3542
3561
  };
3543
3562
  var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
3544
3563
  var didWarnAboutElementRef = {};
3545
- var unknownOwnerDebugStack = deprecatedAPIs[
3546
- "react-stack-bottom-frame"
3547
- ].bind(deprecatedAPIs, UnknownOwner)();
3564
+ var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
3565
+ deprecatedAPIs,
3566
+ UnknownOwner
3567
+ )();
3548
3568
  var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
3549
3569
  var didWarnAboutMaps = false,
3550
3570
  userProvidedKeyEscapeRegex = /\/+/g,
@@ -3596,7 +3616,7 @@ function requireReact_development () {
3596
3616
  return resolveDispatcher().useMemoCache(size);
3597
3617
  }
3598
3618
  });
3599
- exports.Children = {
3619
+ var fnName = {
3600
3620
  map: mapChildren,
3601
3621
  forEach: function (children, forEachFunc, forEachContext) {
3602
3622
  mapChildren(
@@ -3629,6 +3649,8 @@ function requireReact_development () {
3629
3649
  return children;
3630
3650
  }
3631
3651
  };
3652
+ exports.Activity = REACT_ACTIVITY_TYPE;
3653
+ exports.Children = fnName;
3632
3654
  exports.Component = Component;
3633
3655
  exports.Fragment = REACT_FRAGMENT_TYPE;
3634
3656
  exports.Profiler = REACT_PROFILER_TYPE;
@@ -3754,6 +3776,9 @@ function requireReact_development () {
3754
3776
  return fn.apply(null, arguments);
3755
3777
  };
3756
3778
  };
3779
+ exports.cacheSignal = function () {
3780
+ return null;
3781
+ };
3757
3782
  exports.captureOwnerStack = function () {
3758
3783
  var getCurrentStack = ReactSharedInternals.getCurrentStack;
3759
3784
  return null === getCurrentStack ? null : getCurrentStack();
@@ -3806,16 +3831,13 @@ function requireReact_development () {
3806
3831
  props = ReactElement(
3807
3832
  element.type,
3808
3833
  key,
3809
- void 0,
3810
- void 0,
3811
- owner,
3812
3834
  props,
3835
+ owner,
3813
3836
  element._debugStack,
3814
3837
  element._debugTask
3815
3838
  );
3816
3839
  for (key = 2; key < arguments.length; key++)
3817
- (owner = arguments[key]),
3818
- isValidElement(owner) && owner._store && (owner._store.validated = 1);
3840
+ validateChildKeys(arguments[key]);
3819
3841
  return props;
3820
3842
  };
3821
3843
  exports.createContext = function (defaultValue) {
@@ -3837,12 +3859,10 @@ function requireReact_development () {
3837
3859
  return defaultValue;
3838
3860
  };
3839
3861
  exports.createElement = function (type, config, children) {
3840
- for (var i = 2; i < arguments.length; i++) {
3841
- var node = arguments[i];
3842
- isValidElement(node) && node._store && (node._store.validated = 1);
3843
- }
3862
+ for (var i = 2; i < arguments.length; i++)
3863
+ validateChildKeys(arguments[i]);
3844
3864
  i = {};
3845
- node = null;
3865
+ var key = null;
3846
3866
  if (null != config)
3847
3867
  for (propName in (didWarnAboutOldJSXRuntime ||
3848
3868
  !("__self" in config) ||
@@ -3852,7 +3872,7 @@ function requireReact_development () {
3852
3872
  "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
3853
3873
  )),
3854
3874
  hasValidKey(config) &&
3855
- (checkKeyStringCoercion(config.key), (node = "" + config.key)),
3875
+ (checkKeyStringCoercion(config.key), (key = "" + config.key)),
3856
3876
  config))
3857
3877
  hasOwnProperty.call(config, propName) &&
3858
3878
  "key" !== propName &&
@@ -3874,7 +3894,7 @@ function requireReact_development () {
3874
3894
  if (type && type.defaultProps)
3875
3895
  for (propName in ((childrenLength = type.defaultProps), childrenLength))
3876
3896
  void 0 === i[propName] && (i[propName] = childrenLength[propName]);
3877
- node &&
3897
+ key &&
3878
3898
  defineKeyPropWarningGetter(
3879
3899
  i,
3880
3900
  "function" === typeof type
@@ -3884,11 +3904,9 @@ function requireReact_development () {
3884
3904
  var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
3885
3905
  return ReactElement(
3886
3906
  type,
3887
- node,
3888
- void 0,
3889
- void 0,
3890
- getOwner(),
3907
+ key,
3891
3908
  i,
3909
+ getOwner(),
3892
3910
  propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
3893
3911
  propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
3894
3912
  );
@@ -3941,11 +3959,24 @@ function requireReact_development () {
3941
3959
  };
3942
3960
  exports.isValidElement = isValidElement;
3943
3961
  exports.lazy = function (ctor) {
3944
- return {
3945
- $$typeof: REACT_LAZY_TYPE,
3946
- _payload: { _status: -1, _result: ctor },
3947
- _init: lazyInitializer
3948
- };
3962
+ ctor = { _status: -1, _result: ctor };
3963
+ var lazyType = {
3964
+ $$typeof: REACT_LAZY_TYPE,
3965
+ _payload: ctor,
3966
+ _init: lazyInitializer
3967
+ },
3968
+ ioInfo = {
3969
+ name: "lazy",
3970
+ start: -1,
3971
+ end: -1,
3972
+ value: null,
3973
+ owner: null,
3974
+ debugStack: Error("react-stack-top-frame"),
3975
+ debugTask: console.createTask ? console.createTask("lazy()") : null
3976
+ };
3977
+ ctor._ioInfo = ioInfo;
3978
+ lazyType._debugInfo = [{ awaited: ioInfo }];
3979
+ return lazyType;
3949
3980
  };
3950
3981
  exports.memo = function (type, compare) {
3951
3982
  null == type &&
@@ -3978,8 +4009,8 @@ function requireReact_development () {
3978
4009
  exports.startTransition = function (scope) {
3979
4010
  var prevTransition = ReactSharedInternals.T,
3980
4011
  currentTransition = {};
3981
- ReactSharedInternals.T = currentTransition;
3982
4012
  currentTransition._updatedFibers = new Set();
4013
+ ReactSharedInternals.T = currentTransition;
3983
4014
  try {
3984
4015
  var returnValue = scope(),
3985
4016
  onStartTransitionFinish = ReactSharedInternals.S;
@@ -3988,7 +4019,9 @@ function requireReact_development () {
3988
4019
  "object" === typeof returnValue &&
3989
4020
  null !== returnValue &&
3990
4021
  "function" === typeof returnValue.then &&
3991
- returnValue.then(noop, reportGlobalError);
4022
+ (ReactSharedInternals.asyncTransitions++,
4023
+ returnValue.then(releaseAsyncTransition, releaseAsyncTransition),
4024
+ returnValue.then(noop, reportGlobalError));
3992
4025
  } catch (error) {
3993
4026
  reportGlobalError(error);
3994
4027
  } finally {
@@ -4000,6 +4033,14 @@ function requireReact_development () {
4000
4033
  console.warn(
4001
4034
  "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
4002
4035
  )),
4036
+ null !== prevTransition &&
4037
+ null !== currentTransition.types &&
4038
+ (null !== prevTransition.types &&
4039
+ prevTransition.types !== currentTransition.types &&
4040
+ console.error(
4041
+ "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
4042
+ ),
4043
+ (prevTransition.types = currentTransition.types)),
4003
4044
  (ReactSharedInternals.T = prevTransition);
4004
4045
  }
4005
4046
  };
@@ -4033,17 +4074,15 @@ function requireReact_development () {
4033
4074
  exports.useDeferredValue = function (value, initialValue) {
4034
4075
  return resolveDispatcher().useDeferredValue(value, initialValue);
4035
4076
  };
4036
- exports.useEffect = function (create, createDeps, update) {
4077
+ exports.useEffect = function (create, deps) {
4037
4078
  null == create &&
4038
4079
  console.warn(
4039
4080
  "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
4040
4081
  );
4041
- var dispatcher = resolveDispatcher();
4042
- if ("function" === typeof update)
4043
- throw Error(
4044
- "useEffect CRUD overload is not enabled in this build of React."
4045
- );
4046
- return dispatcher.useEffect(create, createDeps);
4082
+ return resolveDispatcher().useEffect(create, deps);
4083
+ };
4084
+ exports.useEffectEvent = function (callback) {
4085
+ return resolveDispatcher().useEffectEvent(callback);
4047
4086
  };
4048
4087
  exports.useId = function () {
4049
4088
  return resolveDispatcher().useId();
@@ -4094,7 +4133,7 @@ function requireReact_development () {
4094
4133
  exports.useTransition = function () {
4095
4134
  return resolveDispatcher().useTransition();
4096
4135
  };
4097
- exports.version = "19.1.0";
4136
+ exports.version = "19.2.0";
4098
4137
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
4099
4138
  "function" ===
4100
4139
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
@@ -9305,7 +9344,7 @@ const unknownType = ZodUnknown.create;
9305
9344
  ZodNever.create;
9306
9345
  const arrayType = ZodArray.create;
9307
9346
  const objectType = ZodObject.create;
9308
- ZodUnion.create;
9347
+ const unionType = ZodUnion.create;
9309
9348
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
9310
9349
  ZodIntersection.create;
9311
9350
  ZodTuple.create;
@@ -9524,7 +9563,7 @@ const safeJSON = (text) => {
9524
9563
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9525
9564
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9526
9565
 
9527
- const VERSION = '2.2.0'; // x-release-please-version
9566
+ const VERSION = '2.4.6'; // x-release-please-version
9528
9567
 
9529
9568
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9530
9569
  /**
@@ -10274,6 +10313,9 @@ class CheckoutSessions extends APIResource {
10274
10313
  create(body, options) {
10275
10314
  return this._client.post('/checkouts', { body, ...options });
10276
10315
  }
10316
+ retrieve(id, options) {
10317
+ return this._client.get(path `/checkouts/${id}`, options);
10318
+ }
10277
10319
  }
10278
10320
 
10279
10321
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -10952,1395 +10994,320 @@ let Headers$1 = class Headers extends APIResource {
10952
10994
  }
10953
10995
  };
10954
10996
 
10955
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
10956
- let Webhooks$1 = class Webhooks extends APIResource {
10957
- constructor() {
10958
- super(...arguments);
10959
- this.headers = new Headers$1(this._client);
10960
- }
10961
- /**
10962
- * Create a new webhook
10963
- */
10964
- create(body, options) {
10965
- return this._client.post('/webhooks', { body, ...options });
10966
- }
10967
- /**
10968
- * Get a webhook by id
10969
- */
10970
- retrieve(webhookID, options) {
10971
- return this._client.get(path `/webhooks/${webhookID}`, options);
10997
+ var dist = {};
10998
+
10999
+ var timing_safe_equal = {};
11000
+
11001
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
11002
+ timing_safe_equal.timingSafeEqual = void 0;
11003
+ function assert(expr, msg = "") {
11004
+ if (!expr) {
11005
+ throw new Error(msg);
10972
11006
  }
10973
- /**
10974
- * Patch a webhook by id
10975
- */
10976
- update(webhookID, body, options) {
10977
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11007
+ }
11008
+ function timingSafeEqual(a, b) {
11009
+ if (a.byteLength !== b.byteLength) {
11010
+ return false;
10978
11011
  }
10979
- /**
10980
- * List all webhooks
10981
- */
10982
- list(query = {}, options) {
10983
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11012
+ if (!(a instanceof DataView)) {
11013
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
10984
11014
  }
10985
- /**
10986
- * Delete a webhook by id
10987
- */
10988
- delete(webhookID, options) {
10989
- return this._client.delete(path `/webhooks/${webhookID}`, {
10990
- ...options,
10991
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
10992
- });
11015
+ if (!(b instanceof DataView)) {
11016
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
10993
11017
  }
10994
- /**
10995
- * Get webhook secret by id
10996
- */
10997
- retrieveSecret(webhookID, options) {
10998
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11018
+ assert(a instanceof DataView);
11019
+ assert(b instanceof DataView);
11020
+ const length = a.byteLength;
11021
+ let out = 0;
11022
+ let i = -1;
11023
+ while (++i < length) {
11024
+ out |= a.getUint8(i) ^ b.getUint8(i);
10999
11025
  }
11000
- };
11001
- Webhooks$1.Headers = Headers$1;
11026
+ return out === 0;
11027
+ }
11028
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
11002
11029
 
11003
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11030
+ var base64$1 = {};
11031
+
11032
+ // Copyright (C) 2016 Dmitry Chestnykh
11033
+ // MIT License. See LICENSE file for details.
11034
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
11035
+ var extendStatics = function (d, b) {
11036
+ extendStatics = Object.setPrototypeOf ||
11037
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11038
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11039
+ return extendStatics(d, b);
11040
+ };
11041
+ return function (d, b) {
11042
+ extendStatics(d, b);
11043
+ function __() { this.constructor = d; }
11044
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11045
+ };
11046
+ })();
11047
+ Object.defineProperty(base64$1, "__esModule", { value: true });
11004
11048
  /**
11005
- * Read an environment variable.
11006
- *
11007
- * Trims beginning and trailing whitespace.
11008
- *
11009
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11049
+ * Package base64 implements Base64 encoding and decoding.
11010
11050
  */
11011
- const readEnv = (env) => {
11012
- if (typeof globalThis.process !== 'undefined') {
11013
- return globalThis.process.env?.[env]?.trim() ?? undefined;
11014
- }
11015
- if (typeof globalThis.Deno !== 'undefined') {
11016
- return globalThis.Deno.env?.get?.(env)?.trim();
11017
- }
11018
- return undefined;
11019
- };
11020
-
11021
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11022
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11023
- const environments = {
11024
- live_mode: 'https://live.dodopayments.com',
11025
- test_mode: 'https://test.dodopayments.com',
11026
- };
11051
+ // Invalid character used in decoding to indicate
11052
+ // that the character to decode is out of range of
11053
+ // alphabet and cannot be decoded.
11054
+ var INVALID_BYTE = 256;
11027
11055
  /**
11028
- * API Client for interfacing with the Dodo Payments API.
11056
+ * Implements standard Base64 encoding.
11057
+ *
11058
+ * Operates in constant time.
11029
11059
  */
11030
- class DodoPayments {
11031
- /**
11032
- * API Client for interfacing with the Dodo Payments API.
11033
- *
11034
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11035
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11036
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11037
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11038
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11039
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11040
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11041
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11042
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11043
- */
11044
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
11045
- _DodoPayments_instances.add(this);
11046
- _DodoPayments_encoder.set(this, void 0);
11047
- this.checkoutSessions = new CheckoutSessions(this);
11048
- this.payments = new Payments(this);
11049
- this.subscriptions = new Subscriptions(this);
11050
- this.invoices = new Invoices(this);
11051
- this.licenses = new Licenses(this);
11052
- this.licenseKeys = new LicenseKeys(this);
11053
- this.licenseKeyInstances = new LicenseKeyInstances(this);
11054
- this.customers = new Customers(this);
11055
- this.refunds = new Refunds(this);
11056
- this.disputes = new Disputes(this);
11057
- this.payouts = new Payouts(this);
11058
- this.webhookEvents = new WebhookEvents(this);
11059
- this.products = new Products(this);
11060
- this.misc = new Misc(this);
11061
- this.discounts = new Discounts(this);
11062
- this.addons = new Addons(this);
11063
- this.brands = new Brands(this);
11064
- this.webhooks = new Webhooks$1(this);
11065
- this.usageEvents = new UsageEvents(this);
11066
- this.meters = new Meters(this);
11067
- if (bearerToken === undefined) {
11068
- throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
11060
+ var Coder = /** @class */ (function () {
11061
+ // TODO(dchest): methods to encode chunk-by-chunk.
11062
+ function Coder(_paddingCharacter) {
11063
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
11064
+ this._paddingCharacter = _paddingCharacter;
11065
+ }
11066
+ Coder.prototype.encodedLength = function (length) {
11067
+ if (!this._paddingCharacter) {
11068
+ return (length * 8 + 5) / 6 | 0;
11069
11069
  }
11070
- const options = {
11071
- bearerToken,
11072
- ...opts,
11073
- baseURL,
11074
- environment: opts.environment ?? 'live_mode',
11075
- };
11076
- if (baseURL && opts.environment) {
11077
- throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
11070
+ return (length + 2) / 3 * 4 | 0;
11071
+ };
11072
+ Coder.prototype.encode = function (data) {
11073
+ var out = "";
11074
+ var i = 0;
11075
+ for (; i < data.length - 2; i += 3) {
11076
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
11077
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11078
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11079
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11080
+ out += this._encodeByte((c >>> 0 * 6) & 63);
11078
11081
  }
11079
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11080
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11081
- this.logger = options.logger ?? console;
11082
- const defaultLogLevel = 'warn';
11083
- // Set default logLevel early so that we can log a warning in parseLogLevel.
11084
- this.logLevel = defaultLogLevel;
11085
- this.logLevel =
11086
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11087
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11088
- defaultLogLevel;
11089
- this.fetchOptions = options.fetchOptions;
11090
- this.maxRetries = options.maxRetries ?? 2;
11091
- this.fetch = options.fetch ?? getDefaultFetch();
11092
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11093
- this._options = options;
11094
- this.bearerToken = bearerToken;
11095
- }
11096
- /**
11097
- * Create a new client instance re-using the same options given to the current client with optional overriding.
11098
- */
11099
- withOptions(options) {
11100
- const client = new this.constructor({
11101
- ...this._options,
11102
- environment: options.environment ? options.environment : undefined,
11103
- baseURL: options.environment ? undefined : this.baseURL,
11104
- maxRetries: this.maxRetries,
11105
- timeout: this.timeout,
11106
- logger: this.logger,
11107
- logLevel: this.logLevel,
11108
- fetch: this.fetch,
11109
- fetchOptions: this.fetchOptions,
11110
- bearerToken: this.bearerToken,
11111
- ...options,
11112
- });
11113
- return client;
11114
- }
11115
- defaultQuery() {
11116
- return this._options.defaultQuery;
11117
- }
11118
- validateHeaders({ values, nulls }) {
11119
- return;
11120
- }
11121
- async authHeaders(opts) {
11122
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
11123
- }
11124
- /**
11125
- * Basic re-implementation of `qs.stringify` for primitive types.
11126
- */
11127
- stringifyQuery(query) {
11128
- return Object.entries(query)
11129
- .filter(([_, value]) => typeof value !== 'undefined')
11130
- .map(([key, value]) => {
11131
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
11132
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
11082
+ var left = data.length - i;
11083
+ if (left > 0) {
11084
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
11085
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11086
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11087
+ if (left === 2) {
11088
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11133
11089
  }
11134
- if (value === null) {
11135
- return `${encodeURIComponent(key)}=`;
11090
+ else {
11091
+ out += this._paddingCharacter || "";
11136
11092
  }
11137
- throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
11138
- })
11139
- .join('&');
11140
- }
11141
- getUserAgent() {
11142
- return `${this.constructor.name}/JS ${VERSION}`;
11143
- }
11144
- defaultIdempotencyKey() {
11145
- return `stainless-node-retry-${uuid4()}`;
11146
- }
11147
- makeStatusError(status, error, message, headers) {
11148
- return APIError.generate(status, error, message, headers);
11149
- }
11150
- buildURL(path, query, defaultBaseURL) {
11151
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
11152
- const url = isAbsoluteURL(path) ?
11153
- new URL(path)
11154
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
11155
- const defaultQuery = this.defaultQuery();
11156
- if (!isEmptyObj(defaultQuery)) {
11157
- query = { ...defaultQuery, ...query };
11093
+ out += this._paddingCharacter || "";
11158
11094
  }
11159
- if (typeof query === 'object' && query && !Array.isArray(query)) {
11160
- url.search = this.stringifyQuery(query);
11095
+ return out;
11096
+ };
11097
+ Coder.prototype.maxDecodedLength = function (length) {
11098
+ if (!this._paddingCharacter) {
11099
+ return (length * 6 + 7) / 8 | 0;
11161
11100
  }
11162
- return url.toString();
11163
- }
11164
- /**
11165
- * Used as a callback for mutating the given `FinalRequestOptions` object.
11166
- */
11167
- async prepareOptions(options) { }
11168
- /**
11169
- * Used as a callback for mutating the given `RequestInit` object.
11170
- *
11171
- * This is useful for cases where you want to add certain headers based off of
11172
- * the request properties, e.g. `method` or `url`.
11173
- */
11174
- async prepareRequest(request, { url, options }) { }
11175
- get(path, opts) {
11176
- return this.methodRequest('get', path, opts);
11177
- }
11178
- post(path, opts) {
11179
- return this.methodRequest('post', path, opts);
11180
- }
11181
- patch(path, opts) {
11182
- return this.methodRequest('patch', path, opts);
11183
- }
11184
- put(path, opts) {
11185
- return this.methodRequest('put', path, opts);
11186
- }
11187
- delete(path, opts) {
11188
- return this.methodRequest('delete', path, opts);
11189
- }
11190
- methodRequest(method, path, opts) {
11191
- return this.request(Promise.resolve(opts).then((opts) => {
11192
- return { method, path, ...opts };
11193
- }));
11194
- }
11195
- request(options, remainingRetries = null) {
11196
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
11197
- }
11198
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
11199
- const options = await optionsInput;
11200
- const maxRetries = options.maxRetries ?? this.maxRetries;
11201
- if (retriesRemaining == null) {
11202
- retriesRemaining = maxRetries;
11101
+ return length / 4 * 3 | 0;
11102
+ };
11103
+ Coder.prototype.decodedLength = function (s) {
11104
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
11105
+ };
11106
+ Coder.prototype.decode = function (s) {
11107
+ if (s.length === 0) {
11108
+ return new Uint8Array(0);
11203
11109
  }
11204
- await this.prepareOptions(options);
11205
- const { req, url, timeout } = await this.buildRequest(options, {
11206
- retryCount: maxRetries - retriesRemaining,
11207
- });
11208
- await this.prepareRequest(req, { url, options });
11209
- /** Not an API request ID, just for correlating local log entries. */
11210
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
11211
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
11212
- const startTime = Date.now();
11213
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
11214
- retryOfRequestLogID,
11215
- method: options.method,
11216
- url,
11217
- options,
11218
- headers: req.headers,
11219
- }));
11220
- if (options.signal?.aborted) {
11221
- throw new APIUserAbortError();
11110
+ var paddingLength = this._getPaddingLength(s);
11111
+ var length = s.length - paddingLength;
11112
+ var out = new Uint8Array(this.maxDecodedLength(length));
11113
+ var op = 0;
11114
+ var i = 0;
11115
+ var haveBad = 0;
11116
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
11117
+ for (; i < length - 4; i += 4) {
11118
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
11119
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11120
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11121
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11122
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11123
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11124
+ out[op++] = (v2 << 6) | v3;
11125
+ haveBad |= v0 & INVALID_BYTE;
11126
+ haveBad |= v1 & INVALID_BYTE;
11127
+ haveBad |= v2 & INVALID_BYTE;
11128
+ haveBad |= v3 & INVALID_BYTE;
11222
11129
  }
11223
- const controller = new AbortController();
11224
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
11225
- const headersTime = Date.now();
11226
- if (response instanceof globalThis.Error) {
11227
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11228
- if (options.signal?.aborted) {
11229
- throw new APIUserAbortError();
11230
- }
11231
- // detect native connection timeout errors
11232
- // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
11233
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
11234
- // others do not provide enough information to distinguish timeouts from other connection errors
11235
- const isTimeout = isAbortError(response) ||
11236
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
11237
- if (retriesRemaining) {
11238
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
11239
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
11240
- retryOfRequestLogID,
11241
- url,
11242
- durationMs: headersTime - startTime,
11243
- message: response.message,
11244
- }));
11245
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
11246
- }
11247
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
11248
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
11249
- retryOfRequestLogID,
11250
- url,
11251
- durationMs: headersTime - startTime,
11252
- message: response.message,
11253
- }));
11254
- if (isTimeout) {
11255
- throw new APIConnectionTimeoutError();
11256
- }
11257
- throw new APIConnectionError({ cause: response });
11130
+ if (i < length - 1) {
11131
+ v0 = this._decodeChar(s.charCodeAt(i));
11132
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11133
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11134
+ haveBad |= v0 & INVALID_BYTE;
11135
+ haveBad |= v1 & INVALID_BYTE;
11258
11136
  }
11259
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
11260
- if (!response.ok) {
11261
- const shouldRetry = await this.shouldRetry(response);
11262
- if (retriesRemaining && shouldRetry) {
11263
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11264
- // We don't need the body of this response.
11265
- await CancelReadableStream(response.body);
11266
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11267
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11268
- retryOfRequestLogID,
11269
- url: response.url,
11270
- status: response.status,
11271
- headers: response.headers,
11272
- durationMs: headersTime - startTime,
11273
- }));
11274
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
11275
- }
11276
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
11277
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11278
- const errText = await response.text().catch((err) => castToError(err).message);
11279
- const errJSON = safeJSON(errText);
11280
- const errMessage = errJSON ? undefined : errText;
11281
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11282
- retryOfRequestLogID,
11283
- url: response.url,
11284
- status: response.status,
11285
- headers: response.headers,
11286
- message: errMessage,
11287
- durationMs: Date.now() - startTime,
11288
- }));
11289
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
11290
- throw err;
11137
+ if (i < length - 2) {
11138
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11139
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11140
+ haveBad |= v2 & INVALID_BYTE;
11291
11141
  }
11292
- loggerFor(this).info(responseInfo);
11293
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
11294
- retryOfRequestLogID,
11295
- url: response.url,
11296
- status: response.status,
11297
- headers: response.headers,
11298
- durationMs: headersTime - startTime,
11299
- }));
11300
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
11301
- }
11302
- getAPIList(path, Page, opts) {
11303
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
11304
- }
11305
- requestAPIList(Page, options) {
11306
- const request = this.makeRequest(options, null, undefined);
11307
- return new PagePromise(this, request, Page);
11308
- }
11309
- async fetchWithTimeout(url, init, ms, controller) {
11310
- const { signal, method, ...options } = init || {};
11311
- if (signal)
11312
- signal.addEventListener('abort', () => controller.abort());
11313
- const timeout = setTimeout(() => controller.abort(), ms);
11314
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
11315
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
11316
- const fetchOptions = {
11317
- signal: controller.signal,
11318
- ...(isReadableBody ? { duplex: 'half' } : {}),
11319
- method: 'GET',
11320
- ...options,
11321
- };
11322
- if (method) {
11323
- // Custom methods like 'patch' need to be uppercased
11324
- // See https://github.com/nodejs/undici/issues/2294
11325
- fetchOptions.method = method.toUpperCase();
11326
- }
11327
- try {
11328
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
11329
- return await this.fetch.call(undefined, url, fetchOptions);
11330
- }
11331
- finally {
11332
- clearTimeout(timeout);
11142
+ if (i < length - 3) {
11143
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11144
+ out[op++] = (v2 << 6) | v3;
11145
+ haveBad |= v3 & INVALID_BYTE;
11333
11146
  }
11334
- }
11335
- async shouldRetry(response) {
11336
- // Note this is not a standard header.
11337
- const shouldRetryHeader = response.headers.get('x-should-retry');
11338
- // If the server explicitly says whether or not to retry, obey.
11339
- if (shouldRetryHeader === 'true')
11340
- return true;
11341
- if (shouldRetryHeader === 'false')
11342
- return false;
11343
- // Retry on request timeouts.
11344
- if (response.status === 408)
11345
- return true;
11346
- // Retry on lock timeouts.
11347
- if (response.status === 409)
11348
- return true;
11349
- // Retry on rate limits.
11350
- if (response.status === 429)
11351
- return true;
11352
- // Retry internal errors.
11353
- if (response.status >= 500)
11354
- return true;
11355
- return false;
11356
- }
11357
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
11358
- let timeoutMillis;
11359
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
11360
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
11361
- if (retryAfterMillisHeader) {
11362
- const timeoutMs = parseFloat(retryAfterMillisHeader);
11363
- if (!Number.isNaN(timeoutMs)) {
11364
- timeoutMillis = timeoutMs;
11365
- }
11147
+ if (haveBad !== 0) {
11148
+ throw new Error("Base64Coder: incorrect characters for decoding");
11366
11149
  }
11367
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
11368
- const retryAfterHeader = responseHeaders?.get('retry-after');
11369
- if (retryAfterHeader && !timeoutMillis) {
11370
- const timeoutSeconds = parseFloat(retryAfterHeader);
11371
- if (!Number.isNaN(timeoutSeconds)) {
11372
- timeoutMillis = timeoutSeconds * 1000;
11150
+ return out;
11151
+ };
11152
+ // Standard encoding have the following encoded/decoded ranges,
11153
+ // which we need to convert between.
11154
+ //
11155
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
11156
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11157
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
11158
+ //
11159
+ // Encode 6 bits in b into a new character.
11160
+ Coder.prototype._encodeByte = function (b) {
11161
+ // Encoding uses constant time operations as follows:
11162
+ //
11163
+ // 1. Define comparison of A with B using (A - B) >>> 8:
11164
+ // if A > B, then result is positive integer
11165
+ // if A <= B, then result is 0
11166
+ //
11167
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
11168
+ // if X == 0, then result is 0
11169
+ // if X != 0, then result is C
11170
+ //
11171
+ // 3. Start with the smallest comparison (b >= 0), which is always
11172
+ // true, so set the result to the starting ASCII value (65).
11173
+ //
11174
+ // 4. Continue comparing b to higher ASCII values, and selecting
11175
+ // zero if comparison isn't true, otherwise selecting a value
11176
+ // to add to result, which:
11177
+ //
11178
+ // a) undoes the previous addition
11179
+ // b) provides new value to add
11180
+ //
11181
+ var result = b;
11182
+ // b >= 0
11183
+ result += 65;
11184
+ // b > 25
11185
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11186
+ // b > 51
11187
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11188
+ // b > 61
11189
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
11190
+ // b > 62
11191
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
11192
+ return String.fromCharCode(result);
11193
+ };
11194
+ // Decode a character code into a byte.
11195
+ // Must return 256 if character is out of alphabet range.
11196
+ Coder.prototype._decodeChar = function (c) {
11197
+ // Decoding works similar to encoding: using the same comparison
11198
+ // function, but now it works on ranges: result is always incremented
11199
+ // by value, but this value becomes zero if the range is not
11200
+ // satisfied.
11201
+ //
11202
+ // Decoding starts with invalid value, 256, which is then
11203
+ // subtracted when the range is satisfied. If none of the ranges
11204
+ // apply, the function returns 256, which is then checked by
11205
+ // the caller to throw error.
11206
+ var result = INVALID_BYTE; // start with invalid character
11207
+ // c == 43 (c > 42 and c < 44)
11208
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
11209
+ // c == 47 (c > 46 and c < 48)
11210
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
11211
+ // c > 47 and c < 58
11212
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11213
+ // c > 64 and c < 91
11214
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11215
+ // c > 96 and c < 123
11216
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11217
+ return result;
11218
+ };
11219
+ Coder.prototype._getPaddingLength = function (s) {
11220
+ var paddingLength = 0;
11221
+ if (this._paddingCharacter) {
11222
+ for (var i = s.length - 1; i >= 0; i--) {
11223
+ if (s[i] !== this._paddingCharacter) {
11224
+ break;
11225
+ }
11226
+ paddingLength++;
11373
11227
  }
11374
- else {
11375
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
11228
+ if (s.length < 4 || paddingLength > 2) {
11229
+ throw new Error("Base64Coder: incorrect padding");
11376
11230
  }
11377
11231
  }
11378
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
11379
- // just do what it says, but otherwise calculate a default
11380
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
11381
- const maxRetries = options.maxRetries ?? this.maxRetries;
11382
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
11383
- }
11384
- await sleep(timeoutMillis);
11385
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
11386
- }
11387
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
11388
- const initialRetryDelay = 0.5;
11389
- const maxRetryDelay = 8.0;
11390
- const numRetries = maxRetries - retriesRemaining;
11391
- // Apply exponential backoff, but not more than the max.
11392
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
11393
- // Apply some jitter, take up to at most 25 percent of the retry time.
11394
- const jitter = 1 - Math.random() * 0.25;
11395
- return sleepSeconds * jitter * 1000;
11396
- }
11397
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
11398
- const options = { ...inputOptions };
11399
- const { method, path, query, defaultBaseURL } = options;
11400
- const url = this.buildURL(path, query, defaultBaseURL);
11401
- if ('timeout' in options)
11402
- validatePositiveInteger('timeout', options.timeout);
11403
- options.timeout = options.timeout ?? this.timeout;
11404
- const { bodyHeaders, body } = this.buildBody({ options });
11405
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
11406
- const req = {
11407
- method,
11408
- headers: reqHeaders,
11409
- ...(options.signal && { signal: options.signal }),
11410
- ...(globalThis.ReadableStream &&
11411
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
11412
- ...(body && { body }),
11413
- ...(this.fetchOptions ?? {}),
11414
- ...(options.fetchOptions ?? {}),
11415
- };
11416
- return { req, url, timeout: options.timeout };
11417
- }
11418
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
11419
- let idempotencyHeaders = {};
11420
- if (this.idempotencyHeader && method !== 'get') {
11421
- if (!options.idempotencyKey)
11422
- options.idempotencyKey = this.defaultIdempotencyKey();
11423
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
11424
- }
11425
- const headers = buildHeaders([
11426
- idempotencyHeaders,
11427
- {
11428
- Accept: 'application/json',
11429
- 'User-Agent': this.getUserAgent(),
11430
- 'X-Stainless-Retry-Count': String(retryCount),
11431
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
11432
- ...getPlatformHeaders(),
11433
- },
11434
- await this.authHeaders(options),
11435
- this._options.defaultHeaders,
11436
- bodyHeaders,
11437
- options.headers,
11438
- ]);
11439
- this.validateHeaders(headers);
11440
- return headers.values;
11441
- }
11442
- buildBody({ options: { body, headers: rawHeaders } }) {
11443
- if (!body) {
11444
- return { bodyHeaders: undefined, body: undefined };
11445
- }
11446
- const headers = buildHeaders([rawHeaders]);
11447
- if (
11448
- // Pass raw type verbatim
11449
- ArrayBuffer.isView(body) ||
11450
- body instanceof ArrayBuffer ||
11451
- body instanceof DataView ||
11452
- (typeof body === 'string' &&
11453
- // Preserve legacy string encoding behavior for now
11454
- headers.values.has('content-type')) ||
11455
- // `Blob` is superset of `File`
11456
- (globalThis.Blob && body instanceof globalThis.Blob) ||
11457
- // `FormData` -> `multipart/form-data`
11458
- body instanceof FormData ||
11459
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
11460
- body instanceof URLSearchParams ||
11461
- // Send chunked stream (each chunk has own `length`)
11462
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
11463
- return { bodyHeaders: undefined, body: body };
11464
- }
11465
- else if (typeof body === 'object' &&
11466
- (Symbol.asyncIterator in body ||
11467
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
11468
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
11469
- }
11470
- else {
11471
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
11472
- }
11232
+ return paddingLength;
11233
+ };
11234
+ return Coder;
11235
+ }());
11236
+ base64$1.Coder = Coder;
11237
+ var stdCoder = new Coder();
11238
+ function encode(data) {
11239
+ return stdCoder.encode(data);
11240
+ }
11241
+ base64$1.encode = encode;
11242
+ function decode(s) {
11243
+ return stdCoder.decode(s);
11244
+ }
11245
+ base64$1.decode = decode;
11246
+ /**
11247
+ * Implements URL-safe Base64 encoding.
11248
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
11249
+ *
11250
+ * Operates in constant time.
11251
+ */
11252
+ var URLSafeCoder = /** @class */ (function (_super) {
11253
+ __extends(URLSafeCoder, _super);
11254
+ function URLSafeCoder() {
11255
+ return _super !== null && _super.apply(this, arguments) || this;
11473
11256
  }
11257
+ // URL-safe encoding have the following encoded/decoded ranges:
11258
+ //
11259
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
11260
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11261
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
11262
+ //
11263
+ URLSafeCoder.prototype._encodeByte = function (b) {
11264
+ var result = b;
11265
+ // b >= 0
11266
+ result += 65;
11267
+ // b > 25
11268
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11269
+ // b > 51
11270
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11271
+ // b > 61
11272
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
11273
+ // b > 62
11274
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
11275
+ return String.fromCharCode(result);
11276
+ };
11277
+ URLSafeCoder.prototype._decodeChar = function (c) {
11278
+ var result = INVALID_BYTE;
11279
+ // c == 45 (c > 44 and c < 46)
11280
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
11281
+ // c == 95 (c > 94 and c < 96)
11282
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
11283
+ // c > 47 and c < 58
11284
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11285
+ // c > 64 and c < 91
11286
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11287
+ // c > 96 and c < 123
11288
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11289
+ return result;
11290
+ };
11291
+ return URLSafeCoder;
11292
+ }(Coder));
11293
+ base64$1.URLSafeCoder = URLSafeCoder;
11294
+ var urlSafeCoder = new URLSafeCoder();
11295
+ function encodeURLSafe(data) {
11296
+ return urlSafeCoder.encode(data);
11474
11297
  }
11475
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
11476
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
11477
- };
11478
- DodoPayments.DodoPayments = _a;
11479
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
11480
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
11481
- DodoPayments.APIError = APIError;
11482
- DodoPayments.APIConnectionError = APIConnectionError;
11483
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
11484
- DodoPayments.APIUserAbortError = APIUserAbortError;
11485
- DodoPayments.NotFoundError = NotFoundError;
11486
- DodoPayments.ConflictError = ConflictError;
11487
- DodoPayments.RateLimitError = RateLimitError;
11488
- DodoPayments.BadRequestError = BadRequestError;
11489
- DodoPayments.AuthenticationError = AuthenticationError;
11490
- DodoPayments.InternalServerError = InternalServerError;
11491
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
11492
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
11493
- DodoPayments.toFile = toFile;
11494
- DodoPayments.CheckoutSessions = CheckoutSessions;
11495
- DodoPayments.Payments = Payments;
11496
- DodoPayments.Subscriptions = Subscriptions;
11497
- DodoPayments.Invoices = Invoices;
11498
- DodoPayments.Licenses = Licenses;
11499
- DodoPayments.LicenseKeys = LicenseKeys;
11500
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
11501
- DodoPayments.Customers = Customers;
11502
- DodoPayments.Refunds = Refunds;
11503
- DodoPayments.Disputes = Disputes;
11504
- DodoPayments.Payouts = Payouts;
11505
- DodoPayments.WebhookEvents = WebhookEvents;
11506
- DodoPayments.Products = Products;
11507
- DodoPayments.Misc = Misc;
11508
- DodoPayments.Discounts = Discounts;
11509
- DodoPayments.Addons = Addons;
11510
- DodoPayments.Brands = Brands;
11511
- DodoPayments.Webhooks = Webhooks$1;
11512
- DodoPayments.UsageEvents = UsageEvents;
11513
- DodoPayments.Meters = Meters;
11514
-
11515
- // src/checkout/checkout.ts
11516
- var checkoutQuerySchema = objectType({
11517
- productId: stringType(),
11518
- quantity: stringType().optional(),
11519
- // Customer fields
11520
- fullName: stringType().optional(),
11521
- firstName: stringType().optional(),
11522
- lastName: stringType().optional(),
11523
- email: stringType().optional(),
11524
- country: stringType().optional(),
11525
- addressLine: stringType().optional(),
11526
- city: stringType().optional(),
11527
- state: stringType().optional(),
11528
- zipCode: stringType().optional(),
11529
- // Disable flags
11530
- disableFullName: stringType().optional(),
11531
- disableFirstName: stringType().optional(),
11532
- disableLastName: stringType().optional(),
11533
- disableEmail: stringType().optional(),
11534
- disableCountry: stringType().optional(),
11535
- disableAddressLine: stringType().optional(),
11536
- disableCity: stringType().optional(),
11537
- disableState: stringType().optional(),
11538
- disableZipCode: stringType().optional(),
11539
- // Advanced controls
11540
- paymentCurrency: stringType().optional(),
11541
- showCurrencySelector: stringType().optional(),
11542
- paymentAmount: stringType().optional(),
11543
- showDiscounts: stringType().optional()
11544
- // Metadata (allow any key starting with metadata_)
11545
- // We'll handle metadata separately in the handler
11546
- }).catchall(unknownType());
11547
- var dynamicCheckoutBodySchema = objectType({
11548
- // For subscription
11549
- product_id: stringType().optional(),
11550
- quantity: numberType().optional(),
11551
- // For one-time payment
11552
- product_cart: arrayType(
11553
- objectType({
11554
- product_id: stringType(),
11555
- quantity: numberType()
11556
- })
11557
- ).optional(),
11558
- // Common fields
11559
- billing: objectType({
11560
- city: stringType(),
11561
- country: stringType(),
11562
- state: stringType(),
11563
- street: stringType(),
11564
- zipcode: stringType()
11565
- }),
11566
- customer: objectType({
11567
- customer_id: stringType().optional(),
11568
- email: stringType().optional(),
11569
- name: stringType().optional()
11570
- }),
11571
- discount_id: stringType().optional(),
11572
- addons: arrayType(
11573
- objectType({
11574
- addon_id: stringType(),
11575
- quantity: numberType()
11576
- })
11577
- ).optional(),
11578
- metadata: recordType(stringType(), stringType()).optional(),
11579
- currency: stringType().optional()
11580
- // Allow any additional fields (for future compatibility)
11581
- }).catchall(unknownType());
11582
- var checkoutSessionProductCartItemSchema = objectType({
11583
- product_id: stringType().min(1, "Product ID is required"),
11584
- quantity: numberType().int().positive("Quantity must be a positive integer")
11585
- });
11586
- var checkoutSessionCustomerSchema = objectType({
11587
- email: stringType().email().optional(),
11588
- name: stringType().min(1).optional(),
11589
- phone_number: stringType().optional()
11590
- }).optional();
11591
- var checkoutSessionBillingAddressSchema = objectType({
11592
- street: stringType().optional(),
11593
- city: stringType().optional(),
11594
- state: stringType().optional(),
11595
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
11596
- zipcode: stringType().optional()
11597
- }).optional();
11598
- var paymentMethodTypeSchema = enumType([
11599
- "credit",
11600
- "debit",
11601
- "upi_collect",
11602
- "upi_intent",
11603
- "apple_pay",
11604
- "google_pay",
11605
- "amazon_pay",
11606
- "klarna",
11607
- "affirm",
11608
- "afterpay_clearpay",
11609
- "sepa",
11610
- "ach"
11611
- ]);
11612
- var checkoutSessionCustomizationSchema = objectType({
11613
- theme: enumType(["light", "dark", "system"]).optional(),
11614
- show_order_details: booleanType().optional(),
11615
- show_on_demand_tag: booleanType().optional()
11616
- }).optional();
11617
- var checkoutSessionFeatureFlagsSchema = objectType({
11618
- allow_currency_selection: booleanType().optional(),
11619
- allow_discount_code: booleanType().optional(),
11620
- allow_phone_number_collection: booleanType().optional(),
11621
- allow_tax_id: booleanType().optional(),
11622
- always_create_new_customer: booleanType().optional()
11623
- }).optional();
11624
- var checkoutSessionSubscriptionDataSchema = objectType({
11625
- trial_period_days: numberType().int().nonnegative().optional()
11626
- }).optional();
11627
- var checkoutSessionPayloadSchema = objectType({
11628
- // Required fields
11629
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
11630
- // Optional fields
11631
- customer: checkoutSessionCustomerSchema,
11632
- billing_address: checkoutSessionBillingAddressSchema,
11633
- return_url: stringType().url().optional(),
11634
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
11635
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
11636
- show_saved_payment_methods: booleanType().optional(),
11637
- confirm: booleanType().optional(),
11638
- discount_code: stringType().optional(),
11639
- metadata: recordType(stringType(), stringType()).optional(),
11640
- customization: checkoutSessionCustomizationSchema,
11641
- feature_flags: checkoutSessionFeatureFlagsSchema,
11642
- subscription_data: checkoutSessionSubscriptionDataSchema
11643
- });
11644
- var checkoutSessionResponseSchema = objectType({
11645
- session_id: stringType().min(1, "Session ID is required"),
11646
- checkout_url: stringType().url("Invalid checkout URL")
11647
- });
11648
- var createCheckoutSession = async (payload, config) => {
11649
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
11650
- if (!validation.success) {
11651
- throw new Error(
11652
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11653
- );
11654
- }
11655
- const dodopayments = new DodoPayments({
11656
- bearerToken: config.bearerToken,
11657
- environment: config.environment
11658
- });
11659
- try {
11660
- const sdkPayload = {
11661
- ...validation.data,
11662
- ...validation.data.billing_address && {
11663
- billing_address: {
11664
- ...validation.data.billing_address,
11665
- country: validation.data.billing_address.country
11666
- }
11667
- }
11668
- };
11669
- const session = await dodopayments.checkoutSessions.create(
11670
- sdkPayload
11671
- );
11672
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
11673
- if (!responseValidation.success) {
11674
- throw new Error(
11675
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11676
- );
11677
- }
11678
- return responseValidation.data;
11679
- } catch (error) {
11680
- if (error instanceof Error) {
11681
- console.error("Dodo Payments Checkout Session API Error:", {
11682
- message: error.message,
11683
- payload: validation.data,
11684
- config: {
11685
- environment: config.environment,
11686
- hasBearerToken: !!config.bearerToken
11687
- }
11688
- });
11689
- throw new Error(`Failed to create checkout session: ${error.message}`);
11690
- }
11691
- console.error("Unknown error creating checkout session:", error);
11692
- throw new Error(
11693
- "Failed to create checkout session due to an unknown error"
11694
- );
11695
- }
11696
- };
11697
- var buildCheckoutUrl = async ({
11698
- queryParams,
11699
- body,
11700
- sessionPayload,
11701
- returnUrl,
11702
- bearerToken,
11703
- environment,
11704
- type = "static"
11705
- }) => {
11706
- if (type === "session") {
11707
- if (!sessionPayload) {
11708
- throw new Error("sessionPayload is required when type is 'session'");
11709
- }
11710
- const session = await createCheckoutSession(sessionPayload, {
11711
- bearerToken,
11712
- environment
11713
- });
11714
- return session.checkout_url;
11715
- }
11716
- const inputData = type === "dynamic" ? body : queryParams;
11717
- let parseResult;
11718
- if (type === "dynamic") {
11719
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
11720
- } else {
11721
- parseResult = checkoutQuerySchema.safeParse(inputData);
11722
- }
11723
- const { success, data, error } = parseResult;
11724
- if (!success) {
11725
- throw new Error(
11726
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
11727
- ${error.message}`
11728
- );
11729
- }
11730
- if (type !== "dynamic") {
11731
- const {
11732
- productId,
11733
- quantity: quantity2,
11734
- fullName,
11735
- firstName,
11736
- lastName,
11737
- email,
11738
- country,
11739
- addressLine,
11740
- city,
11741
- state,
11742
- zipCode,
11743
- disableFullName,
11744
- disableFirstName,
11745
- disableLastName,
11746
- disableEmail,
11747
- disableCountry,
11748
- disableAddressLine,
11749
- disableCity,
11750
- disableState,
11751
- disableZipCode,
11752
- paymentCurrency,
11753
- showCurrencySelector,
11754
- paymentAmount,
11755
- showDiscounts
11756
- // metadata handled below
11757
- } = data;
11758
- const dodopayments2 = new DodoPayments({
11759
- bearerToken,
11760
- environment
11761
- });
11762
- if (!productId) throw new Error("Missing required field: productId");
11763
- try {
11764
- await dodopayments2.products.retrieve(productId);
11765
- } catch (err) {
11766
- console.error(err);
11767
- throw new Error("Product not found");
11768
- }
11769
- const url = new URL(
11770
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
11771
- );
11772
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
11773
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
11774
- if (fullName) url.searchParams.set("fullName", String(fullName));
11775
- if (firstName) url.searchParams.set("firstName", String(firstName));
11776
- if (lastName) url.searchParams.set("lastName", String(lastName));
11777
- if (email) url.searchParams.set("email", String(email));
11778
- if (country) url.searchParams.set("country", String(country));
11779
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
11780
- if (city) url.searchParams.set("city", String(city));
11781
- if (state) url.searchParams.set("state", String(state));
11782
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
11783
- if (disableFullName === "true")
11784
- url.searchParams.set("disableFullName", "true");
11785
- if (disableFirstName === "true")
11786
- url.searchParams.set("disableFirstName", "true");
11787
- if (disableLastName === "true")
11788
- url.searchParams.set("disableLastName", "true");
11789
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
11790
- if (disableCountry === "true")
11791
- url.searchParams.set("disableCountry", "true");
11792
- if (disableAddressLine === "true")
11793
- url.searchParams.set("disableAddressLine", "true");
11794
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
11795
- if (disableState === "true") url.searchParams.set("disableState", "true");
11796
- if (disableZipCode === "true")
11797
- url.searchParams.set("disableZipCode", "true");
11798
- if (paymentCurrency)
11799
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
11800
- if (showCurrencySelector)
11801
- url.searchParams.set(
11802
- "showCurrencySelector",
11803
- String(showCurrencySelector)
11804
- );
11805
- if (paymentAmount)
11806
- url.searchParams.set("paymentAmount", String(paymentAmount));
11807
- if (showDiscounts)
11808
- url.searchParams.set("showDiscounts", String(showDiscounts));
11809
- for (const [key, value] of Object.entries(queryParams || {})) {
11810
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
11811
- url.searchParams.set(key, String(value));
11812
- }
11813
- }
11814
- return url.toString();
11815
- }
11816
- const dyn = data;
11817
- const {
11818
- product_id,
11819
- product_cart,
11820
- quantity,
11821
- billing,
11822
- customer,
11823
- addons,
11824
- metadata,
11825
- allowed_payment_method_types,
11826
- billing_currency,
11827
- discount_code,
11828
- on_demand,
11829
- return_url: bodyReturnUrl,
11830
- show_saved_payment_methods,
11831
- tax_id,
11832
- trial_period_days
11833
- } = dyn;
11834
- const dodopayments = new DodoPayments({
11835
- bearerToken,
11836
- environment
11837
- });
11838
- let isSubscription = false;
11839
- let productIdToFetch = product_id;
11840
- if (!product_id && product_cart && product_cart.length > 0) {
11841
- productIdToFetch = product_cart[0].product_id;
11842
- }
11843
- if (!productIdToFetch)
11844
- throw new Error(
11845
- "Missing required field: product_id or product_cart[0].product_id"
11846
- );
11847
- let product;
11848
- try {
11849
- product = await dodopayments.products.retrieve(productIdToFetch);
11850
- } catch (err) {
11851
- console.error(err);
11852
- throw new Error("Product not found");
11853
- }
11854
- isSubscription = Boolean(product.is_recurring);
11855
- if (isSubscription && !product_id)
11856
- throw new Error("Missing required field: product_id for subscription");
11857
- if (!billing) throw new Error("Missing required field: billing");
11858
- if (!customer) throw new Error("Missing required field: customer");
11859
- if (isSubscription) {
11860
- const subscriptionPayload = {
11861
- billing,
11862
- customer,
11863
- product_id,
11864
- quantity: quantity ? Number(quantity) : 1
11865
- };
11866
- if (metadata) subscriptionPayload.metadata = metadata;
11867
- if (discount_code) subscriptionPayload.discount_code = discount_code;
11868
- if (addons) subscriptionPayload.addons = addons;
11869
- if (allowed_payment_method_types)
11870
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
11871
- if (billing_currency)
11872
- subscriptionPayload.billing_currency = billing_currency;
11873
- if (on_demand) subscriptionPayload.on_demand = on_demand;
11874
- subscriptionPayload.payment_link = true;
11875
- if (bodyReturnUrl) {
11876
- subscriptionPayload.return_url = bodyReturnUrl;
11877
- } else if (returnUrl) {
11878
- subscriptionPayload.return_url = returnUrl;
11879
- }
11880
- if (show_saved_payment_methods)
11881
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
11882
- if (tax_id) subscriptionPayload.tax_id = tax_id;
11883
- if (trial_period_days)
11884
- subscriptionPayload.trial_period_days = trial_period_days;
11885
- let subscription;
11886
- try {
11887
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
11888
- } catch (err) {
11889
- console.error("Error when creating subscription", err);
11890
- throw new Error(err instanceof Error ? err.message : String(err));
11891
- }
11892
- if (!subscription || !subscription.payment_link) {
11893
- throw new Error(
11894
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
11895
- );
11896
- }
11897
- return subscription.payment_link;
11898
- } else {
11899
- let cart = product_cart;
11900
- if (!cart && product_id) {
11901
- cart = [
11902
- { product_id, quantity: quantity ? Number(quantity) : 1 }
11903
- ];
11904
- }
11905
- if (!cart || cart.length === 0)
11906
- throw new Error("Missing required field: product_cart or product_id");
11907
- const paymentPayload = {
11908
- billing,
11909
- customer,
11910
- product_cart: cart
11911
- };
11912
- if (metadata) paymentPayload.metadata = metadata;
11913
- paymentPayload.payment_link = true;
11914
- if (allowed_payment_method_types)
11915
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
11916
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
11917
- if (discount_code) paymentPayload.discount_code = discount_code;
11918
- if (bodyReturnUrl) {
11919
- paymentPayload.return_url = bodyReturnUrl;
11920
- } else if (returnUrl) {
11921
- paymentPayload.return_url = returnUrl;
11922
- }
11923
- if (show_saved_payment_methods)
11924
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
11925
- if (tax_id) paymentPayload.tax_id = tax_id;
11926
- let payment;
11927
- try {
11928
- payment = await dodopayments.payments.create(paymentPayload);
11929
- } catch (err) {
11930
- console.error("Error when creating payment link", err);
11931
- throw new Error(err instanceof Error ? err.message : String(err));
11932
- }
11933
- if (!payment || !payment.payment_link) {
11934
- throw new Error(
11935
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
11936
- );
11937
- }
11938
- return payment.payment_link;
11939
- }
11940
- };
11941
-
11942
- const Checkout = (config) => {
11943
- const getHandler = async (req) => {
11944
- const { searchParams } = new URL(req.url);
11945
- const queryParams = Object.fromEntries(searchParams);
11946
- if (!queryParams.productId) {
11947
- return new serverExports.NextResponse("Please provide productId query parameter", {
11948
- status: 400,
11949
- });
11950
- }
11951
- const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
11952
- if (!success) {
11953
- if (error.errors.some((e) => e.path.toString() === "productId")) {
11954
- return new serverExports.NextResponse("Please provide productId query parameter", {
11955
- status: 400,
11956
- });
11957
- }
11958
- return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
11959
- status: 400,
11960
- });
11961
- }
11962
- let url = "";
11963
- try {
11964
- url = await buildCheckoutUrl({ queryParams: data, ...config });
11965
- }
11966
- catch (error) {
11967
- return new serverExports.NextResponse(error.message, { status: 400 });
11968
- }
11969
- return serverExports.NextResponse.json({ checkout_url: url });
11970
- };
11971
- const postHandler = async (req) => {
11972
- let body;
11973
- try {
11974
- body = await req.json();
11975
- }
11976
- catch (e) {
11977
- return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
11978
- }
11979
- if (config.type === "dynamic") {
11980
- // Handle dynamic checkout
11981
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
11982
- if (!success) {
11983
- return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
11984
- status: 400,
11985
- });
11986
- }
11987
- let url = "";
11988
- try {
11989
- url = await buildCheckoutUrl({
11990
- body: data,
11991
- ...config,
11992
- type: "dynamic",
11993
- });
11994
- }
11995
- catch (error) {
11996
- return new serverExports.NextResponse(error.message, { status: 400 });
11997
- }
11998
- return serverExports.NextResponse.json({ checkout_url: url });
11999
- }
12000
- else {
12001
- // Handle checkout session
12002
- const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12003
- if (!success) {
12004
- return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12005
- status: 400,
12006
- });
12007
- }
12008
- let url = "";
12009
- try {
12010
- url = await buildCheckoutUrl({
12011
- sessionPayload: data,
12012
- ...config,
12013
- type: "session",
12014
- });
12015
- }
12016
- catch (error) {
12017
- return new serverExports.NextResponse(error.message, { status: 400 });
12018
- }
12019
- return serverExports.NextResponse.json({ checkout_url: url });
12020
- }
12021
- };
12022
- return (req) => {
12023
- if (req.method === "POST") {
12024
- return postHandler(req);
12025
- }
12026
- return getHandler(req);
12027
- };
12028
- };
12029
-
12030
- var dist = {};
12031
-
12032
- var timing_safe_equal = {};
12033
-
12034
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
12035
- timing_safe_equal.timingSafeEqual = void 0;
12036
- function assert(expr, msg = "") {
12037
- if (!expr) {
12038
- throw new Error(msg);
12039
- }
12040
- }
12041
- function timingSafeEqual(a, b) {
12042
- if (a.byteLength !== b.byteLength) {
12043
- return false;
12044
- }
12045
- if (!(a instanceof DataView)) {
12046
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
12047
- }
12048
- if (!(b instanceof DataView)) {
12049
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
12050
- }
12051
- assert(a instanceof DataView);
12052
- assert(b instanceof DataView);
12053
- const length = a.byteLength;
12054
- let out = 0;
12055
- let i = -1;
12056
- while (++i < length) {
12057
- out |= a.getUint8(i) ^ b.getUint8(i);
12058
- }
12059
- return out === 0;
12060
- }
12061
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
12062
-
12063
- var base64$1 = {};
12064
-
12065
- // Copyright (C) 2016 Dmitry Chestnykh
12066
- // MIT License. See LICENSE file for details.
12067
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
12068
- var extendStatics = function (d, b) {
12069
- extendStatics = Object.setPrototypeOf ||
12070
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12071
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12072
- return extendStatics(d, b);
12073
- };
12074
- return function (d, b) {
12075
- extendStatics(d, b);
12076
- function __() { this.constructor = d; }
12077
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12078
- };
12079
- })();
12080
- Object.defineProperty(base64$1, "__esModule", { value: true });
12081
- /**
12082
- * Package base64 implements Base64 encoding and decoding.
12083
- */
12084
- // Invalid character used in decoding to indicate
12085
- // that the character to decode is out of range of
12086
- // alphabet and cannot be decoded.
12087
- var INVALID_BYTE = 256;
12088
- /**
12089
- * Implements standard Base64 encoding.
12090
- *
12091
- * Operates in constant time.
12092
- */
12093
- var Coder = /** @class */ (function () {
12094
- // TODO(dchest): methods to encode chunk-by-chunk.
12095
- function Coder(_paddingCharacter) {
12096
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
12097
- this._paddingCharacter = _paddingCharacter;
12098
- }
12099
- Coder.prototype.encodedLength = function (length) {
12100
- if (!this._paddingCharacter) {
12101
- return (length * 8 + 5) / 6 | 0;
12102
- }
12103
- return (length + 2) / 3 * 4 | 0;
12104
- };
12105
- Coder.prototype.encode = function (data) {
12106
- var out = "";
12107
- var i = 0;
12108
- for (; i < data.length - 2; i += 3) {
12109
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
12110
- out += this._encodeByte((c >>> 3 * 6) & 63);
12111
- out += this._encodeByte((c >>> 2 * 6) & 63);
12112
- out += this._encodeByte((c >>> 1 * 6) & 63);
12113
- out += this._encodeByte((c >>> 0 * 6) & 63);
12114
- }
12115
- var left = data.length - i;
12116
- if (left > 0) {
12117
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
12118
- out += this._encodeByte((c >>> 3 * 6) & 63);
12119
- out += this._encodeByte((c >>> 2 * 6) & 63);
12120
- if (left === 2) {
12121
- out += this._encodeByte((c >>> 1 * 6) & 63);
12122
- }
12123
- else {
12124
- out += this._paddingCharacter || "";
12125
- }
12126
- out += this._paddingCharacter || "";
12127
- }
12128
- return out;
12129
- };
12130
- Coder.prototype.maxDecodedLength = function (length) {
12131
- if (!this._paddingCharacter) {
12132
- return (length * 6 + 7) / 8 | 0;
12133
- }
12134
- return length / 4 * 3 | 0;
12135
- };
12136
- Coder.prototype.decodedLength = function (s) {
12137
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
12138
- };
12139
- Coder.prototype.decode = function (s) {
12140
- if (s.length === 0) {
12141
- return new Uint8Array(0);
12142
- }
12143
- var paddingLength = this._getPaddingLength(s);
12144
- var length = s.length - paddingLength;
12145
- var out = new Uint8Array(this.maxDecodedLength(length));
12146
- var op = 0;
12147
- var i = 0;
12148
- var haveBad = 0;
12149
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
12150
- for (; i < length - 4; i += 4) {
12151
- v0 = this._decodeChar(s.charCodeAt(i + 0));
12152
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12153
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12154
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12155
- out[op++] = (v0 << 2) | (v1 >>> 4);
12156
- out[op++] = (v1 << 4) | (v2 >>> 2);
12157
- out[op++] = (v2 << 6) | v3;
12158
- haveBad |= v0 & INVALID_BYTE;
12159
- haveBad |= v1 & INVALID_BYTE;
12160
- haveBad |= v2 & INVALID_BYTE;
12161
- haveBad |= v3 & INVALID_BYTE;
12162
- }
12163
- if (i < length - 1) {
12164
- v0 = this._decodeChar(s.charCodeAt(i));
12165
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12166
- out[op++] = (v0 << 2) | (v1 >>> 4);
12167
- haveBad |= v0 & INVALID_BYTE;
12168
- haveBad |= v1 & INVALID_BYTE;
12169
- }
12170
- if (i < length - 2) {
12171
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12172
- out[op++] = (v1 << 4) | (v2 >>> 2);
12173
- haveBad |= v2 & INVALID_BYTE;
12174
- }
12175
- if (i < length - 3) {
12176
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12177
- out[op++] = (v2 << 6) | v3;
12178
- haveBad |= v3 & INVALID_BYTE;
12179
- }
12180
- if (haveBad !== 0) {
12181
- throw new Error("Base64Coder: incorrect characters for decoding");
12182
- }
12183
- return out;
12184
- };
12185
- // Standard encoding have the following encoded/decoded ranges,
12186
- // which we need to convert between.
12187
- //
12188
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
12189
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12190
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
12191
- //
12192
- // Encode 6 bits in b into a new character.
12193
- Coder.prototype._encodeByte = function (b) {
12194
- // Encoding uses constant time operations as follows:
12195
- //
12196
- // 1. Define comparison of A with B using (A - B) >>> 8:
12197
- // if A > B, then result is positive integer
12198
- // if A <= B, then result is 0
12199
- //
12200
- // 2. Define selection of C or 0 using bitwise AND: X & C:
12201
- // if X == 0, then result is 0
12202
- // if X != 0, then result is C
12203
- //
12204
- // 3. Start with the smallest comparison (b >= 0), which is always
12205
- // true, so set the result to the starting ASCII value (65).
12206
- //
12207
- // 4. Continue comparing b to higher ASCII values, and selecting
12208
- // zero if comparison isn't true, otherwise selecting a value
12209
- // to add to result, which:
12210
- //
12211
- // a) undoes the previous addition
12212
- // b) provides new value to add
12213
- //
12214
- var result = b;
12215
- // b >= 0
12216
- result += 65;
12217
- // b > 25
12218
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12219
- // b > 51
12220
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12221
- // b > 61
12222
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
12223
- // b > 62
12224
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
12225
- return String.fromCharCode(result);
12226
- };
12227
- // Decode a character code into a byte.
12228
- // Must return 256 if character is out of alphabet range.
12229
- Coder.prototype._decodeChar = function (c) {
12230
- // Decoding works similar to encoding: using the same comparison
12231
- // function, but now it works on ranges: result is always incremented
12232
- // by value, but this value becomes zero if the range is not
12233
- // satisfied.
12234
- //
12235
- // Decoding starts with invalid value, 256, which is then
12236
- // subtracted when the range is satisfied. If none of the ranges
12237
- // apply, the function returns 256, which is then checked by
12238
- // the caller to throw error.
12239
- var result = INVALID_BYTE; // start with invalid character
12240
- // c == 43 (c > 42 and c < 44)
12241
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
12242
- // c == 47 (c > 46 and c < 48)
12243
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
12244
- // c > 47 and c < 58
12245
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12246
- // c > 64 and c < 91
12247
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12248
- // c > 96 and c < 123
12249
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12250
- return result;
12251
- };
12252
- Coder.prototype._getPaddingLength = function (s) {
12253
- var paddingLength = 0;
12254
- if (this._paddingCharacter) {
12255
- for (var i = s.length - 1; i >= 0; i--) {
12256
- if (s[i] !== this._paddingCharacter) {
12257
- break;
12258
- }
12259
- paddingLength++;
12260
- }
12261
- if (s.length < 4 || paddingLength > 2) {
12262
- throw new Error("Base64Coder: incorrect padding");
12263
- }
12264
- }
12265
- return paddingLength;
12266
- };
12267
- return Coder;
12268
- }());
12269
- base64$1.Coder = Coder;
12270
- var stdCoder = new Coder();
12271
- function encode(data) {
12272
- return stdCoder.encode(data);
12273
- }
12274
- base64$1.encode = encode;
12275
- function decode(s) {
12276
- return stdCoder.decode(s);
12277
- }
12278
- base64$1.decode = decode;
12279
- /**
12280
- * Implements URL-safe Base64 encoding.
12281
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
12282
- *
12283
- * Operates in constant time.
12284
- */
12285
- var URLSafeCoder = /** @class */ (function (_super) {
12286
- __extends(URLSafeCoder, _super);
12287
- function URLSafeCoder() {
12288
- return _super !== null && _super.apply(this, arguments) || this;
12289
- }
12290
- // URL-safe encoding have the following encoded/decoded ranges:
12291
- //
12292
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
12293
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12294
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
12295
- //
12296
- URLSafeCoder.prototype._encodeByte = function (b) {
12297
- var result = b;
12298
- // b >= 0
12299
- result += 65;
12300
- // b > 25
12301
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12302
- // b > 51
12303
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12304
- // b > 61
12305
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
12306
- // b > 62
12307
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
12308
- return String.fromCharCode(result);
12309
- };
12310
- URLSafeCoder.prototype._decodeChar = function (c) {
12311
- var result = INVALID_BYTE;
12312
- // c == 45 (c > 44 and c < 46)
12313
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
12314
- // c == 95 (c > 94 and c < 96)
12315
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
12316
- // c > 47 and c < 58
12317
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12318
- // c > 64 and c < 91
12319
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12320
- // c > 96 and c < 123
12321
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12322
- return result;
12323
- };
12324
- return URLSafeCoder;
12325
- }(Coder));
12326
- base64$1.URLSafeCoder = URLSafeCoder;
12327
- var urlSafeCoder = new URLSafeCoder();
12328
- function encodeURLSafe(data) {
12329
- return urlSafeCoder.encode(data);
12330
- }
12331
- base64$1.encodeURLSafe = encodeURLSafe;
12332
- function decodeURLSafe(s) {
12333
- return urlSafeCoder.decode(s);
12334
- }
12335
- base64$1.decodeURLSafe = decodeURLSafe;
12336
- base64$1.encodedLength = function (length) {
12337
- return stdCoder.encodedLength(length);
12338
- };
12339
- base64$1.maxDecodedLength = function (length) {
12340
- return stdCoder.maxDecodedLength(length);
12341
- };
12342
- base64$1.decodedLength = function (s) {
12343
- return stdCoder.decodedLength(s);
11298
+ base64$1.encodeURLSafe = encodeURLSafe;
11299
+ function decodeURLSafe(s) {
11300
+ return urlSafeCoder.decode(s);
11301
+ }
11302
+ base64$1.decodeURLSafe = decodeURLSafe;
11303
+ base64$1.encodedLength = function (length) {
11304
+ return stdCoder.encodedLength(length);
11305
+ };
11306
+ base64$1.maxDecodedLength = function (length) {
11307
+ return stdCoder.maxDecodedLength(length);
11308
+ };
11309
+ base64$1.decodedLength = function (s) {
11310
+ return stdCoder.decodedLength(s);
12344
11311
  };
12345
11312
 
12346
11313
  var sha256$1 = {exports: {}};
@@ -12772,109 +11739,1232 @@ var sha256$1 = {exports: {}};
12772
11739
 
12773
11740
  var sha256Exports = sha256$1.exports;
12774
11741
 
12775
- Object.defineProperty(dist, "__esModule", { value: true });
12776
- var Webhook_1 = dist.Webhook = WebhookVerificationError_1 = dist.WebhookVerificationError = void 0;
12777
- const timing_safe_equal_1 = timing_safe_equal;
12778
- const base64 = base64$1;
12779
- const sha256 = sha256Exports;
12780
- const WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
12781
- class ExtendableError extends Error {
12782
- constructor(message) {
12783
- super(message);
12784
- Object.setPrototypeOf(this, ExtendableError.prototype);
12785
- this.name = "ExtendableError";
12786
- this.stack = new Error(message).stack;
11742
+ Object.defineProperty(dist, "__esModule", { value: true });
11743
+ var Webhook_1 = dist.Webhook = WebhookVerificationError_1 = dist.WebhookVerificationError = void 0;
11744
+ const timing_safe_equal_1 = timing_safe_equal;
11745
+ const base64 = base64$1;
11746
+ const sha256 = sha256Exports;
11747
+ const WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
11748
+ class ExtendableError extends Error {
11749
+ constructor(message) {
11750
+ super(message);
11751
+ Object.setPrototypeOf(this, ExtendableError.prototype);
11752
+ this.name = "ExtendableError";
11753
+ this.stack = new Error(message).stack;
11754
+ }
11755
+ }
11756
+ class WebhookVerificationError extends ExtendableError {
11757
+ constructor(message) {
11758
+ super(message);
11759
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
11760
+ this.name = "WebhookVerificationError";
11761
+ }
11762
+ }
11763
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
11764
+ class Webhook {
11765
+ constructor(secret, options) {
11766
+ if (!secret) {
11767
+ throw new Error("Secret can't be empty.");
11768
+ }
11769
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
11770
+ if (secret instanceof Uint8Array) {
11771
+ this.key = secret;
11772
+ }
11773
+ else {
11774
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
11775
+ }
11776
+ }
11777
+ else {
11778
+ if (typeof secret !== "string") {
11779
+ throw new Error("Expected secret to be of type string");
11780
+ }
11781
+ if (secret.startsWith(Webhook.prefix)) {
11782
+ secret = secret.substring(Webhook.prefix.length);
11783
+ }
11784
+ this.key = base64.decode(secret);
11785
+ }
11786
+ }
11787
+ verify(payload, headers_) {
11788
+ const headers = {};
11789
+ for (const key of Object.keys(headers_)) {
11790
+ headers[key.toLowerCase()] = headers_[key];
11791
+ }
11792
+ const msgId = headers["webhook-id"];
11793
+ const msgSignature = headers["webhook-signature"];
11794
+ const msgTimestamp = headers["webhook-timestamp"];
11795
+ if (!msgSignature || !msgId || !msgTimestamp) {
11796
+ throw new WebhookVerificationError("Missing required headers");
11797
+ }
11798
+ const timestamp = this.verifyTimestamp(msgTimestamp);
11799
+ const computedSignature = this.sign(msgId, timestamp, payload);
11800
+ const expectedSignature = computedSignature.split(",")[1];
11801
+ const passedSignatures = msgSignature.split(" ");
11802
+ const encoder = new globalThis.TextEncoder();
11803
+ for (const versionedSignature of passedSignatures) {
11804
+ const [version, signature] = versionedSignature.split(",");
11805
+ if (version !== "v1") {
11806
+ continue;
11807
+ }
11808
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
11809
+ return JSON.parse(payload.toString());
11810
+ }
11811
+ }
11812
+ throw new WebhookVerificationError("No matching signature found");
11813
+ }
11814
+ sign(msgId, timestamp, payload) {
11815
+ if (typeof payload === "string") ;
11816
+ else if (payload.constructor.name === "Buffer") {
11817
+ payload = payload.toString();
11818
+ }
11819
+ else {
11820
+ throw new Error("Expected payload to be of type string or Buffer.");
11821
+ }
11822
+ const encoder = new TextEncoder();
11823
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
11824
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
11825
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
11826
+ return `v1,${expectedSignature}`;
11827
+ }
11828
+ verifyTimestamp(timestampHeader) {
11829
+ const now = Math.floor(Date.now() / 1000);
11830
+ const timestamp = parseInt(timestampHeader, 10);
11831
+ if (isNaN(timestamp)) {
11832
+ throw new WebhookVerificationError("Invalid Signature Headers");
11833
+ }
11834
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
11835
+ throw new WebhookVerificationError("Message timestamp too old");
11836
+ }
11837
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
11838
+ throw new WebhookVerificationError("Message timestamp too new");
11839
+ }
11840
+ return new Date(timestamp * 1000);
11841
+ }
11842
+ }
11843
+ Webhook_1 = dist.Webhook = Webhook;
11844
+ Webhook.prefix = "whsec_";
11845
+
11846
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11847
+ let Webhooks$1 = class Webhooks extends APIResource {
11848
+ constructor() {
11849
+ super(...arguments);
11850
+ this.headers = new Headers$1(this._client);
11851
+ }
11852
+ /**
11853
+ * Create a new webhook
11854
+ */
11855
+ create(body, options) {
11856
+ return this._client.post('/webhooks', { body, ...options });
11857
+ }
11858
+ /**
11859
+ * Get a webhook by id
11860
+ */
11861
+ retrieve(webhookID, options) {
11862
+ return this._client.get(path `/webhooks/${webhookID}`, options);
11863
+ }
11864
+ /**
11865
+ * Patch a webhook by id
11866
+ */
11867
+ update(webhookID, body, options) {
11868
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11869
+ }
11870
+ /**
11871
+ * List all webhooks
11872
+ */
11873
+ list(query = {}, options) {
11874
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11875
+ }
11876
+ /**
11877
+ * Delete a webhook by id
11878
+ */
11879
+ delete(webhookID, options) {
11880
+ return this._client.delete(path `/webhooks/${webhookID}`, {
11881
+ ...options,
11882
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
11883
+ });
11884
+ }
11885
+ /**
11886
+ * Get webhook secret by id
11887
+ */
11888
+ retrieveSecret(webhookID, options) {
11889
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11890
+ }
11891
+ unsafeUnwrap(body) {
11892
+ return JSON.parse(body);
11893
+ }
11894
+ unwrap(body, { headers, key }) {
11895
+ if (headers !== undefined) {
11896
+ const keyStr = key === undefined ? this._client.webhookKey : key;
11897
+ if (keyStr === null)
11898
+ throw new Error('Webhook key must not be null in order to unwrap');
11899
+ const wh = new Webhook_1(keyStr);
11900
+ wh.verify(body, headers);
11901
+ }
11902
+ return JSON.parse(body);
11903
+ }
11904
+ };
11905
+ Webhooks$1.Headers = Headers$1;
11906
+
11907
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11908
+ /**
11909
+ * Read an environment variable.
11910
+ *
11911
+ * Trims beginning and trailing whitespace.
11912
+ *
11913
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11914
+ */
11915
+ const readEnv = (env) => {
11916
+ if (typeof globalThis.process !== 'undefined') {
11917
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
11918
+ }
11919
+ if (typeof globalThis.Deno !== 'undefined') {
11920
+ return globalThis.Deno.env?.get?.(env)?.trim();
11921
+ }
11922
+ return undefined;
11923
+ };
11924
+
11925
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11926
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11927
+ const environments = {
11928
+ live_mode: 'https://live.dodopayments.com',
11929
+ test_mode: 'https://test.dodopayments.com',
11930
+ };
11931
+ /**
11932
+ * API Client for interfacing with the Dodo Payments API.
11933
+ */
11934
+ class DodoPayments {
11935
+ /**
11936
+ * API Client for interfacing with the Dodo Payments API.
11937
+ *
11938
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11939
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
11940
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11941
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11942
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11943
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11944
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11945
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11946
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11947
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11948
+ */
11949
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
11950
+ _DodoPayments_instances.add(this);
11951
+ _DodoPayments_encoder.set(this, void 0);
11952
+ this.checkoutSessions = new CheckoutSessions(this);
11953
+ this.payments = new Payments(this);
11954
+ this.subscriptions = new Subscriptions(this);
11955
+ this.invoices = new Invoices(this);
11956
+ this.licenses = new Licenses(this);
11957
+ this.licenseKeys = new LicenseKeys(this);
11958
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
11959
+ this.customers = new Customers(this);
11960
+ this.refunds = new Refunds(this);
11961
+ this.disputes = new Disputes(this);
11962
+ this.payouts = new Payouts(this);
11963
+ this.products = new Products(this);
11964
+ this.misc = new Misc(this);
11965
+ this.discounts = new Discounts(this);
11966
+ this.addons = new Addons(this);
11967
+ this.brands = new Brands(this);
11968
+ this.webhooks = new Webhooks$1(this);
11969
+ this.webhookEvents = new WebhookEvents(this);
11970
+ this.usageEvents = new UsageEvents(this);
11971
+ this.meters = new Meters(this);
11972
+ if (bearerToken === undefined) {
11973
+ throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
11974
+ }
11975
+ const options = {
11976
+ bearerToken,
11977
+ webhookKey,
11978
+ ...opts,
11979
+ baseURL,
11980
+ environment: opts.environment ?? 'live_mode',
11981
+ };
11982
+ if (baseURL && opts.environment) {
11983
+ throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
11984
+ }
11985
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11986
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11987
+ this.logger = options.logger ?? console;
11988
+ const defaultLogLevel = 'warn';
11989
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
11990
+ this.logLevel = defaultLogLevel;
11991
+ this.logLevel =
11992
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11993
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11994
+ defaultLogLevel;
11995
+ this.fetchOptions = options.fetchOptions;
11996
+ this.maxRetries = options.maxRetries ?? 2;
11997
+ this.fetch = options.fetch ?? getDefaultFetch();
11998
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11999
+ this._options = options;
12000
+ this.bearerToken = bearerToken;
12001
+ this.webhookKey = webhookKey;
12002
+ }
12003
+ /**
12004
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
12005
+ */
12006
+ withOptions(options) {
12007
+ const client = new this.constructor({
12008
+ ...this._options,
12009
+ environment: options.environment ? options.environment : undefined,
12010
+ baseURL: options.environment ? undefined : this.baseURL,
12011
+ maxRetries: this.maxRetries,
12012
+ timeout: this.timeout,
12013
+ logger: this.logger,
12014
+ logLevel: this.logLevel,
12015
+ fetch: this.fetch,
12016
+ fetchOptions: this.fetchOptions,
12017
+ bearerToken: this.bearerToken,
12018
+ webhookKey: this.webhookKey,
12019
+ ...options,
12020
+ });
12021
+ return client;
12022
+ }
12023
+ defaultQuery() {
12024
+ return this._options.defaultQuery;
12025
+ }
12026
+ validateHeaders({ values, nulls }) {
12027
+ return;
12028
+ }
12029
+ async authHeaders(opts) {
12030
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
12031
+ }
12032
+ /**
12033
+ * Basic re-implementation of `qs.stringify` for primitive types.
12034
+ */
12035
+ stringifyQuery(query) {
12036
+ return Object.entries(query)
12037
+ .filter(([_, value]) => typeof value !== 'undefined')
12038
+ .map(([key, value]) => {
12039
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
12040
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
12041
+ }
12042
+ if (value === null) {
12043
+ return `${encodeURIComponent(key)}=`;
12044
+ }
12045
+ throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
12046
+ })
12047
+ .join('&');
12048
+ }
12049
+ getUserAgent() {
12050
+ return `${this.constructor.name}/JS ${VERSION}`;
12051
+ }
12052
+ defaultIdempotencyKey() {
12053
+ return `stainless-node-retry-${uuid4()}`;
12054
+ }
12055
+ makeStatusError(status, error, message, headers) {
12056
+ return APIError.generate(status, error, message, headers);
12057
+ }
12058
+ buildURL(path, query, defaultBaseURL) {
12059
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
12060
+ const url = isAbsoluteURL(path) ?
12061
+ new URL(path)
12062
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
12063
+ const defaultQuery = this.defaultQuery();
12064
+ if (!isEmptyObj(defaultQuery)) {
12065
+ query = { ...defaultQuery, ...query };
12066
+ }
12067
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
12068
+ url.search = this.stringifyQuery(query);
12069
+ }
12070
+ return url.toString();
12071
+ }
12072
+ /**
12073
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
12074
+ */
12075
+ async prepareOptions(options) { }
12076
+ /**
12077
+ * Used as a callback for mutating the given `RequestInit` object.
12078
+ *
12079
+ * This is useful for cases where you want to add certain headers based off of
12080
+ * the request properties, e.g. `method` or `url`.
12081
+ */
12082
+ async prepareRequest(request, { url, options }) { }
12083
+ get(path, opts) {
12084
+ return this.methodRequest('get', path, opts);
12085
+ }
12086
+ post(path, opts) {
12087
+ return this.methodRequest('post', path, opts);
12088
+ }
12089
+ patch(path, opts) {
12090
+ return this.methodRequest('patch', path, opts);
12091
+ }
12092
+ put(path, opts) {
12093
+ return this.methodRequest('put', path, opts);
12094
+ }
12095
+ delete(path, opts) {
12096
+ return this.methodRequest('delete', path, opts);
12097
+ }
12098
+ methodRequest(method, path, opts) {
12099
+ return this.request(Promise.resolve(opts).then((opts) => {
12100
+ return { method, path, ...opts };
12101
+ }));
12102
+ }
12103
+ request(options, remainingRetries = null) {
12104
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
12105
+ }
12106
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
12107
+ const options = await optionsInput;
12108
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12109
+ if (retriesRemaining == null) {
12110
+ retriesRemaining = maxRetries;
12111
+ }
12112
+ await this.prepareOptions(options);
12113
+ const { req, url, timeout } = await this.buildRequest(options, {
12114
+ retryCount: maxRetries - retriesRemaining,
12115
+ });
12116
+ await this.prepareRequest(req, { url, options });
12117
+ /** Not an API request ID, just for correlating local log entries. */
12118
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
12119
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
12120
+ const startTime = Date.now();
12121
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
12122
+ retryOfRequestLogID,
12123
+ method: options.method,
12124
+ url,
12125
+ options,
12126
+ headers: req.headers,
12127
+ }));
12128
+ if (options.signal?.aborted) {
12129
+ throw new APIUserAbortError();
12130
+ }
12131
+ const controller = new AbortController();
12132
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
12133
+ const headersTime = Date.now();
12134
+ if (response instanceof globalThis.Error) {
12135
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12136
+ if (options.signal?.aborted) {
12137
+ throw new APIUserAbortError();
12138
+ }
12139
+ // detect native connection timeout errors
12140
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
12141
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
12142
+ // others do not provide enough information to distinguish timeouts from other connection errors
12143
+ const isTimeout = isAbortError(response) ||
12144
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
12145
+ if (retriesRemaining) {
12146
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
12147
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
12148
+ retryOfRequestLogID,
12149
+ url,
12150
+ durationMs: headersTime - startTime,
12151
+ message: response.message,
12152
+ }));
12153
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
12154
+ }
12155
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
12156
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
12157
+ retryOfRequestLogID,
12158
+ url,
12159
+ durationMs: headersTime - startTime,
12160
+ message: response.message,
12161
+ }));
12162
+ if (isTimeout) {
12163
+ throw new APIConnectionTimeoutError();
12164
+ }
12165
+ throw new APIConnectionError({ cause: response });
12166
+ }
12167
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
12168
+ if (!response.ok) {
12169
+ const shouldRetry = await this.shouldRetry(response);
12170
+ if (retriesRemaining && shouldRetry) {
12171
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12172
+ // We don't need the body of this response.
12173
+ await CancelReadableStream(response.body);
12174
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12175
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12176
+ retryOfRequestLogID,
12177
+ url: response.url,
12178
+ status: response.status,
12179
+ headers: response.headers,
12180
+ durationMs: headersTime - startTime,
12181
+ }));
12182
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
12183
+ }
12184
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
12185
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12186
+ const errText = await response.text().catch((err) => castToError(err).message);
12187
+ const errJSON = safeJSON(errText);
12188
+ const errMessage = errJSON ? undefined : errText;
12189
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12190
+ retryOfRequestLogID,
12191
+ url: response.url,
12192
+ status: response.status,
12193
+ headers: response.headers,
12194
+ message: errMessage,
12195
+ durationMs: Date.now() - startTime,
12196
+ }));
12197
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
12198
+ throw err;
12199
+ }
12200
+ loggerFor(this).info(responseInfo);
12201
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
12202
+ retryOfRequestLogID,
12203
+ url: response.url,
12204
+ status: response.status,
12205
+ headers: response.headers,
12206
+ durationMs: headersTime - startTime,
12207
+ }));
12208
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
12209
+ }
12210
+ getAPIList(path, Page, opts) {
12211
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
12212
+ }
12213
+ requestAPIList(Page, options) {
12214
+ const request = this.makeRequest(options, null, undefined);
12215
+ return new PagePromise(this, request, Page);
12216
+ }
12217
+ async fetchWithTimeout(url, init, ms, controller) {
12218
+ const { signal, method, ...options } = init || {};
12219
+ if (signal)
12220
+ signal.addEventListener('abort', () => controller.abort());
12221
+ const timeout = setTimeout(() => controller.abort(), ms);
12222
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
12223
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
12224
+ const fetchOptions = {
12225
+ signal: controller.signal,
12226
+ ...(isReadableBody ? { duplex: 'half' } : {}),
12227
+ method: 'GET',
12228
+ ...options,
12229
+ };
12230
+ if (method) {
12231
+ // Custom methods like 'patch' need to be uppercased
12232
+ // See https://github.com/nodejs/undici/issues/2294
12233
+ fetchOptions.method = method.toUpperCase();
12234
+ }
12235
+ try {
12236
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
12237
+ return await this.fetch.call(undefined, url, fetchOptions);
12238
+ }
12239
+ finally {
12240
+ clearTimeout(timeout);
12241
+ }
12242
+ }
12243
+ async shouldRetry(response) {
12244
+ // Note this is not a standard header.
12245
+ const shouldRetryHeader = response.headers.get('x-should-retry');
12246
+ // If the server explicitly says whether or not to retry, obey.
12247
+ if (shouldRetryHeader === 'true')
12248
+ return true;
12249
+ if (shouldRetryHeader === 'false')
12250
+ return false;
12251
+ // Retry on request timeouts.
12252
+ if (response.status === 408)
12253
+ return true;
12254
+ // Retry on lock timeouts.
12255
+ if (response.status === 409)
12256
+ return true;
12257
+ // Retry on rate limits.
12258
+ if (response.status === 429)
12259
+ return true;
12260
+ // Retry internal errors.
12261
+ if (response.status >= 500)
12262
+ return true;
12263
+ return false;
12264
+ }
12265
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
12266
+ let timeoutMillis;
12267
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
12268
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
12269
+ if (retryAfterMillisHeader) {
12270
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
12271
+ if (!Number.isNaN(timeoutMs)) {
12272
+ timeoutMillis = timeoutMs;
12273
+ }
12274
+ }
12275
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
12276
+ const retryAfterHeader = responseHeaders?.get('retry-after');
12277
+ if (retryAfterHeader && !timeoutMillis) {
12278
+ const timeoutSeconds = parseFloat(retryAfterHeader);
12279
+ if (!Number.isNaN(timeoutSeconds)) {
12280
+ timeoutMillis = timeoutSeconds * 1000;
12281
+ }
12282
+ else {
12283
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
12284
+ }
12285
+ }
12286
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
12287
+ // just do what it says, but otherwise calculate a default
12288
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
12289
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12290
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
12291
+ }
12292
+ await sleep(timeoutMillis);
12293
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
12294
+ }
12295
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
12296
+ const initialRetryDelay = 0.5;
12297
+ const maxRetryDelay = 8.0;
12298
+ const numRetries = maxRetries - retriesRemaining;
12299
+ // Apply exponential backoff, but not more than the max.
12300
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
12301
+ // Apply some jitter, take up to at most 25 percent of the retry time.
12302
+ const jitter = 1 - Math.random() * 0.25;
12303
+ return sleepSeconds * jitter * 1000;
12304
+ }
12305
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
12306
+ const options = { ...inputOptions };
12307
+ const { method, path, query, defaultBaseURL } = options;
12308
+ const url = this.buildURL(path, query, defaultBaseURL);
12309
+ if ('timeout' in options)
12310
+ validatePositiveInteger('timeout', options.timeout);
12311
+ options.timeout = options.timeout ?? this.timeout;
12312
+ const { bodyHeaders, body } = this.buildBody({ options });
12313
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
12314
+ const req = {
12315
+ method,
12316
+ headers: reqHeaders,
12317
+ ...(options.signal && { signal: options.signal }),
12318
+ ...(globalThis.ReadableStream &&
12319
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
12320
+ ...(body && { body }),
12321
+ ...(this.fetchOptions ?? {}),
12322
+ ...(options.fetchOptions ?? {}),
12323
+ };
12324
+ return { req, url, timeout: options.timeout };
12325
+ }
12326
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
12327
+ let idempotencyHeaders = {};
12328
+ if (this.idempotencyHeader && method !== 'get') {
12329
+ if (!options.idempotencyKey)
12330
+ options.idempotencyKey = this.defaultIdempotencyKey();
12331
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
12332
+ }
12333
+ const headers = buildHeaders([
12334
+ idempotencyHeaders,
12335
+ {
12336
+ Accept: 'application/json',
12337
+ 'User-Agent': this.getUserAgent(),
12338
+ 'X-Stainless-Retry-Count': String(retryCount),
12339
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
12340
+ ...getPlatformHeaders(),
12341
+ },
12342
+ await this.authHeaders(options),
12343
+ this._options.defaultHeaders,
12344
+ bodyHeaders,
12345
+ options.headers,
12346
+ ]);
12347
+ this.validateHeaders(headers);
12348
+ return headers.values;
12349
+ }
12350
+ buildBody({ options: { body, headers: rawHeaders } }) {
12351
+ if (!body) {
12352
+ return { bodyHeaders: undefined, body: undefined };
12353
+ }
12354
+ const headers = buildHeaders([rawHeaders]);
12355
+ if (
12356
+ // Pass raw type verbatim
12357
+ ArrayBuffer.isView(body) ||
12358
+ body instanceof ArrayBuffer ||
12359
+ body instanceof DataView ||
12360
+ (typeof body === 'string' &&
12361
+ // Preserve legacy string encoding behavior for now
12362
+ headers.values.has('content-type')) ||
12363
+ // `Blob` is superset of `File`
12364
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
12365
+ // `FormData` -> `multipart/form-data`
12366
+ body instanceof FormData ||
12367
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
12368
+ body instanceof URLSearchParams ||
12369
+ // Send chunked stream (each chunk has own `length`)
12370
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
12371
+ return { bodyHeaders: undefined, body: body };
12372
+ }
12373
+ else if (typeof body === 'object' &&
12374
+ (Symbol.asyncIterator in body ||
12375
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
12376
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
12377
+ }
12378
+ else {
12379
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
12380
+ }
12381
+ }
12382
+ }
12383
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
12384
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
12385
+ };
12386
+ DodoPayments.DodoPayments = _a;
12387
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
12388
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
12389
+ DodoPayments.APIError = APIError;
12390
+ DodoPayments.APIConnectionError = APIConnectionError;
12391
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
12392
+ DodoPayments.APIUserAbortError = APIUserAbortError;
12393
+ DodoPayments.NotFoundError = NotFoundError;
12394
+ DodoPayments.ConflictError = ConflictError;
12395
+ DodoPayments.RateLimitError = RateLimitError;
12396
+ DodoPayments.BadRequestError = BadRequestError;
12397
+ DodoPayments.AuthenticationError = AuthenticationError;
12398
+ DodoPayments.InternalServerError = InternalServerError;
12399
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
12400
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
12401
+ DodoPayments.toFile = toFile;
12402
+ DodoPayments.CheckoutSessions = CheckoutSessions;
12403
+ DodoPayments.Payments = Payments;
12404
+ DodoPayments.Subscriptions = Subscriptions;
12405
+ DodoPayments.Invoices = Invoices;
12406
+ DodoPayments.Licenses = Licenses;
12407
+ DodoPayments.LicenseKeys = LicenseKeys;
12408
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
12409
+ DodoPayments.Customers = Customers;
12410
+ DodoPayments.Refunds = Refunds;
12411
+ DodoPayments.Disputes = Disputes;
12412
+ DodoPayments.Payouts = Payouts;
12413
+ DodoPayments.Products = Products;
12414
+ DodoPayments.Misc = Misc;
12415
+ DodoPayments.Discounts = Discounts;
12416
+ DodoPayments.Addons = Addons;
12417
+ DodoPayments.Brands = Brands;
12418
+ DodoPayments.Webhooks = Webhooks$1;
12419
+ DodoPayments.WebhookEvents = WebhookEvents;
12420
+ DodoPayments.UsageEvents = UsageEvents;
12421
+ DodoPayments.Meters = Meters;
12422
+
12423
+ // src/checkout/checkout.ts
12424
+ var checkoutQuerySchema = objectType({
12425
+ productId: stringType(),
12426
+ quantity: stringType().optional(),
12427
+ // Customer fields
12428
+ fullName: stringType().optional(),
12429
+ firstName: stringType().optional(),
12430
+ lastName: stringType().optional(),
12431
+ email: stringType().optional(),
12432
+ country: stringType().optional(),
12433
+ addressLine: stringType().optional(),
12434
+ city: stringType().optional(),
12435
+ state: stringType().optional(),
12436
+ zipCode: stringType().optional(),
12437
+ // Disable flags
12438
+ disableFullName: stringType().optional(),
12439
+ disableFirstName: stringType().optional(),
12440
+ disableLastName: stringType().optional(),
12441
+ disableEmail: stringType().optional(),
12442
+ disableCountry: stringType().optional(),
12443
+ disableAddressLine: stringType().optional(),
12444
+ disableCity: stringType().optional(),
12445
+ disableState: stringType().optional(),
12446
+ disableZipCode: stringType().optional(),
12447
+ // Advanced controls
12448
+ paymentCurrency: stringType().optional(),
12449
+ showCurrencySelector: stringType().optional(),
12450
+ paymentAmount: stringType().optional(),
12451
+ showDiscounts: stringType().optional()
12452
+ // Metadata (allow any key starting with metadata_)
12453
+ // We'll handle metadata separately in the handler
12454
+ }).catchall(unknownType());
12455
+ var dynamicCheckoutBodySchema = objectType({
12456
+ // For subscription
12457
+ product_id: stringType().optional(),
12458
+ quantity: numberType().optional(),
12459
+ // For one-time payment
12460
+ product_cart: arrayType(
12461
+ objectType({
12462
+ product_id: stringType(),
12463
+ quantity: numberType()
12464
+ })
12465
+ ).optional(),
12466
+ // Common fields
12467
+ billing: objectType({
12468
+ city: stringType(),
12469
+ country: stringType(),
12470
+ state: stringType(),
12471
+ street: stringType(),
12472
+ zipcode: stringType()
12473
+ }),
12474
+ customer: objectType({
12475
+ customer_id: stringType().optional(),
12476
+ email: stringType().optional(),
12477
+ name: stringType().optional()
12478
+ }),
12479
+ discount_id: stringType().optional(),
12480
+ addons: arrayType(
12481
+ objectType({
12482
+ addon_id: stringType(),
12483
+ quantity: numberType()
12484
+ })
12485
+ ).optional(),
12486
+ metadata: recordType(stringType(), stringType()).optional(),
12487
+ currency: stringType().optional()
12488
+ // Allow any additional fields (for future compatibility)
12489
+ }).catchall(unknownType());
12490
+ var checkoutSessionProductCartItemSchema = objectType({
12491
+ product_id: stringType().min(1, "Product ID is required"),
12492
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
12493
+ addons: arrayType(
12494
+ objectType({
12495
+ addon_id: stringType(),
12496
+ quantity: numberType().int().nonnegative()
12497
+ })
12498
+ ).optional(),
12499
+ amount: numberType().int().nonnegative(
12500
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
12501
+ ).optional()
12502
+ });
12503
+ var checkoutSessionCustomerSchema = unionType([
12504
+ objectType({
12505
+ email: stringType().email(),
12506
+ name: stringType().min(1).optional(),
12507
+ phone_number: stringType().optional()
12508
+ }),
12509
+ objectType({
12510
+ customer_id: stringType()
12511
+ })
12512
+ ]).optional();
12513
+ var checkoutSessionBillingAddressSchema = objectType({
12514
+ street: stringType().optional(),
12515
+ city: stringType().optional(),
12516
+ state: stringType().optional(),
12517
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
12518
+ zipcode: stringType().optional()
12519
+ }).optional();
12520
+ var paymentMethodTypeSchema = enumType([
12521
+ "credit",
12522
+ "debit",
12523
+ "upi_collect",
12524
+ "upi_intent",
12525
+ "apple_pay",
12526
+ "cashapp",
12527
+ "google_pay",
12528
+ "multibanco",
12529
+ "bancontact_card",
12530
+ "eps",
12531
+ "ideal",
12532
+ "przelewy24",
12533
+ "paypal",
12534
+ "affirm",
12535
+ "klarna",
12536
+ "sepa",
12537
+ "ach",
12538
+ "amazon_pay",
12539
+ "afterpay_clearpay"
12540
+ ]);
12541
+ var checkoutSessionCustomizationSchema = objectType({
12542
+ theme: enumType(["light", "dark", "system"]).optional(),
12543
+ show_order_details: booleanType().optional(),
12544
+ show_on_demand_tag: booleanType().optional(),
12545
+ force_language: stringType().optional()
12546
+ }).optional();
12547
+ var checkoutSessionFeatureFlagsSchema = objectType({
12548
+ allow_currency_selection: booleanType().optional(),
12549
+ allow_discount_code: booleanType().optional(),
12550
+ allow_phone_number_collection: booleanType().optional(),
12551
+ allow_tax_id: booleanType().optional(),
12552
+ always_create_new_customer: booleanType().optional()
12553
+ }).optional();
12554
+ var checkoutSessionOnDemandSchema = objectType({
12555
+ mandate_only: booleanType(),
12556
+ product_price: numberType().int().optional(),
12557
+ product_currency: stringType().length(3).optional(),
12558
+ product_description: stringType().optional(),
12559
+ adaptive_currency_fees_inclusive: booleanType().optional()
12560
+ }).optional();
12561
+ var checkoutSessionSubscriptionDataSchema = objectType({
12562
+ trial_period_days: numberType().int().nonnegative().optional(),
12563
+ on_demand: checkoutSessionOnDemandSchema
12564
+ }).optional();
12565
+ var checkoutSessionPayloadSchema = objectType({
12566
+ // Required fields
12567
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
12568
+ // Optional fields
12569
+ customer: checkoutSessionCustomerSchema,
12570
+ billing_address: checkoutSessionBillingAddressSchema,
12571
+ return_url: stringType().url().optional(),
12572
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
12573
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
12574
+ show_saved_payment_methods: booleanType().optional(),
12575
+ confirm: booleanType().optional(),
12576
+ discount_code: stringType().optional(),
12577
+ metadata: recordType(stringType(), stringType()).optional(),
12578
+ customization: checkoutSessionCustomizationSchema,
12579
+ feature_flags: checkoutSessionFeatureFlagsSchema,
12580
+ subscription_data: checkoutSessionSubscriptionDataSchema,
12581
+ force_3ds: booleanType().optional()
12582
+ });
12583
+ var checkoutSessionResponseSchema = objectType({
12584
+ session_id: stringType().min(1, "Session ID is required"),
12585
+ checkout_url: stringType().url("Invalid checkout URL")
12586
+ });
12587
+ var createCheckoutSession = async (payload, config) => {
12588
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
12589
+ if (!validation.success) {
12590
+ throw new Error(
12591
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12592
+ );
12593
+ }
12594
+ const dodopayments = new DodoPayments({
12595
+ bearerToken: config.bearerToken,
12596
+ environment: config.environment
12597
+ });
12598
+ try {
12599
+ const sdkPayload = {
12600
+ ...validation.data,
12601
+ ...validation.data.billing_address && {
12602
+ billing_address: {
12603
+ ...validation.data.billing_address,
12604
+ country: validation.data.billing_address.country
12605
+ }
12606
+ }
12607
+ };
12608
+ const session = await dodopayments.checkoutSessions.create(
12609
+ sdkPayload
12610
+ );
12611
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
12612
+ if (!responseValidation.success) {
12613
+ throw new Error(
12614
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12615
+ );
12616
+ }
12617
+ return responseValidation.data;
12618
+ } catch (error) {
12619
+ if (error instanceof Error) {
12620
+ console.error("Dodo Payments Checkout Session API Error:", {
12621
+ message: error.message,
12622
+ payload: validation.data,
12623
+ config: {
12624
+ environment: config.environment,
12625
+ hasBearerToken: !!config.bearerToken
12626
+ }
12627
+ });
12628
+ throw new Error(`Failed to create checkout session: ${error.message}`);
12629
+ }
12630
+ console.error("Unknown error creating checkout session:", error);
12631
+ throw new Error(
12632
+ "Failed to create checkout session due to an unknown error"
12633
+ );
12634
+ }
12635
+ };
12636
+ var buildCheckoutUrl = async ({
12637
+ queryParams,
12638
+ body,
12639
+ sessionPayload,
12640
+ returnUrl,
12641
+ bearerToken,
12642
+ environment,
12643
+ type = "static"
12644
+ }) => {
12645
+ if (type === "session") {
12646
+ if (!sessionPayload) {
12647
+ throw new Error("sessionPayload is required when type is 'session'");
12648
+ }
12649
+ const session = await createCheckoutSession(sessionPayload, {
12650
+ bearerToken,
12651
+ environment
12652
+ });
12653
+ return session.checkout_url;
12654
+ }
12655
+ const inputData = type === "dynamic" ? body : queryParams;
12656
+ let parseResult;
12657
+ if (type === "dynamic") {
12658
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
12659
+ } else {
12660
+ parseResult = checkoutQuerySchema.safeParse(inputData);
12661
+ }
12662
+ const { success, data, error } = parseResult;
12663
+ if (!success) {
12664
+ throw new Error(
12665
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
12666
+ ${error.message}`
12667
+ );
12668
+ }
12669
+ if (type !== "dynamic") {
12670
+ const {
12671
+ productId,
12672
+ quantity: quantity2,
12673
+ fullName,
12674
+ firstName,
12675
+ lastName,
12676
+ email,
12677
+ country,
12678
+ addressLine,
12679
+ city,
12680
+ state,
12681
+ zipCode,
12682
+ disableFullName,
12683
+ disableFirstName,
12684
+ disableLastName,
12685
+ disableEmail,
12686
+ disableCountry,
12687
+ disableAddressLine,
12688
+ disableCity,
12689
+ disableState,
12690
+ disableZipCode,
12691
+ paymentCurrency,
12692
+ showCurrencySelector,
12693
+ paymentAmount,
12694
+ showDiscounts
12695
+ // metadata handled below
12696
+ } = data;
12697
+ const dodopayments2 = new DodoPayments({
12698
+ bearerToken,
12699
+ environment
12700
+ });
12701
+ if (!productId) throw new Error("Missing required field: productId");
12702
+ try {
12703
+ await dodopayments2.products.retrieve(productId);
12704
+ } catch (err) {
12705
+ console.error(err);
12706
+ throw new Error("Product not found");
12707
+ }
12708
+ const url = new URL(
12709
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
12710
+ );
12711
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
12712
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
12713
+ if (fullName) url.searchParams.set("fullName", String(fullName));
12714
+ if (firstName) url.searchParams.set("firstName", String(firstName));
12715
+ if (lastName) url.searchParams.set("lastName", String(lastName));
12716
+ if (email) url.searchParams.set("email", String(email));
12717
+ if (country) url.searchParams.set("country", String(country));
12718
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
12719
+ if (city) url.searchParams.set("city", String(city));
12720
+ if (state) url.searchParams.set("state", String(state));
12721
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
12722
+ if (disableFullName === "true")
12723
+ url.searchParams.set("disableFullName", "true");
12724
+ if (disableFirstName === "true")
12725
+ url.searchParams.set("disableFirstName", "true");
12726
+ if (disableLastName === "true")
12727
+ url.searchParams.set("disableLastName", "true");
12728
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
12729
+ if (disableCountry === "true")
12730
+ url.searchParams.set("disableCountry", "true");
12731
+ if (disableAddressLine === "true")
12732
+ url.searchParams.set("disableAddressLine", "true");
12733
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
12734
+ if (disableState === "true") url.searchParams.set("disableState", "true");
12735
+ if (disableZipCode === "true")
12736
+ url.searchParams.set("disableZipCode", "true");
12737
+ if (paymentCurrency)
12738
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
12739
+ if (showCurrencySelector)
12740
+ url.searchParams.set(
12741
+ "showCurrencySelector",
12742
+ String(showCurrencySelector)
12743
+ );
12744
+ if (paymentAmount)
12745
+ url.searchParams.set("paymentAmount", String(paymentAmount));
12746
+ if (showDiscounts)
12747
+ url.searchParams.set("showDiscounts", String(showDiscounts));
12748
+ for (const [key, value] of Object.entries(queryParams || {})) {
12749
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
12750
+ url.searchParams.set(key, String(value));
12751
+ }
12752
+ }
12753
+ return url.toString();
12754
+ }
12755
+ const dyn = data;
12756
+ const {
12757
+ product_id,
12758
+ product_cart,
12759
+ quantity,
12760
+ billing,
12761
+ customer,
12762
+ addons,
12763
+ metadata,
12764
+ allowed_payment_method_types,
12765
+ billing_currency,
12766
+ discount_code,
12767
+ on_demand,
12768
+ return_url: bodyReturnUrl,
12769
+ show_saved_payment_methods,
12770
+ tax_id,
12771
+ trial_period_days
12772
+ } = dyn;
12773
+ const dodopayments = new DodoPayments({
12774
+ bearerToken,
12775
+ environment
12776
+ });
12777
+ let isSubscription = false;
12778
+ let productIdToFetch = product_id;
12779
+ if (!product_id && product_cart && product_cart.length > 0) {
12780
+ productIdToFetch = product_cart[0].product_id;
12781
+ }
12782
+ if (!productIdToFetch)
12783
+ throw new Error(
12784
+ "Missing required field: product_id or product_cart[0].product_id"
12785
+ );
12786
+ let product;
12787
+ try {
12788
+ product = await dodopayments.products.retrieve(productIdToFetch);
12789
+ } catch (err) {
12790
+ console.error(err);
12791
+ throw new Error("Product not found");
12792
+ }
12793
+ isSubscription = Boolean(product.is_recurring);
12794
+ if (isSubscription && !product_id)
12795
+ throw new Error("Missing required field: product_id for subscription");
12796
+ if (!billing) throw new Error("Missing required field: billing");
12797
+ if (!customer) throw new Error("Missing required field: customer");
12798
+ if (isSubscription) {
12799
+ const subscriptionPayload = {
12800
+ billing,
12801
+ customer,
12802
+ product_id,
12803
+ quantity: quantity ? Number(quantity) : 1
12804
+ };
12805
+ if (metadata) subscriptionPayload.metadata = metadata;
12806
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
12807
+ if (addons) subscriptionPayload.addons = addons;
12808
+ if (allowed_payment_method_types)
12809
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
12810
+ if (billing_currency)
12811
+ subscriptionPayload.billing_currency = billing_currency;
12812
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
12813
+ subscriptionPayload.payment_link = true;
12814
+ if (bodyReturnUrl) {
12815
+ subscriptionPayload.return_url = bodyReturnUrl;
12816
+ } else if (returnUrl) {
12817
+ subscriptionPayload.return_url = returnUrl;
12787
12818
  }
12788
- }
12789
- class WebhookVerificationError extends ExtendableError {
12790
- constructor(message) {
12791
- super(message);
12792
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
12793
- this.name = "WebhookVerificationError";
12819
+ if (show_saved_payment_methods)
12820
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
12821
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
12822
+ if (trial_period_days)
12823
+ subscriptionPayload.trial_period_days = trial_period_days;
12824
+ let subscription;
12825
+ try {
12826
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
12827
+ } catch (err) {
12828
+ console.error("Error when creating subscription", err);
12829
+ throw new Error(err instanceof Error ? err.message : String(err));
12794
12830
  }
12795
- }
12796
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
12797
- class Webhook {
12798
- constructor(secret, options) {
12799
- if (!secret) {
12800
- throw new Error("Secret can't be empty.");
12831
+ if (!subscription || !subscription.payment_link) {
12832
+ throw new Error(
12833
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
12834
+ );
12835
+ }
12836
+ return subscription.payment_link;
12837
+ } else {
12838
+ let cart = product_cart;
12839
+ if (!cart && product_id) {
12840
+ cart = [
12841
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
12842
+ ];
12843
+ }
12844
+ if (!cart || cart.length === 0)
12845
+ throw new Error("Missing required field: product_cart or product_id");
12846
+ const paymentPayload = {
12847
+ billing,
12848
+ customer,
12849
+ product_cart: cart
12850
+ };
12851
+ if (metadata) paymentPayload.metadata = metadata;
12852
+ paymentPayload.payment_link = true;
12853
+ if (allowed_payment_method_types)
12854
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
12855
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
12856
+ if (discount_code) paymentPayload.discount_code = discount_code;
12857
+ if (bodyReturnUrl) {
12858
+ paymentPayload.return_url = bodyReturnUrl;
12859
+ } else if (returnUrl) {
12860
+ paymentPayload.return_url = returnUrl;
12861
+ }
12862
+ if (show_saved_payment_methods)
12863
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
12864
+ if (tax_id) paymentPayload.tax_id = tax_id;
12865
+ let payment;
12866
+ try {
12867
+ payment = await dodopayments.payments.create(paymentPayload);
12868
+ } catch (err) {
12869
+ console.error("Error when creating payment link", err);
12870
+ throw new Error(err instanceof Error ? err.message : String(err));
12871
+ }
12872
+ if (!payment || !payment.payment_link) {
12873
+ throw new Error(
12874
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
12875
+ );
12876
+ }
12877
+ return payment.payment_link;
12878
+ }
12879
+ };
12880
+
12881
+ const Checkout = (config) => {
12882
+ const getHandler = async (req) => {
12883
+ const { searchParams } = new URL(req.url);
12884
+ const queryParams = Object.fromEntries(searchParams);
12885
+ if (!queryParams.productId) {
12886
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12887
+ status: 400,
12888
+ });
12801
12889
  }
12802
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
12803
- if (secret instanceof Uint8Array) {
12804
- this.key = secret;
12805
- }
12806
- else {
12807
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
12890
+ const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
12891
+ if (!success) {
12892
+ if (error.errors.some((e) => e.path.toString() === "productId")) {
12893
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12894
+ status: 400,
12895
+ });
12808
12896
  }
12897
+ return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
12898
+ status: 400,
12899
+ });
12809
12900
  }
12810
- else {
12811
- if (typeof secret !== "string") {
12812
- throw new Error("Expected secret to be of type string");
12813
- }
12814
- if (secret.startsWith(Webhook.prefix)) {
12815
- secret = secret.substring(Webhook.prefix.length);
12816
- }
12817
- this.key = base64.decode(secret);
12901
+ let url = "";
12902
+ try {
12903
+ url = await buildCheckoutUrl({ queryParams: data, ...config });
12818
12904
  }
12819
- }
12820
- verify(payload, headers_) {
12821
- const headers = {};
12822
- for (const key of Object.keys(headers_)) {
12823
- headers[key.toLowerCase()] = headers_[key];
12905
+ catch (error) {
12906
+ return new serverExports.NextResponse(error.message, { status: 400 });
12824
12907
  }
12825
- const msgId = headers["webhook-id"];
12826
- const msgSignature = headers["webhook-signature"];
12827
- const msgTimestamp = headers["webhook-timestamp"];
12828
- if (!msgSignature || !msgId || !msgTimestamp) {
12829
- throw new WebhookVerificationError("Missing required headers");
12908
+ return serverExports.NextResponse.json({ checkout_url: url });
12909
+ };
12910
+ const postHandler = async (req) => {
12911
+ let body;
12912
+ try {
12913
+ body = await req.json();
12830
12914
  }
12831
- const timestamp = this.verifyTimestamp(msgTimestamp);
12832
- const computedSignature = this.sign(msgId, timestamp, payload);
12833
- const expectedSignature = computedSignature.split(",")[1];
12834
- const passedSignatures = msgSignature.split(" ");
12835
- const encoder = new globalThis.TextEncoder();
12836
- for (const versionedSignature of passedSignatures) {
12837
- const [version, signature] = versionedSignature.split(",");
12838
- if (version !== "v1") {
12839
- continue;
12915
+ catch (e) {
12916
+ return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
12917
+ }
12918
+ if (config.type === "dynamic") {
12919
+ // Handle dynamic checkout
12920
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
12921
+ if (!success) {
12922
+ return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
12923
+ status: 400,
12924
+ });
12840
12925
  }
12841
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
12842
- return JSON.parse(payload.toString());
12926
+ let url = "";
12927
+ try {
12928
+ url = await buildCheckoutUrl({
12929
+ body: data,
12930
+ ...config,
12931
+ type: "dynamic",
12932
+ });
12843
12933
  }
12844
- }
12845
- throw new WebhookVerificationError("No matching signature found");
12846
- }
12847
- sign(msgId, timestamp, payload) {
12848
- if (typeof payload === "string") ;
12849
- else if (payload.constructor.name === "Buffer") {
12850
- payload = payload.toString();
12934
+ catch (error) {
12935
+ return new serverExports.NextResponse(error.message, { status: 400 });
12936
+ }
12937
+ return serverExports.NextResponse.json({ checkout_url: url });
12851
12938
  }
12852
12939
  else {
12853
- throw new Error("Expected payload to be of type string or Buffer.");
12854
- }
12855
- const encoder = new TextEncoder();
12856
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
12857
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
12858
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
12859
- return `v1,${expectedSignature}`;
12860
- }
12861
- verifyTimestamp(timestampHeader) {
12862
- const now = Math.floor(Date.now() / 1000);
12863
- const timestamp = parseInt(timestampHeader, 10);
12864
- if (isNaN(timestamp)) {
12865
- throw new WebhookVerificationError("Invalid Signature Headers");
12866
- }
12867
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
12868
- throw new WebhookVerificationError("Message timestamp too old");
12940
+ // Handle checkout session
12941
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12942
+ if (!success) {
12943
+ return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12944
+ status: 400,
12945
+ });
12946
+ }
12947
+ let url = "";
12948
+ try {
12949
+ url = await buildCheckoutUrl({
12950
+ sessionPayload: data,
12951
+ ...config,
12952
+ type: "session",
12953
+ });
12954
+ }
12955
+ catch (error) {
12956
+ return new serverExports.NextResponse(error.message, { status: 400 });
12957
+ }
12958
+ return serverExports.NextResponse.json({ checkout_url: url });
12869
12959
  }
12870
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
12871
- throw new WebhookVerificationError("Message timestamp too new");
12960
+ };
12961
+ return (req) => {
12962
+ if (req.method === "POST") {
12963
+ return postHandler(req);
12872
12964
  }
12873
- return new Date(timestamp * 1000);
12874
- }
12875
- }
12876
- Webhook_1 = dist.Webhook = Webhook;
12877
- Webhook.prefix = "whsec_";
12965
+ return getHandler(req);
12966
+ };
12967
+ };
12878
12968
 
12879
12969
  // src/schemas/webhook.ts
12880
12970
  var PaymentSchema = objectType({