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