@dodopayments/remix 0.2.1 → 0.2.3

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
@@ -3961,7 +3961,7 @@ const unknownType = ZodUnknown.create;
3961
3961
  ZodNever.create;
3962
3962
  const arrayType = ZodArray.create;
3963
3963
  const objectType = ZodObject.create;
3964
- ZodUnion.create;
3964
+ const unionType = ZodUnion.create;
3965
3965
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
3966
3966
  ZodIntersection.create;
3967
3967
  ZodTuple.create;
@@ -4180,7 +4180,7 @@ const safeJSON = (text) => {
4180
4180
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4181
4181
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4182
4182
 
4183
- const VERSION = '2.2.0'; // x-release-please-version
4183
+ const VERSION = '2.4.6'; // x-release-please-version
4184
4184
 
4185
4185
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4186
4186
  /**
@@ -4930,6 +4930,9 @@ class CheckoutSessions extends APIResource {
4930
4930
  create(body, options) {
4931
4931
  return this._client.post('/checkouts', { body, ...options });
4932
4932
  }
4933
+ retrieve(id, options) {
4934
+ return this._client.get(path `/checkouts/${id}`, options);
4935
+ }
4933
4936
  }
4934
4937
 
4935
4938
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -5608,1464 +5611,287 @@ let Headers$1 = class Headers extends APIResource {
5608
5611
  }
5609
5612
  };
5610
5613
 
5611
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5612
- let Webhooks$1 = class Webhooks extends APIResource {
5613
- constructor() {
5614
- super(...arguments);
5615
- this.headers = new Headers$1(this._client);
5616
- }
5617
- /**
5618
- * Create a new webhook
5619
- */
5620
- create(body, options) {
5621
- return this._client.post('/webhooks', { body, ...options });
5622
- }
5623
- /**
5624
- * Get a webhook by id
5625
- */
5626
- retrieve(webhookID, options) {
5627
- return this._client.get(path `/webhooks/${webhookID}`, options);
5614
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5615
+
5616
+ var dist = {};
5617
+
5618
+ var timing_safe_equal = {};
5619
+
5620
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
5621
+ timing_safe_equal.timingSafeEqual = void 0;
5622
+ function assert(expr, msg = "") {
5623
+ if (!expr) {
5624
+ throw new Error(msg);
5628
5625
  }
5629
- /**
5630
- * Patch a webhook by id
5631
- */
5632
- update(webhookID, body, options) {
5633
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
5626
+ }
5627
+ function timingSafeEqual(a, b) {
5628
+ if (a.byteLength !== b.byteLength) {
5629
+ return false;
5634
5630
  }
5635
- /**
5636
- * List all webhooks
5637
- */
5638
- list(query = {}, options) {
5639
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
5631
+ if (!(a instanceof DataView)) {
5632
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
5640
5633
  }
5641
- /**
5642
- * Delete a webhook by id
5643
- */
5644
- delete(webhookID, options) {
5645
- return this._client.delete(path `/webhooks/${webhookID}`, {
5646
- ...options,
5647
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
5648
- });
5634
+ if (!(b instanceof DataView)) {
5635
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
5649
5636
  }
5650
- /**
5651
- * Get webhook secret by id
5652
- */
5653
- retrieveSecret(webhookID, options) {
5654
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
5637
+ assert(a instanceof DataView);
5638
+ assert(b instanceof DataView);
5639
+ const length = a.byteLength;
5640
+ let out = 0;
5641
+ let i = -1;
5642
+ while (++i < length) {
5643
+ out |= a.getUint8(i) ^ b.getUint8(i);
5655
5644
  }
5656
- };
5657
- Webhooks$1.Headers = Headers$1;
5645
+ return out === 0;
5646
+ }
5647
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
5658
5648
 
5659
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5649
+ var base64$1 = {};
5650
+
5651
+ // Copyright (C) 2016 Dmitry Chestnykh
5652
+ // MIT License. See LICENSE file for details.
5653
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
5654
+ var extendStatics = function (d, b) {
5655
+ extendStatics = Object.setPrototypeOf ||
5656
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5657
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5658
+ return extendStatics(d, b);
5659
+ };
5660
+ return function (d, b) {
5661
+ extendStatics(d, b);
5662
+ function __() { this.constructor = d; }
5663
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5664
+ };
5665
+ })();
5666
+ Object.defineProperty(base64$1, "__esModule", { value: true });
5660
5667
  /**
5661
- * Read an environment variable.
5662
- *
5663
- * Trims beginning and trailing whitespace.
5664
- *
5665
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
5668
+ * Package base64 implements Base64 encoding and decoding.
5666
5669
  */
5667
- const readEnv = (env) => {
5668
- if (typeof globalThis.process !== 'undefined') {
5669
- return globalThis.process.env?.[env]?.trim() ?? undefined;
5670
- }
5671
- if (typeof globalThis.Deno !== 'undefined') {
5672
- return globalThis.Deno.env?.get?.(env)?.trim();
5673
- }
5674
- return undefined;
5675
- };
5676
-
5677
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5678
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
5679
- const environments = {
5680
- live_mode: 'https://live.dodopayments.com',
5681
- test_mode: 'https://test.dodopayments.com',
5682
- };
5670
+ // Invalid character used in decoding to indicate
5671
+ // that the character to decode is out of range of
5672
+ // alphabet and cannot be decoded.
5673
+ var INVALID_BYTE = 256;
5683
5674
  /**
5684
- * API Client for interfacing with the Dodo Payments API.
5675
+ * Implements standard Base64 encoding.
5676
+ *
5677
+ * Operates in constant time.
5685
5678
  */
5686
- class DodoPayments {
5687
- /**
5688
- * API Client for interfacing with the Dodo Payments API.
5689
- *
5690
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
5691
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
5692
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
5693
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
5694
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
5695
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
5696
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
5697
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
5698
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
5699
- */
5700
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
5701
- _DodoPayments_instances.add(this);
5702
- _DodoPayments_encoder.set(this, void 0);
5703
- this.checkoutSessions = new CheckoutSessions(this);
5704
- this.payments = new Payments(this);
5705
- this.subscriptions = new Subscriptions(this);
5706
- this.invoices = new Invoices(this);
5707
- this.licenses = new Licenses(this);
5708
- this.licenseKeys = new LicenseKeys(this);
5709
- this.licenseKeyInstances = new LicenseKeyInstances(this);
5710
- this.customers = new Customers(this);
5711
- this.refunds = new Refunds(this);
5712
- this.disputes = new Disputes(this);
5713
- this.payouts = new Payouts(this);
5714
- this.webhookEvents = new WebhookEvents(this);
5715
- this.products = new Products(this);
5716
- this.misc = new Misc(this);
5717
- this.discounts = new Discounts(this);
5718
- this.addons = new Addons(this);
5719
- this.brands = new Brands(this);
5720
- this.webhooks = new Webhooks$1(this);
5721
- this.usageEvents = new UsageEvents(this);
5722
- this.meters = new Meters(this);
5723
- if (bearerToken === undefined) {
5724
- 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' }).");
5679
+ var Coder = /** @class */ (function () {
5680
+ // TODO(dchest): methods to encode chunk-by-chunk.
5681
+ function Coder(_paddingCharacter) {
5682
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
5683
+ this._paddingCharacter = _paddingCharacter;
5684
+ }
5685
+ Coder.prototype.encodedLength = function (length) {
5686
+ if (!this._paddingCharacter) {
5687
+ return (length * 8 + 5) / 6 | 0;
5725
5688
  }
5726
- const options = {
5727
- bearerToken,
5728
- ...opts,
5729
- baseURL,
5730
- environment: opts.environment ?? 'live_mode',
5731
- };
5732
- if (baseURL && opts.environment) {
5733
- 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');
5689
+ return (length + 2) / 3 * 4 | 0;
5690
+ };
5691
+ Coder.prototype.encode = function (data) {
5692
+ var out = "";
5693
+ var i = 0;
5694
+ for (; i < data.length - 2; i += 3) {
5695
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
5696
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5697
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5698
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5699
+ out += this._encodeByte((c >>> 0 * 6) & 63);
5734
5700
  }
5735
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
5736
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
5737
- this.logger = options.logger ?? console;
5738
- const defaultLogLevel = 'warn';
5739
- // Set default logLevel early so that we can log a warning in parseLogLevel.
5740
- this.logLevel = defaultLogLevel;
5741
- this.logLevel =
5742
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
5743
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
5744
- defaultLogLevel;
5745
- this.fetchOptions = options.fetchOptions;
5746
- this.maxRetries = options.maxRetries ?? 2;
5747
- this.fetch = options.fetch ?? getDefaultFetch();
5748
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
5749
- this._options = options;
5750
- this.bearerToken = bearerToken;
5751
- }
5752
- /**
5753
- * Create a new client instance re-using the same options given to the current client with optional overriding.
5754
- */
5755
- withOptions(options) {
5756
- const client = new this.constructor({
5757
- ...this._options,
5758
- environment: options.environment ? options.environment : undefined,
5759
- baseURL: options.environment ? undefined : this.baseURL,
5760
- maxRetries: this.maxRetries,
5761
- timeout: this.timeout,
5762
- logger: this.logger,
5763
- logLevel: this.logLevel,
5764
- fetch: this.fetch,
5765
- fetchOptions: this.fetchOptions,
5766
- bearerToken: this.bearerToken,
5767
- ...options,
5768
- });
5769
- return client;
5770
- }
5771
- defaultQuery() {
5772
- return this._options.defaultQuery;
5773
- }
5774
- validateHeaders({ values, nulls }) {
5775
- return;
5776
- }
5777
- async authHeaders(opts) {
5778
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
5779
- }
5780
- /**
5781
- * Basic re-implementation of `qs.stringify` for primitive types.
5782
- */
5783
- stringifyQuery(query) {
5784
- return Object.entries(query)
5785
- .filter(([_, value]) => typeof value !== 'undefined')
5786
- .map(([key, value]) => {
5787
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
5788
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
5701
+ var left = data.length - i;
5702
+ if (left > 0) {
5703
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
5704
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5705
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5706
+ if (left === 2) {
5707
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5789
5708
  }
5790
- if (value === null) {
5791
- return `${encodeURIComponent(key)}=`;
5709
+ else {
5710
+ out += this._paddingCharacter || "";
5792
5711
  }
5793
- 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.`);
5794
- })
5795
- .join('&');
5796
- }
5797
- getUserAgent() {
5798
- return `${this.constructor.name}/JS ${VERSION}`;
5799
- }
5800
- defaultIdempotencyKey() {
5801
- return `stainless-node-retry-${uuid4()}`;
5802
- }
5803
- makeStatusError(status, error, message, headers) {
5804
- return APIError.generate(status, error, message, headers);
5805
- }
5806
- buildURL(path, query, defaultBaseURL) {
5807
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
5808
- const url = isAbsoluteURL(path) ?
5809
- new URL(path)
5810
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
5811
- const defaultQuery = this.defaultQuery();
5812
- if (!isEmptyObj(defaultQuery)) {
5813
- query = { ...defaultQuery, ...query };
5814
- }
5815
- if (typeof query === 'object' && query && !Array.isArray(query)) {
5816
- url.search = this.stringifyQuery(query);
5712
+ out += this._paddingCharacter || "";
5817
5713
  }
5818
- return url.toString();
5819
- }
5820
- /**
5821
- * Used as a callback for mutating the given `FinalRequestOptions` object.
5822
- */
5823
- async prepareOptions(options) { }
5824
- /**
5825
- * Used as a callback for mutating the given `RequestInit` object.
5826
- *
5827
- * This is useful for cases where you want to add certain headers based off of
5828
- * the request properties, e.g. `method` or `url`.
5829
- */
5830
- async prepareRequest(request, { url, options }) { }
5831
- get(path, opts) {
5832
- return this.methodRequest('get', path, opts);
5833
- }
5834
- post(path, opts) {
5835
- return this.methodRequest('post', path, opts);
5836
- }
5837
- patch(path, opts) {
5838
- return this.methodRequest('patch', path, opts);
5839
- }
5840
- put(path, opts) {
5841
- return this.methodRequest('put', path, opts);
5842
- }
5843
- delete(path, opts) {
5844
- return this.methodRequest('delete', path, opts);
5845
- }
5846
- methodRequest(method, path, opts) {
5847
- return this.request(Promise.resolve(opts).then((opts) => {
5848
- return { method, path, ...opts };
5849
- }));
5850
- }
5851
- request(options, remainingRetries = null) {
5852
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
5853
- }
5854
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
5855
- const options = await optionsInput;
5856
- const maxRetries = options.maxRetries ?? this.maxRetries;
5857
- if (retriesRemaining == null) {
5858
- retriesRemaining = maxRetries;
5714
+ return out;
5715
+ };
5716
+ Coder.prototype.maxDecodedLength = function (length) {
5717
+ if (!this._paddingCharacter) {
5718
+ return (length * 6 + 7) / 8 | 0;
5859
5719
  }
5860
- await this.prepareOptions(options);
5861
- const { req, url, timeout } = await this.buildRequest(options, {
5862
- retryCount: maxRetries - retriesRemaining,
5863
- });
5864
- await this.prepareRequest(req, { url, options });
5865
- /** Not an API request ID, just for correlating local log entries. */
5866
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
5867
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
5868
- const startTime = Date.now();
5869
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
5870
- retryOfRequestLogID,
5871
- method: options.method,
5872
- url,
5873
- options,
5874
- headers: req.headers,
5875
- }));
5876
- if (options.signal?.aborted) {
5877
- throw new APIUserAbortError();
5720
+ return length / 4 * 3 | 0;
5721
+ };
5722
+ Coder.prototype.decodedLength = function (s) {
5723
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
5724
+ };
5725
+ Coder.prototype.decode = function (s) {
5726
+ if (s.length === 0) {
5727
+ return new Uint8Array(0);
5878
5728
  }
5879
- const controller = new AbortController();
5880
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
5881
- const headersTime = Date.now();
5882
- if (response instanceof globalThis.Error) {
5883
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
5884
- if (options.signal?.aborted) {
5885
- throw new APIUserAbortError();
5886
- }
5887
- // detect native connection timeout errors
5888
- // 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)"
5889
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
5890
- // others do not provide enough information to distinguish timeouts from other connection errors
5891
- const isTimeout = isAbortError(response) ||
5892
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
5893
- if (retriesRemaining) {
5894
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
5895
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
5896
- retryOfRequestLogID,
5897
- url,
5898
- durationMs: headersTime - startTime,
5899
- message: response.message,
5900
- }));
5901
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
5902
- }
5903
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
5904
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
5905
- retryOfRequestLogID,
5906
- url,
5907
- durationMs: headersTime - startTime,
5908
- message: response.message,
5909
- }));
5910
- if (isTimeout) {
5911
- throw new APIConnectionTimeoutError();
5912
- }
5913
- throw new APIConnectionError({ cause: response });
5729
+ var paddingLength = this._getPaddingLength(s);
5730
+ var length = s.length - paddingLength;
5731
+ var out = new Uint8Array(this.maxDecodedLength(length));
5732
+ var op = 0;
5733
+ var i = 0;
5734
+ var haveBad = 0;
5735
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
5736
+ for (; i < length - 4; i += 4) {
5737
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
5738
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5739
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5740
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5741
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5742
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5743
+ out[op++] = (v2 << 6) | v3;
5744
+ haveBad |= v0 & INVALID_BYTE;
5745
+ haveBad |= v1 & INVALID_BYTE;
5746
+ haveBad |= v2 & INVALID_BYTE;
5747
+ haveBad |= v3 & INVALID_BYTE;
5914
5748
  }
5915
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
5916
- if (!response.ok) {
5917
- const shouldRetry = await this.shouldRetry(response);
5918
- if (retriesRemaining && shouldRetry) {
5919
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
5920
- // We don't need the body of this response.
5921
- await CancelReadableStream(response.body);
5922
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
5923
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
5924
- retryOfRequestLogID,
5925
- url: response.url,
5926
- status: response.status,
5927
- headers: response.headers,
5928
- durationMs: headersTime - startTime,
5929
- }));
5930
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
5931
- }
5932
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
5933
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
5934
- const errText = await response.text().catch((err) => castToError(err).message);
5935
- const errJSON = safeJSON(errText);
5936
- const errMessage = errJSON ? undefined : errText;
5937
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
5938
- retryOfRequestLogID,
5939
- url: response.url,
5940
- status: response.status,
5941
- headers: response.headers,
5942
- message: errMessage,
5943
- durationMs: Date.now() - startTime,
5944
- }));
5945
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
5946
- throw err;
5749
+ if (i < length - 1) {
5750
+ v0 = this._decodeChar(s.charCodeAt(i));
5751
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5752
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5753
+ haveBad |= v0 & INVALID_BYTE;
5754
+ haveBad |= v1 & INVALID_BYTE;
5947
5755
  }
5948
- loggerFor(this).info(responseInfo);
5949
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
5950
- retryOfRequestLogID,
5951
- url: response.url,
5952
- status: response.status,
5953
- headers: response.headers,
5954
- durationMs: headersTime - startTime,
5955
- }));
5956
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
5957
- }
5958
- getAPIList(path, Page, opts) {
5959
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
5960
- }
5961
- requestAPIList(Page, options) {
5962
- const request = this.makeRequest(options, null, undefined);
5963
- return new PagePromise(this, request, Page);
5964
- }
5965
- async fetchWithTimeout(url, init, ms, controller) {
5966
- const { signal, method, ...options } = init || {};
5967
- if (signal)
5968
- signal.addEventListener('abort', () => controller.abort());
5969
- const timeout = setTimeout(() => controller.abort(), ms);
5970
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
5971
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
5972
- const fetchOptions = {
5973
- signal: controller.signal,
5974
- ...(isReadableBody ? { duplex: 'half' } : {}),
5975
- method: 'GET',
5976
- ...options,
5977
- };
5978
- if (method) {
5979
- // Custom methods like 'patch' need to be uppercased
5980
- // See https://github.com/nodejs/undici/issues/2294
5981
- fetchOptions.method = method.toUpperCase();
5756
+ if (i < length - 2) {
5757
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5758
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5759
+ haveBad |= v2 & INVALID_BYTE;
5982
5760
  }
5983
- try {
5984
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
5985
- return await this.fetch.call(undefined, url, fetchOptions);
5761
+ if (i < length - 3) {
5762
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5763
+ out[op++] = (v2 << 6) | v3;
5764
+ haveBad |= v3 & INVALID_BYTE;
5986
5765
  }
5987
- finally {
5988
- clearTimeout(timeout);
5766
+ if (haveBad !== 0) {
5767
+ throw new Error("Base64Coder: incorrect characters for decoding");
5989
5768
  }
5990
- }
5991
- async shouldRetry(response) {
5992
- // Note this is not a standard header.
5993
- const shouldRetryHeader = response.headers.get('x-should-retry');
5994
- // If the server explicitly says whether or not to retry, obey.
5995
- if (shouldRetryHeader === 'true')
5996
- return true;
5997
- if (shouldRetryHeader === 'false')
5998
- return false;
5999
- // Retry on request timeouts.
6000
- if (response.status === 408)
6001
- return true;
6002
- // Retry on lock timeouts.
6003
- if (response.status === 409)
6004
- return true;
6005
- // Retry on rate limits.
6006
- if (response.status === 429)
6007
- return true;
6008
- // Retry internal errors.
6009
- if (response.status >= 500)
6010
- return true;
6011
- return false;
6012
- }
6013
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6014
- let timeoutMillis;
6015
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6016
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6017
- if (retryAfterMillisHeader) {
6018
- const timeoutMs = parseFloat(retryAfterMillisHeader);
6019
- if (!Number.isNaN(timeoutMs)) {
6020
- timeoutMillis = timeoutMs;
6021
- }
6022
- }
6023
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6024
- const retryAfterHeader = responseHeaders?.get('retry-after');
6025
- if (retryAfterHeader && !timeoutMillis) {
6026
- const timeoutSeconds = parseFloat(retryAfterHeader);
6027
- if (!Number.isNaN(timeoutSeconds)) {
6028
- timeoutMillis = timeoutSeconds * 1000;
5769
+ return out;
5770
+ };
5771
+ // Standard encoding have the following encoded/decoded ranges,
5772
+ // which we need to convert between.
5773
+ //
5774
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
5775
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5776
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
5777
+ //
5778
+ // Encode 6 bits in b into a new character.
5779
+ Coder.prototype._encodeByte = function (b) {
5780
+ // Encoding uses constant time operations as follows:
5781
+ //
5782
+ // 1. Define comparison of A with B using (A - B) >>> 8:
5783
+ // if A > B, then result is positive integer
5784
+ // if A <= B, then result is 0
5785
+ //
5786
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
5787
+ // if X == 0, then result is 0
5788
+ // if X != 0, then result is C
5789
+ //
5790
+ // 3. Start with the smallest comparison (b >= 0), which is always
5791
+ // true, so set the result to the starting ASCII value (65).
5792
+ //
5793
+ // 4. Continue comparing b to higher ASCII values, and selecting
5794
+ // zero if comparison isn't true, otherwise selecting a value
5795
+ // to add to result, which:
5796
+ //
5797
+ // a) undoes the previous addition
5798
+ // b) provides new value to add
5799
+ //
5800
+ var result = b;
5801
+ // b >= 0
5802
+ result += 65;
5803
+ // b > 25
5804
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5805
+ // b > 51
5806
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5807
+ // b > 61
5808
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
5809
+ // b > 62
5810
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
5811
+ return String.fromCharCode(result);
5812
+ };
5813
+ // Decode a character code into a byte.
5814
+ // Must return 256 if character is out of alphabet range.
5815
+ Coder.prototype._decodeChar = function (c) {
5816
+ // Decoding works similar to encoding: using the same comparison
5817
+ // function, but now it works on ranges: result is always incremented
5818
+ // by value, but this value becomes zero if the range is not
5819
+ // satisfied.
5820
+ //
5821
+ // Decoding starts with invalid value, 256, which is then
5822
+ // subtracted when the range is satisfied. If none of the ranges
5823
+ // apply, the function returns 256, which is then checked by
5824
+ // the caller to throw error.
5825
+ var result = INVALID_BYTE; // start with invalid character
5826
+ // c == 43 (c > 42 and c < 44)
5827
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
5828
+ // c == 47 (c > 46 and c < 48)
5829
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
5830
+ // c > 47 and c < 58
5831
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
5832
+ // c > 64 and c < 91
5833
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
5834
+ // c > 96 and c < 123
5835
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
5836
+ return result;
5837
+ };
5838
+ Coder.prototype._getPaddingLength = function (s) {
5839
+ var paddingLength = 0;
5840
+ if (this._paddingCharacter) {
5841
+ for (var i = s.length - 1; i >= 0; i--) {
5842
+ if (s[i] !== this._paddingCharacter) {
5843
+ break;
5844
+ }
5845
+ paddingLength++;
6029
5846
  }
6030
- else {
6031
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
5847
+ if (s.length < 4 || paddingLength > 2) {
5848
+ throw new Error("Base64Coder: incorrect padding");
6032
5849
  }
6033
5850
  }
6034
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
6035
- // just do what it says, but otherwise calculate a default
6036
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
6037
- const maxRetries = options.maxRetries ?? this.maxRetries;
6038
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6039
- }
6040
- await sleep(timeoutMillis);
6041
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6042
- }
6043
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6044
- const initialRetryDelay = 0.5;
6045
- const maxRetryDelay = 8.0;
6046
- const numRetries = maxRetries - retriesRemaining;
6047
- // Apply exponential backoff, but not more than the max.
6048
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6049
- // Apply some jitter, take up to at most 25 percent of the retry time.
6050
- const jitter = 1 - Math.random() * 0.25;
6051
- return sleepSeconds * jitter * 1000;
6052
- }
6053
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6054
- const options = { ...inputOptions };
6055
- const { method, path, query, defaultBaseURL } = options;
6056
- const url = this.buildURL(path, query, defaultBaseURL);
6057
- if ('timeout' in options)
6058
- validatePositiveInteger('timeout', options.timeout);
6059
- options.timeout = options.timeout ?? this.timeout;
6060
- const { bodyHeaders, body } = this.buildBody({ options });
6061
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6062
- const req = {
6063
- method,
6064
- headers: reqHeaders,
6065
- ...(options.signal && { signal: options.signal }),
6066
- ...(globalThis.ReadableStream &&
6067
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
6068
- ...(body && { body }),
6069
- ...(this.fetchOptions ?? {}),
6070
- ...(options.fetchOptions ?? {}),
6071
- };
6072
- return { req, url, timeout: options.timeout };
6073
- }
6074
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
6075
- let idempotencyHeaders = {};
6076
- if (this.idempotencyHeader && method !== 'get') {
6077
- if (!options.idempotencyKey)
6078
- options.idempotencyKey = this.defaultIdempotencyKey();
6079
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6080
- }
6081
- const headers = buildHeaders([
6082
- idempotencyHeaders,
6083
- {
6084
- Accept: 'application/json',
6085
- 'User-Agent': this.getUserAgent(),
6086
- 'X-Stainless-Retry-Count': String(retryCount),
6087
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
6088
- ...getPlatformHeaders(),
6089
- },
6090
- await this.authHeaders(options),
6091
- this._options.defaultHeaders,
6092
- bodyHeaders,
6093
- options.headers,
6094
- ]);
6095
- this.validateHeaders(headers);
6096
- return headers.values;
6097
- }
6098
- buildBody({ options: { body, headers: rawHeaders } }) {
6099
- if (!body) {
6100
- return { bodyHeaders: undefined, body: undefined };
6101
- }
6102
- const headers = buildHeaders([rawHeaders]);
6103
- if (
6104
- // Pass raw type verbatim
6105
- ArrayBuffer.isView(body) ||
6106
- body instanceof ArrayBuffer ||
6107
- body instanceof DataView ||
6108
- (typeof body === 'string' &&
6109
- // Preserve legacy string encoding behavior for now
6110
- headers.values.has('content-type')) ||
6111
- // `Blob` is superset of `File`
6112
- (globalThis.Blob && body instanceof globalThis.Blob) ||
6113
- // `FormData` -> `multipart/form-data`
6114
- body instanceof FormData ||
6115
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
6116
- body instanceof URLSearchParams ||
6117
- // Send chunked stream (each chunk has own `length`)
6118
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
6119
- return { bodyHeaders: undefined, body: body };
6120
- }
6121
- else if (typeof body === 'object' &&
6122
- (Symbol.asyncIterator in body ||
6123
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
6124
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6125
- }
6126
- else {
6127
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
6128
- }
6129
- }
6130
- }
6131
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
6132
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
6133
- };
6134
- DodoPayments.DodoPayments = _a;
6135
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
6136
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
6137
- DodoPayments.APIError = APIError;
6138
- DodoPayments.APIConnectionError = APIConnectionError;
6139
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
6140
- DodoPayments.APIUserAbortError = APIUserAbortError;
6141
- DodoPayments.NotFoundError = NotFoundError;
6142
- DodoPayments.ConflictError = ConflictError;
6143
- DodoPayments.RateLimitError = RateLimitError;
6144
- DodoPayments.BadRequestError = BadRequestError;
6145
- DodoPayments.AuthenticationError = AuthenticationError;
6146
- DodoPayments.InternalServerError = InternalServerError;
6147
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
6148
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
6149
- DodoPayments.toFile = toFile;
6150
- DodoPayments.CheckoutSessions = CheckoutSessions;
6151
- DodoPayments.Payments = Payments;
6152
- DodoPayments.Subscriptions = Subscriptions;
6153
- DodoPayments.Invoices = Invoices;
6154
- DodoPayments.Licenses = Licenses;
6155
- DodoPayments.LicenseKeys = LicenseKeys;
6156
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
6157
- DodoPayments.Customers = Customers;
6158
- DodoPayments.Refunds = Refunds;
6159
- DodoPayments.Disputes = Disputes;
6160
- DodoPayments.Payouts = Payouts;
6161
- DodoPayments.WebhookEvents = WebhookEvents;
6162
- DodoPayments.Products = Products;
6163
- DodoPayments.Misc = Misc;
6164
- DodoPayments.Discounts = Discounts;
6165
- DodoPayments.Addons = Addons;
6166
- DodoPayments.Brands = Brands;
6167
- DodoPayments.Webhooks = Webhooks$1;
6168
- DodoPayments.UsageEvents = UsageEvents;
6169
- DodoPayments.Meters = Meters;
6170
-
6171
- var __assign = (undefined && undefined.__assign) || function () {
6172
- __assign = Object.assign || function(t) {
6173
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6174
- s = arguments[i];
6175
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6176
- t[p] = s[p];
6177
- }
6178
- return t;
5851
+ return paddingLength;
6179
5852
  };
6180
- return __assign.apply(this, arguments);
6181
- };
6182
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
6183
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6184
- return new (P || (P = Promise))(function (resolve, reject) {
6185
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6186
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6187
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
6188
- step((generator = generator.apply(thisArg, _arguments || [])).next());
6189
- });
6190
- };
6191
- var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
6192
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
6193
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
6194
- function verb(n) { return function (v) { return step([n, v]); }; }
6195
- function step(op) {
6196
- if (f) throw new TypeError("Generator is already executing.");
6197
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
6198
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
6199
- if (y = 0, t) op = [op[0] & 2, t.value];
6200
- switch (op[0]) {
6201
- case 0: case 1: t = op; break;
6202
- case 4: _.label++; return { value: op[1], done: false };
6203
- case 5: _.label++; y = op[1]; op = [0]; continue;
6204
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
6205
- default:
6206
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
6207
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
6208
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
6209
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
6210
- if (t[2]) _.ops.pop();
6211
- _.trys.pop(); continue;
6212
- }
6213
- op = body.call(thisArg, _);
6214
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
6215
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6216
- }
6217
- };
6218
- var checkoutQuerySchema = objectType({
6219
- productId: stringType(),
6220
- quantity: stringType().optional(),
6221
- // Customer fields
6222
- fullName: stringType().optional(),
6223
- firstName: stringType().optional(),
6224
- lastName: stringType().optional(),
6225
- email: stringType().optional(),
6226
- country: stringType().optional(),
6227
- addressLine: stringType().optional(),
6228
- city: stringType().optional(),
6229
- state: stringType().optional(),
6230
- zipCode: stringType().optional(),
6231
- // Disable flags
6232
- disableFullName: stringType().optional(),
6233
- disableFirstName: stringType().optional(),
6234
- disableLastName: stringType().optional(),
6235
- disableEmail: stringType().optional(),
6236
- disableCountry: stringType().optional(),
6237
- disableAddressLine: stringType().optional(),
6238
- disableCity: stringType().optional(),
6239
- disableState: stringType().optional(),
6240
- disableZipCode: stringType().optional(),
6241
- // Advanced controls
6242
- paymentCurrency: stringType().optional(),
6243
- showCurrencySelector: stringType().optional(),
6244
- paymentAmount: stringType().optional(),
6245
- showDiscounts: stringType().optional(),
6246
- // Metadata (allow any key starting with metadata_)
6247
- // We'll handle metadata separately in the handler
6248
- })
6249
- .catchall(unknownType());
6250
- // Add Zod schema for dynamic checkout body
6251
- var dynamicCheckoutBodySchema = objectType({
6252
- // For subscription
6253
- product_id: stringType().optional(),
6254
- quantity: numberType().optional(),
6255
- // For one-time payment
6256
- product_cart: arrayType(objectType({
6257
- product_id: stringType(),
6258
- quantity: numberType(),
6259
- }))
6260
- .optional(),
6261
- // Common fields
6262
- billing: objectType({
6263
- city: stringType(),
6264
- country: stringType(),
6265
- state: stringType(),
6266
- street: stringType(),
6267
- zipcode: stringType(),
6268
- }),
6269
- customer: objectType({
6270
- customer_id: stringType().optional(),
6271
- email: stringType().optional(),
6272
- name: stringType().optional(),
6273
- }),
6274
- discount_id: stringType().optional(),
6275
- addons: arrayType(objectType({
6276
- addon_id: stringType(),
6277
- quantity: numberType(),
6278
- }))
6279
- .optional(),
6280
- metadata: recordType(stringType(), stringType()).optional(),
6281
- currency: stringType().optional(),
6282
- // Allow any additional fields (for future compatibility)
6283
- })
6284
- .catchall(unknownType());
6285
- // ========================================
6286
- // CHECKOUT SESSIONS SCHEMAS & TYPES
6287
- // ========================================
6288
- // Product cart item schema for checkout sessions
6289
- var checkoutSessionProductCartItemSchema = objectType({
6290
- product_id: stringType().min(1, "Product ID is required"),
6291
- quantity: numberType().int().positive("Quantity must be a positive integer"),
6292
- });
6293
- // Customer information schema for checkout sessions
6294
- var checkoutSessionCustomerSchema = objectType({
6295
- email: stringType().email().optional(),
6296
- name: stringType().min(1).optional(),
6297
- phone_number: stringType().optional(),
6298
- })
6299
- .optional();
6300
- // Billing address schema for checkout sessions
6301
- var checkoutSessionBillingAddressSchema = objectType({
6302
- street: stringType().optional(),
6303
- city: stringType().optional(),
6304
- state: stringType().optional(),
6305
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
6306
- zipcode: stringType().optional(),
6307
- })
6308
- .optional();
6309
- // Payment method types enum based on Dodo Payments documentation
6310
- var paymentMethodTypeSchema = enumType([
6311
- "credit",
6312
- "debit",
6313
- "upi_collect",
6314
- "upi_intent",
6315
- "apple_pay",
6316
- "google_pay",
6317
- "amazon_pay",
6318
- "klarna",
6319
- "affirm",
6320
- "afterpay_clearpay",
6321
- "sepa",
6322
- "ach",
6323
- ]);
6324
- // Customization options schema
6325
- var checkoutSessionCustomizationSchema = objectType({
6326
- theme: enumType(["light", "dark", "system"]).optional(),
6327
- show_order_details: booleanType().optional(),
6328
- show_on_demand_tag: booleanType().optional(),
6329
- })
6330
- .optional();
6331
- // Feature flags schema
6332
- var checkoutSessionFeatureFlagsSchema = objectType({
6333
- allow_currency_selection: booleanType().optional(),
6334
- allow_discount_code: booleanType().optional(),
6335
- allow_phone_number_collection: booleanType().optional(),
6336
- allow_tax_id: booleanType().optional(),
6337
- always_create_new_customer: booleanType().optional(),
6338
- })
6339
- .optional();
6340
- // Subscription data schema
6341
- var checkoutSessionSubscriptionDataSchema = objectType({
6342
- trial_period_days: numberType().int().nonnegative().optional(),
6343
- })
6344
- .optional();
6345
- // Main checkout session payload schema
6346
- var checkoutSessionPayloadSchema = objectType({
6347
- // Required fields
6348
- product_cart: arrayType(checkoutSessionProductCartItemSchema)
6349
- .min(1, "At least one product is required"),
6350
- // Optional fields
6351
- customer: checkoutSessionCustomerSchema,
6352
- billing_address: checkoutSessionBillingAddressSchema,
6353
- return_url: stringType().url().optional(),
6354
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
6355
- billing_currency: stringType()
6356
- .length(3, "Currency must be a 3-letter ISO code")
6357
- .optional(),
6358
- show_saved_payment_methods: booleanType().optional(),
6359
- confirm: booleanType().optional(),
6360
- discount_code: stringType().optional(),
6361
- metadata: recordType(stringType(), stringType()).optional(),
6362
- customization: checkoutSessionCustomizationSchema,
6363
- feature_flags: checkoutSessionFeatureFlagsSchema,
6364
- subscription_data: checkoutSessionSubscriptionDataSchema,
6365
- });
6366
- // Checkout session response schema
6367
- var checkoutSessionResponseSchema = objectType({
6368
- session_id: stringType().min(1, "Session ID is required"),
6369
- checkout_url: stringType().url("Invalid checkout URL"),
6370
- });
6371
- /**
6372
- * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
6373
- * This function provides a clean, type-safe interface to the Checkout Sessions API.
6374
- *
6375
- * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
6376
- * @param config - Dodo Payments client configuration (bearerToken, environment)
6377
- * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
6378
- *
6379
- * @throws {Error} When payload validation fails or API request fails
6380
- *
6381
- * @example
6382
- * ```typescript
6383
- * const session = await createCheckoutSession({
6384
- * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
6385
- * customer: { email: 'customer@example.com' },
6386
- * return_url: 'https://yoursite.com/success'
6387
- * }, {
6388
- * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
6389
- * environment: 'test_mode'
6390
- * });
6391
- *
6392
- * ```
6393
- */
6394
- var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
6395
- var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
6396
- return __generator$1(this, function (_a) {
6397
- switch (_a.label) {
6398
- case 0:
6399
- validation = checkoutSessionPayloadSchema.safeParse(payload);
6400
- if (!validation.success) {
6401
- throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
6402
- .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
6403
- .join(", ")));
6404
- }
6405
- dodopayments = new DodoPayments({
6406
- bearerToken: config.bearerToken,
6407
- environment: config.environment,
6408
- });
6409
- _a.label = 1;
6410
- case 1:
6411
- _a.trys.push([1, 3, , 4]);
6412
- sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
6413
- billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
6414
- }));
6415
- return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
6416
- case 2:
6417
- session = _a.sent();
6418
- responseValidation = checkoutSessionResponseSchema.safeParse(session);
6419
- if (!responseValidation.success) {
6420
- throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
6421
- .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
6422
- .join(", ")));
6423
- }
6424
- return [2 /*return*/, responseValidation.data];
6425
- case 3:
6426
- error_1 = _a.sent();
6427
- if (error_1 instanceof Error) {
6428
- console.error("Dodo Payments Checkout Session API Error:", {
6429
- message: error_1.message,
6430
- payload: validation.data,
6431
- config: {
6432
- environment: config.environment,
6433
- hasBearerToken: !!config.bearerToken,
6434
- },
6435
- });
6436
- // Re-throw with a more user-friendly message
6437
- throw new Error("Failed to create checkout session: ".concat(error_1.message));
6438
- }
6439
- // Handle non-Error objects
6440
- console.error("Unknown error creating checkout session:", error_1);
6441
- throw new Error("Failed to create checkout session due to an unknown error");
6442
- case 4: return [2 /*return*/];
6443
- }
6444
- });
6445
- }); };
6446
- var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
6447
- var session, inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
6448
- var queryParams = _b.queryParams, body = _b.body, sessionPayload = _b.sessionPayload, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
6449
- return __generator$1(this, function (_g) {
6450
- switch (_g.label) {
6451
- case 0:
6452
- if (!(type === "session")) return [3 /*break*/, 2];
6453
- if (!sessionPayload) {
6454
- throw new Error("sessionPayload is required when type is 'session'");
6455
- }
6456
- return [4 /*yield*/, createCheckoutSession(sessionPayload, {
6457
- bearerToken: bearerToken,
6458
- environment: environment,
6459
- })];
6460
- case 1:
6461
- session = _g.sent();
6462
- return [2 /*return*/, session.checkout_url];
6463
- case 2:
6464
- inputData = type === "dynamic" ? body : queryParams;
6465
- if (type === "dynamic") {
6466
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
6467
- }
6468
- else {
6469
- parseResult = checkoutQuerySchema.safeParse(inputData);
6470
- }
6471
- success = parseResult.success, data = parseResult.data, error = parseResult.error;
6472
- if (!success) {
6473
- throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
6474
- }
6475
- if (!(type !== "dynamic")) return [3 /*break*/, 7];
6476
- _c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
6477
- dodopayments_1 = new DodoPayments({
6478
- bearerToken: bearerToken,
6479
- environment: environment,
6480
- });
6481
- // Check that the product exists for this merchant
6482
- if (!productId)
6483
- throw new Error("Missing required field: productId");
6484
- _g.label = 3;
6485
- case 3:
6486
- _g.trys.push([3, 5, , 6]);
6487
- return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
6488
- case 4:
6489
- _g.sent();
6490
- return [3 /*break*/, 6];
6491
- case 5:
6492
- err_1 = _g.sent();
6493
- console.error(err_1);
6494
- throw new Error("Product not found");
6495
- case 6:
6496
- url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
6497
- url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
6498
- if (returnUrl)
6499
- url.searchParams.set("redirect_url", returnUrl);
6500
- // Customer/billing fields
6501
- if (fullName)
6502
- url.searchParams.set("fullName", String(fullName));
6503
- if (firstName)
6504
- url.searchParams.set("firstName", String(firstName));
6505
- if (lastName)
6506
- url.searchParams.set("lastName", String(lastName));
6507
- if (email)
6508
- url.searchParams.set("email", String(email));
6509
- if (country)
6510
- url.searchParams.set("country", String(country));
6511
- if (addressLine)
6512
- url.searchParams.set("addressLine", String(addressLine));
6513
- if (city)
6514
- url.searchParams.set("city", String(city));
6515
- if (state)
6516
- url.searchParams.set("state", String(state));
6517
- if (zipCode)
6518
- url.searchParams.set("zipCode", String(zipCode));
6519
- // Disable flags (must be set to 'true' to disable)
6520
- if (disableFullName === "true")
6521
- url.searchParams.set("disableFullName", "true");
6522
- if (disableFirstName === "true")
6523
- url.searchParams.set("disableFirstName", "true");
6524
- if (disableLastName === "true")
6525
- url.searchParams.set("disableLastName", "true");
6526
- if (disableEmail === "true")
6527
- url.searchParams.set("disableEmail", "true");
6528
- if (disableCountry === "true")
6529
- url.searchParams.set("disableCountry", "true");
6530
- if (disableAddressLine === "true")
6531
- url.searchParams.set("disableAddressLine", "true");
6532
- if (disableCity === "true")
6533
- url.searchParams.set("disableCity", "true");
6534
- if (disableState === "true")
6535
- url.searchParams.set("disableState", "true");
6536
- if (disableZipCode === "true")
6537
- url.searchParams.set("disableZipCode", "true");
6538
- // Advanced controls
6539
- if (paymentCurrency)
6540
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
6541
- if (showCurrencySelector)
6542
- url.searchParams.set("showCurrencySelector", String(showCurrencySelector));
6543
- if (paymentAmount)
6544
- url.searchParams.set("paymentAmount", String(paymentAmount));
6545
- if (showDiscounts)
6546
- url.searchParams.set("showDiscounts", String(showDiscounts));
6547
- // Metadata: add all query params starting with metadata_
6548
- for (_i = 0, _d = Object.entries(queryParams || {}); _i < _d.length; _i++) {
6549
- _e = _d[_i], key = _e[0], value = _e[1];
6550
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
6551
- url.searchParams.set(key, String(value));
6552
- }
6553
- }
6554
- return [2 /*return*/, url.toString()];
6555
- case 7:
6556
- dyn = data;
6557
- product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
6558
- dodopayments = new DodoPayments({
6559
- bearerToken: bearerToken,
6560
- environment: environment,
6561
- });
6562
- isSubscription = false;
6563
- productIdToFetch = product_id;
6564
- if (!product_id && product_cart && product_cart.length > 0) {
6565
- productIdToFetch = product_cart[0].product_id;
6566
- }
6567
- if (!productIdToFetch)
6568
- throw new Error("Missing required field: product_id or product_cart[0].product_id");
6569
- _g.label = 8;
6570
- case 8:
6571
- _g.trys.push([8, 10, , 11]);
6572
- return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
6573
- case 9:
6574
- product = _g.sent();
6575
- return [3 /*break*/, 11];
6576
- case 10:
6577
- err_2 = _g.sent();
6578
- console.error(err_2);
6579
- throw new Error("Product not found");
6580
- case 11:
6581
- isSubscription = Boolean(product.is_recurring);
6582
- // Required field validation
6583
- if (isSubscription && !product_id)
6584
- throw new Error("Missing required field: product_id for subscription");
6585
- if (!billing)
6586
- throw new Error("Missing required field: billing");
6587
- if (!customer)
6588
- throw new Error("Missing required field: customer");
6589
- if (!isSubscription) return [3 /*break*/, 16];
6590
- subscriptionPayload = {
6591
- billing: billing,
6592
- customer: customer,
6593
- product_id: product_id,
6594
- quantity: quantity ? Number(quantity) : 1,
6595
- };
6596
- if (metadata)
6597
- subscriptionPayload.metadata = metadata;
6598
- if (discount_code)
6599
- subscriptionPayload.discount_code = discount_code;
6600
- if (addons)
6601
- subscriptionPayload.addons = addons;
6602
- if (allowed_payment_method_types)
6603
- subscriptionPayload.allowed_payment_method_types =
6604
- allowed_payment_method_types;
6605
- if (billing_currency)
6606
- subscriptionPayload.billing_currency = billing_currency;
6607
- if (on_demand)
6608
- subscriptionPayload.on_demand = on_demand;
6609
- subscriptionPayload.payment_link = true;
6610
- // Use bodyReturnUrl if present, otherwise use top-level returnUrl
6611
- if (bodyReturnUrl) {
6612
- subscriptionPayload.return_url = bodyReturnUrl;
6613
- }
6614
- else if (returnUrl) {
6615
- subscriptionPayload.return_url = returnUrl;
6616
- }
6617
- if (show_saved_payment_methods)
6618
- subscriptionPayload.show_saved_payment_methods =
6619
- show_saved_payment_methods;
6620
- if (tax_id)
6621
- subscriptionPayload.tax_id = tax_id;
6622
- if (trial_period_days)
6623
- subscriptionPayload.trial_period_days = trial_period_days;
6624
- subscription = void 0;
6625
- _g.label = 12;
6626
- case 12:
6627
- _g.trys.push([12, 14, , 15]);
6628
- return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
6629
- case 13:
6630
- subscription =
6631
- _g.sent();
6632
- return [3 /*break*/, 15];
6633
- case 14:
6634
- err_3 = _g.sent();
6635
- console.error("Error when creating subscription", err_3);
6636
- throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
6637
- case 15:
6638
- if (!subscription || !subscription.payment_link) {
6639
- throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
6640
- }
6641
- return [2 /*return*/, subscription.payment_link];
6642
- case 16:
6643
- cart = product_cart;
6644
- if (!cart && product_id) {
6645
- cart = [
6646
- { product_id: product_id, quantity: quantity ? Number(quantity) : 1 },
6647
- ];
6648
- }
6649
- if (!cart || cart.length === 0)
6650
- throw new Error("Missing required field: product_cart or product_id");
6651
- paymentPayload = {
6652
- billing: billing,
6653
- customer: customer,
6654
- product_cart: cart,
6655
- };
6656
- if (metadata)
6657
- paymentPayload.metadata = metadata;
6658
- paymentPayload.payment_link = true;
6659
- if (allowed_payment_method_types)
6660
- paymentPayload.allowed_payment_method_types =
6661
- allowed_payment_method_types;
6662
- if (billing_currency)
6663
- paymentPayload.billing_currency = billing_currency;
6664
- if (discount_code)
6665
- paymentPayload.discount_code = discount_code;
6666
- // Use bodyReturnUrl if present, otherwise use top-level returnUrl
6667
- if (bodyReturnUrl) {
6668
- paymentPayload.return_url = bodyReturnUrl;
6669
- }
6670
- else if (returnUrl) {
6671
- paymentPayload.return_url = returnUrl;
6672
- }
6673
- if (show_saved_payment_methods)
6674
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
6675
- if (tax_id)
6676
- paymentPayload.tax_id = tax_id;
6677
- payment = void 0;
6678
- _g.label = 17;
6679
- case 17:
6680
- _g.trys.push([17, 19, , 20]);
6681
- return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
6682
- case 18:
6683
- payment = _g.sent();
6684
- return [3 /*break*/, 20];
6685
- case 19:
6686
- err_4 = _g.sent();
6687
- console.error("Error when creating payment link", err_4);
6688
- throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
6689
- case 20:
6690
- if (!payment || !payment.payment_link) {
6691
- throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
6692
- }
6693
- return [2 /*return*/, payment.payment_link];
6694
- }
6695
- });
6696
- }); };
6697
-
6698
- /**
6699
- * Remix Checkout handler
6700
- * Usage: export const loader = Checkout(config); export const action = Checkout(config);
6701
- */
6702
- function Checkout(config) {
6703
- return async function (request) {
6704
- if (request.method === "POST") {
6705
- // Handle dynamic checkout and checkout sessions (POST)
6706
- let body;
6707
- try {
6708
- body = await request.json();
6709
- }
6710
- catch (e) {
6711
- return new Response("Invalid JSON body", { status: 400 });
6712
- }
6713
- if (config.type === "dynamic") {
6714
- // Handle dynamic checkout
6715
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
6716
- if (!success) {
6717
- return new Response(`Invalid request body.\n ${error.message}`, {
6718
- status: 400,
6719
- });
6720
- }
6721
- let url = "";
6722
- try {
6723
- url = await buildCheckoutUrl({
6724
- body: data,
6725
- ...config,
6726
- type: "dynamic",
6727
- });
6728
- }
6729
- catch (error) {
6730
- return new Response(error.message, { status: 400 });
6731
- }
6732
- return Response.json({ checkout_url: url });
6733
- }
6734
- else {
6735
- // Handle checkout session
6736
- const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
6737
- if (!success) {
6738
- return new Response(`Invalid checkout session payload.\n ${error.message}`, {
6739
- status: 400,
6740
- });
6741
- }
6742
- let url = "";
6743
- try {
6744
- url = await buildCheckoutUrl({
6745
- sessionPayload: data,
6746
- ...config,
6747
- type: "session",
6748
- });
6749
- }
6750
- catch (error) {
6751
- return new Response(error.message, { status: 400 });
6752
- }
6753
- return Response.json({ checkout_url: url });
6754
- }
6755
- }
6756
- else {
6757
- // Handle static checkout (GET)
6758
- const { searchParams } = new URL(request.url);
6759
- const queryParams = Object.fromEntries(searchParams);
6760
- if (!queryParams.productId) {
6761
- return new Response("Please provide productId query parameter", {
6762
- status: 400,
6763
- });
6764
- }
6765
- const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
6766
- if (!success) {
6767
- if (error.errors.some((e) => e.path.toString() === "productId")) {
6768
- return new Response("Please provide productId query parameter", {
6769
- status: 400,
6770
- });
6771
- }
6772
- return new Response(`Invalid query parameters.\n ${error.message}`, {
6773
- status: 400,
6774
- });
6775
- }
6776
- let url = "";
6777
- try {
6778
- url = await buildCheckoutUrl({ queryParams: data, ...config });
6779
- }
6780
- catch (error) {
6781
- return new Response(error.message, { status: 400 });
6782
- }
6783
- return Response.json({ checkout_url: url });
6784
- }
6785
- };
6786
- }
6787
-
6788
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6789
-
6790
- var dist = {};
6791
-
6792
- var timing_safe_equal = {};
6793
-
6794
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
6795
- timing_safe_equal.timingSafeEqual = void 0;
6796
- function assert(expr, msg = "") {
6797
- if (!expr) {
6798
- throw new Error(msg);
6799
- }
5853
+ return Coder;
5854
+ }());
5855
+ base64$1.Coder = Coder;
5856
+ var stdCoder = new Coder();
5857
+ function encode(data) {
5858
+ return stdCoder.encode(data);
6800
5859
  }
6801
- function timingSafeEqual(a, b) {
6802
- if (a.byteLength !== b.byteLength) {
6803
- return false;
6804
- }
6805
- if (!(a instanceof DataView)) {
6806
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
6807
- }
6808
- if (!(b instanceof DataView)) {
6809
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
6810
- }
6811
- assert(a instanceof DataView);
6812
- assert(b instanceof DataView);
6813
- const length = a.byteLength;
6814
- let out = 0;
6815
- let i = -1;
6816
- while (++i < length) {
6817
- out |= a.getUint8(i) ^ b.getUint8(i);
6818
- }
6819
- return out === 0;
5860
+ base64$1.encode = encode;
5861
+ function decode(s) {
5862
+ return stdCoder.decode(s);
6820
5863
  }
6821
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
6822
-
6823
- var base64$1 = {};
6824
-
6825
- // Copyright (C) 2016 Dmitry Chestnykh
6826
- // MIT License. See LICENSE file for details.
6827
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
6828
- var extendStatics = function (d, b) {
6829
- extendStatics = Object.setPrototypeOf ||
6830
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6831
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6832
- return extendStatics(d, b);
6833
- };
6834
- return function (d, b) {
6835
- extendStatics(d, b);
6836
- function __() { this.constructor = d; }
6837
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6838
- };
6839
- })();
6840
- Object.defineProperty(base64$1, "__esModule", { value: true });
6841
- /**
6842
- * Package base64 implements Base64 encoding and decoding.
6843
- */
6844
- // Invalid character used in decoding to indicate
6845
- // that the character to decode is out of range of
6846
- // alphabet and cannot be decoded.
6847
- var INVALID_BYTE = 256;
5864
+ base64$1.decode = decode;
6848
5865
  /**
6849
- * Implements standard Base64 encoding.
5866
+ * Implements URL-safe Base64 encoding.
5867
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
6850
5868
  *
6851
5869
  * Operates in constant time.
6852
5870
  */
6853
- var Coder = /** @class */ (function () {
6854
- // TODO(dchest): methods to encode chunk-by-chunk.
6855
- function Coder(_paddingCharacter) {
6856
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
6857
- this._paddingCharacter = _paddingCharacter;
5871
+ var URLSafeCoder = /** @class */ (function (_super) {
5872
+ __extends(URLSafeCoder, _super);
5873
+ function URLSafeCoder() {
5874
+ return _super !== null && _super.apply(this, arguments) || this;
6858
5875
  }
6859
- Coder.prototype.encodedLength = function (length) {
6860
- if (!this._paddingCharacter) {
6861
- return (length * 8 + 5) / 6 | 0;
6862
- }
6863
- return (length + 2) / 3 * 4 | 0;
6864
- };
6865
- Coder.prototype.encode = function (data) {
6866
- var out = "";
6867
- var i = 0;
6868
- for (; i < data.length - 2; i += 3) {
6869
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
6870
- out += this._encodeByte((c >>> 3 * 6) & 63);
6871
- out += this._encodeByte((c >>> 2 * 6) & 63);
6872
- out += this._encodeByte((c >>> 1 * 6) & 63);
6873
- out += this._encodeByte((c >>> 0 * 6) & 63);
6874
- }
6875
- var left = data.length - i;
6876
- if (left > 0) {
6877
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
6878
- out += this._encodeByte((c >>> 3 * 6) & 63);
6879
- out += this._encodeByte((c >>> 2 * 6) & 63);
6880
- if (left === 2) {
6881
- out += this._encodeByte((c >>> 1 * 6) & 63);
6882
- }
6883
- else {
6884
- out += this._paddingCharacter || "";
6885
- }
6886
- out += this._paddingCharacter || "";
6887
- }
6888
- return out;
6889
- };
6890
- Coder.prototype.maxDecodedLength = function (length) {
6891
- if (!this._paddingCharacter) {
6892
- return (length * 6 + 7) / 8 | 0;
6893
- }
6894
- return length / 4 * 3 | 0;
6895
- };
6896
- Coder.prototype.decodedLength = function (s) {
6897
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
6898
- };
6899
- Coder.prototype.decode = function (s) {
6900
- if (s.length === 0) {
6901
- return new Uint8Array(0);
6902
- }
6903
- var paddingLength = this._getPaddingLength(s);
6904
- var length = s.length - paddingLength;
6905
- var out = new Uint8Array(this.maxDecodedLength(length));
6906
- var op = 0;
6907
- var i = 0;
6908
- var haveBad = 0;
6909
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
6910
- for (; i < length - 4; i += 4) {
6911
- v0 = this._decodeChar(s.charCodeAt(i + 0));
6912
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6913
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6914
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6915
- out[op++] = (v0 << 2) | (v1 >>> 4);
6916
- out[op++] = (v1 << 4) | (v2 >>> 2);
6917
- out[op++] = (v2 << 6) | v3;
6918
- haveBad |= v0 & INVALID_BYTE;
6919
- haveBad |= v1 & INVALID_BYTE;
6920
- haveBad |= v2 & INVALID_BYTE;
6921
- haveBad |= v3 & INVALID_BYTE;
6922
- }
6923
- if (i < length - 1) {
6924
- v0 = this._decodeChar(s.charCodeAt(i));
6925
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6926
- out[op++] = (v0 << 2) | (v1 >>> 4);
6927
- haveBad |= v0 & INVALID_BYTE;
6928
- haveBad |= v1 & INVALID_BYTE;
6929
- }
6930
- if (i < length - 2) {
6931
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6932
- out[op++] = (v1 << 4) | (v2 >>> 2);
6933
- haveBad |= v2 & INVALID_BYTE;
6934
- }
6935
- if (i < length - 3) {
6936
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6937
- out[op++] = (v2 << 6) | v3;
6938
- haveBad |= v3 & INVALID_BYTE;
6939
- }
6940
- if (haveBad !== 0) {
6941
- throw new Error("Base64Coder: incorrect characters for decoding");
6942
- }
6943
- return out;
6944
- };
6945
- // Standard encoding have the following encoded/decoded ranges,
6946
- // which we need to convert between.
6947
- //
6948
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
6949
- // Index: 0 - 25 26 - 51 52 - 61 62 63
6950
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
6951
- //
6952
- // Encode 6 bits in b into a new character.
6953
- Coder.prototype._encodeByte = function (b) {
6954
- // Encoding uses constant time operations as follows:
6955
- //
6956
- // 1. Define comparison of A with B using (A - B) >>> 8:
6957
- // if A > B, then result is positive integer
6958
- // if A <= B, then result is 0
6959
- //
6960
- // 2. Define selection of C or 0 using bitwise AND: X & C:
6961
- // if X == 0, then result is 0
6962
- // if X != 0, then result is C
6963
- //
6964
- // 3. Start with the smallest comparison (b >= 0), which is always
6965
- // true, so set the result to the starting ASCII value (65).
6966
- //
6967
- // 4. Continue comparing b to higher ASCII values, and selecting
6968
- // zero if comparison isn't true, otherwise selecting a value
6969
- // to add to result, which:
6970
- //
6971
- // a) undoes the previous addition
6972
- // b) provides new value to add
6973
- //
6974
- var result = b;
6975
- // b >= 0
6976
- result += 65;
6977
- // b > 25
6978
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
6979
- // b > 51
6980
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
6981
- // b > 61
6982
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
6983
- // b > 62
6984
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
6985
- return String.fromCharCode(result);
6986
- };
6987
- // Decode a character code into a byte.
6988
- // Must return 256 if character is out of alphabet range.
6989
- Coder.prototype._decodeChar = function (c) {
6990
- // Decoding works similar to encoding: using the same comparison
6991
- // function, but now it works on ranges: result is always incremented
6992
- // by value, but this value becomes zero if the range is not
6993
- // satisfied.
6994
- //
6995
- // Decoding starts with invalid value, 256, which is then
6996
- // subtracted when the range is satisfied. If none of the ranges
6997
- // apply, the function returns 256, which is then checked by
6998
- // the caller to throw error.
6999
- var result = INVALID_BYTE; // start with invalid character
7000
- // c == 43 (c > 42 and c < 44)
7001
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
7002
- // c == 47 (c > 46 and c < 48)
7003
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
7004
- // c > 47 and c < 58
7005
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
7006
- // c > 64 and c < 91
7007
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
7008
- // c > 96 and c < 123
7009
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7010
- return result;
7011
- };
7012
- Coder.prototype._getPaddingLength = function (s) {
7013
- var paddingLength = 0;
7014
- if (this._paddingCharacter) {
7015
- for (var i = s.length - 1; i >= 0; i--) {
7016
- if (s[i] !== this._paddingCharacter) {
7017
- break;
7018
- }
7019
- paddingLength++;
7020
- }
7021
- if (s.length < 4 || paddingLength > 2) {
7022
- throw new Error("Base64Coder: incorrect padding");
7023
- }
7024
- }
7025
- return paddingLength;
7026
- };
7027
- return Coder;
7028
- }());
7029
- base64$1.Coder = Coder;
7030
- var stdCoder = new Coder();
7031
- function encode(data) {
7032
- return stdCoder.encode(data);
7033
- }
7034
- base64$1.encode = encode;
7035
- function decode(s) {
7036
- return stdCoder.decode(s);
7037
- }
7038
- base64$1.decode = decode;
7039
- /**
7040
- * Implements URL-safe Base64 encoding.
7041
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
7042
- *
7043
- * Operates in constant time.
7044
- */
7045
- var URLSafeCoder = /** @class */ (function (_super) {
7046
- __extends(URLSafeCoder, _super);
7047
- function URLSafeCoder() {
7048
- return _super !== null && _super.apply(this, arguments) || this;
7049
- }
7050
- // URL-safe encoding have the following encoded/decoded ranges:
7051
- //
7052
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
7053
- // Index: 0 - 25 26 - 51 52 - 61 62 63
7054
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
7055
- //
7056
- URLSafeCoder.prototype._encodeByte = function (b) {
7057
- var result = b;
7058
- // b >= 0
7059
- result += 65;
7060
- // b > 25
7061
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
7062
- // b > 51
7063
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
7064
- // b > 61
7065
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
7066
- // b > 62
7067
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
7068
- return String.fromCharCode(result);
5876
+ // URL-safe encoding have the following encoded/decoded ranges:
5877
+ //
5878
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
5879
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5880
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
5881
+ //
5882
+ URLSafeCoder.prototype._encodeByte = function (b) {
5883
+ var result = b;
5884
+ // b >= 0
5885
+ result += 65;
5886
+ // b > 25
5887
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5888
+ // b > 51
5889
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5890
+ // b > 61
5891
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
5892
+ // b > 62
5893
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
5894
+ return String.fromCharCode(result);
7069
5895
  };
7070
5896
  URLSafeCoder.prototype._decodeChar = function (c) {
7071
5897
  var result = INVALID_BYTE;
@@ -7553,625 +6379,1630 @@ class WebhookVerificationError extends ExtendableError {
7553
6379
  this.name = "WebhookVerificationError";
7554
6380
  }
7555
6381
  }
7556
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
7557
- class Webhook {
7558
- constructor(secret, options) {
7559
- if (!secret) {
7560
- throw new Error("Secret can't be empty.");
7561
- }
7562
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
7563
- if (secret instanceof Uint8Array) {
7564
- this.key = secret;
6382
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
6383
+ class Webhook {
6384
+ constructor(secret, options) {
6385
+ if (!secret) {
6386
+ throw new Error("Secret can't be empty.");
6387
+ }
6388
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
6389
+ if (secret instanceof Uint8Array) {
6390
+ this.key = secret;
6391
+ }
6392
+ else {
6393
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
6394
+ }
6395
+ }
6396
+ else {
6397
+ if (typeof secret !== "string") {
6398
+ throw new Error("Expected secret to be of type string");
6399
+ }
6400
+ if (secret.startsWith(Webhook.prefix)) {
6401
+ secret = secret.substring(Webhook.prefix.length);
6402
+ }
6403
+ this.key = base64.decode(secret);
6404
+ }
6405
+ }
6406
+ verify(payload, headers_) {
6407
+ const headers = {};
6408
+ for (const key of Object.keys(headers_)) {
6409
+ headers[key.toLowerCase()] = headers_[key];
6410
+ }
6411
+ const msgId = headers["webhook-id"];
6412
+ const msgSignature = headers["webhook-signature"];
6413
+ const msgTimestamp = headers["webhook-timestamp"];
6414
+ if (!msgSignature || !msgId || !msgTimestamp) {
6415
+ throw new WebhookVerificationError("Missing required headers");
6416
+ }
6417
+ const timestamp = this.verifyTimestamp(msgTimestamp);
6418
+ const computedSignature = this.sign(msgId, timestamp, payload);
6419
+ const expectedSignature = computedSignature.split(",")[1];
6420
+ const passedSignatures = msgSignature.split(" ");
6421
+ const encoder = new globalThis.TextEncoder();
6422
+ for (const versionedSignature of passedSignatures) {
6423
+ const [version, signature] = versionedSignature.split(",");
6424
+ if (version !== "v1") {
6425
+ continue;
6426
+ }
6427
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
6428
+ return JSON.parse(payload.toString());
6429
+ }
6430
+ }
6431
+ throw new WebhookVerificationError("No matching signature found");
6432
+ }
6433
+ sign(msgId, timestamp, payload) {
6434
+ if (typeof payload === "string") ;
6435
+ else if (payload.constructor.name === "Buffer") {
6436
+ payload = payload.toString();
6437
+ }
6438
+ else {
6439
+ throw new Error("Expected payload to be of type string or Buffer.");
6440
+ }
6441
+ const encoder = new TextEncoder();
6442
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
6443
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
6444
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
6445
+ return `v1,${expectedSignature}`;
6446
+ }
6447
+ verifyTimestamp(timestampHeader) {
6448
+ const now = Math.floor(Date.now() / 1000);
6449
+ const timestamp = parseInt(timestampHeader, 10);
6450
+ if (isNaN(timestamp)) {
6451
+ throw new WebhookVerificationError("Invalid Signature Headers");
6452
+ }
6453
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
6454
+ throw new WebhookVerificationError("Message timestamp too old");
6455
+ }
6456
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
6457
+ throw new WebhookVerificationError("Message timestamp too new");
6458
+ }
6459
+ return new Date(timestamp * 1000);
6460
+ }
6461
+ }
6462
+ Webhook_1 = dist.Webhook = Webhook;
6463
+ Webhook.prefix = "whsec_";
6464
+
6465
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6466
+ let Webhooks$1 = class Webhooks extends APIResource {
6467
+ constructor() {
6468
+ super(...arguments);
6469
+ this.headers = new Headers$1(this._client);
6470
+ }
6471
+ /**
6472
+ * Create a new webhook
6473
+ */
6474
+ create(body, options) {
6475
+ return this._client.post('/webhooks', { body, ...options });
6476
+ }
6477
+ /**
6478
+ * Get a webhook by id
6479
+ */
6480
+ retrieve(webhookID, options) {
6481
+ return this._client.get(path `/webhooks/${webhookID}`, options);
6482
+ }
6483
+ /**
6484
+ * Patch a webhook by id
6485
+ */
6486
+ update(webhookID, body, options) {
6487
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
6488
+ }
6489
+ /**
6490
+ * List all webhooks
6491
+ */
6492
+ list(query = {}, options) {
6493
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
6494
+ }
6495
+ /**
6496
+ * Delete a webhook by id
6497
+ */
6498
+ delete(webhookID, options) {
6499
+ return this._client.delete(path `/webhooks/${webhookID}`, {
6500
+ ...options,
6501
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
6502
+ });
6503
+ }
6504
+ /**
6505
+ * Get webhook secret by id
6506
+ */
6507
+ retrieveSecret(webhookID, options) {
6508
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
6509
+ }
6510
+ unsafeUnwrap(body) {
6511
+ return JSON.parse(body);
6512
+ }
6513
+ unwrap(body, { headers, key }) {
6514
+ if (headers !== undefined) {
6515
+ const keyStr = key === undefined ? this._client.webhookKey : key;
6516
+ if (keyStr === null)
6517
+ throw new Error('Webhook key must not be null in order to unwrap');
6518
+ const wh = new Webhook_1(keyStr);
6519
+ wh.verify(body, headers);
6520
+ }
6521
+ return JSON.parse(body);
6522
+ }
6523
+ };
6524
+ Webhooks$1.Headers = Headers$1;
6525
+
6526
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6527
+ /**
6528
+ * Read an environment variable.
6529
+ *
6530
+ * Trims beginning and trailing whitespace.
6531
+ *
6532
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
6533
+ */
6534
+ const readEnv = (env) => {
6535
+ if (typeof globalThis.process !== 'undefined') {
6536
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
6537
+ }
6538
+ if (typeof globalThis.Deno !== 'undefined') {
6539
+ return globalThis.Deno.env?.get?.(env)?.trim();
6540
+ }
6541
+ return undefined;
6542
+ };
6543
+
6544
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6545
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
6546
+ const environments = {
6547
+ live_mode: 'https://live.dodopayments.com',
6548
+ test_mode: 'https://test.dodopayments.com',
6549
+ };
6550
+ /**
6551
+ * API Client for interfacing with the Dodo Payments API.
6552
+ */
6553
+ class DodoPayments {
6554
+ /**
6555
+ * API Client for interfacing with the Dodo Payments API.
6556
+ *
6557
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
6558
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
6559
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
6560
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
6561
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
6562
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
6563
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
6564
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
6565
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
6566
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
6567
+ */
6568
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
6569
+ _DodoPayments_instances.add(this);
6570
+ _DodoPayments_encoder.set(this, void 0);
6571
+ this.checkoutSessions = new CheckoutSessions(this);
6572
+ this.payments = new Payments(this);
6573
+ this.subscriptions = new Subscriptions(this);
6574
+ this.invoices = new Invoices(this);
6575
+ this.licenses = new Licenses(this);
6576
+ this.licenseKeys = new LicenseKeys(this);
6577
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
6578
+ this.customers = new Customers(this);
6579
+ this.refunds = new Refunds(this);
6580
+ this.disputes = new Disputes(this);
6581
+ this.payouts = new Payouts(this);
6582
+ this.products = new Products(this);
6583
+ this.misc = new Misc(this);
6584
+ this.discounts = new Discounts(this);
6585
+ this.addons = new Addons(this);
6586
+ this.brands = new Brands(this);
6587
+ this.webhooks = new Webhooks$1(this);
6588
+ this.webhookEvents = new WebhookEvents(this);
6589
+ this.usageEvents = new UsageEvents(this);
6590
+ this.meters = new Meters(this);
6591
+ if (bearerToken === undefined) {
6592
+ 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' }).");
6593
+ }
6594
+ const options = {
6595
+ bearerToken,
6596
+ webhookKey,
6597
+ ...opts,
6598
+ baseURL,
6599
+ environment: opts.environment ?? 'live_mode',
6600
+ };
6601
+ if (baseURL && opts.environment) {
6602
+ 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');
6603
+ }
6604
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
6605
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
6606
+ this.logger = options.logger ?? console;
6607
+ const defaultLogLevel = 'warn';
6608
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
6609
+ this.logLevel = defaultLogLevel;
6610
+ this.logLevel =
6611
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
6612
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
6613
+ defaultLogLevel;
6614
+ this.fetchOptions = options.fetchOptions;
6615
+ this.maxRetries = options.maxRetries ?? 2;
6616
+ this.fetch = options.fetch ?? getDefaultFetch();
6617
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
6618
+ this._options = options;
6619
+ this.bearerToken = bearerToken;
6620
+ this.webhookKey = webhookKey;
6621
+ }
6622
+ /**
6623
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
6624
+ */
6625
+ withOptions(options) {
6626
+ const client = new this.constructor({
6627
+ ...this._options,
6628
+ environment: options.environment ? options.environment : undefined,
6629
+ baseURL: options.environment ? undefined : this.baseURL,
6630
+ maxRetries: this.maxRetries,
6631
+ timeout: this.timeout,
6632
+ logger: this.logger,
6633
+ logLevel: this.logLevel,
6634
+ fetch: this.fetch,
6635
+ fetchOptions: this.fetchOptions,
6636
+ bearerToken: this.bearerToken,
6637
+ webhookKey: this.webhookKey,
6638
+ ...options,
6639
+ });
6640
+ return client;
6641
+ }
6642
+ defaultQuery() {
6643
+ return this._options.defaultQuery;
6644
+ }
6645
+ validateHeaders({ values, nulls }) {
6646
+ return;
6647
+ }
6648
+ async authHeaders(opts) {
6649
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
6650
+ }
6651
+ /**
6652
+ * Basic re-implementation of `qs.stringify` for primitive types.
6653
+ */
6654
+ stringifyQuery(query) {
6655
+ return Object.entries(query)
6656
+ .filter(([_, value]) => typeof value !== 'undefined')
6657
+ .map(([key, value]) => {
6658
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
6659
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
6660
+ }
6661
+ if (value === null) {
6662
+ return `${encodeURIComponent(key)}=`;
6663
+ }
6664
+ 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.`);
6665
+ })
6666
+ .join('&');
6667
+ }
6668
+ getUserAgent() {
6669
+ return `${this.constructor.name}/JS ${VERSION}`;
6670
+ }
6671
+ defaultIdempotencyKey() {
6672
+ return `stainless-node-retry-${uuid4()}`;
6673
+ }
6674
+ makeStatusError(status, error, message, headers) {
6675
+ return APIError.generate(status, error, message, headers);
6676
+ }
6677
+ buildURL(path, query, defaultBaseURL) {
6678
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
6679
+ const url = isAbsoluteURL(path) ?
6680
+ new URL(path)
6681
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
6682
+ const defaultQuery = this.defaultQuery();
6683
+ if (!isEmptyObj(defaultQuery)) {
6684
+ query = { ...defaultQuery, ...query };
6685
+ }
6686
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
6687
+ url.search = this.stringifyQuery(query);
6688
+ }
6689
+ return url.toString();
6690
+ }
6691
+ /**
6692
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
6693
+ */
6694
+ async prepareOptions(options) { }
6695
+ /**
6696
+ * Used as a callback for mutating the given `RequestInit` object.
6697
+ *
6698
+ * This is useful for cases where you want to add certain headers based off of
6699
+ * the request properties, e.g. `method` or `url`.
6700
+ */
6701
+ async prepareRequest(request, { url, options }) { }
6702
+ get(path, opts) {
6703
+ return this.methodRequest('get', path, opts);
6704
+ }
6705
+ post(path, opts) {
6706
+ return this.methodRequest('post', path, opts);
6707
+ }
6708
+ patch(path, opts) {
6709
+ return this.methodRequest('patch', path, opts);
6710
+ }
6711
+ put(path, opts) {
6712
+ return this.methodRequest('put', path, opts);
6713
+ }
6714
+ delete(path, opts) {
6715
+ return this.methodRequest('delete', path, opts);
6716
+ }
6717
+ methodRequest(method, path, opts) {
6718
+ return this.request(Promise.resolve(opts).then((opts) => {
6719
+ return { method, path, ...opts };
6720
+ }));
6721
+ }
6722
+ request(options, remainingRetries = null) {
6723
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
6724
+ }
6725
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
6726
+ const options = await optionsInput;
6727
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6728
+ if (retriesRemaining == null) {
6729
+ retriesRemaining = maxRetries;
6730
+ }
6731
+ await this.prepareOptions(options);
6732
+ const { req, url, timeout } = await this.buildRequest(options, {
6733
+ retryCount: maxRetries - retriesRemaining,
6734
+ });
6735
+ await this.prepareRequest(req, { url, options });
6736
+ /** Not an API request ID, just for correlating local log entries. */
6737
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
6738
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
6739
+ const startTime = Date.now();
6740
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
6741
+ retryOfRequestLogID,
6742
+ method: options.method,
6743
+ url,
6744
+ options,
6745
+ headers: req.headers,
6746
+ }));
6747
+ if (options.signal?.aborted) {
6748
+ throw new APIUserAbortError();
6749
+ }
6750
+ const controller = new AbortController();
6751
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
6752
+ const headersTime = Date.now();
6753
+ if (response instanceof globalThis.Error) {
6754
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6755
+ if (options.signal?.aborted) {
6756
+ throw new APIUserAbortError();
6757
+ }
6758
+ // detect native connection timeout errors
6759
+ // 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)"
6760
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
6761
+ // others do not provide enough information to distinguish timeouts from other connection errors
6762
+ const isTimeout = isAbortError(response) ||
6763
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
6764
+ if (retriesRemaining) {
6765
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
6766
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
6767
+ retryOfRequestLogID,
6768
+ url,
6769
+ durationMs: headersTime - startTime,
6770
+ message: response.message,
6771
+ }));
6772
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
6773
+ }
6774
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
6775
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
6776
+ retryOfRequestLogID,
6777
+ url,
6778
+ durationMs: headersTime - startTime,
6779
+ message: response.message,
6780
+ }));
6781
+ if (isTimeout) {
6782
+ throw new APIConnectionTimeoutError();
6783
+ }
6784
+ throw new APIConnectionError({ cause: response });
6785
+ }
6786
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
6787
+ if (!response.ok) {
6788
+ const shouldRetry = await this.shouldRetry(response);
6789
+ if (retriesRemaining && shouldRetry) {
6790
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6791
+ // We don't need the body of this response.
6792
+ await CancelReadableStream(response.body);
6793
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6794
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6795
+ retryOfRequestLogID,
6796
+ url: response.url,
6797
+ status: response.status,
6798
+ headers: response.headers,
6799
+ durationMs: headersTime - startTime,
6800
+ }));
6801
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6802
+ }
6803
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6804
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6805
+ const errText = await response.text().catch((err) => castToError(err).message);
6806
+ const errJSON = safeJSON(errText);
6807
+ const errMessage = errJSON ? undefined : errText;
6808
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6809
+ retryOfRequestLogID,
6810
+ url: response.url,
6811
+ status: response.status,
6812
+ headers: response.headers,
6813
+ message: errMessage,
6814
+ durationMs: Date.now() - startTime,
6815
+ }));
6816
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6817
+ throw err;
6818
+ }
6819
+ loggerFor(this).info(responseInfo);
6820
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6821
+ retryOfRequestLogID,
6822
+ url: response.url,
6823
+ status: response.status,
6824
+ headers: response.headers,
6825
+ durationMs: headersTime - startTime,
6826
+ }));
6827
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6828
+ }
6829
+ getAPIList(path, Page, opts) {
6830
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
6831
+ }
6832
+ requestAPIList(Page, options) {
6833
+ const request = this.makeRequest(options, null, undefined);
6834
+ return new PagePromise(this, request, Page);
6835
+ }
6836
+ async fetchWithTimeout(url, init, ms, controller) {
6837
+ const { signal, method, ...options } = init || {};
6838
+ if (signal)
6839
+ signal.addEventListener('abort', () => controller.abort());
6840
+ const timeout = setTimeout(() => controller.abort(), ms);
6841
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
6842
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
6843
+ const fetchOptions = {
6844
+ signal: controller.signal,
6845
+ ...(isReadableBody ? { duplex: 'half' } : {}),
6846
+ method: 'GET',
6847
+ ...options,
6848
+ };
6849
+ if (method) {
6850
+ // Custom methods like 'patch' need to be uppercased
6851
+ // See https://github.com/nodejs/undici/issues/2294
6852
+ fetchOptions.method = method.toUpperCase();
6853
+ }
6854
+ try {
6855
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
6856
+ return await this.fetch.call(undefined, url, fetchOptions);
6857
+ }
6858
+ finally {
6859
+ clearTimeout(timeout);
6860
+ }
6861
+ }
6862
+ async shouldRetry(response) {
6863
+ // Note this is not a standard header.
6864
+ const shouldRetryHeader = response.headers.get('x-should-retry');
6865
+ // If the server explicitly says whether or not to retry, obey.
6866
+ if (shouldRetryHeader === 'true')
6867
+ return true;
6868
+ if (shouldRetryHeader === 'false')
6869
+ return false;
6870
+ // Retry on request timeouts.
6871
+ if (response.status === 408)
6872
+ return true;
6873
+ // Retry on lock timeouts.
6874
+ if (response.status === 409)
6875
+ return true;
6876
+ // Retry on rate limits.
6877
+ if (response.status === 429)
6878
+ return true;
6879
+ // Retry internal errors.
6880
+ if (response.status >= 500)
6881
+ return true;
6882
+ return false;
6883
+ }
6884
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6885
+ let timeoutMillis;
6886
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6887
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6888
+ if (retryAfterMillisHeader) {
6889
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
6890
+ if (!Number.isNaN(timeoutMs)) {
6891
+ timeoutMillis = timeoutMs;
6892
+ }
6893
+ }
6894
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6895
+ const retryAfterHeader = responseHeaders?.get('retry-after');
6896
+ if (retryAfterHeader && !timeoutMillis) {
6897
+ const timeoutSeconds = parseFloat(retryAfterHeader);
6898
+ if (!Number.isNaN(timeoutSeconds)) {
6899
+ timeoutMillis = timeoutSeconds * 1000;
6900
+ }
6901
+ else {
6902
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
6903
+ }
6904
+ }
6905
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
6906
+ // just do what it says, but otherwise calculate a default
6907
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
6908
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6909
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6910
+ }
6911
+ await sleep(timeoutMillis);
6912
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6913
+ }
6914
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6915
+ const initialRetryDelay = 0.5;
6916
+ const maxRetryDelay = 8.0;
6917
+ const numRetries = maxRetries - retriesRemaining;
6918
+ // Apply exponential backoff, but not more than the max.
6919
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6920
+ // Apply some jitter, take up to at most 25 percent of the retry time.
6921
+ const jitter = 1 - Math.random() * 0.25;
6922
+ return sleepSeconds * jitter * 1000;
6923
+ }
6924
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6925
+ const options = { ...inputOptions };
6926
+ const { method, path, query, defaultBaseURL } = options;
6927
+ const url = this.buildURL(path, query, defaultBaseURL);
6928
+ if ('timeout' in options)
6929
+ validatePositiveInteger('timeout', options.timeout);
6930
+ options.timeout = options.timeout ?? this.timeout;
6931
+ const { bodyHeaders, body } = this.buildBody({ options });
6932
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6933
+ const req = {
6934
+ method,
6935
+ headers: reqHeaders,
6936
+ ...(options.signal && { signal: options.signal }),
6937
+ ...(globalThis.ReadableStream &&
6938
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
6939
+ ...(body && { body }),
6940
+ ...(this.fetchOptions ?? {}),
6941
+ ...(options.fetchOptions ?? {}),
6942
+ };
6943
+ return { req, url, timeout: options.timeout };
6944
+ }
6945
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
6946
+ let idempotencyHeaders = {};
6947
+ if (this.idempotencyHeader && method !== 'get') {
6948
+ if (!options.idempotencyKey)
6949
+ options.idempotencyKey = this.defaultIdempotencyKey();
6950
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6951
+ }
6952
+ const headers = buildHeaders([
6953
+ idempotencyHeaders,
6954
+ {
6955
+ Accept: 'application/json',
6956
+ 'User-Agent': this.getUserAgent(),
6957
+ 'X-Stainless-Retry-Count': String(retryCount),
6958
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
6959
+ ...getPlatformHeaders(),
6960
+ },
6961
+ await this.authHeaders(options),
6962
+ this._options.defaultHeaders,
6963
+ bodyHeaders,
6964
+ options.headers,
6965
+ ]);
6966
+ this.validateHeaders(headers);
6967
+ return headers.values;
6968
+ }
6969
+ buildBody({ options: { body, headers: rawHeaders } }) {
6970
+ if (!body) {
6971
+ return { bodyHeaders: undefined, body: undefined };
6972
+ }
6973
+ const headers = buildHeaders([rawHeaders]);
6974
+ if (
6975
+ // Pass raw type verbatim
6976
+ ArrayBuffer.isView(body) ||
6977
+ body instanceof ArrayBuffer ||
6978
+ body instanceof DataView ||
6979
+ (typeof body === 'string' &&
6980
+ // Preserve legacy string encoding behavior for now
6981
+ headers.values.has('content-type')) ||
6982
+ // `Blob` is superset of `File`
6983
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
6984
+ // `FormData` -> `multipart/form-data`
6985
+ body instanceof FormData ||
6986
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
6987
+ body instanceof URLSearchParams ||
6988
+ // Send chunked stream (each chunk has own `length`)
6989
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
6990
+ return { bodyHeaders: undefined, body: body };
6991
+ }
6992
+ else if (typeof body === 'object' &&
6993
+ (Symbol.asyncIterator in body ||
6994
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
6995
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6996
+ }
6997
+ else {
6998
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
6999
+ }
7000
+ }
7001
+ }
7002
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
7003
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
7004
+ };
7005
+ DodoPayments.DodoPayments = _a;
7006
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
7007
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
7008
+ DodoPayments.APIError = APIError;
7009
+ DodoPayments.APIConnectionError = APIConnectionError;
7010
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
7011
+ DodoPayments.APIUserAbortError = APIUserAbortError;
7012
+ DodoPayments.NotFoundError = NotFoundError;
7013
+ DodoPayments.ConflictError = ConflictError;
7014
+ DodoPayments.RateLimitError = RateLimitError;
7015
+ DodoPayments.BadRequestError = BadRequestError;
7016
+ DodoPayments.AuthenticationError = AuthenticationError;
7017
+ DodoPayments.InternalServerError = InternalServerError;
7018
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
7019
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
7020
+ DodoPayments.toFile = toFile;
7021
+ DodoPayments.CheckoutSessions = CheckoutSessions;
7022
+ DodoPayments.Payments = Payments;
7023
+ DodoPayments.Subscriptions = Subscriptions;
7024
+ DodoPayments.Invoices = Invoices;
7025
+ DodoPayments.Licenses = Licenses;
7026
+ DodoPayments.LicenseKeys = LicenseKeys;
7027
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
7028
+ DodoPayments.Customers = Customers;
7029
+ DodoPayments.Refunds = Refunds;
7030
+ DodoPayments.Disputes = Disputes;
7031
+ DodoPayments.Payouts = Payouts;
7032
+ DodoPayments.Products = Products;
7033
+ DodoPayments.Misc = Misc;
7034
+ DodoPayments.Discounts = Discounts;
7035
+ DodoPayments.Addons = Addons;
7036
+ DodoPayments.Brands = Brands;
7037
+ DodoPayments.Webhooks = Webhooks$1;
7038
+ DodoPayments.WebhookEvents = WebhookEvents;
7039
+ DodoPayments.UsageEvents = UsageEvents;
7040
+ DodoPayments.Meters = Meters;
7041
+
7042
+ // src/checkout/checkout.ts
7043
+ var checkoutQuerySchema = objectType({
7044
+ productId: stringType(),
7045
+ quantity: stringType().optional(),
7046
+ // Customer fields
7047
+ fullName: stringType().optional(),
7048
+ firstName: stringType().optional(),
7049
+ lastName: stringType().optional(),
7050
+ email: stringType().optional(),
7051
+ country: stringType().optional(),
7052
+ addressLine: stringType().optional(),
7053
+ city: stringType().optional(),
7054
+ state: stringType().optional(),
7055
+ zipCode: stringType().optional(),
7056
+ // Disable flags
7057
+ disableFullName: stringType().optional(),
7058
+ disableFirstName: stringType().optional(),
7059
+ disableLastName: stringType().optional(),
7060
+ disableEmail: stringType().optional(),
7061
+ disableCountry: stringType().optional(),
7062
+ disableAddressLine: stringType().optional(),
7063
+ disableCity: stringType().optional(),
7064
+ disableState: stringType().optional(),
7065
+ disableZipCode: stringType().optional(),
7066
+ // Advanced controls
7067
+ paymentCurrency: stringType().optional(),
7068
+ showCurrencySelector: stringType().optional(),
7069
+ paymentAmount: stringType().optional(),
7070
+ showDiscounts: stringType().optional()
7071
+ // Metadata (allow any key starting with metadata_)
7072
+ // We'll handle metadata separately in the handler
7073
+ }).catchall(unknownType());
7074
+ var dynamicCheckoutBodySchema = objectType({
7075
+ // For subscription
7076
+ product_id: stringType().optional(),
7077
+ quantity: numberType().optional(),
7078
+ // For one-time payment
7079
+ product_cart: arrayType(
7080
+ objectType({
7081
+ product_id: stringType(),
7082
+ quantity: numberType()
7083
+ })
7084
+ ).optional(),
7085
+ // Common fields
7086
+ billing: objectType({
7087
+ city: stringType(),
7088
+ country: stringType(),
7089
+ state: stringType(),
7090
+ street: stringType(),
7091
+ zipcode: stringType()
7092
+ }),
7093
+ customer: objectType({
7094
+ customer_id: stringType().optional(),
7095
+ email: stringType().optional(),
7096
+ name: stringType().optional()
7097
+ }),
7098
+ discount_id: stringType().optional(),
7099
+ addons: arrayType(
7100
+ objectType({
7101
+ addon_id: stringType(),
7102
+ quantity: numberType()
7103
+ })
7104
+ ).optional(),
7105
+ metadata: recordType(stringType(), stringType()).optional(),
7106
+ currency: stringType().optional()
7107
+ // Allow any additional fields (for future compatibility)
7108
+ }).catchall(unknownType());
7109
+ var checkoutSessionProductCartItemSchema = objectType({
7110
+ product_id: stringType().min(1, "Product ID is required"),
7111
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
7112
+ addons: arrayType(
7113
+ objectType({
7114
+ addon_id: stringType(),
7115
+ quantity: numberType().int().nonnegative()
7116
+ })
7117
+ ).optional(),
7118
+ amount: numberType().int().nonnegative(
7119
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
7120
+ ).optional()
7121
+ });
7122
+ var checkoutSessionCustomerSchema = unionType([
7123
+ objectType({
7124
+ email: stringType().email(),
7125
+ name: stringType().min(1).optional(),
7126
+ phone_number: stringType().optional()
7127
+ }),
7128
+ objectType({
7129
+ customer_id: stringType()
7130
+ })
7131
+ ]).optional();
7132
+ var checkoutSessionBillingAddressSchema = objectType({
7133
+ street: stringType().optional(),
7134
+ city: stringType().optional(),
7135
+ state: stringType().optional(),
7136
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
7137
+ zipcode: stringType().optional()
7138
+ }).optional();
7139
+ var paymentMethodTypeSchema = enumType([
7140
+ "credit",
7141
+ "debit",
7142
+ "upi_collect",
7143
+ "upi_intent",
7144
+ "apple_pay",
7145
+ "cashapp",
7146
+ "google_pay",
7147
+ "multibanco",
7148
+ "bancontact_card",
7149
+ "eps",
7150
+ "ideal",
7151
+ "przelewy24",
7152
+ "paypal",
7153
+ "affirm",
7154
+ "klarna",
7155
+ "sepa",
7156
+ "ach",
7157
+ "amazon_pay",
7158
+ "afterpay_clearpay"
7159
+ ]);
7160
+ var checkoutSessionCustomizationSchema = objectType({
7161
+ theme: enumType(["light", "dark", "system"]).optional(),
7162
+ show_order_details: booleanType().optional(),
7163
+ show_on_demand_tag: booleanType().optional(),
7164
+ force_language: stringType().optional()
7165
+ }).optional();
7166
+ var checkoutSessionFeatureFlagsSchema = objectType({
7167
+ allow_currency_selection: booleanType().optional(),
7168
+ allow_discount_code: booleanType().optional(),
7169
+ allow_phone_number_collection: booleanType().optional(),
7170
+ allow_tax_id: booleanType().optional(),
7171
+ always_create_new_customer: booleanType().optional()
7172
+ }).optional();
7173
+ var checkoutSessionOnDemandSchema = objectType({
7174
+ mandate_only: booleanType(),
7175
+ product_price: numberType().int().optional(),
7176
+ product_currency: stringType().length(3).optional(),
7177
+ product_description: stringType().optional(),
7178
+ adaptive_currency_fees_inclusive: booleanType().optional()
7179
+ }).optional();
7180
+ var checkoutSessionSubscriptionDataSchema = objectType({
7181
+ trial_period_days: numberType().int().nonnegative().optional(),
7182
+ on_demand: checkoutSessionOnDemandSchema
7183
+ }).optional();
7184
+ var checkoutSessionPayloadSchema = objectType({
7185
+ // Required fields
7186
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
7187
+ // Optional fields
7188
+ customer: checkoutSessionCustomerSchema,
7189
+ billing_address: checkoutSessionBillingAddressSchema,
7190
+ return_url: stringType().url().optional(),
7191
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
7192
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
7193
+ show_saved_payment_methods: booleanType().optional(),
7194
+ confirm: booleanType().optional(),
7195
+ discount_code: stringType().optional(),
7196
+ metadata: recordType(stringType(), stringType()).optional(),
7197
+ customization: checkoutSessionCustomizationSchema,
7198
+ feature_flags: checkoutSessionFeatureFlagsSchema,
7199
+ subscription_data: checkoutSessionSubscriptionDataSchema,
7200
+ force_3ds: booleanType().optional()
7201
+ });
7202
+ var checkoutSessionResponseSchema = objectType({
7203
+ session_id: stringType().min(1, "Session ID is required"),
7204
+ checkout_url: stringType().url("Invalid checkout URL")
7205
+ });
7206
+ var createCheckoutSession = async (payload, config) => {
7207
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
7208
+ if (!validation.success) {
7209
+ throw new Error(
7210
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7211
+ );
7212
+ }
7213
+ const dodopayments = new DodoPayments({
7214
+ bearerToken: config.bearerToken,
7215
+ environment: config.environment
7216
+ });
7217
+ try {
7218
+ const sdkPayload = {
7219
+ ...validation.data,
7220
+ ...validation.data.billing_address && {
7221
+ billing_address: {
7222
+ ...validation.data.billing_address,
7223
+ country: validation.data.billing_address.country
7224
+ }
7225
+ }
7226
+ };
7227
+ const session = await dodopayments.checkoutSessions.create(
7228
+ sdkPayload
7229
+ );
7230
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
7231
+ if (!responseValidation.success) {
7232
+ throw new Error(
7233
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7234
+ );
7235
+ }
7236
+ return responseValidation.data;
7237
+ } catch (error) {
7238
+ if (error instanceof Error) {
7239
+ console.error("Dodo Payments Checkout Session API Error:", {
7240
+ message: error.message,
7241
+ payload: validation.data,
7242
+ config: {
7243
+ environment: config.environment,
7244
+ hasBearerToken: !!config.bearerToken
7245
+ }
7246
+ });
7247
+ throw new Error(`Failed to create checkout session: ${error.message}`);
7248
+ }
7249
+ console.error("Unknown error creating checkout session:", error);
7250
+ throw new Error(
7251
+ "Failed to create checkout session due to an unknown error"
7252
+ );
7253
+ }
7254
+ };
7255
+ var buildCheckoutUrl = async ({
7256
+ queryParams,
7257
+ body,
7258
+ sessionPayload,
7259
+ returnUrl,
7260
+ bearerToken,
7261
+ environment,
7262
+ type = "static"
7263
+ }) => {
7264
+ if (type === "session") {
7265
+ if (!sessionPayload) {
7266
+ throw new Error("sessionPayload is required when type is 'session'");
7267
+ }
7268
+ const session = await createCheckoutSession(sessionPayload, {
7269
+ bearerToken,
7270
+ environment
7271
+ });
7272
+ return session.checkout_url;
7273
+ }
7274
+ const inputData = type === "dynamic" ? body : queryParams;
7275
+ let parseResult;
7276
+ if (type === "dynamic") {
7277
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
7278
+ } else {
7279
+ parseResult = checkoutQuerySchema.safeParse(inputData);
7280
+ }
7281
+ const { success, data, error } = parseResult;
7282
+ if (!success) {
7283
+ throw new Error(
7284
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
7285
+ ${error.message}`
7286
+ );
7287
+ }
7288
+ if (type !== "dynamic") {
7289
+ const {
7290
+ productId,
7291
+ quantity: quantity2,
7292
+ fullName,
7293
+ firstName,
7294
+ lastName,
7295
+ email,
7296
+ country,
7297
+ addressLine,
7298
+ city,
7299
+ state,
7300
+ zipCode,
7301
+ disableFullName,
7302
+ disableFirstName,
7303
+ disableLastName,
7304
+ disableEmail,
7305
+ disableCountry,
7306
+ disableAddressLine,
7307
+ disableCity,
7308
+ disableState,
7309
+ disableZipCode,
7310
+ paymentCurrency,
7311
+ showCurrencySelector,
7312
+ paymentAmount,
7313
+ showDiscounts
7314
+ // metadata handled below
7315
+ } = data;
7316
+ const dodopayments2 = new DodoPayments({
7317
+ bearerToken,
7318
+ environment
7319
+ });
7320
+ if (!productId) throw new Error("Missing required field: productId");
7321
+ try {
7322
+ await dodopayments2.products.retrieve(productId);
7323
+ } catch (err) {
7324
+ console.error(err);
7325
+ throw new Error("Product not found");
7326
+ }
7327
+ const url = new URL(
7328
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
7329
+ );
7330
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
7331
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
7332
+ if (fullName) url.searchParams.set("fullName", String(fullName));
7333
+ if (firstName) url.searchParams.set("firstName", String(firstName));
7334
+ if (lastName) url.searchParams.set("lastName", String(lastName));
7335
+ if (email) url.searchParams.set("email", String(email));
7336
+ if (country) url.searchParams.set("country", String(country));
7337
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
7338
+ if (city) url.searchParams.set("city", String(city));
7339
+ if (state) url.searchParams.set("state", String(state));
7340
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
7341
+ if (disableFullName === "true")
7342
+ url.searchParams.set("disableFullName", "true");
7343
+ if (disableFirstName === "true")
7344
+ url.searchParams.set("disableFirstName", "true");
7345
+ if (disableLastName === "true")
7346
+ url.searchParams.set("disableLastName", "true");
7347
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
7348
+ if (disableCountry === "true")
7349
+ url.searchParams.set("disableCountry", "true");
7350
+ if (disableAddressLine === "true")
7351
+ url.searchParams.set("disableAddressLine", "true");
7352
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
7353
+ if (disableState === "true") url.searchParams.set("disableState", "true");
7354
+ if (disableZipCode === "true")
7355
+ url.searchParams.set("disableZipCode", "true");
7356
+ if (paymentCurrency)
7357
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
7358
+ if (showCurrencySelector)
7359
+ url.searchParams.set(
7360
+ "showCurrencySelector",
7361
+ String(showCurrencySelector)
7362
+ );
7363
+ if (paymentAmount)
7364
+ url.searchParams.set("paymentAmount", String(paymentAmount));
7365
+ if (showDiscounts)
7366
+ url.searchParams.set("showDiscounts", String(showDiscounts));
7367
+ for (const [key, value] of Object.entries(queryParams || {})) {
7368
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
7369
+ url.searchParams.set(key, String(value));
7370
+ }
7371
+ }
7372
+ return url.toString();
7373
+ }
7374
+ const dyn = data;
7375
+ const {
7376
+ product_id,
7377
+ product_cart,
7378
+ quantity,
7379
+ billing,
7380
+ customer,
7381
+ addons,
7382
+ metadata,
7383
+ allowed_payment_method_types,
7384
+ billing_currency,
7385
+ discount_code,
7386
+ on_demand,
7387
+ return_url: bodyReturnUrl,
7388
+ show_saved_payment_methods,
7389
+ tax_id,
7390
+ trial_period_days
7391
+ } = dyn;
7392
+ const dodopayments = new DodoPayments({
7393
+ bearerToken,
7394
+ environment
7395
+ });
7396
+ let isSubscription = false;
7397
+ let productIdToFetch = product_id;
7398
+ if (!product_id && product_cart && product_cart.length > 0) {
7399
+ productIdToFetch = product_cart[0].product_id;
7400
+ }
7401
+ if (!productIdToFetch)
7402
+ throw new Error(
7403
+ "Missing required field: product_id or product_cart[0].product_id"
7404
+ );
7405
+ let product;
7406
+ try {
7407
+ product = await dodopayments.products.retrieve(productIdToFetch);
7408
+ } catch (err) {
7409
+ console.error(err);
7410
+ throw new Error("Product not found");
7411
+ }
7412
+ isSubscription = Boolean(product.is_recurring);
7413
+ if (isSubscription && !product_id)
7414
+ throw new Error("Missing required field: product_id for subscription");
7415
+ if (!billing) throw new Error("Missing required field: billing");
7416
+ if (!customer) throw new Error("Missing required field: customer");
7417
+ if (isSubscription) {
7418
+ const subscriptionPayload = {
7419
+ billing,
7420
+ customer,
7421
+ product_id,
7422
+ quantity: quantity ? Number(quantity) : 1
7423
+ };
7424
+ if (metadata) subscriptionPayload.metadata = metadata;
7425
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
7426
+ if (addons) subscriptionPayload.addons = addons;
7427
+ if (allowed_payment_method_types)
7428
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
7429
+ if (billing_currency)
7430
+ subscriptionPayload.billing_currency = billing_currency;
7431
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
7432
+ subscriptionPayload.payment_link = true;
7433
+ if (bodyReturnUrl) {
7434
+ subscriptionPayload.return_url = bodyReturnUrl;
7435
+ } else if (returnUrl) {
7436
+ subscriptionPayload.return_url = returnUrl;
7437
+ }
7438
+ if (show_saved_payment_methods)
7439
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
7440
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
7441
+ if (trial_period_days)
7442
+ subscriptionPayload.trial_period_days = trial_period_days;
7443
+ let subscription;
7444
+ try {
7445
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
7446
+ } catch (err) {
7447
+ console.error("Error when creating subscription", err);
7448
+ throw new Error(err instanceof Error ? err.message : String(err));
7449
+ }
7450
+ if (!subscription || !subscription.payment_link) {
7451
+ throw new Error(
7452
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
7453
+ );
7454
+ }
7455
+ return subscription.payment_link;
7456
+ } else {
7457
+ let cart = product_cart;
7458
+ if (!cart && product_id) {
7459
+ cart = [
7460
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
7461
+ ];
7462
+ }
7463
+ if (!cart || cart.length === 0)
7464
+ throw new Error("Missing required field: product_cart or product_id");
7465
+ const paymentPayload = {
7466
+ billing,
7467
+ customer,
7468
+ product_cart: cart
7469
+ };
7470
+ if (metadata) paymentPayload.metadata = metadata;
7471
+ paymentPayload.payment_link = true;
7472
+ if (allowed_payment_method_types)
7473
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
7474
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
7475
+ if (discount_code) paymentPayload.discount_code = discount_code;
7476
+ if (bodyReturnUrl) {
7477
+ paymentPayload.return_url = bodyReturnUrl;
7478
+ } else if (returnUrl) {
7479
+ paymentPayload.return_url = returnUrl;
7480
+ }
7481
+ if (show_saved_payment_methods)
7482
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
7483
+ if (tax_id) paymentPayload.tax_id = tax_id;
7484
+ let payment;
7485
+ try {
7486
+ payment = await dodopayments.payments.create(paymentPayload);
7487
+ } catch (err) {
7488
+ console.error("Error when creating payment link", err);
7489
+ throw new Error(err instanceof Error ? err.message : String(err));
7490
+ }
7491
+ if (!payment || !payment.payment_link) {
7492
+ throw new Error(
7493
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
7494
+ );
7495
+ }
7496
+ return payment.payment_link;
7497
+ }
7498
+ };
7499
+
7500
+ /**
7501
+ * Remix Checkout handler
7502
+ * Usage: export const loader = Checkout(config); export const action = Checkout(config);
7503
+ */
7504
+ function Checkout(config) {
7505
+ return async function (request) {
7506
+ if (request.method === "POST") {
7507
+ // Handle dynamic checkout and checkout sessions (POST)
7508
+ let body;
7509
+ try {
7510
+ body = await request.json();
7511
+ }
7512
+ catch (e) {
7513
+ return new Response("Invalid JSON body", { status: 400 });
7514
+ }
7515
+ if (config.type === "dynamic") {
7516
+ // Handle dynamic checkout
7517
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
7518
+ if (!success) {
7519
+ return new Response(`Invalid request body.\n ${error.message}`, {
7520
+ status: 400,
7521
+ });
7522
+ }
7523
+ let url = "";
7524
+ try {
7525
+ url = await buildCheckoutUrl({
7526
+ body: data,
7527
+ ...config,
7528
+ type: "dynamic",
7529
+ });
7530
+ }
7531
+ catch (error) {
7532
+ return new Response(error.message, { status: 400 });
7533
+ }
7534
+ return Response.json({ checkout_url: url });
7565
7535
  }
7566
7536
  else {
7567
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
7537
+ // Handle checkout session
7538
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
7539
+ if (!success) {
7540
+ return new Response(`Invalid checkout session payload.\n ${error.message}`, {
7541
+ status: 400,
7542
+ });
7543
+ }
7544
+ let url = "";
7545
+ try {
7546
+ url = await buildCheckoutUrl({
7547
+ sessionPayload: data,
7548
+ ...config,
7549
+ type: "session",
7550
+ });
7551
+ }
7552
+ catch (error) {
7553
+ return new Response(error.message, { status: 400 });
7554
+ }
7555
+ return Response.json({ checkout_url: url });
7568
7556
  }
7569
7557
  }
7570
7558
  else {
7571
- if (typeof secret !== "string") {
7572
- throw new Error("Expected secret to be of type string");
7559
+ // Handle static checkout (GET)
7560
+ const { searchParams } = new URL(request.url);
7561
+ const queryParams = Object.fromEntries(searchParams);
7562
+ if (!queryParams.productId) {
7563
+ return new Response("Please provide productId query parameter", {
7564
+ status: 400,
7565
+ });
7573
7566
  }
7574
- if (secret.startsWith(Webhook.prefix)) {
7575
- secret = secret.substring(Webhook.prefix.length);
7567
+ const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
7568
+ if (!success) {
7569
+ if (error.errors.some((e) => e.path.toString() === "productId")) {
7570
+ return new Response("Please provide productId query parameter", {
7571
+ status: 400,
7572
+ });
7573
+ }
7574
+ return new Response(`Invalid query parameters.\n ${error.message}`, {
7575
+ status: 400,
7576
+ });
7576
7577
  }
7577
- this.key = base64.decode(secret);
7578
- }
7579
- }
7580
- verify(payload, headers_) {
7581
- const headers = {};
7582
- for (const key of Object.keys(headers_)) {
7583
- headers[key.toLowerCase()] = headers_[key];
7584
- }
7585
- const msgId = headers["webhook-id"];
7586
- const msgSignature = headers["webhook-signature"];
7587
- const msgTimestamp = headers["webhook-timestamp"];
7588
- if (!msgSignature || !msgId || !msgTimestamp) {
7589
- throw new WebhookVerificationError("Missing required headers");
7590
- }
7591
- const timestamp = this.verifyTimestamp(msgTimestamp);
7592
- const computedSignature = this.sign(msgId, timestamp, payload);
7593
- const expectedSignature = computedSignature.split(",")[1];
7594
- const passedSignatures = msgSignature.split(" ");
7595
- const encoder = new globalThis.TextEncoder();
7596
- for (const versionedSignature of passedSignatures) {
7597
- const [version, signature] = versionedSignature.split(",");
7598
- if (version !== "v1") {
7599
- continue;
7578
+ let url = "";
7579
+ try {
7580
+ url = await buildCheckoutUrl({ queryParams: data, ...config });
7600
7581
  }
7601
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
7602
- return JSON.parse(payload.toString());
7582
+ catch (error) {
7583
+ return new Response(error.message, { status: 400 });
7603
7584
  }
7585
+ return Response.json({ checkout_url: url });
7604
7586
  }
7605
- throw new WebhookVerificationError("No matching signature found");
7606
- }
7607
- sign(msgId, timestamp, payload) {
7608
- if (typeof payload === "string") ;
7609
- else if (payload.constructor.name === "Buffer") {
7610
- payload = payload.toString();
7611
- }
7612
- else {
7613
- throw new Error("Expected payload to be of type string or Buffer.");
7614
- }
7615
- const encoder = new TextEncoder();
7616
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
7617
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
7618
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
7619
- return `v1,${expectedSignature}`;
7620
- }
7621
- verifyTimestamp(timestampHeader) {
7622
- const now = Math.floor(Date.now() / 1000);
7623
- const timestamp = parseInt(timestampHeader, 10);
7624
- if (isNaN(timestamp)) {
7625
- throw new WebhookVerificationError("Invalid Signature Headers");
7626
- }
7627
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
7628
- throw new WebhookVerificationError("Message timestamp too old");
7629
- }
7630
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
7631
- throw new WebhookVerificationError("Message timestamp too new");
7632
- }
7633
- return new Date(timestamp * 1000);
7634
- }
7587
+ };
7635
7588
  }
7636
- Webhook_1 = dist.Webhook = Webhook;
7637
- Webhook.prefix = "whsec_";
7638
7589
 
7590
+ // src/schemas/webhook.ts
7639
7591
  var PaymentSchema = objectType({
7640
- payload_type: literalType("Payment"),
7641
- billing: objectType({
7642
- city: stringType().nullable(),
7643
- country: stringType().nullable(),
7644
- state: stringType().nullable(),
7645
- street: stringType().nullable(),
7646
- zipcode: stringType().nullable(),
7647
- }),
7648
- brand_id: stringType(),
7649
- business_id: stringType(),
7650
- card_issuing_country: stringType().nullable(),
7651
- card_last_four: stringType().nullable(),
7652
- card_network: stringType().nullable(),
7653
- card_type: stringType().nullable(),
7654
- created_at: stringType().transform(function (d) { return new Date(d); }),
7655
- currency: stringType(),
7656
- customer: objectType({
7657
- customer_id: stringType(),
7658
- email: stringType(),
7659
- name: stringType().nullable(),
7660
- }),
7661
- digital_products_delivered: booleanType(),
7662
- discount_id: stringType().nullable(),
7663
- disputes: arrayType(objectType({
7664
- amount: stringType(),
7665
- business_id: stringType(),
7666
- created_at: stringType().transform(function (d) { return new Date(d); }),
7667
- currency: stringType(),
7668
- dispute_id: stringType(),
7669
- dispute_stage: enumType([
7670
- "pre_dispute",
7671
- "dispute_opened",
7672
- "dispute_won",
7673
- "dispute_lost",
7674
- ]),
7675
- dispute_status: enumType([
7676
- "dispute_opened",
7677
- "dispute_won",
7678
- "dispute_lost",
7679
- "dispute_accepted",
7680
- "dispute_cancelled",
7681
- "dispute_challenged",
7682
- ]),
7683
- payment_id: stringType(),
7684
- remarks: stringType().nullable(),
7685
- }))
7686
- .nullable(),
7687
- error_code: stringType().nullable(),
7688
- error_message: stringType().nullable(),
7689
- metadata: recordType(anyType()).nullable(),
7690
- payment_id: stringType(),
7691
- payment_link: stringType().nullable(),
7692
- payment_method: stringType().nullable(),
7693
- payment_method_type: stringType().nullable(),
7694
- product_cart: arrayType(objectType({
7695
- product_id: stringType(),
7696
- quantity: numberType(),
7697
- }))
7698
- .nullable(),
7699
- refunds: arrayType(objectType({
7700
- amount: numberType(),
7701
- business_id: stringType(),
7702
- created_at: stringType().transform(function (d) { return new Date(d); }),
7703
- currency: stringType(),
7704
- is_partial: booleanType(),
7705
- payment_id: stringType(),
7706
- reason: stringType().nullable(),
7707
- refund_id: stringType(),
7708
- status: enumType(["succeeded", "failed", "pending"]),
7709
- }))
7710
- .nullable(),
7711
- settlement_amount: numberType(),
7712
- settlement_currency: stringType(),
7713
- settlement_tax: numberType().nullable(),
7714
- status: enumType(["succeeded", "failed", "pending", "processing", "cancelled"]),
7715
- subscription_id: stringType().nullable(),
7716
- tax: numberType().nullable(),
7717
- total_amount: numberType(),
7718
- updated_at: stringType()
7719
- .transform(function (d) { return new Date(d); })
7720
- .nullable(),
7721
- });
7722
- var SubscriptionSchema = objectType({
7723
- payload_type: literalType("Subscription"),
7724
- addons: arrayType(objectType({
7725
- addon_id: stringType(),
7726
- quantity: numberType(),
7727
- }))
7728
- .nullable(),
7729
- billing: objectType({
7730
- city: stringType().nullable(),
7731
- country: stringType().nullable(),
7732
- state: stringType().nullable(),
7733
- street: stringType().nullable(),
7734
- zipcode: stringType().nullable(),
7735
- }),
7736
- cancel_at_next_billing_date: booleanType(),
7737
- cancelled_at: stringType()
7738
- .transform(function (d) { return new Date(d); })
7739
- .nullable(),
7740
- created_at: stringType().transform(function (d) { return new Date(d); }),
7741
- currency: stringType(),
7742
- customer: objectType({
7743
- customer_id: stringType(),
7744
- email: stringType(),
7745
- name: stringType().nullable(),
7746
- }),
7747
- discount_id: stringType().nullable(),
7748
- metadata: recordType(anyType()).nullable(),
7749
- next_billing_date: stringType()
7750
- .transform(function (d) { return new Date(d); })
7751
- .nullable(),
7752
- on_demand: booleanType(),
7753
- payment_frequency_count: numberType(),
7754
- payment_frequency_interval: enumType(["Day", "Week", "Month", "Year"]),
7755
- previous_billing_date: stringType()
7756
- .transform(function (d) { return new Date(d); })
7757
- .nullable(),
7758
- product_id: stringType(),
7759
- quantity: numberType(),
7760
- recurring_pre_tax_amount: numberType(),
7761
- status: enumType([
7762
- "pending",
7763
- "active",
7764
- "on_hold",
7765
- "paused",
7766
- "cancelled",
7767
- "expired",
7768
- "failed",
7769
- ]),
7770
- subscription_id: stringType(),
7771
- subscription_period_count: numberType(),
7772
- subscription_period_interval: enumType(["Day", "Week", "Month", "Year"]),
7773
- tax_inclusive: booleanType(),
7774
- trial_period_days: numberType(),
7775
- });
7776
- var RefundSchema = objectType({
7777
- payload_type: literalType("Refund"),
7778
- amount: numberType(),
7779
- business_id: stringType(),
7780
- created_at: stringType().transform(function (d) { return new Date(d); }),
7781
- currency: stringType(),
7782
- is_partial: booleanType(),
7783
- payment_id: stringType(),
7784
- reason: stringType().nullable(),
7785
- refund_id: stringType(),
7786
- status: enumType(["succeeded", "failed", "pending"]),
7787
- });
7788
- var DisputeSchema = objectType({
7789
- payload_type: literalType("Dispute"),
7790
- amount: stringType(),
7791
- business_id: stringType(),
7792
- created_at: stringType().transform(function (d) { return new Date(d); }),
7793
- currency: stringType(),
7794
- dispute_id: stringType(),
7795
- dispute_stage: enumType([
7592
+ payload_type: literalType("Payment"),
7593
+ billing: objectType({
7594
+ city: stringType().nullable(),
7595
+ country: stringType().nullable(),
7596
+ state: stringType().nullable(),
7597
+ street: stringType().nullable(),
7598
+ zipcode: stringType().nullable()
7599
+ }),
7600
+ brand_id: stringType(),
7601
+ business_id: stringType(),
7602
+ card_issuing_country: stringType().nullable(),
7603
+ card_last_four: stringType().nullable(),
7604
+ card_network: stringType().nullable(),
7605
+ card_type: stringType().nullable(),
7606
+ created_at: stringType().transform((d) => new Date(d)),
7607
+ currency: stringType(),
7608
+ customer: objectType({
7609
+ customer_id: stringType(),
7610
+ email: stringType(),
7611
+ name: stringType().nullable()
7612
+ }),
7613
+ digital_products_delivered: booleanType(),
7614
+ discount_id: stringType().nullable(),
7615
+ disputes: arrayType(
7616
+ objectType({
7617
+ amount: stringType(),
7618
+ business_id: stringType(),
7619
+ created_at: stringType().transform((d) => new Date(d)),
7620
+ currency: stringType(),
7621
+ dispute_id: stringType(),
7622
+ dispute_stage: enumType([
7796
7623
  "pre_dispute",
7797
7624
  "dispute_opened",
7798
7625
  "dispute_won",
7799
- "dispute_lost",
7800
- ]),
7801
- dispute_status: enumType([
7626
+ "dispute_lost"
7627
+ ]),
7628
+ dispute_status: enumType([
7802
7629
  "dispute_opened",
7803
7630
  "dispute_won",
7804
7631
  "dispute_lost",
7805
7632
  "dispute_accepted",
7806
7633
  "dispute_cancelled",
7807
- "dispute_challenged",
7808
- ]),
7809
- payment_id: stringType(),
7810
- remarks: stringType().nullable(),
7634
+ "dispute_challenged"
7635
+ ]),
7636
+ payment_id: stringType(),
7637
+ remarks: stringType().nullable()
7638
+ })
7639
+ ).nullable(),
7640
+ error_code: stringType().nullable(),
7641
+ error_message: stringType().nullable(),
7642
+ metadata: recordType(anyType()).nullable(),
7643
+ payment_id: stringType(),
7644
+ payment_link: stringType().nullable(),
7645
+ payment_method: stringType().nullable(),
7646
+ payment_method_type: stringType().nullable(),
7647
+ product_cart: arrayType(
7648
+ objectType({
7649
+ product_id: stringType(),
7650
+ quantity: numberType()
7651
+ })
7652
+ ).nullable(),
7653
+ refunds: arrayType(
7654
+ objectType({
7655
+ amount: numberType(),
7656
+ business_id: stringType(),
7657
+ created_at: stringType().transform((d) => new Date(d)),
7658
+ currency: stringType(),
7659
+ is_partial: booleanType(),
7660
+ payment_id: stringType(),
7661
+ reason: stringType().nullable(),
7662
+ refund_id: stringType(),
7663
+ status: enumType(["succeeded", "failed", "pending"])
7664
+ })
7665
+ ).nullable(),
7666
+ settlement_amount: numberType(),
7667
+ settlement_currency: stringType(),
7668
+ settlement_tax: numberType().nullable(),
7669
+ status: enumType(["succeeded", "failed", "pending", "processing", "cancelled"]),
7670
+ subscription_id: stringType().nullable(),
7671
+ tax: numberType().nullable(),
7672
+ total_amount: numberType(),
7673
+ updated_at: stringType().transform((d) => new Date(d)).nullable()
7811
7674
  });
7812
- var LicenseKeySchema = objectType({
7813
- payload_type: literalType("LicenseKey"),
7814
- activations_limit: numberType(),
7815
- business_id: stringType(),
7816
- created_at: stringType().transform(function (d) { return new Date(d); }),
7675
+ var SubscriptionSchema = objectType({
7676
+ payload_type: literalType("Subscription"),
7677
+ addons: arrayType(
7678
+ objectType({
7679
+ addon_id: stringType(),
7680
+ quantity: numberType()
7681
+ })
7682
+ ).nullable(),
7683
+ billing: objectType({
7684
+ city: stringType().nullable(),
7685
+ country: stringType().nullable(),
7686
+ state: stringType().nullable(),
7687
+ street: stringType().nullable(),
7688
+ zipcode: stringType().nullable()
7689
+ }),
7690
+ cancel_at_next_billing_date: booleanType(),
7691
+ cancelled_at: stringType().transform((d) => new Date(d)).nullable(),
7692
+ created_at: stringType().transform((d) => new Date(d)),
7693
+ currency: stringType(),
7694
+ customer: objectType({
7817
7695
  customer_id: stringType(),
7818
- expires_at: stringType()
7819
- .transform(function (d) { return new Date(d); })
7820
- .nullable(),
7821
- id: stringType(),
7822
- instances_count: numberType(),
7823
- key: stringType(),
7824
- payment_id: stringType(),
7825
- product_id: stringType(),
7826
- status: enumType(["active", "inactive", "expired"]),
7827
- subscription_id: stringType().nullable(),
7696
+ email: stringType(),
7697
+ name: stringType().nullable()
7698
+ }),
7699
+ discount_id: stringType().nullable(),
7700
+ metadata: recordType(anyType()).nullable(),
7701
+ next_billing_date: stringType().transform((d) => new Date(d)).nullable(),
7702
+ on_demand: booleanType(),
7703
+ payment_frequency_count: numberType(),
7704
+ payment_frequency_interval: enumType(["Day", "Week", "Month", "Year"]),
7705
+ previous_billing_date: stringType().transform((d) => new Date(d)).nullable(),
7706
+ product_id: stringType(),
7707
+ quantity: numberType(),
7708
+ recurring_pre_tax_amount: numberType(),
7709
+ status: enumType([
7710
+ "pending",
7711
+ "active",
7712
+ "on_hold",
7713
+ "paused",
7714
+ "cancelled",
7715
+ "expired",
7716
+ "failed"
7717
+ ]),
7718
+ subscription_id: stringType(),
7719
+ subscription_period_count: numberType(),
7720
+ subscription_period_interval: enumType(["Day", "Week", "Month", "Year"]),
7721
+ tax_inclusive: booleanType(),
7722
+ trial_period_days: numberType()
7723
+ });
7724
+ var RefundSchema = objectType({
7725
+ payload_type: literalType("Refund"),
7726
+ amount: numberType(),
7727
+ business_id: stringType(),
7728
+ created_at: stringType().transform((d) => new Date(d)),
7729
+ currency: stringType(),
7730
+ is_partial: booleanType(),
7731
+ payment_id: stringType(),
7732
+ reason: stringType().nullable(),
7733
+ refund_id: stringType(),
7734
+ status: enumType(["succeeded", "failed", "pending"])
7735
+ });
7736
+ var DisputeSchema = objectType({
7737
+ payload_type: literalType("Dispute"),
7738
+ amount: stringType(),
7739
+ business_id: stringType(),
7740
+ created_at: stringType().transform((d) => new Date(d)),
7741
+ currency: stringType(),
7742
+ dispute_id: stringType(),
7743
+ dispute_stage: enumType([
7744
+ "pre_dispute",
7745
+ "dispute_opened",
7746
+ "dispute_won",
7747
+ "dispute_lost"
7748
+ ]),
7749
+ dispute_status: enumType([
7750
+ "dispute_opened",
7751
+ "dispute_won",
7752
+ "dispute_lost",
7753
+ "dispute_accepted",
7754
+ "dispute_cancelled",
7755
+ "dispute_challenged"
7756
+ ]),
7757
+ payment_id: stringType(),
7758
+ remarks: stringType().nullable()
7759
+ });
7760
+ var LicenseKeySchema = objectType({
7761
+ payload_type: literalType("LicenseKey"),
7762
+ activations_limit: numberType(),
7763
+ business_id: stringType(),
7764
+ created_at: stringType().transform((d) => new Date(d)),
7765
+ customer_id: stringType(),
7766
+ expires_at: stringType().transform((d) => new Date(d)).nullable(),
7767
+ id: stringType(),
7768
+ instances_count: numberType(),
7769
+ key: stringType(),
7770
+ payment_id: stringType(),
7771
+ product_id: stringType(),
7772
+ status: enumType(["active", "inactive", "expired"]),
7773
+ subscription_id: stringType().nullable()
7828
7774
  });
7829
7775
  var PaymentSucceededPayloadSchema = objectType({
7830
- business_id: stringType(),
7831
- type: literalType("payment.succeeded"),
7832
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7833
- data: PaymentSchema,
7776
+ business_id: stringType(),
7777
+ type: literalType("payment.succeeded"),
7778
+ timestamp: stringType().transform((d) => new Date(d)),
7779
+ data: PaymentSchema
7834
7780
  });
7835
7781
  var PaymentFailedPayloadSchema = objectType({
7836
- business_id: stringType(),
7837
- type: literalType("payment.failed"),
7838
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7839
- data: PaymentSchema,
7782
+ business_id: stringType(),
7783
+ type: literalType("payment.failed"),
7784
+ timestamp: stringType().transform((d) => new Date(d)),
7785
+ data: PaymentSchema
7840
7786
  });
7841
7787
  var PaymentProcessingPayloadSchema = objectType({
7842
- business_id: stringType(),
7843
- type: literalType("payment.processing"),
7844
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7845
- data: PaymentSchema,
7788
+ business_id: stringType(),
7789
+ type: literalType("payment.processing"),
7790
+ timestamp: stringType().transform((d) => new Date(d)),
7791
+ data: PaymentSchema
7846
7792
  });
7847
7793
  var PaymentCancelledPayloadSchema = objectType({
7848
- business_id: stringType(),
7849
- type: literalType("payment.cancelled"),
7850
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7851
- data: PaymentSchema,
7794
+ business_id: stringType(),
7795
+ type: literalType("payment.cancelled"),
7796
+ timestamp: stringType().transform((d) => new Date(d)),
7797
+ data: PaymentSchema
7852
7798
  });
7853
7799
  var RefundSucceededPayloadSchema = objectType({
7854
- business_id: stringType(),
7855
- type: literalType("refund.succeeded"),
7856
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7857
- data: RefundSchema,
7800
+ business_id: stringType(),
7801
+ type: literalType("refund.succeeded"),
7802
+ timestamp: stringType().transform((d) => new Date(d)),
7803
+ data: RefundSchema
7858
7804
  });
7859
7805
  var RefundFailedPayloadSchema = objectType({
7860
- business_id: stringType(),
7861
- type: literalType("refund.failed"),
7862
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7863
- data: RefundSchema,
7806
+ business_id: stringType(),
7807
+ type: literalType("refund.failed"),
7808
+ timestamp: stringType().transform((d) => new Date(d)),
7809
+ data: RefundSchema
7864
7810
  });
7865
7811
  var DisputeOpenedPayloadSchema = objectType({
7866
- business_id: stringType(),
7867
- type: literalType("dispute.opened"),
7868
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7869
- data: DisputeSchema,
7812
+ business_id: stringType(),
7813
+ type: literalType("dispute.opened"),
7814
+ timestamp: stringType().transform((d) => new Date(d)),
7815
+ data: DisputeSchema
7870
7816
  });
7871
7817
  var DisputeExpiredPayloadSchema = objectType({
7872
- business_id: stringType(),
7873
- type: literalType("dispute.expired"),
7874
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7875
- data: DisputeSchema,
7818
+ business_id: stringType(),
7819
+ type: literalType("dispute.expired"),
7820
+ timestamp: stringType().transform((d) => new Date(d)),
7821
+ data: DisputeSchema
7876
7822
  });
7877
7823
  var DisputeAcceptedPayloadSchema = objectType({
7878
- business_id: stringType(),
7879
- type: literalType("dispute.accepted"),
7880
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7881
- data: DisputeSchema,
7824
+ business_id: stringType(),
7825
+ type: literalType("dispute.accepted"),
7826
+ timestamp: stringType().transform((d) => new Date(d)),
7827
+ data: DisputeSchema
7882
7828
  });
7883
7829
  var DisputeCancelledPayloadSchema = objectType({
7884
- business_id: stringType(),
7885
- type: literalType("dispute.cancelled"),
7886
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7887
- data: DisputeSchema,
7830
+ business_id: stringType(),
7831
+ type: literalType("dispute.cancelled"),
7832
+ timestamp: stringType().transform((d) => new Date(d)),
7833
+ data: DisputeSchema
7888
7834
  });
7889
7835
  var DisputeChallengedPayloadSchema = objectType({
7890
- business_id: stringType(),
7891
- type: literalType("dispute.challenged"),
7892
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7893
- data: DisputeSchema,
7836
+ business_id: stringType(),
7837
+ type: literalType("dispute.challenged"),
7838
+ timestamp: stringType().transform((d) => new Date(d)),
7839
+ data: DisputeSchema
7894
7840
  });
7895
7841
  var DisputeWonPayloadSchema = objectType({
7896
- business_id: stringType(),
7897
- type: literalType("dispute.won"),
7898
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7899
- data: DisputeSchema,
7842
+ business_id: stringType(),
7843
+ type: literalType("dispute.won"),
7844
+ timestamp: stringType().transform((d) => new Date(d)),
7845
+ data: DisputeSchema
7900
7846
  });
7901
7847
  var DisputeLostPayloadSchema = objectType({
7902
- business_id: stringType(),
7903
- type: literalType("dispute.lost"),
7904
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7905
- data: DisputeSchema,
7848
+ business_id: stringType(),
7849
+ type: literalType("dispute.lost"),
7850
+ timestamp: stringType().transform((d) => new Date(d)),
7851
+ data: DisputeSchema
7906
7852
  });
7907
7853
  var SubscriptionActivePayloadSchema = objectType({
7908
- business_id: stringType(),
7909
- type: literalType("subscription.active"),
7910
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7911
- data: SubscriptionSchema,
7854
+ business_id: stringType(),
7855
+ type: literalType("subscription.active"),
7856
+ timestamp: stringType().transform((d) => new Date(d)),
7857
+ data: SubscriptionSchema
7912
7858
  });
7913
7859
  var SubscriptionOnHoldPayloadSchema = objectType({
7914
- business_id: stringType(),
7915
- type: literalType("subscription.on_hold"),
7916
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7917
- data: SubscriptionSchema,
7860
+ business_id: stringType(),
7861
+ type: literalType("subscription.on_hold"),
7862
+ timestamp: stringType().transform((d) => new Date(d)),
7863
+ data: SubscriptionSchema
7918
7864
  });
7919
7865
  var SubscriptionRenewedPayloadSchema = objectType({
7920
- business_id: stringType(),
7921
- type: literalType("subscription.renewed"),
7922
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7923
- data: SubscriptionSchema,
7866
+ business_id: stringType(),
7867
+ type: literalType("subscription.renewed"),
7868
+ timestamp: stringType().transform((d) => new Date(d)),
7869
+ data: SubscriptionSchema
7924
7870
  });
7925
7871
  var SubscriptionPausedPayloadSchema = objectType({
7926
- business_id: stringType(),
7927
- type: literalType("subscription.paused"),
7928
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7929
- data: SubscriptionSchema,
7872
+ business_id: stringType(),
7873
+ type: literalType("subscription.paused"),
7874
+ timestamp: stringType().transform((d) => new Date(d)),
7875
+ data: SubscriptionSchema
7930
7876
  });
7931
7877
  var SubscriptionPlanChangedPayloadSchema = objectType({
7932
- business_id: stringType(),
7933
- type: literalType("subscription.plan_changed"),
7934
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7935
- data: SubscriptionSchema,
7878
+ business_id: stringType(),
7879
+ type: literalType("subscription.plan_changed"),
7880
+ timestamp: stringType().transform((d) => new Date(d)),
7881
+ data: SubscriptionSchema
7936
7882
  });
7937
7883
  var SubscriptionCancelledPayloadSchema = objectType({
7938
- business_id: stringType(),
7939
- type: literalType("subscription.cancelled"),
7940
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7941
- data: SubscriptionSchema,
7884
+ business_id: stringType(),
7885
+ type: literalType("subscription.cancelled"),
7886
+ timestamp: stringType().transform((d) => new Date(d)),
7887
+ data: SubscriptionSchema
7942
7888
  });
7943
7889
  var SubscriptionFailedPayloadSchema = objectType({
7944
- business_id: stringType(),
7945
- type: literalType("subscription.failed"),
7946
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7947
- data: SubscriptionSchema,
7890
+ business_id: stringType(),
7891
+ type: literalType("subscription.failed"),
7892
+ timestamp: stringType().transform((d) => new Date(d)),
7893
+ data: SubscriptionSchema
7948
7894
  });
7949
7895
  var SubscriptionExpiredPayloadSchema = objectType({
7950
- business_id: stringType(),
7951
- type: literalType("subscription.expired"),
7952
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7953
- data: SubscriptionSchema,
7896
+ business_id: stringType(),
7897
+ type: literalType("subscription.expired"),
7898
+ timestamp: stringType().transform((d) => new Date(d)),
7899
+ data: SubscriptionSchema
7954
7900
  });
7955
7901
  var LicenseKeyCreatedPayloadSchema = objectType({
7956
- business_id: stringType(),
7957
- type: literalType("license_key.created"),
7958
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7959
- data: LicenseKeySchema,
7902
+ business_id: stringType(),
7903
+ type: literalType("license_key.created"),
7904
+ timestamp: stringType().transform((d) => new Date(d)),
7905
+ data: LicenseKeySchema
7960
7906
  });
7961
7907
  var WebhookPayloadSchema = discriminatedUnionType("type", [
7962
- PaymentSucceededPayloadSchema,
7963
- PaymentFailedPayloadSchema,
7964
- PaymentProcessingPayloadSchema,
7965
- PaymentCancelledPayloadSchema,
7966
- RefundSucceededPayloadSchema,
7967
- RefundFailedPayloadSchema,
7968
- DisputeOpenedPayloadSchema,
7969
- DisputeExpiredPayloadSchema,
7970
- DisputeAcceptedPayloadSchema,
7971
- DisputeCancelledPayloadSchema,
7972
- DisputeChallengedPayloadSchema,
7973
- DisputeWonPayloadSchema,
7974
- DisputeLostPayloadSchema,
7975
- SubscriptionActivePayloadSchema,
7976
- SubscriptionOnHoldPayloadSchema,
7977
- SubscriptionRenewedPayloadSchema,
7978
- SubscriptionPausedPayloadSchema,
7979
- SubscriptionPlanChangedPayloadSchema,
7980
- SubscriptionCancelledPayloadSchema,
7981
- SubscriptionFailedPayloadSchema,
7982
- SubscriptionExpiredPayloadSchema,
7983
- LicenseKeyCreatedPayloadSchema,
7908
+ PaymentSucceededPayloadSchema,
7909
+ PaymentFailedPayloadSchema,
7910
+ PaymentProcessingPayloadSchema,
7911
+ PaymentCancelledPayloadSchema,
7912
+ RefundSucceededPayloadSchema,
7913
+ RefundFailedPayloadSchema,
7914
+ DisputeOpenedPayloadSchema,
7915
+ DisputeExpiredPayloadSchema,
7916
+ DisputeAcceptedPayloadSchema,
7917
+ DisputeCancelledPayloadSchema,
7918
+ DisputeChallengedPayloadSchema,
7919
+ DisputeWonPayloadSchema,
7920
+ DisputeLostPayloadSchema,
7921
+ SubscriptionActivePayloadSchema,
7922
+ SubscriptionOnHoldPayloadSchema,
7923
+ SubscriptionRenewedPayloadSchema,
7924
+ SubscriptionPausedPayloadSchema,
7925
+ SubscriptionPlanChangedPayloadSchema,
7926
+ SubscriptionCancelledPayloadSchema,
7927
+ SubscriptionFailedPayloadSchema,
7928
+ SubscriptionExpiredPayloadSchema,
7929
+ LicenseKeyCreatedPayloadSchema
7984
7930
  ]);
7985
7931
 
7986
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7987
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7988
- return new (P || (P = Promise))(function (resolve, reject) {
7989
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7990
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7991
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7992
- step((generator = generator.apply(thisArg, _arguments || [])).next());
7993
- });
7994
- };
7995
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
7996
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
7997
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7998
- function verb(n) { return function (v) { return step([n, v]); }; }
7999
- function step(op) {
8000
- if (f) throw new TypeError("Generator is already executing.");
8001
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
8002
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
8003
- if (y = 0, t) op = [op[0] & 2, t.value];
8004
- switch (op[0]) {
8005
- case 0: case 1: t = op; break;
8006
- case 4: _.label++; return { value: op[1], done: false };
8007
- case 5: _.label++; y = op[1]; op = [0]; continue;
8008
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
8009
- default:
8010
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
8011
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
8012
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
8013
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
8014
- if (t[2]) _.ops.pop();
8015
- _.trys.pop(); continue;
8016
- }
8017
- op = body.call(thisArg, _);
8018
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
8019
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
8020
- }
8021
- };
8022
- // Implementation
8023
- function handleWebhookPayload(payload, config, context) {
8024
- return __awaiter(this, void 0, void 0, function () {
8025
- var callHandler;
8026
- return __generator(this, function (_a) {
8027
- switch (_a.label) {
8028
- case 0:
8029
- callHandler = function (handler, payload) {
8030
- if (!handler)
8031
- return;
8032
- return handler(payload);
8033
- };
8034
- if (!config.onPayload) return [3 /*break*/, 2];
8035
- return [4 /*yield*/, callHandler(config.onPayload, payload)];
8036
- case 1:
8037
- _a.sent();
8038
- _a.label = 2;
8039
- case 2:
8040
- if (!(payload.type === "payment.succeeded")) return [3 /*break*/, 4];
8041
- return [4 /*yield*/, callHandler(config.onPaymentSucceeded, payload)];
8042
- case 3:
8043
- _a.sent();
8044
- _a.label = 4;
8045
- case 4:
8046
- if (!(payload.type === "payment.failed")) return [3 /*break*/, 6];
8047
- return [4 /*yield*/, callHandler(config.onPaymentFailed, payload)];
8048
- case 5:
8049
- _a.sent();
8050
- _a.label = 6;
8051
- case 6:
8052
- if (!(payload.type === "payment.processing")) return [3 /*break*/, 8];
8053
- return [4 /*yield*/, callHandler(config.onPaymentProcessing, payload)];
8054
- case 7:
8055
- _a.sent();
8056
- _a.label = 8;
8057
- case 8:
8058
- if (!(payload.type === "payment.cancelled")) return [3 /*break*/, 10];
8059
- return [4 /*yield*/, callHandler(config.onPaymentCancelled, payload)];
8060
- case 9:
8061
- _a.sent();
8062
- _a.label = 10;
8063
- case 10:
8064
- if (!(payload.type === "refund.succeeded")) return [3 /*break*/, 12];
8065
- return [4 /*yield*/, callHandler(config.onRefundSucceeded, payload)];
8066
- case 11:
8067
- _a.sent();
8068
- _a.label = 12;
8069
- case 12:
8070
- if (!(payload.type === "refund.failed")) return [3 /*break*/, 14];
8071
- return [4 /*yield*/, callHandler(config.onRefundFailed, payload)];
8072
- case 13:
8073
- _a.sent();
8074
- _a.label = 14;
8075
- case 14:
8076
- if (!(payload.type === "dispute.opened")) return [3 /*break*/, 16];
8077
- return [4 /*yield*/, callHandler(config.onDisputeOpened, payload)];
8078
- case 15:
8079
- _a.sent();
8080
- _a.label = 16;
8081
- case 16:
8082
- if (!(payload.type === "dispute.expired")) return [3 /*break*/, 18];
8083
- return [4 /*yield*/, callHandler(config.onDisputeExpired, payload)];
8084
- case 17:
8085
- _a.sent();
8086
- _a.label = 18;
8087
- case 18:
8088
- if (!(payload.type === "dispute.accepted")) return [3 /*break*/, 20];
8089
- return [4 /*yield*/, callHandler(config.onDisputeAccepted, payload)];
8090
- case 19:
8091
- _a.sent();
8092
- _a.label = 20;
8093
- case 20:
8094
- if (!(payload.type === "dispute.cancelled")) return [3 /*break*/, 22];
8095
- return [4 /*yield*/, callHandler(config.onDisputeCancelled, payload)];
8096
- case 21:
8097
- _a.sent();
8098
- _a.label = 22;
8099
- case 22:
8100
- if (!(payload.type === "dispute.challenged")) return [3 /*break*/, 24];
8101
- return [4 /*yield*/, callHandler(config.onDisputeChallenged, payload)];
8102
- case 23:
8103
- _a.sent();
8104
- _a.label = 24;
8105
- case 24:
8106
- if (!(payload.type === "dispute.won")) return [3 /*break*/, 26];
8107
- return [4 /*yield*/, callHandler(config.onDisputeWon, payload)];
8108
- case 25:
8109
- _a.sent();
8110
- _a.label = 26;
8111
- case 26:
8112
- if (!(payload.type === "dispute.lost")) return [3 /*break*/, 28];
8113
- return [4 /*yield*/, callHandler(config.onDisputeLost, payload)];
8114
- case 27:
8115
- _a.sent();
8116
- _a.label = 28;
8117
- case 28:
8118
- if (!(payload.type === "subscription.active")) return [3 /*break*/, 30];
8119
- return [4 /*yield*/, callHandler(config.onSubscriptionActive, payload)];
8120
- case 29:
8121
- _a.sent();
8122
- _a.label = 30;
8123
- case 30:
8124
- if (!(payload.type === "subscription.on_hold")) return [3 /*break*/, 32];
8125
- return [4 /*yield*/, callHandler(config.onSubscriptionOnHold, payload)];
8126
- case 31:
8127
- _a.sent();
8128
- _a.label = 32;
8129
- case 32:
8130
- if (!(payload.type === "subscription.renewed")) return [3 /*break*/, 34];
8131
- return [4 /*yield*/, callHandler(config.onSubscriptionRenewed, payload)];
8132
- case 33:
8133
- _a.sent();
8134
- _a.label = 34;
8135
- case 34:
8136
- if (!(payload.type === "subscription.paused")) return [3 /*break*/, 36];
8137
- return [4 /*yield*/, callHandler(config.onSubscriptionPaused, payload)];
8138
- case 35:
8139
- _a.sent();
8140
- _a.label = 36;
8141
- case 36:
8142
- if (!(payload.type === "subscription.plan_changed")) return [3 /*break*/, 38];
8143
- return [4 /*yield*/, callHandler(config.onSubscriptionPlanChanged, payload)];
8144
- case 37:
8145
- _a.sent();
8146
- _a.label = 38;
8147
- case 38:
8148
- if (!(payload.type === "subscription.cancelled")) return [3 /*break*/, 40];
8149
- return [4 /*yield*/, callHandler(config.onSubscriptionCancelled, payload)];
8150
- case 39:
8151
- _a.sent();
8152
- _a.label = 40;
8153
- case 40:
8154
- if (!(payload.type === "subscription.failed")) return [3 /*break*/, 42];
8155
- return [4 /*yield*/, callHandler(config.onSubscriptionFailed, payload)];
8156
- case 41:
8157
- _a.sent();
8158
- _a.label = 42;
8159
- case 42:
8160
- if (!(payload.type === "subscription.expired")) return [3 /*break*/, 44];
8161
- return [4 /*yield*/, callHandler(config.onSubscriptionExpired, payload)];
8162
- case 43:
8163
- _a.sent();
8164
- _a.label = 44;
8165
- case 44:
8166
- if (!(payload.type === "license_key.created")) return [3 /*break*/, 46];
8167
- return [4 /*yield*/, callHandler(config.onLicenseKeyCreated, payload)];
8168
- case 45:
8169
- _a.sent();
8170
- _a.label = 46;
8171
- case 46: return [2 /*return*/];
8172
- }
8173
- });
8174
- });
7932
+ async function handleWebhookPayload(payload, config, context) {
7933
+ const callHandler = (handler, payload2) => {
7934
+ if (!handler) return;
7935
+ return handler(payload2);
7936
+ };
7937
+ if (config.onPayload) {
7938
+ await callHandler(config.onPayload, payload);
7939
+ }
7940
+ if (payload.type === "payment.succeeded") {
7941
+ await callHandler(config.onPaymentSucceeded, payload);
7942
+ }
7943
+ if (payload.type === "payment.failed") {
7944
+ await callHandler(config.onPaymentFailed, payload);
7945
+ }
7946
+ if (payload.type === "payment.processing") {
7947
+ await callHandler(config.onPaymentProcessing, payload);
7948
+ }
7949
+ if (payload.type === "payment.cancelled") {
7950
+ await callHandler(config.onPaymentCancelled, payload);
7951
+ }
7952
+ if (payload.type === "refund.succeeded") {
7953
+ await callHandler(config.onRefundSucceeded, payload);
7954
+ }
7955
+ if (payload.type === "refund.failed") {
7956
+ await callHandler(config.onRefundFailed, payload);
7957
+ }
7958
+ if (payload.type === "dispute.opened") {
7959
+ await callHandler(config.onDisputeOpened, payload);
7960
+ }
7961
+ if (payload.type === "dispute.expired") {
7962
+ await callHandler(config.onDisputeExpired, payload);
7963
+ }
7964
+ if (payload.type === "dispute.accepted") {
7965
+ await callHandler(config.onDisputeAccepted, payload);
7966
+ }
7967
+ if (payload.type === "dispute.cancelled") {
7968
+ await callHandler(config.onDisputeCancelled, payload);
7969
+ }
7970
+ if (payload.type === "dispute.challenged") {
7971
+ await callHandler(config.onDisputeChallenged, payload);
7972
+ }
7973
+ if (payload.type === "dispute.won") {
7974
+ await callHandler(config.onDisputeWon, payload);
7975
+ }
7976
+ if (payload.type === "dispute.lost") {
7977
+ await callHandler(config.onDisputeLost, payload);
7978
+ }
7979
+ if (payload.type === "subscription.active") {
7980
+ await callHandler(config.onSubscriptionActive, payload);
7981
+ }
7982
+ if (payload.type === "subscription.on_hold") {
7983
+ await callHandler(config.onSubscriptionOnHold, payload);
7984
+ }
7985
+ if (payload.type === "subscription.renewed") {
7986
+ await callHandler(config.onSubscriptionRenewed, payload);
7987
+ }
7988
+ if (payload.type === "subscription.paused") {
7989
+ await callHandler(config.onSubscriptionPaused, payload);
7990
+ }
7991
+ if (payload.type === "subscription.plan_changed") {
7992
+ await callHandler(config.onSubscriptionPlanChanged, payload);
7993
+ }
7994
+ if (payload.type === "subscription.cancelled") {
7995
+ await callHandler(config.onSubscriptionCancelled, payload);
7996
+ }
7997
+ if (payload.type === "subscription.failed") {
7998
+ await callHandler(config.onSubscriptionFailed, payload);
7999
+ }
8000
+ if (payload.type === "subscription.expired") {
8001
+ await callHandler(config.onSubscriptionExpired, payload);
8002
+ }
8003
+ if (payload.type === "license_key.created") {
8004
+ await callHandler(config.onLicenseKeyCreated, payload);
8005
+ }
8175
8006
  }
8176
8007
 
8177
8008
  const Webhooks = ({ webhookKey, ...eventHandlers }) => {