@dodopayments/express 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.cjs CHANGED
@@ -3961,7 +3961,7 @@ const unknownType = ZodUnknown.create;
3961
3961
  ZodNever.create;
3962
3962
  const arrayType = ZodArray.create;
3963
3963
  const objectType = ZodObject.create;
3964
- ZodUnion.create;
3964
+ const unionType = ZodUnion.create;
3965
3965
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
3966
3966
  ZodIntersection.create;
3967
3967
  ZodTuple.create;
@@ -4180,7 +4180,7 @@ const safeJSON = (text) => {
4180
4180
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4181
4181
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4182
4182
 
4183
- const VERSION = '2.2.0'; // x-release-please-version
4183
+ const VERSION = '2.4.6'; // x-release-please-version
4184
4184
 
4185
4185
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4186
4186
  /**
@@ -4930,6 +4930,9 @@ class CheckoutSessions extends APIResource {
4930
4930
  create(body, options) {
4931
4931
  return this._client.post('/checkouts', { body, ...options });
4932
4932
  }
4933
+ retrieve(id, options) {
4934
+ return this._client.get(path `/checkouts/${id}`, options);
4935
+ }
4933
4936
  }
4934
4937
 
4935
4938
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -5608,1421 +5611,325 @@ let Headers$1 = class Headers extends APIResource {
5608
5611
  }
5609
5612
  };
5610
5613
 
5611
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5612
- let Webhooks$1 = class Webhooks extends APIResource {
5613
- constructor() {
5614
- super(...arguments);
5615
- this.headers = new Headers$1(this._client);
5616
- }
5617
- /**
5618
- * Create a new webhook
5619
- */
5620
- create(body, options) {
5621
- return this._client.post('/webhooks', { body, ...options });
5622
- }
5623
- /**
5624
- * Get a webhook by id
5625
- */
5626
- retrieve(webhookID, options) {
5627
- return this._client.get(path `/webhooks/${webhookID}`, options);
5614
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5615
+
5616
+ var dist = {};
5617
+
5618
+ var timing_safe_equal = {};
5619
+
5620
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
5621
+ timing_safe_equal.timingSafeEqual = void 0;
5622
+ function assert(expr, msg = "") {
5623
+ if (!expr) {
5624
+ throw new Error(msg);
5628
5625
  }
5629
- /**
5630
- * Patch a webhook by id
5631
- */
5632
- update(webhookID, body, options) {
5633
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
5626
+ }
5627
+ function timingSafeEqual(a, b) {
5628
+ if (a.byteLength !== b.byteLength) {
5629
+ return false;
5634
5630
  }
5635
- /**
5636
- * List all webhooks
5637
- */
5638
- list(query = {}, options) {
5639
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
5631
+ if (!(a instanceof DataView)) {
5632
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
5640
5633
  }
5641
- /**
5642
- * Delete a webhook by id
5643
- */
5644
- delete(webhookID, options) {
5645
- return this._client.delete(path `/webhooks/${webhookID}`, {
5646
- ...options,
5647
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
5648
- });
5634
+ if (!(b instanceof DataView)) {
5635
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
5649
5636
  }
5650
- /**
5651
- * Get webhook secret by id
5652
- */
5653
- retrieveSecret(webhookID, options) {
5654
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
5637
+ assert(a instanceof DataView);
5638
+ assert(b instanceof DataView);
5639
+ const length = a.byteLength;
5640
+ let out = 0;
5641
+ let i = -1;
5642
+ while (++i < length) {
5643
+ out |= a.getUint8(i) ^ b.getUint8(i);
5655
5644
  }
5656
- };
5657
- Webhooks$1.Headers = Headers$1;
5645
+ return out === 0;
5646
+ }
5647
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
5658
5648
 
5659
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5649
+ var base64$1 = {};
5650
+
5651
+ // Copyright (C) 2016 Dmitry Chestnykh
5652
+ // MIT License. See LICENSE file for details.
5653
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
5654
+ var extendStatics = function (d, b) {
5655
+ extendStatics = Object.setPrototypeOf ||
5656
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5657
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5658
+ return extendStatics(d, b);
5659
+ };
5660
+ return function (d, b) {
5661
+ extendStatics(d, b);
5662
+ function __() { this.constructor = d; }
5663
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5664
+ };
5665
+ })();
5666
+ Object.defineProperty(base64$1, "__esModule", { value: true });
5660
5667
  /**
5661
- * Read an environment variable.
5662
- *
5663
- * Trims beginning and trailing whitespace.
5664
- *
5665
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
5668
+ * Package base64 implements Base64 encoding and decoding.
5666
5669
  */
5667
- const readEnv = (env) => {
5668
- if (typeof globalThis.process !== 'undefined') {
5669
- return globalThis.process.env?.[env]?.trim() ?? undefined;
5670
- }
5671
- if (typeof globalThis.Deno !== 'undefined') {
5672
- return globalThis.Deno.env?.get?.(env)?.trim();
5673
- }
5674
- return undefined;
5675
- };
5676
-
5677
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5678
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
5679
- const environments = {
5680
- live_mode: 'https://live.dodopayments.com',
5681
- test_mode: 'https://test.dodopayments.com',
5682
- };
5670
+ // Invalid character used in decoding to indicate
5671
+ // that the character to decode is out of range of
5672
+ // alphabet and cannot be decoded.
5673
+ var INVALID_BYTE = 256;
5683
5674
  /**
5684
- * API Client for interfacing with the Dodo Payments API.
5675
+ * Implements standard Base64 encoding.
5676
+ *
5677
+ * Operates in constant time.
5685
5678
  */
5686
- class DodoPayments {
5687
- /**
5688
- * API Client for interfacing with the Dodo Payments API.
5689
- *
5690
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
5691
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
5692
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
5693
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
5694
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
5695
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
5696
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
5697
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
5698
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
5699
- */
5700
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
5701
- _DodoPayments_instances.add(this);
5702
- _DodoPayments_encoder.set(this, void 0);
5703
- this.checkoutSessions = new CheckoutSessions(this);
5704
- this.payments = new Payments(this);
5705
- this.subscriptions = new Subscriptions(this);
5706
- this.invoices = new Invoices(this);
5707
- this.licenses = new Licenses(this);
5708
- this.licenseKeys = new LicenseKeys(this);
5709
- this.licenseKeyInstances = new LicenseKeyInstances(this);
5710
- this.customers = new Customers(this);
5711
- this.refunds = new Refunds(this);
5712
- this.disputes = new Disputes(this);
5713
- this.payouts = new Payouts(this);
5714
- this.webhookEvents = new WebhookEvents(this);
5715
- this.products = new Products(this);
5716
- this.misc = new Misc(this);
5717
- this.discounts = new Discounts(this);
5718
- this.addons = new Addons(this);
5719
- this.brands = new Brands(this);
5720
- this.webhooks = new Webhooks$1(this);
5721
- this.usageEvents = new UsageEvents(this);
5722
- this.meters = new Meters(this);
5723
- if (bearerToken === undefined) {
5724
- throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
5679
+ var Coder = /** @class */ (function () {
5680
+ // TODO(dchest): methods to encode chunk-by-chunk.
5681
+ function Coder(_paddingCharacter) {
5682
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
5683
+ this._paddingCharacter = _paddingCharacter;
5684
+ }
5685
+ Coder.prototype.encodedLength = function (length) {
5686
+ if (!this._paddingCharacter) {
5687
+ return (length * 8 + 5) / 6 | 0;
5725
5688
  }
5726
- const options = {
5727
- bearerToken,
5728
- ...opts,
5729
- baseURL,
5730
- environment: opts.environment ?? 'live_mode',
5731
- };
5732
- if (baseURL && opts.environment) {
5733
- throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
5689
+ return (length + 2) / 3 * 4 | 0;
5690
+ };
5691
+ Coder.prototype.encode = function (data) {
5692
+ var out = "";
5693
+ var i = 0;
5694
+ for (; i < data.length - 2; i += 3) {
5695
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
5696
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5697
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5698
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5699
+ out += this._encodeByte((c >>> 0 * 6) & 63);
5734
5700
  }
5735
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
5736
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
5737
- this.logger = options.logger ?? console;
5738
- const defaultLogLevel = 'warn';
5739
- // Set default logLevel early so that we can log a warning in parseLogLevel.
5740
- this.logLevel = defaultLogLevel;
5741
- this.logLevel =
5742
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
5743
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
5744
- defaultLogLevel;
5745
- this.fetchOptions = options.fetchOptions;
5746
- this.maxRetries = options.maxRetries ?? 2;
5747
- this.fetch = options.fetch ?? getDefaultFetch();
5748
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
5749
- this._options = options;
5750
- this.bearerToken = bearerToken;
5751
- }
5752
- /**
5753
- * Create a new client instance re-using the same options given to the current client with optional overriding.
5754
- */
5755
- withOptions(options) {
5756
- const client = new this.constructor({
5757
- ...this._options,
5758
- environment: options.environment ? options.environment : undefined,
5759
- baseURL: options.environment ? undefined : this.baseURL,
5760
- maxRetries: this.maxRetries,
5761
- timeout: this.timeout,
5762
- logger: this.logger,
5763
- logLevel: this.logLevel,
5764
- fetch: this.fetch,
5765
- fetchOptions: this.fetchOptions,
5766
- bearerToken: this.bearerToken,
5767
- ...options,
5768
- });
5769
- return client;
5770
- }
5771
- defaultQuery() {
5772
- return this._options.defaultQuery;
5773
- }
5774
- validateHeaders({ values, nulls }) {
5775
- return;
5776
- }
5777
- async authHeaders(opts) {
5778
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
5779
- }
5780
- /**
5781
- * Basic re-implementation of `qs.stringify` for primitive types.
5782
- */
5783
- stringifyQuery(query) {
5784
- return Object.entries(query)
5785
- .filter(([_, value]) => typeof value !== 'undefined')
5786
- .map(([key, value]) => {
5787
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
5788
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
5701
+ var left = data.length - i;
5702
+ if (left > 0) {
5703
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
5704
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5705
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5706
+ if (left === 2) {
5707
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5789
5708
  }
5790
- if (value === null) {
5791
- return `${encodeURIComponent(key)}=`;
5709
+ else {
5710
+ out += this._paddingCharacter || "";
5792
5711
  }
5793
- throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
5794
- })
5795
- .join('&');
5796
- }
5797
- getUserAgent() {
5798
- return `${this.constructor.name}/JS ${VERSION}`;
5799
- }
5800
- defaultIdempotencyKey() {
5801
- return `stainless-node-retry-${uuid4()}`;
5802
- }
5803
- makeStatusError(status, error, message, headers) {
5804
- return APIError.generate(status, error, message, headers);
5805
- }
5806
- buildURL(path, query, defaultBaseURL) {
5807
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
5808
- const url = isAbsoluteURL(path) ?
5809
- new URL(path)
5810
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
5811
- const defaultQuery = this.defaultQuery();
5812
- if (!isEmptyObj(defaultQuery)) {
5813
- query = { ...defaultQuery, ...query };
5814
- }
5815
- if (typeof query === 'object' && query && !Array.isArray(query)) {
5816
- url.search = this.stringifyQuery(query);
5712
+ out += this._paddingCharacter || "";
5817
5713
  }
5818
- return url.toString();
5819
- }
5820
- /**
5821
- * Used as a callback for mutating the given `FinalRequestOptions` object.
5822
- */
5823
- async prepareOptions(options) { }
5824
- /**
5825
- * Used as a callback for mutating the given `RequestInit` object.
5826
- *
5827
- * This is useful for cases where you want to add certain headers based off of
5828
- * the request properties, e.g. `method` or `url`.
5829
- */
5830
- async prepareRequest(request, { url, options }) { }
5831
- get(path, opts) {
5832
- return this.methodRequest('get', path, opts);
5833
- }
5834
- post(path, opts) {
5835
- return this.methodRequest('post', path, opts);
5836
- }
5837
- patch(path, opts) {
5838
- return this.methodRequest('patch', path, opts);
5839
- }
5840
- put(path, opts) {
5841
- return this.methodRequest('put', path, opts);
5842
- }
5843
- delete(path, opts) {
5844
- return this.methodRequest('delete', path, opts);
5845
- }
5846
- methodRequest(method, path, opts) {
5847
- return this.request(Promise.resolve(opts).then((opts) => {
5848
- return { method, path, ...opts };
5849
- }));
5850
- }
5851
- request(options, remainingRetries = null) {
5852
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
5853
- }
5854
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
5855
- const options = await optionsInput;
5856
- const maxRetries = options.maxRetries ?? this.maxRetries;
5857
- if (retriesRemaining == null) {
5858
- retriesRemaining = maxRetries;
5714
+ return out;
5715
+ };
5716
+ Coder.prototype.maxDecodedLength = function (length) {
5717
+ if (!this._paddingCharacter) {
5718
+ return (length * 6 + 7) / 8 | 0;
5859
5719
  }
5860
- await this.prepareOptions(options);
5861
- const { req, url, timeout } = await this.buildRequest(options, {
5862
- retryCount: maxRetries - retriesRemaining,
5863
- });
5864
- await this.prepareRequest(req, { url, options });
5865
- /** Not an API request ID, just for correlating local log entries. */
5866
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
5867
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
5868
- const startTime = Date.now();
5869
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
5870
- retryOfRequestLogID,
5871
- method: options.method,
5872
- url,
5873
- options,
5874
- headers: req.headers,
5875
- }));
5876
- if (options.signal?.aborted) {
5877
- throw new APIUserAbortError();
5720
+ return length / 4 * 3 | 0;
5721
+ };
5722
+ Coder.prototype.decodedLength = function (s) {
5723
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
5724
+ };
5725
+ Coder.prototype.decode = function (s) {
5726
+ if (s.length === 0) {
5727
+ return new Uint8Array(0);
5878
5728
  }
5879
- const controller = new AbortController();
5880
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
5881
- const headersTime = Date.now();
5882
- if (response instanceof globalThis.Error) {
5883
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
5884
- if (options.signal?.aborted) {
5885
- throw new APIUserAbortError();
5886
- }
5887
- // detect native connection timeout errors
5888
- // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
5889
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
5890
- // others do not provide enough information to distinguish timeouts from other connection errors
5891
- const isTimeout = isAbortError(response) ||
5892
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
5893
- if (retriesRemaining) {
5894
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
5895
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
5896
- retryOfRequestLogID,
5897
- url,
5898
- durationMs: headersTime - startTime,
5899
- message: response.message,
5900
- }));
5901
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
5902
- }
5903
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
5904
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
5905
- retryOfRequestLogID,
5906
- url,
5907
- durationMs: headersTime - startTime,
5908
- message: response.message,
5909
- }));
5910
- if (isTimeout) {
5911
- throw new APIConnectionTimeoutError();
5912
- }
5913
- throw new APIConnectionError({ cause: response });
5729
+ var paddingLength = this._getPaddingLength(s);
5730
+ var length = s.length - paddingLength;
5731
+ var out = new Uint8Array(this.maxDecodedLength(length));
5732
+ var op = 0;
5733
+ var i = 0;
5734
+ var haveBad = 0;
5735
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
5736
+ for (; i < length - 4; i += 4) {
5737
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
5738
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5739
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5740
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5741
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5742
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5743
+ out[op++] = (v2 << 6) | v3;
5744
+ haveBad |= v0 & INVALID_BYTE;
5745
+ haveBad |= v1 & INVALID_BYTE;
5746
+ haveBad |= v2 & INVALID_BYTE;
5747
+ haveBad |= v3 & INVALID_BYTE;
5914
5748
  }
5915
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
5916
- if (!response.ok) {
5917
- const shouldRetry = await this.shouldRetry(response);
5918
- if (retriesRemaining && shouldRetry) {
5919
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
5920
- // We don't need the body of this response.
5921
- await CancelReadableStream(response.body);
5922
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
5923
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
5924
- retryOfRequestLogID,
5925
- url: response.url,
5926
- status: response.status,
5927
- headers: response.headers,
5928
- durationMs: headersTime - startTime,
5929
- }));
5930
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
5931
- }
5932
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
5933
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
5934
- const errText = await response.text().catch((err) => castToError(err).message);
5935
- const errJSON = safeJSON(errText);
5936
- const errMessage = errJSON ? undefined : errText;
5937
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
5938
- retryOfRequestLogID,
5939
- url: response.url,
5940
- status: response.status,
5941
- headers: response.headers,
5942
- message: errMessage,
5943
- durationMs: Date.now() - startTime,
5944
- }));
5945
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
5946
- throw err;
5749
+ if (i < length - 1) {
5750
+ v0 = this._decodeChar(s.charCodeAt(i));
5751
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5752
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5753
+ haveBad |= v0 & INVALID_BYTE;
5754
+ haveBad |= v1 & INVALID_BYTE;
5947
5755
  }
5948
- loggerFor(this).info(responseInfo);
5949
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
5950
- retryOfRequestLogID,
5951
- url: response.url,
5952
- status: response.status,
5953
- headers: response.headers,
5954
- durationMs: headersTime - startTime,
5955
- }));
5956
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
5957
- }
5958
- getAPIList(path, Page, opts) {
5959
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
5960
- }
5961
- requestAPIList(Page, options) {
5962
- const request = this.makeRequest(options, null, undefined);
5963
- return new PagePromise(this, request, Page);
5964
- }
5965
- async fetchWithTimeout(url, init, ms, controller) {
5966
- const { signal, method, ...options } = init || {};
5967
- if (signal)
5968
- signal.addEventListener('abort', () => controller.abort());
5969
- const timeout = setTimeout(() => controller.abort(), ms);
5970
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
5971
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
5972
- const fetchOptions = {
5973
- signal: controller.signal,
5974
- ...(isReadableBody ? { duplex: 'half' } : {}),
5975
- method: 'GET',
5976
- ...options,
5977
- };
5978
- if (method) {
5979
- // Custom methods like 'patch' need to be uppercased
5980
- // See https://github.com/nodejs/undici/issues/2294
5981
- fetchOptions.method = method.toUpperCase();
5756
+ if (i < length - 2) {
5757
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5758
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5759
+ haveBad |= v2 & INVALID_BYTE;
5982
5760
  }
5983
- try {
5984
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
5985
- return await this.fetch.call(undefined, url, fetchOptions);
5761
+ if (i < length - 3) {
5762
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5763
+ out[op++] = (v2 << 6) | v3;
5764
+ haveBad |= v3 & INVALID_BYTE;
5986
5765
  }
5987
- finally {
5988
- clearTimeout(timeout);
5766
+ if (haveBad !== 0) {
5767
+ throw new Error("Base64Coder: incorrect characters for decoding");
5989
5768
  }
5990
- }
5991
- async shouldRetry(response) {
5992
- // Note this is not a standard header.
5993
- const shouldRetryHeader = response.headers.get('x-should-retry');
5994
- // If the server explicitly says whether or not to retry, obey.
5995
- if (shouldRetryHeader === 'true')
5996
- return true;
5997
- if (shouldRetryHeader === 'false')
5998
- return false;
5999
- // Retry on request timeouts.
6000
- if (response.status === 408)
6001
- return true;
6002
- // Retry on lock timeouts.
6003
- if (response.status === 409)
6004
- return true;
6005
- // Retry on rate limits.
6006
- if (response.status === 429)
6007
- return true;
6008
- // Retry internal errors.
6009
- if (response.status >= 500)
6010
- return true;
6011
- return false;
6012
- }
6013
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6014
- let timeoutMillis;
6015
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6016
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6017
- if (retryAfterMillisHeader) {
6018
- const timeoutMs = parseFloat(retryAfterMillisHeader);
6019
- if (!Number.isNaN(timeoutMs)) {
6020
- timeoutMillis = timeoutMs;
6021
- }
6022
- }
6023
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6024
- const retryAfterHeader = responseHeaders?.get('retry-after');
6025
- if (retryAfterHeader && !timeoutMillis) {
6026
- const timeoutSeconds = parseFloat(retryAfterHeader);
6027
- if (!Number.isNaN(timeoutSeconds)) {
6028
- timeoutMillis = timeoutSeconds * 1000;
5769
+ return out;
5770
+ };
5771
+ // Standard encoding have the following encoded/decoded ranges,
5772
+ // which we need to convert between.
5773
+ //
5774
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
5775
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5776
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
5777
+ //
5778
+ // Encode 6 bits in b into a new character.
5779
+ Coder.prototype._encodeByte = function (b) {
5780
+ // Encoding uses constant time operations as follows:
5781
+ //
5782
+ // 1. Define comparison of A with B using (A - B) >>> 8:
5783
+ // if A > B, then result is positive integer
5784
+ // if A <= B, then result is 0
5785
+ //
5786
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
5787
+ // if X == 0, then result is 0
5788
+ // if X != 0, then result is C
5789
+ //
5790
+ // 3. Start with the smallest comparison (b >= 0), which is always
5791
+ // true, so set the result to the starting ASCII value (65).
5792
+ //
5793
+ // 4. Continue comparing b to higher ASCII values, and selecting
5794
+ // zero if comparison isn't true, otherwise selecting a value
5795
+ // to add to result, which:
5796
+ //
5797
+ // a) undoes the previous addition
5798
+ // b) provides new value to add
5799
+ //
5800
+ var result = b;
5801
+ // b >= 0
5802
+ result += 65;
5803
+ // b > 25
5804
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5805
+ // b > 51
5806
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5807
+ // b > 61
5808
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
5809
+ // b > 62
5810
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
5811
+ return String.fromCharCode(result);
5812
+ };
5813
+ // Decode a character code into a byte.
5814
+ // Must return 256 if character is out of alphabet range.
5815
+ Coder.prototype._decodeChar = function (c) {
5816
+ // Decoding works similar to encoding: using the same comparison
5817
+ // function, but now it works on ranges: result is always incremented
5818
+ // by value, but this value becomes zero if the range is not
5819
+ // satisfied.
5820
+ //
5821
+ // Decoding starts with invalid value, 256, which is then
5822
+ // subtracted when the range is satisfied. If none of the ranges
5823
+ // apply, the function returns 256, which is then checked by
5824
+ // the caller to throw error.
5825
+ var result = INVALID_BYTE; // start with invalid character
5826
+ // c == 43 (c > 42 and c < 44)
5827
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
5828
+ // c == 47 (c > 46 and c < 48)
5829
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
5830
+ // c > 47 and c < 58
5831
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
5832
+ // c > 64 and c < 91
5833
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
5834
+ // c > 96 and c < 123
5835
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
5836
+ return result;
5837
+ };
5838
+ Coder.prototype._getPaddingLength = function (s) {
5839
+ var paddingLength = 0;
5840
+ if (this._paddingCharacter) {
5841
+ for (var i = s.length - 1; i >= 0; i--) {
5842
+ if (s[i] !== this._paddingCharacter) {
5843
+ break;
5844
+ }
5845
+ paddingLength++;
6029
5846
  }
6030
- else {
6031
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
5847
+ if (s.length < 4 || paddingLength > 2) {
5848
+ throw new Error("Base64Coder: incorrect padding");
6032
5849
  }
6033
5850
  }
6034
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
6035
- // just do what it says, but otherwise calculate a default
6036
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
6037
- const maxRetries = options.maxRetries ?? this.maxRetries;
6038
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6039
- }
6040
- await sleep(timeoutMillis);
6041
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6042
- }
6043
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6044
- const initialRetryDelay = 0.5;
6045
- const maxRetryDelay = 8.0;
6046
- const numRetries = maxRetries - retriesRemaining;
6047
- // Apply exponential backoff, but not more than the max.
6048
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6049
- // Apply some jitter, take up to at most 25 percent of the retry time.
6050
- const jitter = 1 - Math.random() * 0.25;
6051
- return sleepSeconds * jitter * 1000;
6052
- }
6053
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6054
- const options = { ...inputOptions };
6055
- const { method, path, query, defaultBaseURL } = options;
6056
- const url = this.buildURL(path, query, defaultBaseURL);
6057
- if ('timeout' in options)
6058
- validatePositiveInteger('timeout', options.timeout);
6059
- options.timeout = options.timeout ?? this.timeout;
6060
- const { bodyHeaders, body } = this.buildBody({ options });
6061
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6062
- const req = {
6063
- method,
6064
- headers: reqHeaders,
6065
- ...(options.signal && { signal: options.signal }),
6066
- ...(globalThis.ReadableStream &&
6067
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
6068
- ...(body && { body }),
6069
- ...(this.fetchOptions ?? {}),
6070
- ...(options.fetchOptions ?? {}),
6071
- };
6072
- return { req, url, timeout: options.timeout };
6073
- }
6074
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
6075
- let idempotencyHeaders = {};
6076
- if (this.idempotencyHeader && method !== 'get') {
6077
- if (!options.idempotencyKey)
6078
- options.idempotencyKey = this.defaultIdempotencyKey();
6079
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6080
- }
6081
- const headers = buildHeaders([
6082
- idempotencyHeaders,
6083
- {
6084
- Accept: 'application/json',
6085
- 'User-Agent': this.getUserAgent(),
6086
- 'X-Stainless-Retry-Count': String(retryCount),
6087
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
6088
- ...getPlatformHeaders(),
6089
- },
6090
- await this.authHeaders(options),
6091
- this._options.defaultHeaders,
6092
- bodyHeaders,
6093
- options.headers,
6094
- ]);
6095
- this.validateHeaders(headers);
6096
- return headers.values;
6097
- }
6098
- buildBody({ options: { body, headers: rawHeaders } }) {
6099
- if (!body) {
6100
- return { bodyHeaders: undefined, body: undefined };
6101
- }
6102
- const headers = buildHeaders([rawHeaders]);
6103
- if (
6104
- // Pass raw type verbatim
6105
- ArrayBuffer.isView(body) ||
6106
- body instanceof ArrayBuffer ||
6107
- body instanceof DataView ||
6108
- (typeof body === 'string' &&
6109
- // Preserve legacy string encoding behavior for now
6110
- headers.values.has('content-type')) ||
6111
- // `Blob` is superset of `File`
6112
- (globalThis.Blob && body instanceof globalThis.Blob) ||
6113
- // `FormData` -> `multipart/form-data`
6114
- body instanceof FormData ||
6115
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
6116
- body instanceof URLSearchParams ||
6117
- // Send chunked stream (each chunk has own `length`)
6118
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
6119
- return { bodyHeaders: undefined, body: body };
6120
- }
6121
- else if (typeof body === 'object' &&
6122
- (Symbol.asyncIterator in body ||
6123
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
6124
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6125
- }
6126
- else {
6127
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
6128
- }
6129
- }
5851
+ return paddingLength;
5852
+ };
5853
+ return Coder;
5854
+ }());
5855
+ base64$1.Coder = Coder;
5856
+ var stdCoder = new Coder();
5857
+ function encode(data) {
5858
+ return stdCoder.encode(data);
6130
5859
  }
6131
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
6132
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
6133
- };
6134
- DodoPayments.DodoPayments = _a;
6135
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
6136
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
6137
- DodoPayments.APIError = APIError;
6138
- DodoPayments.APIConnectionError = APIConnectionError;
6139
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
6140
- DodoPayments.APIUserAbortError = APIUserAbortError;
6141
- DodoPayments.NotFoundError = NotFoundError;
6142
- DodoPayments.ConflictError = ConflictError;
6143
- DodoPayments.RateLimitError = RateLimitError;
6144
- DodoPayments.BadRequestError = BadRequestError;
6145
- DodoPayments.AuthenticationError = AuthenticationError;
6146
- DodoPayments.InternalServerError = InternalServerError;
6147
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
6148
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
6149
- DodoPayments.toFile = toFile;
6150
- DodoPayments.CheckoutSessions = CheckoutSessions;
6151
- DodoPayments.Payments = Payments;
6152
- DodoPayments.Subscriptions = Subscriptions;
6153
- DodoPayments.Invoices = Invoices;
6154
- DodoPayments.Licenses = Licenses;
6155
- DodoPayments.LicenseKeys = LicenseKeys;
6156
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
6157
- DodoPayments.Customers = Customers;
6158
- DodoPayments.Refunds = Refunds;
6159
- DodoPayments.Disputes = Disputes;
6160
- DodoPayments.Payouts = Payouts;
6161
- DodoPayments.WebhookEvents = WebhookEvents;
6162
- DodoPayments.Products = Products;
6163
- DodoPayments.Misc = Misc;
6164
- DodoPayments.Discounts = Discounts;
6165
- DodoPayments.Addons = Addons;
6166
- DodoPayments.Brands = Brands;
6167
- DodoPayments.Webhooks = Webhooks$1;
6168
- DodoPayments.UsageEvents = UsageEvents;
6169
- DodoPayments.Meters = Meters;
6170
-
6171
- // src/checkout/checkout.ts
6172
- var checkoutQuerySchema = objectType({
6173
- productId: stringType(),
6174
- quantity: stringType().optional(),
6175
- // Customer fields
6176
- fullName: stringType().optional(),
6177
- firstName: stringType().optional(),
6178
- lastName: stringType().optional(),
6179
- email: stringType().optional(),
6180
- country: stringType().optional(),
6181
- addressLine: stringType().optional(),
6182
- city: stringType().optional(),
6183
- state: stringType().optional(),
6184
- zipCode: stringType().optional(),
6185
- // Disable flags
6186
- disableFullName: stringType().optional(),
6187
- disableFirstName: stringType().optional(),
6188
- disableLastName: stringType().optional(),
6189
- disableEmail: stringType().optional(),
6190
- disableCountry: stringType().optional(),
6191
- disableAddressLine: stringType().optional(),
6192
- disableCity: stringType().optional(),
6193
- disableState: stringType().optional(),
6194
- disableZipCode: stringType().optional(),
6195
- // Advanced controls
6196
- paymentCurrency: stringType().optional(),
6197
- showCurrencySelector: stringType().optional(),
6198
- paymentAmount: stringType().optional(),
6199
- showDiscounts: stringType().optional()
6200
- // Metadata (allow any key starting with metadata_)
6201
- // We'll handle metadata separately in the handler
6202
- }).catchall(unknownType());
6203
- var dynamicCheckoutBodySchema = objectType({
6204
- // For subscription
6205
- product_id: stringType().optional(),
6206
- quantity: numberType().optional(),
6207
- // For one-time payment
6208
- product_cart: arrayType(
6209
- objectType({
6210
- product_id: stringType(),
6211
- quantity: numberType()
6212
- })
6213
- ).optional(),
6214
- // Common fields
6215
- billing: objectType({
6216
- city: stringType(),
6217
- country: stringType(),
6218
- state: stringType(),
6219
- street: stringType(),
6220
- zipcode: stringType()
6221
- }),
6222
- customer: objectType({
6223
- customer_id: stringType().optional(),
6224
- email: stringType().optional(),
6225
- name: stringType().optional()
6226
- }),
6227
- discount_id: stringType().optional(),
6228
- addons: arrayType(
6229
- objectType({
6230
- addon_id: stringType(),
6231
- quantity: numberType()
6232
- })
6233
- ).optional(),
6234
- metadata: recordType(stringType(), stringType()).optional(),
6235
- currency: stringType().optional()
6236
- // Allow any additional fields (for future compatibility)
6237
- }).catchall(unknownType());
6238
- var checkoutSessionProductCartItemSchema = objectType({
6239
- product_id: stringType().min(1, "Product ID is required"),
6240
- quantity: numberType().int().positive("Quantity must be a positive integer")
6241
- });
6242
- var checkoutSessionCustomerSchema = objectType({
6243
- email: stringType().email().optional(),
6244
- name: stringType().min(1).optional(),
6245
- phone_number: stringType().optional()
6246
- }).optional();
6247
- var checkoutSessionBillingAddressSchema = objectType({
6248
- street: stringType().optional(),
6249
- city: stringType().optional(),
6250
- state: stringType().optional(),
6251
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
6252
- zipcode: stringType().optional()
6253
- }).optional();
6254
- var paymentMethodTypeSchema = enumType([
6255
- "credit",
6256
- "debit",
6257
- "upi_collect",
6258
- "upi_intent",
6259
- "apple_pay",
6260
- "google_pay",
6261
- "amazon_pay",
6262
- "klarna",
6263
- "affirm",
6264
- "afterpay_clearpay",
6265
- "sepa",
6266
- "ach"
6267
- ]);
6268
- var checkoutSessionCustomizationSchema = objectType({
6269
- theme: enumType(["light", "dark", "system"]).optional(),
6270
- show_order_details: booleanType().optional(),
6271
- show_on_demand_tag: booleanType().optional()
6272
- }).optional();
6273
- var checkoutSessionFeatureFlagsSchema = objectType({
6274
- allow_currency_selection: booleanType().optional(),
6275
- allow_discount_code: booleanType().optional(),
6276
- allow_phone_number_collection: booleanType().optional(),
6277
- allow_tax_id: booleanType().optional(),
6278
- always_create_new_customer: booleanType().optional()
6279
- }).optional();
6280
- var checkoutSessionSubscriptionDataSchema = objectType({
6281
- trial_period_days: numberType().int().nonnegative().optional()
6282
- }).optional();
6283
- var checkoutSessionPayloadSchema = objectType({
6284
- // Required fields
6285
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
6286
- // Optional fields
6287
- customer: checkoutSessionCustomerSchema,
6288
- billing_address: checkoutSessionBillingAddressSchema,
6289
- return_url: stringType().url().optional(),
6290
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
6291
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
6292
- show_saved_payment_methods: booleanType().optional(),
6293
- confirm: booleanType().optional(),
6294
- discount_code: stringType().optional(),
6295
- metadata: recordType(stringType(), stringType()).optional(),
6296
- customization: checkoutSessionCustomizationSchema,
6297
- feature_flags: checkoutSessionFeatureFlagsSchema,
6298
- subscription_data: checkoutSessionSubscriptionDataSchema
6299
- });
6300
- var checkoutSessionResponseSchema = objectType({
6301
- session_id: stringType().min(1, "Session ID is required"),
6302
- checkout_url: stringType().url("Invalid checkout URL")
6303
- });
6304
- var createCheckoutSession = async (payload, config) => {
6305
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
6306
- if (!validation.success) {
6307
- throw new Error(
6308
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6309
- );
6310
- }
6311
- const dodopayments = new DodoPayments({
6312
- bearerToken: config.bearerToken,
6313
- environment: config.environment
6314
- });
6315
- try {
6316
- const sdkPayload = {
6317
- ...validation.data,
6318
- ...validation.data.billing_address && {
6319
- billing_address: {
6320
- ...validation.data.billing_address,
6321
- country: validation.data.billing_address.country
6322
- }
6323
- }
6324
- };
6325
- const session = await dodopayments.checkoutSessions.create(
6326
- sdkPayload
6327
- );
6328
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
6329
- if (!responseValidation.success) {
6330
- throw new Error(
6331
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6332
- );
6333
- }
6334
- return responseValidation.data;
6335
- } catch (error) {
6336
- if (error instanceof Error) {
6337
- console.error("Dodo Payments Checkout Session API Error:", {
6338
- message: error.message,
6339
- payload: validation.data,
6340
- config: {
6341
- environment: config.environment,
6342
- hasBearerToken: !!config.bearerToken
6343
- }
6344
- });
6345
- throw new Error(`Failed to create checkout session: ${error.message}`);
5860
+ base64$1.encode = encode;
5861
+ function decode(s) {
5862
+ return stdCoder.decode(s);
5863
+ }
5864
+ base64$1.decode = decode;
5865
+ /**
5866
+ * Implements URL-safe Base64 encoding.
5867
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
5868
+ *
5869
+ * Operates in constant time.
5870
+ */
5871
+ var URLSafeCoder = /** @class */ (function (_super) {
5872
+ __extends(URLSafeCoder, _super);
5873
+ function URLSafeCoder() {
5874
+ return _super !== null && _super.apply(this, arguments) || this;
6346
5875
  }
6347
- console.error("Unknown error creating checkout session:", error);
6348
- throw new Error(
6349
- "Failed to create checkout session due to an unknown error"
6350
- );
6351
- }
5876
+ // URL-safe encoding have the following encoded/decoded ranges:
5877
+ //
5878
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
5879
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5880
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
5881
+ //
5882
+ URLSafeCoder.prototype._encodeByte = function (b) {
5883
+ var result = b;
5884
+ // b >= 0
5885
+ result += 65;
5886
+ // b > 25
5887
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5888
+ // b > 51
5889
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5890
+ // b > 61
5891
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
5892
+ // b > 62
5893
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
5894
+ return String.fromCharCode(result);
5895
+ };
5896
+ URLSafeCoder.prototype._decodeChar = function (c) {
5897
+ var result = INVALID_BYTE;
5898
+ // c == 45 (c > 44 and c < 46)
5899
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
5900
+ // c == 95 (c > 94 and c < 96)
5901
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
5902
+ // c > 47 and c < 58
5903
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
5904
+ // c > 64 and c < 91
5905
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
5906
+ // c > 96 and c < 123
5907
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
5908
+ return result;
5909
+ };
5910
+ return URLSafeCoder;
5911
+ }(Coder));
5912
+ base64$1.URLSafeCoder = URLSafeCoder;
5913
+ var urlSafeCoder = new URLSafeCoder();
5914
+ function encodeURLSafe(data) {
5915
+ return urlSafeCoder.encode(data);
5916
+ }
5917
+ base64$1.encodeURLSafe = encodeURLSafe;
5918
+ function decodeURLSafe(s) {
5919
+ return urlSafeCoder.decode(s);
5920
+ }
5921
+ base64$1.decodeURLSafe = decodeURLSafe;
5922
+ base64$1.encodedLength = function (length) {
5923
+ return stdCoder.encodedLength(length);
6352
5924
  };
6353
- var buildCheckoutUrl = async ({
6354
- queryParams,
6355
- body,
6356
- sessionPayload,
6357
- returnUrl,
6358
- bearerToken,
6359
- environment,
6360
- type = "static"
6361
- }) => {
6362
- if (type === "session") {
6363
- if (!sessionPayload) {
6364
- throw new Error("sessionPayload is required when type is 'session'");
6365
- }
6366
- const session = await createCheckoutSession(sessionPayload, {
6367
- bearerToken,
6368
- environment
6369
- });
6370
- return session.checkout_url;
6371
- }
6372
- const inputData = type === "dynamic" ? body : queryParams;
6373
- let parseResult;
6374
- if (type === "dynamic") {
6375
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
6376
- } else {
6377
- parseResult = checkoutQuerySchema.safeParse(inputData);
6378
- }
6379
- const { success, data, error } = parseResult;
6380
- if (!success) {
6381
- throw new Error(
6382
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
6383
- ${error.message}`
6384
- );
6385
- }
6386
- if (type !== "dynamic") {
6387
- const {
6388
- productId,
6389
- quantity: quantity2,
6390
- fullName,
6391
- firstName,
6392
- lastName,
6393
- email,
6394
- country,
6395
- addressLine,
6396
- city,
6397
- state,
6398
- zipCode,
6399
- disableFullName,
6400
- disableFirstName,
6401
- disableLastName,
6402
- disableEmail,
6403
- disableCountry,
6404
- disableAddressLine,
6405
- disableCity,
6406
- disableState,
6407
- disableZipCode,
6408
- paymentCurrency,
6409
- showCurrencySelector,
6410
- paymentAmount,
6411
- showDiscounts
6412
- // metadata handled below
6413
- } = data;
6414
- const dodopayments2 = new DodoPayments({
6415
- bearerToken,
6416
- environment
6417
- });
6418
- if (!productId) throw new Error("Missing required field: productId");
6419
- try {
6420
- await dodopayments2.products.retrieve(productId);
6421
- } catch (err) {
6422
- console.error(err);
6423
- throw new Error("Product not found");
6424
- }
6425
- const url = new URL(
6426
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
6427
- );
6428
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
6429
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
6430
- if (fullName) url.searchParams.set("fullName", String(fullName));
6431
- if (firstName) url.searchParams.set("firstName", String(firstName));
6432
- if (lastName) url.searchParams.set("lastName", String(lastName));
6433
- if (email) url.searchParams.set("email", String(email));
6434
- if (country) url.searchParams.set("country", String(country));
6435
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
6436
- if (city) url.searchParams.set("city", String(city));
6437
- if (state) url.searchParams.set("state", String(state));
6438
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
6439
- if (disableFullName === "true")
6440
- url.searchParams.set("disableFullName", "true");
6441
- if (disableFirstName === "true")
6442
- url.searchParams.set("disableFirstName", "true");
6443
- if (disableLastName === "true")
6444
- url.searchParams.set("disableLastName", "true");
6445
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
6446
- if (disableCountry === "true")
6447
- url.searchParams.set("disableCountry", "true");
6448
- if (disableAddressLine === "true")
6449
- url.searchParams.set("disableAddressLine", "true");
6450
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
6451
- if (disableState === "true") url.searchParams.set("disableState", "true");
6452
- if (disableZipCode === "true")
6453
- url.searchParams.set("disableZipCode", "true");
6454
- if (paymentCurrency)
6455
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
6456
- if (showCurrencySelector)
6457
- url.searchParams.set(
6458
- "showCurrencySelector",
6459
- String(showCurrencySelector)
6460
- );
6461
- if (paymentAmount)
6462
- url.searchParams.set("paymentAmount", String(paymentAmount));
6463
- if (showDiscounts)
6464
- url.searchParams.set("showDiscounts", String(showDiscounts));
6465
- for (const [key, value] of Object.entries(queryParams || {})) {
6466
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
6467
- url.searchParams.set(key, String(value));
6468
- }
6469
- }
6470
- return url.toString();
6471
- }
6472
- const dyn = data;
6473
- const {
6474
- product_id,
6475
- product_cart,
6476
- quantity,
6477
- billing,
6478
- customer,
6479
- addons,
6480
- metadata,
6481
- allowed_payment_method_types,
6482
- billing_currency,
6483
- discount_code,
6484
- on_demand,
6485
- return_url: bodyReturnUrl,
6486
- show_saved_payment_methods,
6487
- tax_id,
6488
- trial_period_days
6489
- } = dyn;
6490
- const dodopayments = new DodoPayments({
6491
- bearerToken,
6492
- environment
6493
- });
6494
- let isSubscription = false;
6495
- let productIdToFetch = product_id;
6496
- if (!product_id && product_cart && product_cart.length > 0) {
6497
- productIdToFetch = product_cart[0].product_id;
6498
- }
6499
- if (!productIdToFetch)
6500
- throw new Error(
6501
- "Missing required field: product_id or product_cart[0].product_id"
6502
- );
6503
- let product;
6504
- try {
6505
- product = await dodopayments.products.retrieve(productIdToFetch);
6506
- } catch (err) {
6507
- console.error(err);
6508
- throw new Error("Product not found");
6509
- }
6510
- isSubscription = Boolean(product.is_recurring);
6511
- if (isSubscription && !product_id)
6512
- throw new Error("Missing required field: product_id for subscription");
6513
- if (!billing) throw new Error("Missing required field: billing");
6514
- if (!customer) throw new Error("Missing required field: customer");
6515
- if (isSubscription) {
6516
- const subscriptionPayload = {
6517
- billing,
6518
- customer,
6519
- product_id,
6520
- quantity: quantity ? Number(quantity) : 1
6521
- };
6522
- if (metadata) subscriptionPayload.metadata = metadata;
6523
- if (discount_code) subscriptionPayload.discount_code = discount_code;
6524
- if (addons) subscriptionPayload.addons = addons;
6525
- if (allowed_payment_method_types)
6526
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
6527
- if (billing_currency)
6528
- subscriptionPayload.billing_currency = billing_currency;
6529
- if (on_demand) subscriptionPayload.on_demand = on_demand;
6530
- subscriptionPayload.payment_link = true;
6531
- if (bodyReturnUrl) {
6532
- subscriptionPayload.return_url = bodyReturnUrl;
6533
- } else if (returnUrl) {
6534
- subscriptionPayload.return_url = returnUrl;
6535
- }
6536
- if (show_saved_payment_methods)
6537
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
6538
- if (tax_id) subscriptionPayload.tax_id = tax_id;
6539
- if (trial_period_days)
6540
- subscriptionPayload.trial_period_days = trial_period_days;
6541
- let subscription;
6542
- try {
6543
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
6544
- } catch (err) {
6545
- console.error("Error when creating subscription", err);
6546
- throw new Error(err instanceof Error ? err.message : String(err));
6547
- }
6548
- if (!subscription || !subscription.payment_link) {
6549
- throw new Error(
6550
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
6551
- );
6552
- }
6553
- return subscription.payment_link;
6554
- } else {
6555
- let cart = product_cart;
6556
- if (!cart && product_id) {
6557
- cart = [
6558
- { product_id, quantity: quantity ? Number(quantity) : 1 }
6559
- ];
6560
- }
6561
- if (!cart || cart.length === 0)
6562
- throw new Error("Missing required field: product_cart or product_id");
6563
- const paymentPayload = {
6564
- billing,
6565
- customer,
6566
- product_cart: cart
6567
- };
6568
- if (metadata) paymentPayload.metadata = metadata;
6569
- paymentPayload.payment_link = true;
6570
- if (allowed_payment_method_types)
6571
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
6572
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
6573
- if (discount_code) paymentPayload.discount_code = discount_code;
6574
- if (bodyReturnUrl) {
6575
- paymentPayload.return_url = bodyReturnUrl;
6576
- } else if (returnUrl) {
6577
- paymentPayload.return_url = returnUrl;
6578
- }
6579
- if (show_saved_payment_methods)
6580
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
6581
- if (tax_id) paymentPayload.tax_id = tax_id;
6582
- let payment;
6583
- try {
6584
- payment = await dodopayments.payments.create(paymentPayload);
6585
- } catch (err) {
6586
- console.error("Error when creating payment link", err);
6587
- throw new Error(err instanceof Error ? err.message : String(err));
6588
- }
6589
- if (!payment || !payment.payment_link) {
6590
- throw new Error(
6591
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
6592
- );
6593
- }
6594
- return payment.payment_link;
6595
- }
5925
+ base64$1.maxDecodedLength = function (length) {
5926
+ return stdCoder.maxDecodedLength(length);
5927
+ };
5928
+ base64$1.decodedLength = function (s) {
5929
+ return stdCoder.decodedLength(s);
6596
5930
  };
6597
5931
 
6598
- function checkoutHandler(config) {
6599
- const getHandler = async (req, res) => {
6600
- const queryParams = req.query;
6601
- if (!queryParams.productId) {
6602
- return res.status(400).send("Please provide productId query parameter");
6603
- }
6604
- const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
6605
- if (!success) {
6606
- if (error.errors.some((e) => e.path.toString() === "productId")) {
6607
- return res.status(400).send("Please provide productId query parameter");
6608
- }
6609
- return res
6610
- .status(400)
6611
- .send(`Invalid query parameters.\n ${error.message}`);
6612
- }
6613
- let url = "";
6614
- try {
6615
- url = await buildCheckoutUrl({ queryParams: data, ...config });
6616
- }
6617
- catch (error) {
6618
- return res.status(400).send(error.message);
6619
- }
6620
- return res.json({ checkout_url: url });
6621
- };
6622
- const postHandler = async (req, res) => {
6623
- if (config.type === "dynamic") {
6624
- // Handle dynamic checkout
6625
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(req.body);
6626
- if (!success) {
6627
- return res.status(400).send(`Invalid request body.\n ${error.message}`);
6628
- }
6629
- let url = "";
6630
- try {
6631
- url = await buildCheckoutUrl({
6632
- body: data,
6633
- ...config,
6634
- type: "dynamic",
6635
- });
6636
- }
6637
- catch (error) {
6638
- return res.status(400).send(error.message);
6639
- }
6640
- return res.json({ checkout_url: url });
6641
- }
6642
- else {
6643
- // Handle checkout session
6644
- const { success, data, error } = checkoutSessionPayloadSchema.safeParse(req.body);
6645
- if (!success) {
6646
- return res
6647
- .status(400)
6648
- .send(`Invalid checkout session payload.\n ${error.message}`);
6649
- }
6650
- let url = "";
6651
- try {
6652
- url = await buildCheckoutUrl({
6653
- sessionPayload: data,
6654
- ...config,
6655
- type: "session",
6656
- });
6657
- }
6658
- catch (error) {
6659
- return res.status(400).send(error.message);
6660
- }
6661
- return res.json({ checkout_url: url });
6662
- }
6663
- };
6664
- return (req, res) => {
6665
- if (req.method === "POST") {
6666
- return postHandler(req, res);
6667
- }
6668
- if (req.method === "GET") {
6669
- return getHandler(req, res);
6670
- }
6671
- return res.status(405).send("Method Not Allowed");
6672
- };
6673
- }
6674
-
6675
- const CustomerPortal = ({ bearerToken, environment, }) => {
6676
- const getHandler = async (req, res) => {
6677
- // Extract customerId from query parameters
6678
- const { customer_id: customerId, send_email } = req.query;
6679
- const params = {
6680
- send_email: false,
6681
- };
6682
- const sendEmail = Boolean(send_email);
6683
- if (sendEmail) {
6684
- params.send_email = sendEmail;
6685
- }
6686
- if (!customerId) {
6687
- return res.status(400).send("Missing customerId in query parameters");
6688
- }
6689
- const dodopayments = new DodoPayments({
6690
- bearerToken,
6691
- environment,
6692
- });
6693
- try {
6694
- const session = await dodopayments.customers.customerPortal.create(customerId, params);
6695
- return res.redirect(session.link);
6696
- }
6697
- catch (error) {
6698
- console.error("Error creating customer portal session:", error);
6699
- return res
6700
- .status(500)
6701
- .send(`Failed to create customer portal session: ${error.message}`);
6702
- }
6703
- };
6704
- return getHandler;
6705
- };
6706
-
6707
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6708
-
6709
- var dist = {};
6710
-
6711
- var timing_safe_equal = {};
6712
-
6713
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
6714
- timing_safe_equal.timingSafeEqual = void 0;
6715
- function assert(expr, msg = "") {
6716
- if (!expr) {
6717
- throw new Error(msg);
6718
- }
6719
- }
6720
- function timingSafeEqual(a, b) {
6721
- if (a.byteLength !== b.byteLength) {
6722
- return false;
6723
- }
6724
- if (!(a instanceof DataView)) {
6725
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
6726
- }
6727
- if (!(b instanceof DataView)) {
6728
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
6729
- }
6730
- assert(a instanceof DataView);
6731
- assert(b instanceof DataView);
6732
- const length = a.byteLength;
6733
- let out = 0;
6734
- let i = -1;
6735
- while (++i < length) {
6736
- out |= a.getUint8(i) ^ b.getUint8(i);
6737
- }
6738
- return out === 0;
6739
- }
6740
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
6741
-
6742
- var base64$1 = {};
6743
-
6744
- // Copyright (C) 2016 Dmitry Chestnykh
6745
- // MIT License. See LICENSE file for details.
6746
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
6747
- var extendStatics = function (d, b) {
6748
- extendStatics = Object.setPrototypeOf ||
6749
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6750
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6751
- return extendStatics(d, b);
6752
- };
6753
- return function (d, b) {
6754
- extendStatics(d, b);
6755
- function __() { this.constructor = d; }
6756
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6757
- };
6758
- })();
6759
- Object.defineProperty(base64$1, "__esModule", { value: true });
6760
- /**
6761
- * Package base64 implements Base64 encoding and decoding.
6762
- */
6763
- // Invalid character used in decoding to indicate
6764
- // that the character to decode is out of range of
6765
- // alphabet and cannot be decoded.
6766
- var INVALID_BYTE = 256;
6767
- /**
6768
- * Implements standard Base64 encoding.
6769
- *
6770
- * Operates in constant time.
6771
- */
6772
- var Coder = /** @class */ (function () {
6773
- // TODO(dchest): methods to encode chunk-by-chunk.
6774
- function Coder(_paddingCharacter) {
6775
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
6776
- this._paddingCharacter = _paddingCharacter;
6777
- }
6778
- Coder.prototype.encodedLength = function (length) {
6779
- if (!this._paddingCharacter) {
6780
- return (length * 8 + 5) / 6 | 0;
6781
- }
6782
- return (length + 2) / 3 * 4 | 0;
6783
- };
6784
- Coder.prototype.encode = function (data) {
6785
- var out = "";
6786
- var i = 0;
6787
- for (; i < data.length - 2; i += 3) {
6788
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
6789
- out += this._encodeByte((c >>> 3 * 6) & 63);
6790
- out += this._encodeByte((c >>> 2 * 6) & 63);
6791
- out += this._encodeByte((c >>> 1 * 6) & 63);
6792
- out += this._encodeByte((c >>> 0 * 6) & 63);
6793
- }
6794
- var left = data.length - i;
6795
- if (left > 0) {
6796
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
6797
- out += this._encodeByte((c >>> 3 * 6) & 63);
6798
- out += this._encodeByte((c >>> 2 * 6) & 63);
6799
- if (left === 2) {
6800
- out += this._encodeByte((c >>> 1 * 6) & 63);
6801
- }
6802
- else {
6803
- out += this._paddingCharacter || "";
6804
- }
6805
- out += this._paddingCharacter || "";
6806
- }
6807
- return out;
6808
- };
6809
- Coder.prototype.maxDecodedLength = function (length) {
6810
- if (!this._paddingCharacter) {
6811
- return (length * 6 + 7) / 8 | 0;
6812
- }
6813
- return length / 4 * 3 | 0;
6814
- };
6815
- Coder.prototype.decodedLength = function (s) {
6816
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
6817
- };
6818
- Coder.prototype.decode = function (s) {
6819
- if (s.length === 0) {
6820
- return new Uint8Array(0);
6821
- }
6822
- var paddingLength = this._getPaddingLength(s);
6823
- var length = s.length - paddingLength;
6824
- var out = new Uint8Array(this.maxDecodedLength(length));
6825
- var op = 0;
6826
- var i = 0;
6827
- var haveBad = 0;
6828
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
6829
- for (; i < length - 4; i += 4) {
6830
- v0 = this._decodeChar(s.charCodeAt(i + 0));
6831
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6832
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6833
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6834
- out[op++] = (v0 << 2) | (v1 >>> 4);
6835
- out[op++] = (v1 << 4) | (v2 >>> 2);
6836
- out[op++] = (v2 << 6) | v3;
6837
- haveBad |= v0 & INVALID_BYTE;
6838
- haveBad |= v1 & INVALID_BYTE;
6839
- haveBad |= v2 & INVALID_BYTE;
6840
- haveBad |= v3 & INVALID_BYTE;
6841
- }
6842
- if (i < length - 1) {
6843
- v0 = this._decodeChar(s.charCodeAt(i));
6844
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6845
- out[op++] = (v0 << 2) | (v1 >>> 4);
6846
- haveBad |= v0 & INVALID_BYTE;
6847
- haveBad |= v1 & INVALID_BYTE;
6848
- }
6849
- if (i < length - 2) {
6850
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6851
- out[op++] = (v1 << 4) | (v2 >>> 2);
6852
- haveBad |= v2 & INVALID_BYTE;
6853
- }
6854
- if (i < length - 3) {
6855
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6856
- out[op++] = (v2 << 6) | v3;
6857
- haveBad |= v3 & INVALID_BYTE;
6858
- }
6859
- if (haveBad !== 0) {
6860
- throw new Error("Base64Coder: incorrect characters for decoding");
6861
- }
6862
- return out;
6863
- };
6864
- // Standard encoding have the following encoded/decoded ranges,
6865
- // which we need to convert between.
6866
- //
6867
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
6868
- // Index: 0 - 25 26 - 51 52 - 61 62 63
6869
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
6870
- //
6871
- // Encode 6 bits in b into a new character.
6872
- Coder.prototype._encodeByte = function (b) {
6873
- // Encoding uses constant time operations as follows:
6874
- //
6875
- // 1. Define comparison of A with B using (A - B) >>> 8:
6876
- // if A > B, then result is positive integer
6877
- // if A <= B, then result is 0
6878
- //
6879
- // 2. Define selection of C or 0 using bitwise AND: X & C:
6880
- // if X == 0, then result is 0
6881
- // if X != 0, then result is C
6882
- //
6883
- // 3. Start with the smallest comparison (b >= 0), which is always
6884
- // true, so set the result to the starting ASCII value (65).
6885
- //
6886
- // 4. Continue comparing b to higher ASCII values, and selecting
6887
- // zero if comparison isn't true, otherwise selecting a value
6888
- // to add to result, which:
6889
- //
6890
- // a) undoes the previous addition
6891
- // b) provides new value to add
6892
- //
6893
- var result = b;
6894
- // b >= 0
6895
- result += 65;
6896
- // b > 25
6897
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
6898
- // b > 51
6899
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
6900
- // b > 61
6901
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
6902
- // b > 62
6903
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
6904
- return String.fromCharCode(result);
6905
- };
6906
- // Decode a character code into a byte.
6907
- // Must return 256 if character is out of alphabet range.
6908
- Coder.prototype._decodeChar = function (c) {
6909
- // Decoding works similar to encoding: using the same comparison
6910
- // function, but now it works on ranges: result is always incremented
6911
- // by value, but this value becomes zero if the range is not
6912
- // satisfied.
6913
- //
6914
- // Decoding starts with invalid value, 256, which is then
6915
- // subtracted when the range is satisfied. If none of the ranges
6916
- // apply, the function returns 256, which is then checked by
6917
- // the caller to throw error.
6918
- var result = INVALID_BYTE; // start with invalid character
6919
- // c == 43 (c > 42 and c < 44)
6920
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
6921
- // c == 47 (c > 46 and c < 48)
6922
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
6923
- // c > 47 and c < 58
6924
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
6925
- // c > 64 and c < 91
6926
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
6927
- // c > 96 and c < 123
6928
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
6929
- return result;
6930
- };
6931
- Coder.prototype._getPaddingLength = function (s) {
6932
- var paddingLength = 0;
6933
- if (this._paddingCharacter) {
6934
- for (var i = s.length - 1; i >= 0; i--) {
6935
- if (s[i] !== this._paddingCharacter) {
6936
- break;
6937
- }
6938
- paddingLength++;
6939
- }
6940
- if (s.length < 4 || paddingLength > 2) {
6941
- throw new Error("Base64Coder: incorrect padding");
6942
- }
6943
- }
6944
- return paddingLength;
6945
- };
6946
- return Coder;
6947
- }());
6948
- base64$1.Coder = Coder;
6949
- var stdCoder = new Coder();
6950
- function encode(data) {
6951
- return stdCoder.encode(data);
6952
- }
6953
- base64$1.encode = encode;
6954
- function decode(s) {
6955
- return stdCoder.decode(s);
6956
- }
6957
- base64$1.decode = decode;
6958
- /**
6959
- * Implements URL-safe Base64 encoding.
6960
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
6961
- *
6962
- * Operates in constant time.
6963
- */
6964
- var URLSafeCoder = /** @class */ (function (_super) {
6965
- __extends(URLSafeCoder, _super);
6966
- function URLSafeCoder() {
6967
- return _super !== null && _super.apply(this, arguments) || this;
6968
- }
6969
- // URL-safe encoding have the following encoded/decoded ranges:
6970
- //
6971
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
6972
- // Index: 0 - 25 26 - 51 52 - 61 62 63
6973
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
6974
- //
6975
- URLSafeCoder.prototype._encodeByte = function (b) {
6976
- var result = b;
6977
- // b >= 0
6978
- result += 65;
6979
- // b > 25
6980
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
6981
- // b > 51
6982
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
6983
- // b > 61
6984
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
6985
- // b > 62
6986
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
6987
- return String.fromCharCode(result);
6988
- };
6989
- URLSafeCoder.prototype._decodeChar = function (c) {
6990
- var result = INVALID_BYTE;
6991
- // c == 45 (c > 44 and c < 46)
6992
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
6993
- // c == 95 (c > 94 and c < 96)
6994
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
6995
- // c > 47 and c < 58
6996
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
6997
- // c > 64 and c < 91
6998
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
6999
- // c > 96 and c < 123
7000
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7001
- return result;
7002
- };
7003
- return URLSafeCoder;
7004
- }(Coder));
7005
- base64$1.URLSafeCoder = URLSafeCoder;
7006
- var urlSafeCoder = new URLSafeCoder();
7007
- function encodeURLSafe(data) {
7008
- return urlSafeCoder.encode(data);
7009
- }
7010
- base64$1.encodeURLSafe = encodeURLSafe;
7011
- function decodeURLSafe(s) {
7012
- return urlSafeCoder.decode(s);
7013
- }
7014
- base64$1.decodeURLSafe = decodeURLSafe;
7015
- base64$1.encodedLength = function (length) {
7016
- return stdCoder.encodedLength(length);
7017
- };
7018
- base64$1.maxDecodedLength = function (length) {
7019
- return stdCoder.maxDecodedLength(length);
7020
- };
7021
- base64$1.decodedLength = function (s) {
7022
- return stdCoder.decodedLength(s);
7023
- };
7024
-
7025
- var sha256$1 = {exports: {}};
5932
+ var sha256$1 = {exports: {}};
7026
5933
 
7027
5934
  (function (module) {
7028
5935
  (function (root, factory) {
@@ -7464,96 +6371,1240 @@ class ExtendableError extends Error {
7464
6371
  this.name = "ExtendableError";
7465
6372
  this.stack = new Error(message).stack;
7466
6373
  }
7467
- }
7468
- class WebhookVerificationError extends ExtendableError {
7469
- constructor(message) {
7470
- super(message);
7471
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
7472
- this.name = "WebhookVerificationError";
6374
+ }
6375
+ class WebhookVerificationError extends ExtendableError {
6376
+ constructor(message) {
6377
+ super(message);
6378
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
6379
+ this.name = "WebhookVerificationError";
6380
+ }
6381
+ }
6382
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
6383
+ class Webhook {
6384
+ constructor(secret, options) {
6385
+ if (!secret) {
6386
+ throw new Error("Secret can't be empty.");
6387
+ }
6388
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
6389
+ if (secret instanceof Uint8Array) {
6390
+ this.key = secret;
6391
+ }
6392
+ else {
6393
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
6394
+ }
6395
+ }
6396
+ else {
6397
+ if (typeof secret !== "string") {
6398
+ throw new Error("Expected secret to be of type string");
6399
+ }
6400
+ if (secret.startsWith(Webhook.prefix)) {
6401
+ secret = secret.substring(Webhook.prefix.length);
6402
+ }
6403
+ this.key = base64.decode(secret);
6404
+ }
6405
+ }
6406
+ verify(payload, headers_) {
6407
+ const headers = {};
6408
+ for (const key of Object.keys(headers_)) {
6409
+ headers[key.toLowerCase()] = headers_[key];
6410
+ }
6411
+ const msgId = headers["webhook-id"];
6412
+ const msgSignature = headers["webhook-signature"];
6413
+ const msgTimestamp = headers["webhook-timestamp"];
6414
+ if (!msgSignature || !msgId || !msgTimestamp) {
6415
+ throw new WebhookVerificationError("Missing required headers");
6416
+ }
6417
+ const timestamp = this.verifyTimestamp(msgTimestamp);
6418
+ const computedSignature = this.sign(msgId, timestamp, payload);
6419
+ const expectedSignature = computedSignature.split(",")[1];
6420
+ const passedSignatures = msgSignature.split(" ");
6421
+ const encoder = new globalThis.TextEncoder();
6422
+ for (const versionedSignature of passedSignatures) {
6423
+ const [version, signature] = versionedSignature.split(",");
6424
+ if (version !== "v1") {
6425
+ continue;
6426
+ }
6427
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
6428
+ return JSON.parse(payload.toString());
6429
+ }
6430
+ }
6431
+ throw new WebhookVerificationError("No matching signature found");
6432
+ }
6433
+ sign(msgId, timestamp, payload) {
6434
+ if (typeof payload === "string") ;
6435
+ else if (payload.constructor.name === "Buffer") {
6436
+ payload = payload.toString();
6437
+ }
6438
+ else {
6439
+ throw new Error("Expected payload to be of type string or Buffer.");
6440
+ }
6441
+ const encoder = new TextEncoder();
6442
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
6443
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
6444
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
6445
+ return `v1,${expectedSignature}`;
6446
+ }
6447
+ verifyTimestamp(timestampHeader) {
6448
+ const now = Math.floor(Date.now() / 1000);
6449
+ const timestamp = parseInt(timestampHeader, 10);
6450
+ if (isNaN(timestamp)) {
6451
+ throw new WebhookVerificationError("Invalid Signature Headers");
6452
+ }
6453
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
6454
+ throw new WebhookVerificationError("Message timestamp too old");
6455
+ }
6456
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
6457
+ throw new WebhookVerificationError("Message timestamp too new");
6458
+ }
6459
+ return new Date(timestamp * 1000);
6460
+ }
6461
+ }
6462
+ Webhook_1 = dist.Webhook = Webhook;
6463
+ Webhook.prefix = "whsec_";
6464
+
6465
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6466
+ let Webhooks$1 = class Webhooks extends APIResource {
6467
+ constructor() {
6468
+ super(...arguments);
6469
+ this.headers = new Headers$1(this._client);
6470
+ }
6471
+ /**
6472
+ * Create a new webhook
6473
+ */
6474
+ create(body, options) {
6475
+ return this._client.post('/webhooks', { body, ...options });
6476
+ }
6477
+ /**
6478
+ * Get a webhook by id
6479
+ */
6480
+ retrieve(webhookID, options) {
6481
+ return this._client.get(path `/webhooks/${webhookID}`, options);
6482
+ }
6483
+ /**
6484
+ * Patch a webhook by id
6485
+ */
6486
+ update(webhookID, body, options) {
6487
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
6488
+ }
6489
+ /**
6490
+ * List all webhooks
6491
+ */
6492
+ list(query = {}, options) {
6493
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
6494
+ }
6495
+ /**
6496
+ * Delete a webhook by id
6497
+ */
6498
+ delete(webhookID, options) {
6499
+ return this._client.delete(path `/webhooks/${webhookID}`, {
6500
+ ...options,
6501
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
6502
+ });
6503
+ }
6504
+ /**
6505
+ * Get webhook secret by id
6506
+ */
6507
+ retrieveSecret(webhookID, options) {
6508
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
6509
+ }
6510
+ unsafeUnwrap(body) {
6511
+ return JSON.parse(body);
6512
+ }
6513
+ unwrap(body, { headers, key }) {
6514
+ if (headers !== undefined) {
6515
+ const keyStr = key === undefined ? this._client.webhookKey : key;
6516
+ if (keyStr === null)
6517
+ throw new Error('Webhook key must not be null in order to unwrap');
6518
+ const wh = new Webhook_1(keyStr);
6519
+ wh.verify(body, headers);
6520
+ }
6521
+ return JSON.parse(body);
6522
+ }
6523
+ };
6524
+ Webhooks$1.Headers = Headers$1;
6525
+
6526
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6527
+ /**
6528
+ * Read an environment variable.
6529
+ *
6530
+ * Trims beginning and trailing whitespace.
6531
+ *
6532
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
6533
+ */
6534
+ const readEnv = (env) => {
6535
+ if (typeof globalThis.process !== 'undefined') {
6536
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
6537
+ }
6538
+ if (typeof globalThis.Deno !== 'undefined') {
6539
+ return globalThis.Deno.env?.get?.(env)?.trim();
6540
+ }
6541
+ return undefined;
6542
+ };
6543
+
6544
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6545
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
6546
+ const environments = {
6547
+ live_mode: 'https://live.dodopayments.com',
6548
+ test_mode: 'https://test.dodopayments.com',
6549
+ };
6550
+ /**
6551
+ * API Client for interfacing with the Dodo Payments API.
6552
+ */
6553
+ class DodoPayments {
6554
+ /**
6555
+ * API Client for interfacing with the Dodo Payments API.
6556
+ *
6557
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
6558
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
6559
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
6560
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
6561
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
6562
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
6563
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
6564
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
6565
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
6566
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
6567
+ */
6568
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
6569
+ _DodoPayments_instances.add(this);
6570
+ _DodoPayments_encoder.set(this, void 0);
6571
+ this.checkoutSessions = new CheckoutSessions(this);
6572
+ this.payments = new Payments(this);
6573
+ this.subscriptions = new Subscriptions(this);
6574
+ this.invoices = new Invoices(this);
6575
+ this.licenses = new Licenses(this);
6576
+ this.licenseKeys = new LicenseKeys(this);
6577
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
6578
+ this.customers = new Customers(this);
6579
+ this.refunds = new Refunds(this);
6580
+ this.disputes = new Disputes(this);
6581
+ this.payouts = new Payouts(this);
6582
+ this.products = new Products(this);
6583
+ this.misc = new Misc(this);
6584
+ this.discounts = new Discounts(this);
6585
+ this.addons = new Addons(this);
6586
+ this.brands = new Brands(this);
6587
+ this.webhooks = new Webhooks$1(this);
6588
+ this.webhookEvents = new WebhookEvents(this);
6589
+ this.usageEvents = new UsageEvents(this);
6590
+ this.meters = new Meters(this);
6591
+ if (bearerToken === undefined) {
6592
+ throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
6593
+ }
6594
+ const options = {
6595
+ bearerToken,
6596
+ webhookKey,
6597
+ ...opts,
6598
+ baseURL,
6599
+ environment: opts.environment ?? 'live_mode',
6600
+ };
6601
+ if (baseURL && opts.environment) {
6602
+ throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
6603
+ }
6604
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
6605
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
6606
+ this.logger = options.logger ?? console;
6607
+ const defaultLogLevel = 'warn';
6608
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
6609
+ this.logLevel = defaultLogLevel;
6610
+ this.logLevel =
6611
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
6612
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
6613
+ defaultLogLevel;
6614
+ this.fetchOptions = options.fetchOptions;
6615
+ this.maxRetries = options.maxRetries ?? 2;
6616
+ this.fetch = options.fetch ?? getDefaultFetch();
6617
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
6618
+ this._options = options;
6619
+ this.bearerToken = bearerToken;
6620
+ this.webhookKey = webhookKey;
6621
+ }
6622
+ /**
6623
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
6624
+ */
6625
+ withOptions(options) {
6626
+ const client = new this.constructor({
6627
+ ...this._options,
6628
+ environment: options.environment ? options.environment : undefined,
6629
+ baseURL: options.environment ? undefined : this.baseURL,
6630
+ maxRetries: this.maxRetries,
6631
+ timeout: this.timeout,
6632
+ logger: this.logger,
6633
+ logLevel: this.logLevel,
6634
+ fetch: this.fetch,
6635
+ fetchOptions: this.fetchOptions,
6636
+ bearerToken: this.bearerToken,
6637
+ webhookKey: this.webhookKey,
6638
+ ...options,
6639
+ });
6640
+ return client;
6641
+ }
6642
+ defaultQuery() {
6643
+ return this._options.defaultQuery;
6644
+ }
6645
+ validateHeaders({ values, nulls }) {
6646
+ return;
6647
+ }
6648
+ async authHeaders(opts) {
6649
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
6650
+ }
6651
+ /**
6652
+ * Basic re-implementation of `qs.stringify` for primitive types.
6653
+ */
6654
+ stringifyQuery(query) {
6655
+ return Object.entries(query)
6656
+ .filter(([_, value]) => typeof value !== 'undefined')
6657
+ .map(([key, value]) => {
6658
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
6659
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
6660
+ }
6661
+ if (value === null) {
6662
+ return `${encodeURIComponent(key)}=`;
6663
+ }
6664
+ throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
6665
+ })
6666
+ .join('&');
6667
+ }
6668
+ getUserAgent() {
6669
+ return `${this.constructor.name}/JS ${VERSION}`;
6670
+ }
6671
+ defaultIdempotencyKey() {
6672
+ return `stainless-node-retry-${uuid4()}`;
6673
+ }
6674
+ makeStatusError(status, error, message, headers) {
6675
+ return APIError.generate(status, error, message, headers);
6676
+ }
6677
+ buildURL(path, query, defaultBaseURL) {
6678
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
6679
+ const url = isAbsoluteURL(path) ?
6680
+ new URL(path)
6681
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
6682
+ const defaultQuery = this.defaultQuery();
6683
+ if (!isEmptyObj(defaultQuery)) {
6684
+ query = { ...defaultQuery, ...query };
6685
+ }
6686
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
6687
+ url.search = this.stringifyQuery(query);
6688
+ }
6689
+ return url.toString();
6690
+ }
6691
+ /**
6692
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
6693
+ */
6694
+ async prepareOptions(options) { }
6695
+ /**
6696
+ * Used as a callback for mutating the given `RequestInit` object.
6697
+ *
6698
+ * This is useful for cases where you want to add certain headers based off of
6699
+ * the request properties, e.g. `method` or `url`.
6700
+ */
6701
+ async prepareRequest(request, { url, options }) { }
6702
+ get(path, opts) {
6703
+ return this.methodRequest('get', path, opts);
6704
+ }
6705
+ post(path, opts) {
6706
+ return this.methodRequest('post', path, opts);
6707
+ }
6708
+ patch(path, opts) {
6709
+ return this.methodRequest('patch', path, opts);
6710
+ }
6711
+ put(path, opts) {
6712
+ return this.methodRequest('put', path, opts);
6713
+ }
6714
+ delete(path, opts) {
6715
+ return this.methodRequest('delete', path, opts);
6716
+ }
6717
+ methodRequest(method, path, opts) {
6718
+ return this.request(Promise.resolve(opts).then((opts) => {
6719
+ return { method, path, ...opts };
6720
+ }));
6721
+ }
6722
+ request(options, remainingRetries = null) {
6723
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
6724
+ }
6725
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
6726
+ const options = await optionsInput;
6727
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6728
+ if (retriesRemaining == null) {
6729
+ retriesRemaining = maxRetries;
6730
+ }
6731
+ await this.prepareOptions(options);
6732
+ const { req, url, timeout } = await this.buildRequest(options, {
6733
+ retryCount: maxRetries - retriesRemaining,
6734
+ });
6735
+ await this.prepareRequest(req, { url, options });
6736
+ /** Not an API request ID, just for correlating local log entries. */
6737
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
6738
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
6739
+ const startTime = Date.now();
6740
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
6741
+ retryOfRequestLogID,
6742
+ method: options.method,
6743
+ url,
6744
+ options,
6745
+ headers: req.headers,
6746
+ }));
6747
+ if (options.signal?.aborted) {
6748
+ throw new APIUserAbortError();
6749
+ }
6750
+ const controller = new AbortController();
6751
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
6752
+ const headersTime = Date.now();
6753
+ if (response instanceof globalThis.Error) {
6754
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6755
+ if (options.signal?.aborted) {
6756
+ throw new APIUserAbortError();
6757
+ }
6758
+ // detect native connection timeout errors
6759
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
6760
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
6761
+ // others do not provide enough information to distinguish timeouts from other connection errors
6762
+ const isTimeout = isAbortError(response) ||
6763
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
6764
+ if (retriesRemaining) {
6765
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
6766
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
6767
+ retryOfRequestLogID,
6768
+ url,
6769
+ durationMs: headersTime - startTime,
6770
+ message: response.message,
6771
+ }));
6772
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
6773
+ }
6774
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
6775
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
6776
+ retryOfRequestLogID,
6777
+ url,
6778
+ durationMs: headersTime - startTime,
6779
+ message: response.message,
6780
+ }));
6781
+ if (isTimeout) {
6782
+ throw new APIConnectionTimeoutError();
6783
+ }
6784
+ throw new APIConnectionError({ cause: response });
6785
+ }
6786
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
6787
+ if (!response.ok) {
6788
+ const shouldRetry = await this.shouldRetry(response);
6789
+ if (retriesRemaining && shouldRetry) {
6790
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6791
+ // We don't need the body of this response.
6792
+ await CancelReadableStream(response.body);
6793
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6794
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6795
+ retryOfRequestLogID,
6796
+ url: response.url,
6797
+ status: response.status,
6798
+ headers: response.headers,
6799
+ durationMs: headersTime - startTime,
6800
+ }));
6801
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6802
+ }
6803
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6804
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6805
+ const errText = await response.text().catch((err) => castToError(err).message);
6806
+ const errJSON = safeJSON(errText);
6807
+ const errMessage = errJSON ? undefined : errText;
6808
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6809
+ retryOfRequestLogID,
6810
+ url: response.url,
6811
+ status: response.status,
6812
+ headers: response.headers,
6813
+ message: errMessage,
6814
+ durationMs: Date.now() - startTime,
6815
+ }));
6816
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6817
+ throw err;
6818
+ }
6819
+ loggerFor(this).info(responseInfo);
6820
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6821
+ retryOfRequestLogID,
6822
+ url: response.url,
6823
+ status: response.status,
6824
+ headers: response.headers,
6825
+ durationMs: headersTime - startTime,
6826
+ }));
6827
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6828
+ }
6829
+ getAPIList(path, Page, opts) {
6830
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
6831
+ }
6832
+ requestAPIList(Page, options) {
6833
+ const request = this.makeRequest(options, null, undefined);
6834
+ return new PagePromise(this, request, Page);
6835
+ }
6836
+ async fetchWithTimeout(url, init, ms, controller) {
6837
+ const { signal, method, ...options } = init || {};
6838
+ if (signal)
6839
+ signal.addEventListener('abort', () => controller.abort());
6840
+ const timeout = setTimeout(() => controller.abort(), ms);
6841
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
6842
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
6843
+ const fetchOptions = {
6844
+ signal: controller.signal,
6845
+ ...(isReadableBody ? { duplex: 'half' } : {}),
6846
+ method: 'GET',
6847
+ ...options,
6848
+ };
6849
+ if (method) {
6850
+ // Custom methods like 'patch' need to be uppercased
6851
+ // See https://github.com/nodejs/undici/issues/2294
6852
+ fetchOptions.method = method.toUpperCase();
6853
+ }
6854
+ try {
6855
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
6856
+ return await this.fetch.call(undefined, url, fetchOptions);
6857
+ }
6858
+ finally {
6859
+ clearTimeout(timeout);
6860
+ }
6861
+ }
6862
+ async shouldRetry(response) {
6863
+ // Note this is not a standard header.
6864
+ const shouldRetryHeader = response.headers.get('x-should-retry');
6865
+ // If the server explicitly says whether or not to retry, obey.
6866
+ if (shouldRetryHeader === 'true')
6867
+ return true;
6868
+ if (shouldRetryHeader === 'false')
6869
+ return false;
6870
+ // Retry on request timeouts.
6871
+ if (response.status === 408)
6872
+ return true;
6873
+ // Retry on lock timeouts.
6874
+ if (response.status === 409)
6875
+ return true;
6876
+ // Retry on rate limits.
6877
+ if (response.status === 429)
6878
+ return true;
6879
+ // Retry internal errors.
6880
+ if (response.status >= 500)
6881
+ return true;
6882
+ return false;
6883
+ }
6884
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6885
+ let timeoutMillis;
6886
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6887
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6888
+ if (retryAfterMillisHeader) {
6889
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
6890
+ if (!Number.isNaN(timeoutMs)) {
6891
+ timeoutMillis = timeoutMs;
6892
+ }
6893
+ }
6894
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6895
+ const retryAfterHeader = responseHeaders?.get('retry-after');
6896
+ if (retryAfterHeader && !timeoutMillis) {
6897
+ const timeoutSeconds = parseFloat(retryAfterHeader);
6898
+ if (!Number.isNaN(timeoutSeconds)) {
6899
+ timeoutMillis = timeoutSeconds * 1000;
6900
+ }
6901
+ else {
6902
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
6903
+ }
6904
+ }
6905
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
6906
+ // just do what it says, but otherwise calculate a default
6907
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
6908
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6909
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6910
+ }
6911
+ await sleep(timeoutMillis);
6912
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6913
+ }
6914
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6915
+ const initialRetryDelay = 0.5;
6916
+ const maxRetryDelay = 8.0;
6917
+ const numRetries = maxRetries - retriesRemaining;
6918
+ // Apply exponential backoff, but not more than the max.
6919
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6920
+ // Apply some jitter, take up to at most 25 percent of the retry time.
6921
+ const jitter = 1 - Math.random() * 0.25;
6922
+ return sleepSeconds * jitter * 1000;
6923
+ }
6924
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6925
+ const options = { ...inputOptions };
6926
+ const { method, path, query, defaultBaseURL } = options;
6927
+ const url = this.buildURL(path, query, defaultBaseURL);
6928
+ if ('timeout' in options)
6929
+ validatePositiveInteger('timeout', options.timeout);
6930
+ options.timeout = options.timeout ?? this.timeout;
6931
+ const { bodyHeaders, body } = this.buildBody({ options });
6932
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6933
+ const req = {
6934
+ method,
6935
+ headers: reqHeaders,
6936
+ ...(options.signal && { signal: options.signal }),
6937
+ ...(globalThis.ReadableStream &&
6938
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
6939
+ ...(body && { body }),
6940
+ ...(this.fetchOptions ?? {}),
6941
+ ...(options.fetchOptions ?? {}),
6942
+ };
6943
+ return { req, url, timeout: options.timeout };
6944
+ }
6945
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
6946
+ let idempotencyHeaders = {};
6947
+ if (this.idempotencyHeader && method !== 'get') {
6948
+ if (!options.idempotencyKey)
6949
+ options.idempotencyKey = this.defaultIdempotencyKey();
6950
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6951
+ }
6952
+ const headers = buildHeaders([
6953
+ idempotencyHeaders,
6954
+ {
6955
+ Accept: 'application/json',
6956
+ 'User-Agent': this.getUserAgent(),
6957
+ 'X-Stainless-Retry-Count': String(retryCount),
6958
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
6959
+ ...getPlatformHeaders(),
6960
+ },
6961
+ await this.authHeaders(options),
6962
+ this._options.defaultHeaders,
6963
+ bodyHeaders,
6964
+ options.headers,
6965
+ ]);
6966
+ this.validateHeaders(headers);
6967
+ return headers.values;
6968
+ }
6969
+ buildBody({ options: { body, headers: rawHeaders } }) {
6970
+ if (!body) {
6971
+ return { bodyHeaders: undefined, body: undefined };
6972
+ }
6973
+ const headers = buildHeaders([rawHeaders]);
6974
+ if (
6975
+ // Pass raw type verbatim
6976
+ ArrayBuffer.isView(body) ||
6977
+ body instanceof ArrayBuffer ||
6978
+ body instanceof DataView ||
6979
+ (typeof body === 'string' &&
6980
+ // Preserve legacy string encoding behavior for now
6981
+ headers.values.has('content-type')) ||
6982
+ // `Blob` is superset of `File`
6983
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
6984
+ // `FormData` -> `multipart/form-data`
6985
+ body instanceof FormData ||
6986
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
6987
+ body instanceof URLSearchParams ||
6988
+ // Send chunked stream (each chunk has own `length`)
6989
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
6990
+ return { bodyHeaders: undefined, body: body };
6991
+ }
6992
+ else if (typeof body === 'object' &&
6993
+ (Symbol.asyncIterator in body ||
6994
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
6995
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6996
+ }
6997
+ else {
6998
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
6999
+ }
7000
+ }
7001
+ }
7002
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
7003
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
7004
+ };
7005
+ DodoPayments.DodoPayments = _a;
7006
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
7007
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
7008
+ DodoPayments.APIError = APIError;
7009
+ DodoPayments.APIConnectionError = APIConnectionError;
7010
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
7011
+ DodoPayments.APIUserAbortError = APIUserAbortError;
7012
+ DodoPayments.NotFoundError = NotFoundError;
7013
+ DodoPayments.ConflictError = ConflictError;
7014
+ DodoPayments.RateLimitError = RateLimitError;
7015
+ DodoPayments.BadRequestError = BadRequestError;
7016
+ DodoPayments.AuthenticationError = AuthenticationError;
7017
+ DodoPayments.InternalServerError = InternalServerError;
7018
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
7019
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
7020
+ DodoPayments.toFile = toFile;
7021
+ DodoPayments.CheckoutSessions = CheckoutSessions;
7022
+ DodoPayments.Payments = Payments;
7023
+ DodoPayments.Subscriptions = Subscriptions;
7024
+ DodoPayments.Invoices = Invoices;
7025
+ DodoPayments.Licenses = Licenses;
7026
+ DodoPayments.LicenseKeys = LicenseKeys;
7027
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
7028
+ DodoPayments.Customers = Customers;
7029
+ DodoPayments.Refunds = Refunds;
7030
+ DodoPayments.Disputes = Disputes;
7031
+ DodoPayments.Payouts = Payouts;
7032
+ DodoPayments.Products = Products;
7033
+ DodoPayments.Misc = Misc;
7034
+ DodoPayments.Discounts = Discounts;
7035
+ DodoPayments.Addons = Addons;
7036
+ DodoPayments.Brands = Brands;
7037
+ DodoPayments.Webhooks = Webhooks$1;
7038
+ DodoPayments.WebhookEvents = WebhookEvents;
7039
+ DodoPayments.UsageEvents = UsageEvents;
7040
+ DodoPayments.Meters = Meters;
7041
+
7042
+ // src/checkout/checkout.ts
7043
+ var checkoutQuerySchema = objectType({
7044
+ productId: stringType(),
7045
+ quantity: stringType().optional(),
7046
+ // Customer fields
7047
+ fullName: stringType().optional(),
7048
+ firstName: stringType().optional(),
7049
+ lastName: stringType().optional(),
7050
+ email: stringType().optional(),
7051
+ country: stringType().optional(),
7052
+ addressLine: stringType().optional(),
7053
+ city: stringType().optional(),
7054
+ state: stringType().optional(),
7055
+ zipCode: stringType().optional(),
7056
+ // Disable flags
7057
+ disableFullName: stringType().optional(),
7058
+ disableFirstName: stringType().optional(),
7059
+ disableLastName: stringType().optional(),
7060
+ disableEmail: stringType().optional(),
7061
+ disableCountry: stringType().optional(),
7062
+ disableAddressLine: stringType().optional(),
7063
+ disableCity: stringType().optional(),
7064
+ disableState: stringType().optional(),
7065
+ disableZipCode: stringType().optional(),
7066
+ // Advanced controls
7067
+ paymentCurrency: stringType().optional(),
7068
+ showCurrencySelector: stringType().optional(),
7069
+ paymentAmount: stringType().optional(),
7070
+ showDiscounts: stringType().optional()
7071
+ // Metadata (allow any key starting with metadata_)
7072
+ // We'll handle metadata separately in the handler
7073
+ }).catchall(unknownType());
7074
+ var dynamicCheckoutBodySchema = objectType({
7075
+ // For subscription
7076
+ product_id: stringType().optional(),
7077
+ quantity: numberType().optional(),
7078
+ // For one-time payment
7079
+ product_cart: arrayType(
7080
+ objectType({
7081
+ product_id: stringType(),
7082
+ quantity: numberType()
7083
+ })
7084
+ ).optional(),
7085
+ // Common fields
7086
+ billing: objectType({
7087
+ city: stringType(),
7088
+ country: stringType(),
7089
+ state: stringType(),
7090
+ street: stringType(),
7091
+ zipcode: stringType()
7092
+ }),
7093
+ customer: objectType({
7094
+ customer_id: stringType().optional(),
7095
+ email: stringType().optional(),
7096
+ name: stringType().optional()
7097
+ }),
7098
+ discount_id: stringType().optional(),
7099
+ addons: arrayType(
7100
+ objectType({
7101
+ addon_id: stringType(),
7102
+ quantity: numberType()
7103
+ })
7104
+ ).optional(),
7105
+ metadata: recordType(stringType(), stringType()).optional(),
7106
+ currency: stringType().optional()
7107
+ // Allow any additional fields (for future compatibility)
7108
+ }).catchall(unknownType());
7109
+ var checkoutSessionProductCartItemSchema = objectType({
7110
+ product_id: stringType().min(1, "Product ID is required"),
7111
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
7112
+ addons: arrayType(
7113
+ objectType({
7114
+ addon_id: stringType(),
7115
+ quantity: numberType().int().nonnegative()
7116
+ })
7117
+ ).optional(),
7118
+ amount: numberType().int().nonnegative(
7119
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
7120
+ ).optional()
7121
+ });
7122
+ var checkoutSessionCustomerSchema = unionType([
7123
+ objectType({
7124
+ email: stringType().email(),
7125
+ name: stringType().min(1).optional(),
7126
+ phone_number: stringType().optional()
7127
+ }),
7128
+ objectType({
7129
+ customer_id: stringType()
7130
+ })
7131
+ ]).optional();
7132
+ var checkoutSessionBillingAddressSchema = objectType({
7133
+ street: stringType().optional(),
7134
+ city: stringType().optional(),
7135
+ state: stringType().optional(),
7136
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
7137
+ zipcode: stringType().optional()
7138
+ }).optional();
7139
+ var paymentMethodTypeSchema = enumType([
7140
+ "credit",
7141
+ "debit",
7142
+ "upi_collect",
7143
+ "upi_intent",
7144
+ "apple_pay",
7145
+ "cashapp",
7146
+ "google_pay",
7147
+ "multibanco",
7148
+ "bancontact_card",
7149
+ "eps",
7150
+ "ideal",
7151
+ "przelewy24",
7152
+ "paypal",
7153
+ "affirm",
7154
+ "klarna",
7155
+ "sepa",
7156
+ "ach",
7157
+ "amazon_pay",
7158
+ "afterpay_clearpay"
7159
+ ]);
7160
+ var checkoutSessionCustomizationSchema = objectType({
7161
+ theme: enumType(["light", "dark", "system"]).optional(),
7162
+ show_order_details: booleanType().optional(),
7163
+ show_on_demand_tag: booleanType().optional(),
7164
+ force_language: stringType().optional()
7165
+ }).optional();
7166
+ var checkoutSessionFeatureFlagsSchema = objectType({
7167
+ allow_currency_selection: booleanType().optional(),
7168
+ allow_discount_code: booleanType().optional(),
7169
+ allow_phone_number_collection: booleanType().optional(),
7170
+ allow_tax_id: booleanType().optional(),
7171
+ always_create_new_customer: booleanType().optional()
7172
+ }).optional();
7173
+ var checkoutSessionOnDemandSchema = objectType({
7174
+ mandate_only: booleanType(),
7175
+ product_price: numberType().int().optional(),
7176
+ product_currency: stringType().length(3).optional(),
7177
+ product_description: stringType().optional(),
7178
+ adaptive_currency_fees_inclusive: booleanType().optional()
7179
+ }).optional();
7180
+ var checkoutSessionSubscriptionDataSchema = objectType({
7181
+ trial_period_days: numberType().int().nonnegative().optional(),
7182
+ on_demand: checkoutSessionOnDemandSchema
7183
+ }).optional();
7184
+ var checkoutSessionPayloadSchema = objectType({
7185
+ // Required fields
7186
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
7187
+ // Optional fields
7188
+ customer: checkoutSessionCustomerSchema,
7189
+ billing_address: checkoutSessionBillingAddressSchema,
7190
+ return_url: stringType().url().optional(),
7191
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
7192
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
7193
+ show_saved_payment_methods: booleanType().optional(),
7194
+ confirm: booleanType().optional(),
7195
+ discount_code: stringType().optional(),
7196
+ metadata: recordType(stringType(), stringType()).optional(),
7197
+ customization: checkoutSessionCustomizationSchema,
7198
+ feature_flags: checkoutSessionFeatureFlagsSchema,
7199
+ subscription_data: checkoutSessionSubscriptionDataSchema,
7200
+ force_3ds: booleanType().optional()
7201
+ });
7202
+ var checkoutSessionResponseSchema = objectType({
7203
+ session_id: stringType().min(1, "Session ID is required"),
7204
+ checkout_url: stringType().url("Invalid checkout URL")
7205
+ });
7206
+ var createCheckoutSession = async (payload, config) => {
7207
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
7208
+ if (!validation.success) {
7209
+ throw new Error(
7210
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7211
+ );
7212
+ }
7213
+ const dodopayments = new DodoPayments({
7214
+ bearerToken: config.bearerToken,
7215
+ environment: config.environment
7216
+ });
7217
+ try {
7218
+ const sdkPayload = {
7219
+ ...validation.data,
7220
+ ...validation.data.billing_address && {
7221
+ billing_address: {
7222
+ ...validation.data.billing_address,
7223
+ country: validation.data.billing_address.country
7224
+ }
7225
+ }
7226
+ };
7227
+ const session = await dodopayments.checkoutSessions.create(
7228
+ sdkPayload
7229
+ );
7230
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
7231
+ if (!responseValidation.success) {
7232
+ throw new Error(
7233
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7234
+ );
7235
+ }
7236
+ return responseValidation.data;
7237
+ } catch (error) {
7238
+ if (error instanceof Error) {
7239
+ console.error("Dodo Payments Checkout Session API Error:", {
7240
+ message: error.message,
7241
+ payload: validation.data,
7242
+ config: {
7243
+ environment: config.environment,
7244
+ hasBearerToken: !!config.bearerToken
7245
+ }
7246
+ });
7247
+ throw new Error(`Failed to create checkout session: ${error.message}`);
7248
+ }
7249
+ console.error("Unknown error creating checkout session:", error);
7250
+ throw new Error(
7251
+ "Failed to create checkout session due to an unknown error"
7252
+ );
7253
+ }
7254
+ };
7255
+ var buildCheckoutUrl = async ({
7256
+ queryParams,
7257
+ body,
7258
+ sessionPayload,
7259
+ returnUrl,
7260
+ bearerToken,
7261
+ environment,
7262
+ type = "static"
7263
+ }) => {
7264
+ if (type === "session") {
7265
+ if (!sessionPayload) {
7266
+ throw new Error("sessionPayload is required when type is 'session'");
7267
+ }
7268
+ const session = await createCheckoutSession(sessionPayload, {
7269
+ bearerToken,
7270
+ environment
7271
+ });
7272
+ return session.checkout_url;
7273
+ }
7274
+ const inputData = type === "dynamic" ? body : queryParams;
7275
+ let parseResult;
7276
+ if (type === "dynamic") {
7277
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
7278
+ } else {
7279
+ parseResult = checkoutQuerySchema.safeParse(inputData);
7280
+ }
7281
+ const { success, data, error } = parseResult;
7282
+ if (!success) {
7283
+ throw new Error(
7284
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
7285
+ ${error.message}`
7286
+ );
7287
+ }
7288
+ if (type !== "dynamic") {
7289
+ const {
7290
+ productId,
7291
+ quantity: quantity2,
7292
+ fullName,
7293
+ firstName,
7294
+ lastName,
7295
+ email,
7296
+ country,
7297
+ addressLine,
7298
+ city,
7299
+ state,
7300
+ zipCode,
7301
+ disableFullName,
7302
+ disableFirstName,
7303
+ disableLastName,
7304
+ disableEmail,
7305
+ disableCountry,
7306
+ disableAddressLine,
7307
+ disableCity,
7308
+ disableState,
7309
+ disableZipCode,
7310
+ paymentCurrency,
7311
+ showCurrencySelector,
7312
+ paymentAmount,
7313
+ showDiscounts
7314
+ // metadata handled below
7315
+ } = data;
7316
+ const dodopayments2 = new DodoPayments({
7317
+ bearerToken,
7318
+ environment
7319
+ });
7320
+ if (!productId) throw new Error("Missing required field: productId");
7321
+ try {
7322
+ await dodopayments2.products.retrieve(productId);
7323
+ } catch (err) {
7324
+ console.error(err);
7325
+ throw new Error("Product not found");
7326
+ }
7327
+ const url = new URL(
7328
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
7329
+ );
7330
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
7331
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
7332
+ if (fullName) url.searchParams.set("fullName", String(fullName));
7333
+ if (firstName) url.searchParams.set("firstName", String(firstName));
7334
+ if (lastName) url.searchParams.set("lastName", String(lastName));
7335
+ if (email) url.searchParams.set("email", String(email));
7336
+ if (country) url.searchParams.set("country", String(country));
7337
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
7338
+ if (city) url.searchParams.set("city", String(city));
7339
+ if (state) url.searchParams.set("state", String(state));
7340
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
7341
+ if (disableFullName === "true")
7342
+ url.searchParams.set("disableFullName", "true");
7343
+ if (disableFirstName === "true")
7344
+ url.searchParams.set("disableFirstName", "true");
7345
+ if (disableLastName === "true")
7346
+ url.searchParams.set("disableLastName", "true");
7347
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
7348
+ if (disableCountry === "true")
7349
+ url.searchParams.set("disableCountry", "true");
7350
+ if (disableAddressLine === "true")
7351
+ url.searchParams.set("disableAddressLine", "true");
7352
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
7353
+ if (disableState === "true") url.searchParams.set("disableState", "true");
7354
+ if (disableZipCode === "true")
7355
+ url.searchParams.set("disableZipCode", "true");
7356
+ if (paymentCurrency)
7357
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
7358
+ if (showCurrencySelector)
7359
+ url.searchParams.set(
7360
+ "showCurrencySelector",
7361
+ String(showCurrencySelector)
7362
+ );
7363
+ if (paymentAmount)
7364
+ url.searchParams.set("paymentAmount", String(paymentAmount));
7365
+ if (showDiscounts)
7366
+ url.searchParams.set("showDiscounts", String(showDiscounts));
7367
+ for (const [key, value] of Object.entries(queryParams || {})) {
7368
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
7369
+ url.searchParams.set(key, String(value));
7370
+ }
7371
+ }
7372
+ return url.toString();
7373
+ }
7374
+ const dyn = data;
7375
+ const {
7376
+ product_id,
7377
+ product_cart,
7378
+ quantity,
7379
+ billing,
7380
+ customer,
7381
+ addons,
7382
+ metadata,
7383
+ allowed_payment_method_types,
7384
+ billing_currency,
7385
+ discount_code,
7386
+ on_demand,
7387
+ return_url: bodyReturnUrl,
7388
+ show_saved_payment_methods,
7389
+ tax_id,
7390
+ trial_period_days
7391
+ } = dyn;
7392
+ const dodopayments = new DodoPayments({
7393
+ bearerToken,
7394
+ environment
7395
+ });
7396
+ let isSubscription = false;
7397
+ let productIdToFetch = product_id;
7398
+ if (!product_id && product_cart && product_cart.length > 0) {
7399
+ productIdToFetch = product_cart[0].product_id;
7400
+ }
7401
+ if (!productIdToFetch)
7402
+ throw new Error(
7403
+ "Missing required field: product_id or product_cart[0].product_id"
7404
+ );
7405
+ let product;
7406
+ try {
7407
+ product = await dodopayments.products.retrieve(productIdToFetch);
7408
+ } catch (err) {
7409
+ console.error(err);
7410
+ throw new Error("Product not found");
7411
+ }
7412
+ isSubscription = Boolean(product.is_recurring);
7413
+ if (isSubscription && !product_id)
7414
+ throw new Error("Missing required field: product_id for subscription");
7415
+ if (!billing) throw new Error("Missing required field: billing");
7416
+ if (!customer) throw new Error("Missing required field: customer");
7417
+ if (isSubscription) {
7418
+ const subscriptionPayload = {
7419
+ billing,
7420
+ customer,
7421
+ product_id,
7422
+ quantity: quantity ? Number(quantity) : 1
7423
+ };
7424
+ if (metadata) subscriptionPayload.metadata = metadata;
7425
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
7426
+ if (addons) subscriptionPayload.addons = addons;
7427
+ if (allowed_payment_method_types)
7428
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
7429
+ if (billing_currency)
7430
+ subscriptionPayload.billing_currency = billing_currency;
7431
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
7432
+ subscriptionPayload.payment_link = true;
7433
+ if (bodyReturnUrl) {
7434
+ subscriptionPayload.return_url = bodyReturnUrl;
7435
+ } else if (returnUrl) {
7436
+ subscriptionPayload.return_url = returnUrl;
7437
+ }
7438
+ if (show_saved_payment_methods)
7439
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
7440
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
7441
+ if (trial_period_days)
7442
+ subscriptionPayload.trial_period_days = trial_period_days;
7443
+ let subscription;
7444
+ try {
7445
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
7446
+ } catch (err) {
7447
+ console.error("Error when creating subscription", err);
7448
+ throw new Error(err instanceof Error ? err.message : String(err));
7473
7449
  }
7474
- }
7475
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
7476
- class Webhook {
7477
- constructor(secret, options) {
7478
- if (!secret) {
7479
- throw new Error("Secret can't be empty.");
7450
+ if (!subscription || !subscription.payment_link) {
7451
+ throw new Error(
7452
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
7453
+ );
7454
+ }
7455
+ return subscription.payment_link;
7456
+ } else {
7457
+ let cart = product_cart;
7458
+ if (!cart && product_id) {
7459
+ cart = [
7460
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
7461
+ ];
7462
+ }
7463
+ if (!cart || cart.length === 0)
7464
+ throw new Error("Missing required field: product_cart or product_id");
7465
+ const paymentPayload = {
7466
+ billing,
7467
+ customer,
7468
+ product_cart: cart
7469
+ };
7470
+ if (metadata) paymentPayload.metadata = metadata;
7471
+ paymentPayload.payment_link = true;
7472
+ if (allowed_payment_method_types)
7473
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
7474
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
7475
+ if (discount_code) paymentPayload.discount_code = discount_code;
7476
+ if (bodyReturnUrl) {
7477
+ paymentPayload.return_url = bodyReturnUrl;
7478
+ } else if (returnUrl) {
7479
+ paymentPayload.return_url = returnUrl;
7480
+ }
7481
+ if (show_saved_payment_methods)
7482
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
7483
+ if (tax_id) paymentPayload.tax_id = tax_id;
7484
+ let payment;
7485
+ try {
7486
+ payment = await dodopayments.payments.create(paymentPayload);
7487
+ } catch (err) {
7488
+ console.error("Error when creating payment link", err);
7489
+ throw new Error(err instanceof Error ? err.message : String(err));
7490
+ }
7491
+ if (!payment || !payment.payment_link) {
7492
+ throw new Error(
7493
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
7494
+ );
7495
+ }
7496
+ return payment.payment_link;
7497
+ }
7498
+ };
7499
+
7500
+ function checkoutHandler(config) {
7501
+ const getHandler = async (req, res) => {
7502
+ const queryParams = req.query;
7503
+ if (!queryParams.productId) {
7504
+ return res.status(400).send("Please provide productId query parameter");
7480
7505
  }
7481
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
7482
- if (secret instanceof Uint8Array) {
7483
- this.key = secret;
7484
- }
7485
- else {
7486
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
7506
+ const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
7507
+ if (!success) {
7508
+ if (error.errors.some((e) => e.path.toString() === "productId")) {
7509
+ return res.status(400).send("Please provide productId query parameter");
7487
7510
  }
7511
+ return res
7512
+ .status(400)
7513
+ .send(`Invalid query parameters.\n ${error.message}`);
7488
7514
  }
7489
- else {
7490
- if (typeof secret !== "string") {
7491
- throw new Error("Expected secret to be of type string");
7492
- }
7493
- if (secret.startsWith(Webhook.prefix)) {
7494
- secret = secret.substring(Webhook.prefix.length);
7495
- }
7496
- this.key = base64.decode(secret);
7515
+ let url = "";
7516
+ try {
7517
+ url = await buildCheckoutUrl({ queryParams: data, ...config });
7497
7518
  }
7498
- }
7499
- verify(payload, headers_) {
7500
- const headers = {};
7501
- for (const key of Object.keys(headers_)) {
7502
- headers[key.toLowerCase()] = headers_[key];
7519
+ catch (error) {
7520
+ return res.status(400).send(error.message);
7503
7521
  }
7504
- const msgId = headers["webhook-id"];
7505
- const msgSignature = headers["webhook-signature"];
7506
- const msgTimestamp = headers["webhook-timestamp"];
7507
- if (!msgSignature || !msgId || !msgTimestamp) {
7508
- throw new WebhookVerificationError("Missing required headers");
7522
+ return res.json({ checkout_url: url });
7523
+ };
7524
+ const postHandler = async (req, res) => {
7525
+ if (config.type === "dynamic") {
7526
+ // Handle dynamic checkout
7527
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(req.body);
7528
+ if (!success) {
7529
+ return res.status(400).send(`Invalid request body.\n ${error.message}`);
7530
+ }
7531
+ let url = "";
7532
+ try {
7533
+ url = await buildCheckoutUrl({
7534
+ body: data,
7535
+ ...config,
7536
+ type: "dynamic",
7537
+ });
7538
+ }
7539
+ catch (error) {
7540
+ return res.status(400).send(error.message);
7541
+ }
7542
+ return res.json({ checkout_url: url });
7509
7543
  }
7510
- const timestamp = this.verifyTimestamp(msgTimestamp);
7511
- const computedSignature = this.sign(msgId, timestamp, payload);
7512
- const expectedSignature = computedSignature.split(",")[1];
7513
- const passedSignatures = msgSignature.split(" ");
7514
- const encoder = new globalThis.TextEncoder();
7515
- for (const versionedSignature of passedSignatures) {
7516
- const [version, signature] = versionedSignature.split(",");
7517
- if (version !== "v1") {
7518
- continue;
7544
+ else {
7545
+ // Handle checkout session
7546
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(req.body);
7547
+ if (!success) {
7548
+ return res
7549
+ .status(400)
7550
+ .send(`Invalid checkout session payload.\n ${error.message}`);
7519
7551
  }
7520
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
7521
- return JSON.parse(payload.toString());
7552
+ let url = "";
7553
+ try {
7554
+ url = await buildCheckoutUrl({
7555
+ sessionPayload: data,
7556
+ ...config,
7557
+ type: "session",
7558
+ });
7559
+ }
7560
+ catch (error) {
7561
+ return res.status(400).send(error.message);
7522
7562
  }
7563
+ return res.json({ checkout_url: url });
7523
7564
  }
7524
- throw new WebhookVerificationError("No matching signature found");
7525
- }
7526
- sign(msgId, timestamp, payload) {
7527
- if (typeof payload === "string") ;
7528
- else if (payload.constructor.name === "Buffer") {
7529
- payload = payload.toString();
7565
+ };
7566
+ return (req, res) => {
7567
+ if (req.method === "POST") {
7568
+ return postHandler(req, res);
7530
7569
  }
7531
- else {
7532
- throw new Error("Expected payload to be of type string or Buffer.");
7570
+ if (req.method === "GET") {
7571
+ return getHandler(req, res);
7533
7572
  }
7534
- const encoder = new TextEncoder();
7535
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
7536
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
7537
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
7538
- return `v1,${expectedSignature}`;
7539
- }
7540
- verifyTimestamp(timestampHeader) {
7541
- const now = Math.floor(Date.now() / 1000);
7542
- const timestamp = parseInt(timestampHeader, 10);
7543
- if (isNaN(timestamp)) {
7544
- throw new WebhookVerificationError("Invalid Signature Headers");
7573
+ return res.status(405).send("Method Not Allowed");
7574
+ };
7575
+ }
7576
+
7577
+ const CustomerPortal = ({ bearerToken, environment, }) => {
7578
+ const getHandler = async (req, res) => {
7579
+ // Extract customerId from query parameters
7580
+ const { customer_id: customerId, send_email } = req.query;
7581
+ const params = {
7582
+ send_email: false,
7583
+ };
7584
+ const sendEmail = Boolean(send_email);
7585
+ if (sendEmail) {
7586
+ params.send_email = sendEmail;
7545
7587
  }
7546
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
7547
- throw new WebhookVerificationError("Message timestamp too old");
7588
+ if (!customerId) {
7589
+ return res.status(400).send("Missing customerId in query parameters");
7548
7590
  }
7549
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
7550
- throw new WebhookVerificationError("Message timestamp too new");
7591
+ const dodopayments = new DodoPayments({
7592
+ bearerToken,
7593
+ environment,
7594
+ });
7595
+ try {
7596
+ const session = await dodopayments.customers.customerPortal.create(customerId, params);
7597
+ return res.redirect(session.link);
7551
7598
  }
7552
- return new Date(timestamp * 1000);
7553
- }
7554
- }
7555
- Webhook_1 = dist.Webhook = Webhook;
7556
- Webhook.prefix = "whsec_";
7599
+ catch (error) {
7600
+ console.error("Error creating customer portal session:", error);
7601
+ return res
7602
+ .status(500)
7603
+ .send(`Failed to create customer portal session: ${error.message}`);
7604
+ }
7605
+ };
7606
+ return getHandler;
7607
+ };
7557
7608
 
7558
7609
  // src/schemas/webhook.ts
7559
7610
  var PaymentSchema = objectType({