@dodopayments/fastify 0.2.1 → 0.2.3

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