@dodopayments/sveltekit 0.2.2 → 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,1389 +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
- }
5943
+ return paddingLength;
5944
+ };
5945
+ return Coder;
5946
+ }());
5947
+ base64$1.Coder = Coder;
5948
+ var stdCoder = new Coder();
5949
+ function encode(data) {
5950
+ return stdCoder.encode(data);
6222
5951
  }
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
- // src/checkout/checkout.ts
6264
- var checkoutQuerySchema = objectType({
6265
- productId: stringType(),
6266
- quantity: stringType().optional(),
6267
- // Customer fields
6268
- fullName: stringType().optional(),
6269
- firstName: stringType().optional(),
6270
- lastName: stringType().optional(),
6271
- email: stringType().optional(),
6272
- country: stringType().optional(),
6273
- addressLine: stringType().optional(),
6274
- city: stringType().optional(),
6275
- state: stringType().optional(),
6276
- zipCode: stringType().optional(),
6277
- // Disable flags
6278
- disableFullName: stringType().optional(),
6279
- disableFirstName: stringType().optional(),
6280
- disableLastName: stringType().optional(),
6281
- disableEmail: stringType().optional(),
6282
- disableCountry: stringType().optional(),
6283
- disableAddressLine: stringType().optional(),
6284
- disableCity: stringType().optional(),
6285
- disableState: stringType().optional(),
6286
- disableZipCode: stringType().optional(),
6287
- // Advanced controls
6288
- paymentCurrency: stringType().optional(),
6289
- showCurrencySelector: stringType().optional(),
6290
- paymentAmount: stringType().optional(),
6291
- showDiscounts: stringType().optional()
6292
- // Metadata (allow any key starting with metadata_)
6293
- // We'll handle metadata separately in the handler
6294
- }).catchall(unknownType());
6295
- var dynamicCheckoutBodySchema = objectType({
6296
- // For subscription
6297
- product_id: stringType().optional(),
6298
- quantity: numberType().optional(),
6299
- // For one-time payment
6300
- product_cart: arrayType(
6301
- objectType({
6302
- product_id: stringType(),
6303
- quantity: numberType()
6304
- })
6305
- ).optional(),
6306
- // Common fields
6307
- billing: objectType({
6308
- city: stringType(),
6309
- country: stringType(),
6310
- state: stringType(),
6311
- street: stringType(),
6312
- zipcode: stringType()
6313
- }),
6314
- customer: objectType({
6315
- customer_id: stringType().optional(),
6316
- email: stringType().optional(),
6317
- name: stringType().optional()
6318
- }),
6319
- discount_id: stringType().optional(),
6320
- addons: arrayType(
6321
- objectType({
6322
- addon_id: stringType(),
6323
- quantity: numberType()
6324
- })
6325
- ).optional(),
6326
- metadata: recordType(stringType(), stringType()).optional(),
6327
- currency: stringType().optional()
6328
- // Allow any additional fields (for future compatibility)
6329
- }).catchall(unknownType());
6330
- var checkoutSessionProductCartItemSchema = objectType({
6331
- product_id: stringType().min(1, "Product ID is required"),
6332
- quantity: numberType().int().positive("Quantity must be a positive integer")
6333
- });
6334
- var checkoutSessionCustomerSchema = objectType({
6335
- email: stringType().email().optional(),
6336
- name: stringType().min(1).optional(),
6337
- phone_number: stringType().optional()
6338
- }).optional();
6339
- var checkoutSessionBillingAddressSchema = objectType({
6340
- street: stringType().optional(),
6341
- city: stringType().optional(),
6342
- state: stringType().optional(),
6343
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
6344
- zipcode: stringType().optional()
6345
- }).optional();
6346
- var paymentMethodTypeSchema = enumType([
6347
- "credit",
6348
- "debit",
6349
- "upi_collect",
6350
- "upi_intent",
6351
- "apple_pay",
6352
- "google_pay",
6353
- "amazon_pay",
6354
- "klarna",
6355
- "affirm",
6356
- "afterpay_clearpay",
6357
- "sepa",
6358
- "ach"
6359
- ]);
6360
- var checkoutSessionCustomizationSchema = objectType({
6361
- theme: enumType(["light", "dark", "system"]).optional(),
6362
- show_order_details: booleanType().optional(),
6363
- show_on_demand_tag: booleanType().optional()
6364
- }).optional();
6365
- var checkoutSessionFeatureFlagsSchema = objectType({
6366
- allow_currency_selection: booleanType().optional(),
6367
- allow_discount_code: booleanType().optional(),
6368
- allow_phone_number_collection: booleanType().optional(),
6369
- allow_tax_id: booleanType().optional(),
6370
- always_create_new_customer: booleanType().optional()
6371
- }).optional();
6372
- var checkoutSessionSubscriptionDataSchema = objectType({
6373
- trial_period_days: numberType().int().nonnegative().optional()
6374
- }).optional();
6375
- var checkoutSessionPayloadSchema = objectType({
6376
- // Required fields
6377
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
6378
- // Optional fields
6379
- customer: checkoutSessionCustomerSchema,
6380
- billing_address: checkoutSessionBillingAddressSchema,
6381
- return_url: stringType().url().optional(),
6382
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
6383
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
6384
- show_saved_payment_methods: booleanType().optional(),
6385
- confirm: booleanType().optional(),
6386
- discount_code: stringType().optional(),
6387
- metadata: recordType(stringType(), stringType()).optional(),
6388
- customization: checkoutSessionCustomizationSchema,
6389
- feature_flags: checkoutSessionFeatureFlagsSchema,
6390
- subscription_data: checkoutSessionSubscriptionDataSchema
6391
- });
6392
- var checkoutSessionResponseSchema = objectType({
6393
- session_id: stringType().min(1, "Session ID is required"),
6394
- checkout_url: stringType().url("Invalid checkout URL")
6395
- });
6396
- var createCheckoutSession = async (payload, config) => {
6397
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
6398
- if (!validation.success) {
6399
- throw new Error(
6400
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6401
- );
6402
- }
6403
- const dodopayments = new DodoPayments({
6404
- bearerToken: config.bearerToken,
6405
- environment: config.environment
6406
- });
6407
- try {
6408
- const sdkPayload = {
6409
- ...validation.data,
6410
- ...validation.data.billing_address && {
6411
- billing_address: {
6412
- ...validation.data.billing_address,
6413
- country: validation.data.billing_address.country
6414
- }
6415
- }
6416
- };
6417
- const session = await dodopayments.checkoutSessions.create(
6418
- sdkPayload
6419
- );
6420
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
6421
- if (!responseValidation.success) {
6422
- throw new Error(
6423
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6424
- );
6425
- }
6426
- return responseValidation.data;
6427
- } catch (error) {
6428
- if (error instanceof Error) {
6429
- console.error("Dodo Payments Checkout Session API Error:", {
6430
- message: error.message,
6431
- payload: validation.data,
6432
- config: {
6433
- environment: config.environment,
6434
- hasBearerToken: !!config.bearerToken
6435
- }
6436
- });
6437
- throw new Error(`Failed to create checkout session: ${error.message}`);
5952
+ base64$1.encode = encode;
5953
+ function decode(s) {
5954
+ return stdCoder.decode(s);
5955
+ }
5956
+ base64$1.decode = decode;
5957
+ /**
5958
+ * Implements URL-safe Base64 encoding.
5959
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
5960
+ *
5961
+ * Operates in constant time.
5962
+ */
5963
+ var URLSafeCoder = /** @class */ (function (_super) {
5964
+ __extends(URLSafeCoder, _super);
5965
+ function URLSafeCoder() {
5966
+ return _super !== null && _super.apply(this, arguments) || this;
6438
5967
  }
6439
- console.error("Unknown error creating checkout session:", error);
6440
- throw new Error(
6441
- "Failed to create checkout session due to an unknown error"
6442
- );
6443
- }
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);
5987
+ };
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;
6001
+ };
6002
+ return URLSafeCoder;
6003
+ }(Coder));
6004
+ base64$1.URLSafeCoder = URLSafeCoder;
6005
+ var urlSafeCoder = new URLSafeCoder();
6006
+ function encodeURLSafe(data) {
6007
+ return urlSafeCoder.encode(data);
6008
+ }
6009
+ base64$1.encodeURLSafe = encodeURLSafe;
6010
+ function decodeURLSafe(s) {
6011
+ return urlSafeCoder.decode(s);
6012
+ }
6013
+ base64$1.decodeURLSafe = decodeURLSafe;
6014
+ base64$1.encodedLength = function (length) {
6015
+ return stdCoder.encodedLength(length);
6444
6016
  };
6445
- var buildCheckoutUrl = async ({
6446
- queryParams,
6447
- body,
6448
- sessionPayload,
6449
- returnUrl,
6450
- bearerToken,
6451
- environment,
6452
- type = "static"
6453
- }) => {
6454
- if (type === "session") {
6455
- if (!sessionPayload) {
6456
- throw new Error("sessionPayload is required when type is 'session'");
6457
- }
6458
- const session = await createCheckoutSession(sessionPayload, {
6459
- bearerToken,
6460
- environment
6461
- });
6462
- return session.checkout_url;
6463
- }
6464
- const inputData = type === "dynamic" ? body : queryParams;
6465
- let parseResult;
6466
- if (type === "dynamic") {
6467
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
6468
- } else {
6469
- parseResult = checkoutQuerySchema.safeParse(inputData);
6470
- }
6471
- const { success, data, error } = parseResult;
6472
- if (!success) {
6473
- throw new Error(
6474
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
6475
- ${error.message}`
6476
- );
6477
- }
6478
- if (type !== "dynamic") {
6479
- const {
6480
- productId,
6481
- quantity: quantity2,
6482
- fullName,
6483
- firstName,
6484
- lastName,
6485
- email,
6486
- country,
6487
- addressLine,
6488
- city,
6489
- state,
6490
- zipCode,
6491
- disableFullName,
6492
- disableFirstName,
6493
- disableLastName,
6494
- disableEmail,
6495
- disableCountry,
6496
- disableAddressLine,
6497
- disableCity,
6498
- disableState,
6499
- disableZipCode,
6500
- paymentCurrency,
6501
- showCurrencySelector,
6502
- paymentAmount,
6503
- showDiscounts
6504
- // metadata handled below
6505
- } = data;
6506
- const dodopayments2 = new DodoPayments({
6507
- bearerToken,
6508
- environment
6509
- });
6510
- if (!productId) throw new Error("Missing required field: productId");
6511
- try {
6512
- await dodopayments2.products.retrieve(productId);
6513
- } catch (err) {
6514
- console.error(err);
6515
- throw new Error("Product not found");
6516
- }
6517
- const url = new URL(
6518
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
6519
- );
6520
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
6521
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
6522
- if (fullName) url.searchParams.set("fullName", String(fullName));
6523
- if (firstName) url.searchParams.set("firstName", String(firstName));
6524
- if (lastName) url.searchParams.set("lastName", String(lastName));
6525
- if (email) url.searchParams.set("email", String(email));
6526
- if (country) url.searchParams.set("country", String(country));
6527
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
6528
- if (city) url.searchParams.set("city", String(city));
6529
- if (state) url.searchParams.set("state", String(state));
6530
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
6531
- if (disableFullName === "true")
6532
- url.searchParams.set("disableFullName", "true");
6533
- if (disableFirstName === "true")
6534
- url.searchParams.set("disableFirstName", "true");
6535
- if (disableLastName === "true")
6536
- url.searchParams.set("disableLastName", "true");
6537
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
6538
- if (disableCountry === "true")
6539
- url.searchParams.set("disableCountry", "true");
6540
- if (disableAddressLine === "true")
6541
- url.searchParams.set("disableAddressLine", "true");
6542
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
6543
- if (disableState === "true") url.searchParams.set("disableState", "true");
6544
- if (disableZipCode === "true")
6545
- url.searchParams.set("disableZipCode", "true");
6546
- if (paymentCurrency)
6547
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
6548
- if (showCurrencySelector)
6549
- url.searchParams.set(
6550
- "showCurrencySelector",
6551
- String(showCurrencySelector)
6552
- );
6553
- if (paymentAmount)
6554
- url.searchParams.set("paymentAmount", String(paymentAmount));
6555
- if (showDiscounts)
6556
- url.searchParams.set("showDiscounts", String(showDiscounts));
6557
- for (const [key, value] of Object.entries(queryParams || {})) {
6558
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
6559
- url.searchParams.set(key, String(value));
6560
- }
6561
- }
6562
- return url.toString();
6563
- }
6564
- const dyn = data;
6565
- const {
6566
- product_id,
6567
- product_cart,
6568
- quantity,
6569
- billing,
6570
- customer,
6571
- addons,
6572
- metadata,
6573
- allowed_payment_method_types,
6574
- billing_currency,
6575
- discount_code,
6576
- on_demand,
6577
- return_url: bodyReturnUrl,
6578
- show_saved_payment_methods,
6579
- tax_id,
6580
- trial_period_days
6581
- } = dyn;
6582
- const dodopayments = new DodoPayments({
6583
- bearerToken,
6584
- environment
6585
- });
6586
- let isSubscription = false;
6587
- let productIdToFetch = product_id;
6588
- if (!product_id && product_cart && product_cart.length > 0) {
6589
- productIdToFetch = product_cart[0].product_id;
6590
- }
6591
- if (!productIdToFetch)
6592
- throw new Error(
6593
- "Missing required field: product_id or product_cart[0].product_id"
6594
- );
6595
- let product;
6596
- try {
6597
- product = await dodopayments.products.retrieve(productIdToFetch);
6598
- } catch (err) {
6599
- console.error(err);
6600
- throw new Error("Product not found");
6601
- }
6602
- isSubscription = Boolean(product.is_recurring);
6603
- if (isSubscription && !product_id)
6604
- throw new Error("Missing required field: product_id for subscription");
6605
- if (!billing) throw new Error("Missing required field: billing");
6606
- if (!customer) throw new Error("Missing required field: customer");
6607
- if (isSubscription) {
6608
- const subscriptionPayload = {
6609
- billing,
6610
- customer,
6611
- product_id,
6612
- quantity: quantity ? Number(quantity) : 1
6613
- };
6614
- if (metadata) subscriptionPayload.metadata = metadata;
6615
- if (discount_code) subscriptionPayload.discount_code = discount_code;
6616
- if (addons) subscriptionPayload.addons = addons;
6617
- if (allowed_payment_method_types)
6618
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
6619
- if (billing_currency)
6620
- subscriptionPayload.billing_currency = billing_currency;
6621
- if (on_demand) subscriptionPayload.on_demand = on_demand;
6622
- subscriptionPayload.payment_link = true;
6623
- if (bodyReturnUrl) {
6624
- subscriptionPayload.return_url = bodyReturnUrl;
6625
- } else if (returnUrl) {
6626
- subscriptionPayload.return_url = returnUrl;
6627
- }
6628
- if (show_saved_payment_methods)
6629
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
6630
- if (tax_id) subscriptionPayload.tax_id = tax_id;
6631
- if (trial_period_days)
6632
- subscriptionPayload.trial_period_days = trial_period_days;
6633
- let subscription;
6634
- try {
6635
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
6636
- } catch (err) {
6637
- console.error("Error when creating subscription", err);
6638
- throw new Error(err instanceof Error ? err.message : String(err));
6639
- }
6640
- if (!subscription || !subscription.payment_link) {
6641
- throw new Error(
6642
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
6643
- );
6644
- }
6645
- return subscription.payment_link;
6646
- } else {
6647
- let cart = product_cart;
6648
- if (!cart && product_id) {
6649
- cart = [
6650
- { product_id, quantity: quantity ? Number(quantity) : 1 }
6651
- ];
6652
- }
6653
- if (!cart || cart.length === 0)
6654
- throw new Error("Missing required field: product_cart or product_id");
6655
- const paymentPayload = {
6656
- billing,
6657
- customer,
6658
- product_cart: cart
6659
- };
6660
- if (metadata) paymentPayload.metadata = metadata;
6661
- paymentPayload.payment_link = true;
6662
- if (allowed_payment_method_types)
6663
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
6664
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
6665
- if (discount_code) paymentPayload.discount_code = discount_code;
6666
- if (bodyReturnUrl) {
6667
- paymentPayload.return_url = bodyReturnUrl;
6668
- } else if (returnUrl) {
6669
- paymentPayload.return_url = returnUrl;
6670
- }
6671
- if (show_saved_payment_methods)
6672
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
6673
- if (tax_id) paymentPayload.tax_id = tax_id;
6674
- let payment;
6675
- try {
6676
- payment = await dodopayments.payments.create(paymentPayload);
6677
- } catch (err) {
6678
- console.error("Error when creating payment link", err);
6679
- throw new Error(err instanceof Error ? err.message : String(err));
6680
- }
6681
- if (!payment || !payment.payment_link) {
6682
- throw new Error(
6683
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
6684
- );
6685
- }
6686
- return payment.payment_link;
6687
- }
6017
+ base64$1.maxDecodedLength = function (length) {
6018
+ return stdCoder.maxDecodedLength(length);
6019
+ };
6020
+ base64$1.decodedLength = function (s) {
6021
+ return stdCoder.decodedLength(s);
6688
6022
  };
6689
6023
 
6690
- const Checkout = (config) => {
6691
- const getHandler = async (event) => {
6692
- const searchParams = event.url.searchParams;
6693
- const queryParams = Object.fromEntries(searchParams);
6694
- if (!queryParams.productId) {
6695
- throw error(400, "Please provide productId query parameter");
6696
- }
6697
- const { success, data, error: zodError, } = checkoutQuerySchema.safeParse(queryParams);
6698
- if (!success) {
6699
- if (zodError.errors.some((e) => e.path.toString() === "productId")) {
6700
- throw error(400, "Please provide productId query parameter");
6701
- }
6702
- throw error(400, `Invalid query parameters.\n ${zodError.message}`);
6703
- }
6704
- let urlStr = "";
6705
- try {
6706
- urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
6707
- }
6708
- catch (err) {
6709
- throw error(400, err.message);
6710
- }
6711
- return Response.json({ checkout_url: urlStr });
6712
- };
6713
- const postHandler = async (event) => {
6714
- let body;
6715
- try {
6716
- body = await event.request.json();
6717
- }
6718
- catch (e) {
6719
- throw error(400, "Invalid JSON body");
6720
- }
6721
- if (config.type === "dynamic") {
6722
- // Handle dynamic checkout
6723
- const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
6724
- if (!success) {
6725
- throw error(400, `Invalid request body.\n ${zodError.message}`);
6726
- }
6727
- let urlStr = "";
6728
- try {
6729
- urlStr = await buildCheckoutUrl({
6730
- body: data,
6731
- ...config,
6732
- type: "dynamic",
6733
- });
6734
- }
6735
- catch (err) {
6736
- throw error(400, err.message);
6737
- }
6738
- return Response.json({ checkout_url: urlStr });
6739
- }
6740
- else {
6741
- // Handle checkout session
6742
- const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
6743
- if (!success) {
6744
- throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
6745
- }
6746
- let urlStr = "";
6747
- try {
6748
- urlStr = await buildCheckoutUrl({
6749
- sessionPayload: data,
6750
- ...config,
6751
- type: "session",
6752
- });
6753
- }
6754
- catch (err) {
6755
- throw error(400, err.message);
6756
- }
6757
- return Response.json({ checkout_url: urlStr });
6758
- }
6759
- };
6760
- // SvelteKit expects named exports for HTTP verbs
6761
- return {
6762
- GET: getHandler,
6763
- POST: postHandler,
6764
- };
6765
- };
6766
-
6767
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6768
-
6769
- var dist = {};
6770
-
6771
- var timing_safe_equal = {};
6772
-
6773
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
6774
- timing_safe_equal.timingSafeEqual = void 0;
6775
- function assert(expr, msg = "") {
6776
- if (!expr) {
6777
- throw new Error(msg);
6778
- }
6779
- }
6780
- function timingSafeEqual(a, b) {
6781
- if (a.byteLength !== b.byteLength) {
6782
- return false;
6783
- }
6784
- if (!(a instanceof DataView)) {
6785
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
6786
- }
6787
- if (!(b instanceof DataView)) {
6788
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
6789
- }
6790
- assert(a instanceof DataView);
6791
- assert(b instanceof DataView);
6792
- const length = a.byteLength;
6793
- let out = 0;
6794
- let i = -1;
6795
- while (++i < length) {
6796
- out |= a.getUint8(i) ^ b.getUint8(i);
6797
- }
6798
- return out === 0;
6799
- }
6800
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
6801
-
6802
- var base64$1 = {};
6803
-
6804
- // Copyright (C) 2016 Dmitry Chestnykh
6805
- // MIT License. See LICENSE file for details.
6806
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
6807
- var extendStatics = function (d, b) {
6808
- extendStatics = Object.setPrototypeOf ||
6809
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6810
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6811
- return extendStatics(d, b);
6812
- };
6813
- return function (d, b) {
6814
- extendStatics(d, b);
6815
- function __() { this.constructor = d; }
6816
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6817
- };
6818
- })();
6819
- Object.defineProperty(base64$1, "__esModule", { value: true });
6820
- /**
6821
- * Package base64 implements Base64 encoding and decoding.
6822
- */
6823
- // Invalid character used in decoding to indicate
6824
- // that the character to decode is out of range of
6825
- // alphabet and cannot be decoded.
6826
- var INVALID_BYTE = 256;
6827
- /**
6828
- * Implements standard Base64 encoding.
6829
- *
6830
- * Operates in constant time.
6831
- */
6832
- var Coder = /** @class */ (function () {
6833
- // TODO(dchest): methods to encode chunk-by-chunk.
6834
- function Coder(_paddingCharacter) {
6835
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
6836
- this._paddingCharacter = _paddingCharacter;
6837
- }
6838
- Coder.prototype.encodedLength = function (length) {
6839
- if (!this._paddingCharacter) {
6840
- return (length * 8 + 5) / 6 | 0;
6841
- }
6842
- return (length + 2) / 3 * 4 | 0;
6843
- };
6844
- Coder.prototype.encode = function (data) {
6845
- var out = "";
6846
- var i = 0;
6847
- for (; i < data.length - 2; i += 3) {
6848
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
6849
- out += this._encodeByte((c >>> 3 * 6) & 63);
6850
- out += this._encodeByte((c >>> 2 * 6) & 63);
6851
- out += this._encodeByte((c >>> 1 * 6) & 63);
6852
- out += this._encodeByte((c >>> 0 * 6) & 63);
6853
- }
6854
- var left = data.length - i;
6855
- if (left > 0) {
6856
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
6857
- out += this._encodeByte((c >>> 3 * 6) & 63);
6858
- out += this._encodeByte((c >>> 2 * 6) & 63);
6859
- if (left === 2) {
6860
- out += this._encodeByte((c >>> 1 * 6) & 63);
6861
- }
6862
- else {
6863
- out += this._paddingCharacter || "";
6864
- }
6865
- out += this._paddingCharacter || "";
6866
- }
6867
- return out;
6868
- };
6869
- Coder.prototype.maxDecodedLength = function (length) {
6870
- if (!this._paddingCharacter) {
6871
- return (length * 6 + 7) / 8 | 0;
6872
- }
6873
- return length / 4 * 3 | 0;
6874
- };
6875
- Coder.prototype.decodedLength = function (s) {
6876
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
6877
- };
6878
- Coder.prototype.decode = function (s) {
6879
- if (s.length === 0) {
6880
- return new Uint8Array(0);
6881
- }
6882
- var paddingLength = this._getPaddingLength(s);
6883
- var length = s.length - paddingLength;
6884
- var out = new Uint8Array(this.maxDecodedLength(length));
6885
- var op = 0;
6886
- var i = 0;
6887
- var haveBad = 0;
6888
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
6889
- for (; i < length - 4; i += 4) {
6890
- v0 = this._decodeChar(s.charCodeAt(i + 0));
6891
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6892
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6893
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6894
- out[op++] = (v0 << 2) | (v1 >>> 4);
6895
- out[op++] = (v1 << 4) | (v2 >>> 2);
6896
- out[op++] = (v2 << 6) | v3;
6897
- haveBad |= v0 & INVALID_BYTE;
6898
- haveBad |= v1 & INVALID_BYTE;
6899
- haveBad |= v2 & INVALID_BYTE;
6900
- haveBad |= v3 & INVALID_BYTE;
6901
- }
6902
- if (i < length - 1) {
6903
- v0 = this._decodeChar(s.charCodeAt(i));
6904
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6905
- out[op++] = (v0 << 2) | (v1 >>> 4);
6906
- haveBad |= v0 & INVALID_BYTE;
6907
- haveBad |= v1 & INVALID_BYTE;
6908
- }
6909
- if (i < length - 2) {
6910
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6911
- out[op++] = (v1 << 4) | (v2 >>> 2);
6912
- haveBad |= v2 & INVALID_BYTE;
6913
- }
6914
- if (i < length - 3) {
6915
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6916
- out[op++] = (v2 << 6) | v3;
6917
- haveBad |= v3 & INVALID_BYTE;
6918
- }
6919
- if (haveBad !== 0) {
6920
- throw new Error("Base64Coder: incorrect characters for decoding");
6921
- }
6922
- return out;
6923
- };
6924
- // Standard encoding have the following encoded/decoded ranges,
6925
- // which we need to convert between.
6926
- //
6927
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
6928
- // Index: 0 - 25 26 - 51 52 - 61 62 63
6929
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
6930
- //
6931
- // Encode 6 bits in b into a new character.
6932
- Coder.prototype._encodeByte = function (b) {
6933
- // Encoding uses constant time operations as follows:
6934
- //
6935
- // 1. Define comparison of A with B using (A - B) >>> 8:
6936
- // if A > B, then result is positive integer
6937
- // if A <= B, then result is 0
6938
- //
6939
- // 2. Define selection of C or 0 using bitwise AND: X & C:
6940
- // if X == 0, then result is 0
6941
- // if X != 0, then result is C
6942
- //
6943
- // 3. Start with the smallest comparison (b >= 0), which is always
6944
- // true, so set the result to the starting ASCII value (65).
6945
- //
6946
- // 4. Continue comparing b to higher ASCII values, and selecting
6947
- // zero if comparison isn't true, otherwise selecting a value
6948
- // to add to result, which:
6949
- //
6950
- // a) undoes the previous addition
6951
- // b) provides new value to add
6952
- //
6953
- var result = b;
6954
- // b >= 0
6955
- result += 65;
6956
- // b > 25
6957
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
6958
- // b > 51
6959
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
6960
- // b > 61
6961
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
6962
- // b > 62
6963
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
6964
- return String.fromCharCode(result);
6965
- };
6966
- // Decode a character code into a byte.
6967
- // Must return 256 if character is out of alphabet range.
6968
- Coder.prototype._decodeChar = function (c) {
6969
- // Decoding works similar to encoding: using the same comparison
6970
- // function, but now it works on ranges: result is always incremented
6971
- // by value, but this value becomes zero if the range is not
6972
- // satisfied.
6973
- //
6974
- // Decoding starts with invalid value, 256, which is then
6975
- // subtracted when the range is satisfied. If none of the ranges
6976
- // apply, the function returns 256, which is then checked by
6977
- // the caller to throw error.
6978
- var result = INVALID_BYTE; // start with invalid character
6979
- // c == 43 (c > 42 and c < 44)
6980
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
6981
- // c == 47 (c > 46 and c < 48)
6982
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
6983
- // c > 47 and c < 58
6984
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
6985
- // c > 64 and c < 91
6986
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
6987
- // c > 96 and c < 123
6988
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
6989
- return result;
6990
- };
6991
- Coder.prototype._getPaddingLength = function (s) {
6992
- var paddingLength = 0;
6993
- if (this._paddingCharacter) {
6994
- for (var i = s.length - 1; i >= 0; i--) {
6995
- if (s[i] !== this._paddingCharacter) {
6996
- break;
6997
- }
6998
- paddingLength++;
6999
- }
7000
- if (s.length < 4 || paddingLength > 2) {
7001
- throw new Error("Base64Coder: incorrect padding");
7002
- }
7003
- }
7004
- return paddingLength;
7005
- };
7006
- return Coder;
7007
- }());
7008
- base64$1.Coder = Coder;
7009
- var stdCoder = new Coder();
7010
- function encode(data) {
7011
- return stdCoder.encode(data);
7012
- }
7013
- base64$1.encode = encode;
7014
- function decode(s) {
7015
- return stdCoder.decode(s);
7016
- }
7017
- base64$1.decode = decode;
7018
- /**
7019
- * Implements URL-safe Base64 encoding.
7020
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
7021
- *
7022
- * Operates in constant time.
7023
- */
7024
- var URLSafeCoder = /** @class */ (function (_super) {
7025
- __extends(URLSafeCoder, _super);
7026
- function URLSafeCoder() {
7027
- return _super !== null && _super.apply(this, arguments) || this;
7028
- }
7029
- // URL-safe encoding have the following encoded/decoded ranges:
7030
- //
7031
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
7032
- // Index: 0 - 25 26 - 51 52 - 61 62 63
7033
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
7034
- //
7035
- URLSafeCoder.prototype._encodeByte = function (b) {
7036
- var result = b;
7037
- // b >= 0
7038
- result += 65;
7039
- // b > 25
7040
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
7041
- // b > 51
7042
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
7043
- // b > 61
7044
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
7045
- // b > 62
7046
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
7047
- return String.fromCharCode(result);
7048
- };
7049
- URLSafeCoder.prototype._decodeChar = function (c) {
7050
- var result = INVALID_BYTE;
7051
- // c == 45 (c > 44 and c < 46)
7052
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
7053
- // c == 95 (c > 94 and c < 96)
7054
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
7055
- // c > 47 and c < 58
7056
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
7057
- // c > 64 and c < 91
7058
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
7059
- // c > 96 and c < 123
7060
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7061
- return result;
7062
- };
7063
- return URLSafeCoder;
7064
- }(Coder));
7065
- base64$1.URLSafeCoder = URLSafeCoder;
7066
- var urlSafeCoder = new URLSafeCoder();
7067
- function encodeURLSafe(data) {
7068
- return urlSafeCoder.encode(data);
7069
- }
7070
- base64$1.encodeURLSafe = encodeURLSafe;
7071
- function decodeURLSafe(s) {
7072
- return urlSafeCoder.decode(s);
7073
- }
7074
- base64$1.decodeURLSafe = decodeURLSafe;
7075
- base64$1.encodedLength = function (length) {
7076
- return stdCoder.encodedLength(length);
7077
- };
7078
- base64$1.maxDecodedLength = function (length) {
7079
- return stdCoder.maxDecodedLength(length);
7080
- };
7081
- base64$1.decodedLength = function (s) {
7082
- return stdCoder.decodedLength(s);
7083
- };
7084
-
7085
- var sha256$1 = {exports: {}};
6024
+ var sha256$1 = {exports: {}};
7086
6025
 
7087
6026
  (function (module) {
7088
6027
  (function (root, factory) {
@@ -7524,96 +6463,1208 @@ class ExtendableError extends Error {
7524
6463
  this.name = "ExtendableError";
7525
6464
  this.stack = new Error(message).stack;
7526
6465
  }
7527
- }
7528
- class WebhookVerificationError extends ExtendableError {
7529
- constructor(message) {
7530
- super(message);
7531
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
7532
- this.name = "WebhookVerificationError";
6466
+ }
6467
+ class WebhookVerificationError extends ExtendableError {
6468
+ constructor(message) {
6469
+ super(message);
6470
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
6471
+ this.name = "WebhookVerificationError";
6472
+ }
6473
+ }
6474
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
6475
+ class Webhook {
6476
+ constructor(secret, options) {
6477
+ if (!secret) {
6478
+ throw new Error("Secret can't be empty.");
6479
+ }
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) };
7088
+ }
7089
+ else {
7090
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
7091
+ }
7092
+ }
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));
7533
7541
  }
7534
- }
7535
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
7536
- class Webhook {
7537
- constructor(secret, options) {
7538
- if (!secret) {
7539
- throw new Error("Secret can't be empty.");
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");
7540
7598
  }
7541
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
7542
- if (secret instanceof Uint8Array) {
7543
- this.key = secret;
7544
- }
7545
- else {
7546
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
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");
7547
7603
  }
7604
+ throw error(400, `Invalid query parameters.\n ${zodError.message}`);
7548
7605
  }
7549
- else {
7550
- if (typeof secret !== "string") {
7551
- throw new Error("Expected secret to be of type string");
7552
- }
7553
- if (secret.startsWith(Webhook.prefix)) {
7554
- secret = secret.substring(Webhook.prefix.length);
7555
- }
7556
- this.key = base64.decode(secret);
7606
+ let urlStr = "";
7607
+ try {
7608
+ urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
7557
7609
  }
7558
- }
7559
- verify(payload, headers_) {
7560
- const headers = {};
7561
- for (const key of Object.keys(headers_)) {
7562
- headers[key.toLowerCase()] = headers_[key];
7610
+ catch (err) {
7611
+ throw error(400, err.message);
7563
7612
  }
7564
- const msgId = headers["webhook-id"];
7565
- const msgSignature = headers["webhook-signature"];
7566
- const msgTimestamp = headers["webhook-timestamp"];
7567
- if (!msgSignature || !msgId || !msgTimestamp) {
7568
- throw new WebhookVerificationError("Missing required 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();
7569
7619
  }
7570
- const timestamp = this.verifyTimestamp(msgTimestamp);
7571
- const computedSignature = this.sign(msgId, timestamp, payload);
7572
- const expectedSignature = computedSignature.split(",")[1];
7573
- const passedSignatures = msgSignature.split(" ");
7574
- const encoder = new globalThis.TextEncoder();
7575
- for (const versionedSignature of passedSignatures) {
7576
- const [version, signature] = versionedSignature.split(",");
7577
- if (version !== "v1") {
7578
- continue;
7620
+ catch (e) {
7621
+ throw error(400, "Invalid JSON body");
7622
+ }
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}`);
7579
7628
  }
7580
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
7581
- return JSON.parse(payload.toString());
7629
+ let urlStr = "";
7630
+ try {
7631
+ urlStr = await buildCheckoutUrl({
7632
+ body: data,
7633
+ ...config,
7634
+ type: "dynamic",
7635
+ });
7582
7636
  }
7583
- }
7584
- throw new WebhookVerificationError("No matching signature found");
7585
- }
7586
- sign(msgId, timestamp, payload) {
7587
- if (typeof payload === "string") ;
7588
- else if (payload.constructor.name === "Buffer") {
7589
- payload = payload.toString();
7637
+ catch (err) {
7638
+ throw error(400, err.message);
7639
+ }
7640
+ return Response.json({ checkout_url: urlStr });
7590
7641
  }
7591
7642
  else {
7592
- throw new Error("Expected payload to be of type string or Buffer.");
7593
- }
7594
- const encoder = new TextEncoder();
7595
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
7596
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
7597
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
7598
- return `v1,${expectedSignature}`;
7599
- }
7600
- verifyTimestamp(timestampHeader) {
7601
- const now = Math.floor(Date.now() / 1000);
7602
- const timestamp = parseInt(timestampHeader, 10);
7603
- if (isNaN(timestamp)) {
7604
- throw new WebhookVerificationError("Invalid Signature Headers");
7605
- }
7606
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
7607
- throw new WebhookVerificationError("Message timestamp too old");
7608
- }
7609
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
7610
- throw new WebhookVerificationError("Message timestamp too new");
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 });
7611
7660
  }
7612
- return new Date(timestamp * 1000);
7613
- }
7614
- }
7615
- Webhook_1 = dist.Webhook = Webhook;
7616
- Webhook.prefix = "whsec_";
7661
+ };
7662
+ // SvelteKit expects named exports for HTTP verbs
7663
+ return {
7664
+ GET: getHandler,
7665
+ POST: postHandler,
7666
+ };
7667
+ };
7617
7668
 
7618
7669
  // src/schemas/webhook.ts
7619
7670
  var PaymentSchema = objectType({