@dodopayments/nextjs 0.3.0 → 0.3.1

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
@@ -9342,7 +9342,7 @@ const unknownType = ZodUnknown.create;
9342
9342
  ZodNever.create;
9343
9343
  const arrayType = ZodArray.create;
9344
9344
  const objectType = ZodObject.create;
9345
- ZodUnion.create;
9345
+ const unionType = ZodUnion.create;
9346
9346
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
9347
9347
  ZodIntersection.create;
9348
9348
  ZodTuple.create;
@@ -9561,7 +9561,7 @@ const safeJSON = (text) => {
9561
9561
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9562
9562
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9563
9563
 
9564
- const VERSION = '2.2.0'; // x-release-please-version
9564
+ const VERSION = '2.4.6'; // x-release-please-version
9565
9565
 
9566
9566
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9567
9567
  /**
@@ -10311,6 +10311,9 @@ class CheckoutSessions extends APIResource {
10311
10311
  create(body, options) {
10312
10312
  return this._client.post('/checkouts', { body, ...options });
10313
10313
  }
10314
+ retrieve(id, options) {
10315
+ return this._client.get(path `/checkouts/${id}`, options);
10316
+ }
10314
10317
  }
10315
10318
 
10316
10319
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -10989,1398 +10992,323 @@ let Headers$1 = class Headers extends APIResource {
10989
10992
  }
10990
10993
  };
10991
10994
 
10992
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
10993
- let Webhooks$1 = class Webhooks extends APIResource {
10994
- constructor() {
10995
- super(...arguments);
10996
- this.headers = new Headers$1(this._client);
10997
- }
10998
- /**
10999
- * Create a new webhook
11000
- */
11001
- create(body, options) {
11002
- return this._client.post('/webhooks', { body, ...options });
11003
- }
11004
- /**
11005
- * Get a webhook by id
11006
- */
11007
- retrieve(webhookID, options) {
11008
- return this._client.get(path `/webhooks/${webhookID}`, options);
10995
+ var dist = {};
10996
+
10997
+ var timing_safe_equal = {};
10998
+
10999
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
11000
+ timing_safe_equal.timingSafeEqual = void 0;
11001
+ function assert(expr, msg = "") {
11002
+ if (!expr) {
11003
+ throw new Error(msg);
11009
11004
  }
11010
- /**
11011
- * Patch a webhook by id
11012
- */
11013
- update(webhookID, body, options) {
11014
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11005
+ }
11006
+ function timingSafeEqual(a, b) {
11007
+ if (a.byteLength !== b.byteLength) {
11008
+ return false;
11015
11009
  }
11016
- /**
11017
- * List all webhooks
11018
- */
11019
- list(query = {}, options) {
11020
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11010
+ if (!(a instanceof DataView)) {
11011
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
11021
11012
  }
11022
- /**
11023
- * Delete a webhook by id
11024
- */
11025
- delete(webhookID, options) {
11026
- return this._client.delete(path `/webhooks/${webhookID}`, {
11027
- ...options,
11028
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
11029
- });
11013
+ if (!(b instanceof DataView)) {
11014
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
11030
11015
  }
11031
- /**
11032
- * Get webhook secret by id
11033
- */
11034
- retrieveSecret(webhookID, options) {
11035
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11016
+ assert(a instanceof DataView);
11017
+ assert(b instanceof DataView);
11018
+ const length = a.byteLength;
11019
+ let out = 0;
11020
+ let i = -1;
11021
+ while (++i < length) {
11022
+ out |= a.getUint8(i) ^ b.getUint8(i);
11036
11023
  }
11037
- };
11038
- Webhooks$1.Headers = Headers$1;
11024
+ return out === 0;
11025
+ }
11026
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
11039
11027
 
11040
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11028
+ var base64$1 = {};
11029
+
11030
+ // Copyright (C) 2016 Dmitry Chestnykh
11031
+ // MIT License. See LICENSE file for details.
11032
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
11033
+ var extendStatics = function (d, b) {
11034
+ extendStatics = Object.setPrototypeOf ||
11035
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11036
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11037
+ return extendStatics(d, b);
11038
+ };
11039
+ return function (d, b) {
11040
+ extendStatics(d, b);
11041
+ function __() { this.constructor = d; }
11042
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11043
+ };
11044
+ })();
11045
+ Object.defineProperty(base64$1, "__esModule", { value: true });
11041
11046
  /**
11042
- * Read an environment variable.
11043
- *
11044
- * Trims beginning and trailing whitespace.
11045
- *
11046
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11047
+ * Package base64 implements Base64 encoding and decoding.
11047
11048
  */
11048
- const readEnv = (env) => {
11049
- if (typeof globalThis.process !== 'undefined') {
11050
- return globalThis.process.env?.[env]?.trim() ?? undefined;
11051
- }
11052
- if (typeof globalThis.Deno !== 'undefined') {
11053
- return globalThis.Deno.env?.get?.(env)?.trim();
11054
- }
11055
- return undefined;
11056
- };
11057
-
11058
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11059
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11060
- const environments = {
11061
- live_mode: 'https://live.dodopayments.com',
11062
- test_mode: 'https://test.dodopayments.com',
11063
- };
11049
+ // Invalid character used in decoding to indicate
11050
+ // that the character to decode is out of range of
11051
+ // alphabet and cannot be decoded.
11052
+ var INVALID_BYTE = 256;
11064
11053
  /**
11065
- * API Client for interfacing with the Dodo Payments API.
11054
+ * Implements standard Base64 encoding.
11055
+ *
11056
+ * Operates in constant time.
11066
11057
  */
11067
- class DodoPayments {
11068
- /**
11069
- * API Client for interfacing with the Dodo Payments API.
11070
- *
11071
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11072
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11073
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11074
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11075
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11076
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11077
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11078
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11079
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11080
- */
11081
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
11082
- _DodoPayments_instances.add(this);
11083
- _DodoPayments_encoder.set(this, void 0);
11084
- this.checkoutSessions = new CheckoutSessions(this);
11085
- this.payments = new Payments(this);
11086
- this.subscriptions = new Subscriptions(this);
11087
- this.invoices = new Invoices(this);
11088
- this.licenses = new Licenses(this);
11089
- this.licenseKeys = new LicenseKeys(this);
11090
- this.licenseKeyInstances = new LicenseKeyInstances(this);
11091
- this.customers = new Customers(this);
11092
- this.refunds = new Refunds(this);
11093
- this.disputes = new Disputes(this);
11094
- this.payouts = new Payouts(this);
11095
- this.webhookEvents = new WebhookEvents(this);
11096
- this.products = new Products(this);
11097
- this.misc = new Misc(this);
11098
- this.discounts = new Discounts(this);
11099
- this.addons = new Addons(this);
11100
- this.brands = new Brands(this);
11101
- this.webhooks = new Webhooks$1(this);
11102
- this.usageEvents = new UsageEvents(this);
11103
- this.meters = new Meters(this);
11104
- if (bearerToken === undefined) {
11105
- 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' }).");
11058
+ var Coder = /** @class */ (function () {
11059
+ // TODO(dchest): methods to encode chunk-by-chunk.
11060
+ function Coder(_paddingCharacter) {
11061
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
11062
+ this._paddingCharacter = _paddingCharacter;
11063
+ }
11064
+ Coder.prototype.encodedLength = function (length) {
11065
+ if (!this._paddingCharacter) {
11066
+ return (length * 8 + 5) / 6 | 0;
11106
11067
  }
11107
- const options = {
11108
- bearerToken,
11109
- ...opts,
11110
- baseURL,
11111
- environment: opts.environment ?? 'live_mode',
11112
- };
11113
- if (baseURL && opts.environment) {
11114
- 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');
11068
+ return (length + 2) / 3 * 4 | 0;
11069
+ };
11070
+ Coder.prototype.encode = function (data) {
11071
+ var out = "";
11072
+ var i = 0;
11073
+ for (; i < data.length - 2; i += 3) {
11074
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
11075
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11076
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11077
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11078
+ out += this._encodeByte((c >>> 0 * 6) & 63);
11115
11079
  }
11116
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11117
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11118
- this.logger = options.logger ?? console;
11119
- const defaultLogLevel = 'warn';
11120
- // Set default logLevel early so that we can log a warning in parseLogLevel.
11121
- this.logLevel = defaultLogLevel;
11122
- this.logLevel =
11123
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11124
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11125
- defaultLogLevel;
11126
- this.fetchOptions = options.fetchOptions;
11127
- this.maxRetries = options.maxRetries ?? 2;
11128
- this.fetch = options.fetch ?? getDefaultFetch();
11129
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11130
- this._options = options;
11131
- this.bearerToken = bearerToken;
11132
- }
11133
- /**
11134
- * Create a new client instance re-using the same options given to the current client with optional overriding.
11135
- */
11136
- withOptions(options) {
11137
- const client = new this.constructor({
11138
- ...this._options,
11139
- environment: options.environment ? options.environment : undefined,
11140
- baseURL: options.environment ? undefined : this.baseURL,
11141
- maxRetries: this.maxRetries,
11142
- timeout: this.timeout,
11143
- logger: this.logger,
11144
- logLevel: this.logLevel,
11145
- fetch: this.fetch,
11146
- fetchOptions: this.fetchOptions,
11147
- bearerToken: this.bearerToken,
11148
- ...options,
11149
- });
11150
- return client;
11151
- }
11152
- defaultQuery() {
11153
- return this._options.defaultQuery;
11154
- }
11155
- validateHeaders({ values, nulls }) {
11156
- return;
11157
- }
11158
- async authHeaders(opts) {
11159
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
11160
- }
11161
- /**
11162
- * Basic re-implementation of `qs.stringify` for primitive types.
11163
- */
11164
- stringifyQuery(query) {
11165
- return Object.entries(query)
11166
- .filter(([_, value]) => typeof value !== 'undefined')
11167
- .map(([key, value]) => {
11168
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
11169
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
11080
+ var left = data.length - i;
11081
+ if (left > 0) {
11082
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
11083
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11084
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11085
+ if (left === 2) {
11086
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11170
11087
  }
11171
- if (value === null) {
11172
- return `${encodeURIComponent(key)}=`;
11088
+ else {
11089
+ out += this._paddingCharacter || "";
11173
11090
  }
11174
- 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.`);
11175
- })
11176
- .join('&');
11177
- }
11178
- getUserAgent() {
11179
- return `${this.constructor.name}/JS ${VERSION}`;
11180
- }
11181
- defaultIdempotencyKey() {
11182
- return `stainless-node-retry-${uuid4()}`;
11183
- }
11184
- makeStatusError(status, error, message, headers) {
11185
- return APIError.generate(status, error, message, headers);
11186
- }
11187
- buildURL(path, query, defaultBaseURL) {
11188
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
11189
- const url = isAbsoluteURL(path) ?
11190
- new URL(path)
11191
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
11192
- const defaultQuery = this.defaultQuery();
11193
- if (!isEmptyObj(defaultQuery)) {
11194
- query = { ...defaultQuery, ...query };
11195
- }
11196
- if (typeof query === 'object' && query && !Array.isArray(query)) {
11197
- url.search = this.stringifyQuery(query);
11091
+ out += this._paddingCharacter || "";
11198
11092
  }
11199
- return url.toString();
11200
- }
11201
- /**
11202
- * Used as a callback for mutating the given `FinalRequestOptions` object.
11203
- */
11204
- async prepareOptions(options) { }
11205
- /**
11206
- * Used as a callback for mutating the given `RequestInit` object.
11207
- *
11208
- * This is useful for cases where you want to add certain headers based off of
11209
- * the request properties, e.g. `method` or `url`.
11210
- */
11211
- async prepareRequest(request, { url, options }) { }
11212
- get(path, opts) {
11213
- return this.methodRequest('get', path, opts);
11214
- }
11215
- post(path, opts) {
11216
- return this.methodRequest('post', path, opts);
11217
- }
11218
- patch(path, opts) {
11219
- return this.methodRequest('patch', path, opts);
11220
- }
11221
- put(path, opts) {
11222
- return this.methodRequest('put', path, opts);
11223
- }
11224
- delete(path, opts) {
11225
- return this.methodRequest('delete', path, opts);
11226
- }
11227
- methodRequest(method, path, opts) {
11228
- return this.request(Promise.resolve(opts).then((opts) => {
11229
- return { method, path, ...opts };
11230
- }));
11231
- }
11232
- request(options, remainingRetries = null) {
11233
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
11234
- }
11235
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
11236
- const options = await optionsInput;
11237
- const maxRetries = options.maxRetries ?? this.maxRetries;
11238
- if (retriesRemaining == null) {
11239
- retriesRemaining = maxRetries;
11093
+ return out;
11094
+ };
11095
+ Coder.prototype.maxDecodedLength = function (length) {
11096
+ if (!this._paddingCharacter) {
11097
+ return (length * 6 + 7) / 8 | 0;
11240
11098
  }
11241
- await this.prepareOptions(options);
11242
- const { req, url, timeout } = await this.buildRequest(options, {
11243
- retryCount: maxRetries - retriesRemaining,
11244
- });
11245
- await this.prepareRequest(req, { url, options });
11246
- /** Not an API request ID, just for correlating local log entries. */
11247
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
11248
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
11249
- const startTime = Date.now();
11250
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
11251
- retryOfRequestLogID,
11252
- method: options.method,
11253
- url,
11254
- options,
11255
- headers: req.headers,
11256
- }));
11257
- if (options.signal?.aborted) {
11258
- throw new APIUserAbortError();
11099
+ return length / 4 * 3 | 0;
11100
+ };
11101
+ Coder.prototype.decodedLength = function (s) {
11102
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
11103
+ };
11104
+ Coder.prototype.decode = function (s) {
11105
+ if (s.length === 0) {
11106
+ return new Uint8Array(0);
11259
11107
  }
11260
- const controller = new AbortController();
11261
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
11262
- const headersTime = Date.now();
11263
- if (response instanceof globalThis.Error) {
11264
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11265
- if (options.signal?.aborted) {
11266
- throw new APIUserAbortError();
11267
- }
11268
- // detect native connection timeout errors
11269
- // 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)"
11270
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
11271
- // others do not provide enough information to distinguish timeouts from other connection errors
11272
- const isTimeout = isAbortError(response) ||
11273
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
11274
- if (retriesRemaining) {
11275
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
11276
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
11277
- retryOfRequestLogID,
11278
- url,
11279
- durationMs: headersTime - startTime,
11280
- message: response.message,
11281
- }));
11282
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
11283
- }
11284
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
11285
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
11286
- retryOfRequestLogID,
11287
- url,
11288
- durationMs: headersTime - startTime,
11289
- message: response.message,
11290
- }));
11291
- if (isTimeout) {
11292
- throw new APIConnectionTimeoutError();
11293
- }
11294
- throw new APIConnectionError({ cause: response });
11108
+ var paddingLength = this._getPaddingLength(s);
11109
+ var length = s.length - paddingLength;
11110
+ var out = new Uint8Array(this.maxDecodedLength(length));
11111
+ var op = 0;
11112
+ var i = 0;
11113
+ var haveBad = 0;
11114
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
11115
+ for (; i < length - 4; i += 4) {
11116
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
11117
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11118
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11119
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11120
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11121
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11122
+ out[op++] = (v2 << 6) | v3;
11123
+ haveBad |= v0 & INVALID_BYTE;
11124
+ haveBad |= v1 & INVALID_BYTE;
11125
+ haveBad |= v2 & INVALID_BYTE;
11126
+ haveBad |= v3 & INVALID_BYTE;
11295
11127
  }
11296
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
11297
- if (!response.ok) {
11298
- const shouldRetry = await this.shouldRetry(response);
11299
- if (retriesRemaining && shouldRetry) {
11300
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11301
- // We don't need the body of this response.
11302
- await CancelReadableStream(response.body);
11303
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11304
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11305
- retryOfRequestLogID,
11306
- url: response.url,
11307
- status: response.status,
11308
- headers: response.headers,
11309
- durationMs: headersTime - startTime,
11310
- }));
11311
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
11312
- }
11313
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
11314
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11315
- const errText = await response.text().catch((err) => castToError(err).message);
11316
- const errJSON = safeJSON(errText);
11317
- const errMessage = errJSON ? undefined : errText;
11318
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11319
- retryOfRequestLogID,
11320
- url: response.url,
11321
- status: response.status,
11322
- headers: response.headers,
11323
- message: errMessage,
11324
- durationMs: Date.now() - startTime,
11325
- }));
11326
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
11327
- throw err;
11128
+ if (i < length - 1) {
11129
+ v0 = this._decodeChar(s.charCodeAt(i));
11130
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11131
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11132
+ haveBad |= v0 & INVALID_BYTE;
11133
+ haveBad |= v1 & INVALID_BYTE;
11328
11134
  }
11329
- loggerFor(this).info(responseInfo);
11330
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
11331
- retryOfRequestLogID,
11332
- url: response.url,
11333
- status: response.status,
11334
- headers: response.headers,
11335
- durationMs: headersTime - startTime,
11336
- }));
11337
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
11338
- }
11339
- getAPIList(path, Page, opts) {
11340
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
11341
- }
11342
- requestAPIList(Page, options) {
11343
- const request = this.makeRequest(options, null, undefined);
11344
- return new PagePromise(this, request, Page);
11345
- }
11346
- async fetchWithTimeout(url, init, ms, controller) {
11347
- const { signal, method, ...options } = init || {};
11348
- if (signal)
11349
- signal.addEventListener('abort', () => controller.abort());
11350
- const timeout = setTimeout(() => controller.abort(), ms);
11351
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
11352
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
11353
- const fetchOptions = {
11354
- signal: controller.signal,
11355
- ...(isReadableBody ? { duplex: 'half' } : {}),
11356
- method: 'GET',
11357
- ...options,
11358
- };
11359
- if (method) {
11360
- // Custom methods like 'patch' need to be uppercased
11361
- // See https://github.com/nodejs/undici/issues/2294
11362
- fetchOptions.method = method.toUpperCase();
11135
+ if (i < length - 2) {
11136
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11137
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11138
+ haveBad |= v2 & INVALID_BYTE;
11363
11139
  }
11364
- try {
11365
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
11366
- return await this.fetch.call(undefined, url, fetchOptions);
11140
+ if (i < length - 3) {
11141
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11142
+ out[op++] = (v2 << 6) | v3;
11143
+ haveBad |= v3 & INVALID_BYTE;
11367
11144
  }
11368
- finally {
11369
- clearTimeout(timeout);
11145
+ if (haveBad !== 0) {
11146
+ throw new Error("Base64Coder: incorrect characters for decoding");
11370
11147
  }
11371
- }
11372
- async shouldRetry(response) {
11373
- // Note this is not a standard header.
11374
- const shouldRetryHeader = response.headers.get('x-should-retry');
11375
- // If the server explicitly says whether or not to retry, obey.
11376
- if (shouldRetryHeader === 'true')
11377
- return true;
11378
- if (shouldRetryHeader === 'false')
11379
- return false;
11380
- // Retry on request timeouts.
11381
- if (response.status === 408)
11382
- return true;
11383
- // Retry on lock timeouts.
11384
- if (response.status === 409)
11385
- return true;
11386
- // Retry on rate limits.
11387
- if (response.status === 429)
11388
- return true;
11389
- // Retry internal errors.
11390
- if (response.status >= 500)
11391
- return true;
11392
- return false;
11393
- }
11394
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
11395
- let timeoutMillis;
11396
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
11397
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
11398
- if (retryAfterMillisHeader) {
11399
- const timeoutMs = parseFloat(retryAfterMillisHeader);
11400
- if (!Number.isNaN(timeoutMs)) {
11401
- timeoutMillis = timeoutMs;
11402
- }
11403
- }
11404
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
11405
- const retryAfterHeader = responseHeaders?.get('retry-after');
11406
- if (retryAfterHeader && !timeoutMillis) {
11407
- const timeoutSeconds = parseFloat(retryAfterHeader);
11408
- if (!Number.isNaN(timeoutSeconds)) {
11409
- timeoutMillis = timeoutSeconds * 1000;
11148
+ return out;
11149
+ };
11150
+ // Standard encoding have the following encoded/decoded ranges,
11151
+ // which we need to convert between.
11152
+ //
11153
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
11154
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11155
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
11156
+ //
11157
+ // Encode 6 bits in b into a new character.
11158
+ Coder.prototype._encodeByte = function (b) {
11159
+ // Encoding uses constant time operations as follows:
11160
+ //
11161
+ // 1. Define comparison of A with B using (A - B) >>> 8:
11162
+ // if A > B, then result is positive integer
11163
+ // if A <= B, then result is 0
11164
+ //
11165
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
11166
+ // if X == 0, then result is 0
11167
+ // if X != 0, then result is C
11168
+ //
11169
+ // 3. Start with the smallest comparison (b >= 0), which is always
11170
+ // true, so set the result to the starting ASCII value (65).
11171
+ //
11172
+ // 4. Continue comparing b to higher ASCII values, and selecting
11173
+ // zero if comparison isn't true, otherwise selecting a value
11174
+ // to add to result, which:
11175
+ //
11176
+ // a) undoes the previous addition
11177
+ // b) provides new value to add
11178
+ //
11179
+ var result = b;
11180
+ // b >= 0
11181
+ result += 65;
11182
+ // b > 25
11183
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11184
+ // b > 51
11185
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11186
+ // b > 61
11187
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
11188
+ // b > 62
11189
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
11190
+ return String.fromCharCode(result);
11191
+ };
11192
+ // Decode a character code into a byte.
11193
+ // Must return 256 if character is out of alphabet range.
11194
+ Coder.prototype._decodeChar = function (c) {
11195
+ // Decoding works similar to encoding: using the same comparison
11196
+ // function, but now it works on ranges: result is always incremented
11197
+ // by value, but this value becomes zero if the range is not
11198
+ // satisfied.
11199
+ //
11200
+ // Decoding starts with invalid value, 256, which is then
11201
+ // subtracted when the range is satisfied. If none of the ranges
11202
+ // apply, the function returns 256, which is then checked by
11203
+ // the caller to throw error.
11204
+ var result = INVALID_BYTE; // start with invalid character
11205
+ // c == 43 (c > 42 and c < 44)
11206
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
11207
+ // c == 47 (c > 46 and c < 48)
11208
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
11209
+ // c > 47 and c < 58
11210
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11211
+ // c > 64 and c < 91
11212
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11213
+ // c > 96 and c < 123
11214
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11215
+ return result;
11216
+ };
11217
+ Coder.prototype._getPaddingLength = function (s) {
11218
+ var paddingLength = 0;
11219
+ if (this._paddingCharacter) {
11220
+ for (var i = s.length - 1; i >= 0; i--) {
11221
+ if (s[i] !== this._paddingCharacter) {
11222
+ break;
11223
+ }
11224
+ paddingLength++;
11410
11225
  }
11411
- else {
11412
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
11226
+ if (s.length < 4 || paddingLength > 2) {
11227
+ throw new Error("Base64Coder: incorrect padding");
11413
11228
  }
11414
11229
  }
11415
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
11416
- // just do what it says, but otherwise calculate a default
11417
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
11418
- const maxRetries = options.maxRetries ?? this.maxRetries;
11419
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
11420
- }
11421
- await sleep(timeoutMillis);
11422
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
11423
- }
11424
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
11425
- const initialRetryDelay = 0.5;
11426
- const maxRetryDelay = 8.0;
11427
- const numRetries = maxRetries - retriesRemaining;
11428
- // Apply exponential backoff, but not more than the max.
11429
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
11430
- // Apply some jitter, take up to at most 25 percent of the retry time.
11431
- const jitter = 1 - Math.random() * 0.25;
11432
- return sleepSeconds * jitter * 1000;
11433
- }
11434
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
11435
- const options = { ...inputOptions };
11436
- const { method, path, query, defaultBaseURL } = options;
11437
- const url = this.buildURL(path, query, defaultBaseURL);
11438
- if ('timeout' in options)
11439
- validatePositiveInteger('timeout', options.timeout);
11440
- options.timeout = options.timeout ?? this.timeout;
11441
- const { bodyHeaders, body } = this.buildBody({ options });
11442
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
11443
- const req = {
11444
- method,
11445
- headers: reqHeaders,
11446
- ...(options.signal && { signal: options.signal }),
11447
- ...(globalThis.ReadableStream &&
11448
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
11449
- ...(body && { body }),
11450
- ...(this.fetchOptions ?? {}),
11451
- ...(options.fetchOptions ?? {}),
11452
- };
11453
- return { req, url, timeout: options.timeout };
11454
- }
11455
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
11456
- let idempotencyHeaders = {};
11457
- if (this.idempotencyHeader && method !== 'get') {
11458
- if (!options.idempotencyKey)
11459
- options.idempotencyKey = this.defaultIdempotencyKey();
11460
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
11461
- }
11462
- const headers = buildHeaders([
11463
- idempotencyHeaders,
11464
- {
11465
- Accept: 'application/json',
11466
- 'User-Agent': this.getUserAgent(),
11467
- 'X-Stainless-Retry-Count': String(retryCount),
11468
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
11469
- ...getPlatformHeaders(),
11470
- },
11471
- await this.authHeaders(options),
11472
- this._options.defaultHeaders,
11473
- bodyHeaders,
11474
- options.headers,
11475
- ]);
11476
- this.validateHeaders(headers);
11477
- return headers.values;
11478
- }
11479
- buildBody({ options: { body, headers: rawHeaders } }) {
11480
- if (!body) {
11481
- return { bodyHeaders: undefined, body: undefined };
11482
- }
11483
- const headers = buildHeaders([rawHeaders]);
11484
- if (
11485
- // Pass raw type verbatim
11486
- ArrayBuffer.isView(body) ||
11487
- body instanceof ArrayBuffer ||
11488
- body instanceof DataView ||
11489
- (typeof body === 'string' &&
11490
- // Preserve legacy string encoding behavior for now
11491
- headers.values.has('content-type')) ||
11492
- // `Blob` is superset of `File`
11493
- (globalThis.Blob && body instanceof globalThis.Blob) ||
11494
- // `FormData` -> `multipart/form-data`
11495
- body instanceof FormData ||
11496
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
11497
- body instanceof URLSearchParams ||
11498
- // Send chunked stream (each chunk has own `length`)
11499
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
11500
- return { bodyHeaders: undefined, body: body };
11501
- }
11502
- else if (typeof body === 'object' &&
11503
- (Symbol.asyncIterator in body ||
11504
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
11505
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
11506
- }
11507
- else {
11508
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
11509
- }
11230
+ return paddingLength;
11231
+ };
11232
+ return Coder;
11233
+ }());
11234
+ base64$1.Coder = Coder;
11235
+ var stdCoder = new Coder();
11236
+ function encode(data) {
11237
+ return stdCoder.encode(data);
11238
+ }
11239
+ base64$1.encode = encode;
11240
+ function decode(s) {
11241
+ return stdCoder.decode(s);
11242
+ }
11243
+ base64$1.decode = decode;
11244
+ /**
11245
+ * Implements URL-safe Base64 encoding.
11246
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
11247
+ *
11248
+ * Operates in constant time.
11249
+ */
11250
+ var URLSafeCoder = /** @class */ (function (_super) {
11251
+ __extends(URLSafeCoder, _super);
11252
+ function URLSafeCoder() {
11253
+ return _super !== null && _super.apply(this, arguments) || this;
11510
11254
  }
11255
+ // URL-safe encoding have the following encoded/decoded ranges:
11256
+ //
11257
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
11258
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11259
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
11260
+ //
11261
+ URLSafeCoder.prototype._encodeByte = function (b) {
11262
+ var result = b;
11263
+ // b >= 0
11264
+ result += 65;
11265
+ // b > 25
11266
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11267
+ // b > 51
11268
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11269
+ // b > 61
11270
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
11271
+ // b > 62
11272
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
11273
+ return String.fromCharCode(result);
11274
+ };
11275
+ URLSafeCoder.prototype._decodeChar = function (c) {
11276
+ var result = INVALID_BYTE;
11277
+ // c == 45 (c > 44 and c < 46)
11278
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
11279
+ // c == 95 (c > 94 and c < 96)
11280
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
11281
+ // c > 47 and c < 58
11282
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11283
+ // c > 64 and c < 91
11284
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11285
+ // c > 96 and c < 123
11286
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11287
+ return result;
11288
+ };
11289
+ return URLSafeCoder;
11290
+ }(Coder));
11291
+ base64$1.URLSafeCoder = URLSafeCoder;
11292
+ var urlSafeCoder = new URLSafeCoder();
11293
+ function encodeURLSafe(data) {
11294
+ return urlSafeCoder.encode(data);
11511
11295
  }
11512
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
11513
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
11296
+ base64$1.encodeURLSafe = encodeURLSafe;
11297
+ function decodeURLSafe(s) {
11298
+ return urlSafeCoder.decode(s);
11299
+ }
11300
+ base64$1.decodeURLSafe = decodeURLSafe;
11301
+ base64$1.encodedLength = function (length) {
11302
+ return stdCoder.encodedLength(length);
11514
11303
  };
11515
- DodoPayments.DodoPayments = _a;
11516
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
11517
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
11518
- DodoPayments.APIError = APIError;
11519
- DodoPayments.APIConnectionError = APIConnectionError;
11520
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
11521
- DodoPayments.APIUserAbortError = APIUserAbortError;
11522
- DodoPayments.NotFoundError = NotFoundError;
11523
- DodoPayments.ConflictError = ConflictError;
11524
- DodoPayments.RateLimitError = RateLimitError;
11525
- DodoPayments.BadRequestError = BadRequestError;
11526
- DodoPayments.AuthenticationError = AuthenticationError;
11527
- DodoPayments.InternalServerError = InternalServerError;
11528
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
11529
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
11530
- DodoPayments.toFile = toFile;
11531
- DodoPayments.CheckoutSessions = CheckoutSessions;
11532
- DodoPayments.Payments = Payments;
11533
- DodoPayments.Subscriptions = Subscriptions;
11534
- DodoPayments.Invoices = Invoices;
11535
- DodoPayments.Licenses = Licenses;
11536
- DodoPayments.LicenseKeys = LicenseKeys;
11537
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
11538
- DodoPayments.Customers = Customers;
11539
- DodoPayments.Refunds = Refunds;
11540
- DodoPayments.Disputes = Disputes;
11541
- DodoPayments.Payouts = Payouts;
11542
- DodoPayments.WebhookEvents = WebhookEvents;
11543
- DodoPayments.Products = Products;
11544
- DodoPayments.Misc = Misc;
11545
- DodoPayments.Discounts = Discounts;
11546
- DodoPayments.Addons = Addons;
11547
- DodoPayments.Brands = Brands;
11548
- DodoPayments.Webhooks = Webhooks$1;
11549
- DodoPayments.UsageEvents = UsageEvents;
11550
- DodoPayments.Meters = Meters;
11551
-
11552
- // src/checkout/checkout.ts
11553
- var checkoutQuerySchema = objectType({
11554
- productId: stringType(),
11555
- quantity: stringType().optional(),
11556
- // Customer fields
11557
- fullName: stringType().optional(),
11558
- firstName: stringType().optional(),
11559
- lastName: stringType().optional(),
11560
- email: stringType().optional(),
11561
- country: stringType().optional(),
11562
- addressLine: stringType().optional(),
11563
- city: stringType().optional(),
11564
- state: stringType().optional(),
11565
- zipCode: stringType().optional(),
11566
- // Disable flags
11567
- disableFullName: stringType().optional(),
11568
- disableFirstName: stringType().optional(),
11569
- disableLastName: stringType().optional(),
11570
- disableEmail: stringType().optional(),
11571
- disableCountry: stringType().optional(),
11572
- disableAddressLine: stringType().optional(),
11573
- disableCity: stringType().optional(),
11574
- disableState: stringType().optional(),
11575
- disableZipCode: stringType().optional(),
11576
- // Advanced controls
11577
- paymentCurrency: stringType().optional(),
11578
- showCurrencySelector: stringType().optional(),
11579
- paymentAmount: stringType().optional(),
11580
- showDiscounts: stringType().optional()
11581
- // Metadata (allow any key starting with metadata_)
11582
- // We'll handle metadata separately in the handler
11583
- }).catchall(unknownType());
11584
- var dynamicCheckoutBodySchema = objectType({
11585
- // For subscription
11586
- product_id: stringType().optional(),
11587
- quantity: numberType().optional(),
11588
- // For one-time payment
11589
- product_cart: arrayType(
11590
- objectType({
11591
- product_id: stringType(),
11592
- quantity: numberType()
11593
- })
11594
- ).optional(),
11595
- // Common fields
11596
- billing: objectType({
11597
- city: stringType(),
11598
- country: stringType(),
11599
- state: stringType(),
11600
- street: stringType(),
11601
- zipcode: stringType()
11602
- }),
11603
- customer: objectType({
11604
- customer_id: stringType().optional(),
11605
- email: stringType().optional(),
11606
- name: stringType().optional()
11607
- }),
11608
- discount_id: stringType().optional(),
11609
- addons: arrayType(
11610
- objectType({
11611
- addon_id: stringType(),
11612
- quantity: numberType()
11613
- })
11614
- ).optional(),
11615
- metadata: recordType(stringType(), stringType()).optional(),
11616
- currency: stringType().optional()
11617
- // Allow any additional fields (for future compatibility)
11618
- }).catchall(unknownType());
11619
- var checkoutSessionProductCartItemSchema = objectType({
11620
- product_id: stringType().min(1, "Product ID is required"),
11621
- quantity: numberType().int().positive("Quantity must be a positive integer")
11622
- });
11623
- var checkoutSessionCustomerSchema = objectType({
11624
- email: stringType().email().optional(),
11625
- name: stringType().min(1).optional(),
11626
- phone_number: stringType().optional()
11627
- }).optional();
11628
- var checkoutSessionBillingAddressSchema = objectType({
11629
- street: stringType().optional(),
11630
- city: stringType().optional(),
11631
- state: stringType().optional(),
11632
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
11633
- zipcode: stringType().optional()
11634
- }).optional();
11635
- var paymentMethodTypeSchema = enumType([
11636
- "credit",
11637
- "debit",
11638
- "upi_collect",
11639
- "upi_intent",
11640
- "apple_pay",
11641
- "google_pay",
11642
- "amazon_pay",
11643
- "klarna",
11644
- "affirm",
11645
- "afterpay_clearpay",
11646
- "sepa",
11647
- "ach"
11648
- ]);
11649
- var checkoutSessionCustomizationSchema = objectType({
11650
- theme: enumType(["light", "dark", "system"]).optional(),
11651
- show_order_details: booleanType().optional(),
11652
- show_on_demand_tag: booleanType().optional()
11653
- }).optional();
11654
- var checkoutSessionFeatureFlagsSchema = objectType({
11655
- allow_currency_selection: booleanType().optional(),
11656
- allow_discount_code: booleanType().optional(),
11657
- allow_phone_number_collection: booleanType().optional(),
11658
- allow_tax_id: booleanType().optional(),
11659
- always_create_new_customer: booleanType().optional()
11660
- }).optional();
11661
- var checkoutSessionSubscriptionDataSchema = objectType({
11662
- trial_period_days: numberType().int().nonnegative().optional()
11663
- }).optional();
11664
- var checkoutSessionPayloadSchema = objectType({
11665
- // Required fields
11666
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
11667
- // Optional fields
11668
- customer: checkoutSessionCustomerSchema,
11669
- billing_address: checkoutSessionBillingAddressSchema,
11670
- return_url: stringType().url().optional(),
11671
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
11672
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
11673
- show_saved_payment_methods: booleanType().optional(),
11674
- confirm: booleanType().optional(),
11675
- discount_code: stringType().optional(),
11676
- metadata: recordType(stringType(), stringType()).optional(),
11677
- customization: checkoutSessionCustomizationSchema,
11678
- feature_flags: checkoutSessionFeatureFlagsSchema,
11679
- subscription_data: checkoutSessionSubscriptionDataSchema
11680
- });
11681
- var checkoutSessionResponseSchema = objectType({
11682
- session_id: stringType().min(1, "Session ID is required"),
11683
- checkout_url: stringType().url("Invalid checkout URL")
11684
- });
11685
- var createCheckoutSession = async (payload, config) => {
11686
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
11687
- if (!validation.success) {
11688
- throw new Error(
11689
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11690
- );
11691
- }
11692
- const dodopayments = new DodoPayments({
11693
- bearerToken: config.bearerToken,
11694
- environment: config.environment
11695
- });
11696
- try {
11697
- const sdkPayload = {
11698
- ...validation.data,
11699
- ...validation.data.billing_address && {
11700
- billing_address: {
11701
- ...validation.data.billing_address,
11702
- country: validation.data.billing_address.country
11703
- }
11704
- }
11705
- };
11706
- const session = await dodopayments.checkoutSessions.create(
11707
- sdkPayload
11708
- );
11709
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
11710
- if (!responseValidation.success) {
11711
- throw new Error(
11712
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11713
- );
11714
- }
11715
- return responseValidation.data;
11716
- } catch (error) {
11717
- if (error instanceof Error) {
11718
- console.error("Dodo Payments Checkout Session API Error:", {
11719
- message: error.message,
11720
- payload: validation.data,
11721
- config: {
11722
- environment: config.environment,
11723
- hasBearerToken: !!config.bearerToken
11724
- }
11725
- });
11726
- throw new Error(`Failed to create checkout session: ${error.message}`);
11727
- }
11728
- console.error("Unknown error creating checkout session:", error);
11729
- throw new Error(
11730
- "Failed to create checkout session due to an unknown error"
11731
- );
11732
- }
11304
+ base64$1.maxDecodedLength = function (length) {
11305
+ return stdCoder.maxDecodedLength(length);
11733
11306
  };
11734
- var buildCheckoutUrl = async ({
11735
- queryParams,
11736
- body,
11737
- sessionPayload,
11738
- returnUrl,
11739
- bearerToken,
11740
- environment,
11741
- type = "static"
11742
- }) => {
11743
- if (type === "session") {
11744
- if (!sessionPayload) {
11745
- throw new Error("sessionPayload is required when type is 'session'");
11746
- }
11747
- const session = await createCheckoutSession(sessionPayload, {
11748
- bearerToken,
11749
- environment
11750
- });
11751
- return session.checkout_url;
11752
- }
11753
- const inputData = type === "dynamic" ? body : queryParams;
11754
- let parseResult;
11755
- if (type === "dynamic") {
11756
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
11757
- } else {
11758
- parseResult = checkoutQuerySchema.safeParse(inputData);
11759
- }
11760
- const { success, data, error } = parseResult;
11761
- if (!success) {
11762
- throw new Error(
11763
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
11764
- ${error.message}`
11765
- );
11766
- }
11767
- if (type !== "dynamic") {
11768
- const {
11769
- productId,
11770
- quantity: quantity2,
11771
- fullName,
11772
- firstName,
11773
- lastName,
11774
- email,
11775
- country,
11776
- addressLine,
11777
- city,
11778
- state,
11779
- zipCode,
11780
- disableFullName,
11781
- disableFirstName,
11782
- disableLastName,
11783
- disableEmail,
11784
- disableCountry,
11785
- disableAddressLine,
11786
- disableCity,
11787
- disableState,
11788
- disableZipCode,
11789
- paymentCurrency,
11790
- showCurrencySelector,
11791
- paymentAmount,
11792
- showDiscounts
11793
- // metadata handled below
11794
- } = data;
11795
- const dodopayments2 = new DodoPayments({
11796
- bearerToken,
11797
- environment
11798
- });
11799
- if (!productId) throw new Error("Missing required field: productId");
11800
- try {
11801
- await dodopayments2.products.retrieve(productId);
11802
- } catch (err) {
11803
- console.error(err);
11804
- throw new Error("Product not found");
11805
- }
11806
- const url = new URL(
11807
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
11808
- );
11809
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
11810
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
11811
- if (fullName) url.searchParams.set("fullName", String(fullName));
11812
- if (firstName) url.searchParams.set("firstName", String(firstName));
11813
- if (lastName) url.searchParams.set("lastName", String(lastName));
11814
- if (email) url.searchParams.set("email", String(email));
11815
- if (country) url.searchParams.set("country", String(country));
11816
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
11817
- if (city) url.searchParams.set("city", String(city));
11818
- if (state) url.searchParams.set("state", String(state));
11819
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
11820
- if (disableFullName === "true")
11821
- url.searchParams.set("disableFullName", "true");
11822
- if (disableFirstName === "true")
11823
- url.searchParams.set("disableFirstName", "true");
11824
- if (disableLastName === "true")
11825
- url.searchParams.set("disableLastName", "true");
11826
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
11827
- if (disableCountry === "true")
11828
- url.searchParams.set("disableCountry", "true");
11829
- if (disableAddressLine === "true")
11830
- url.searchParams.set("disableAddressLine", "true");
11831
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
11832
- if (disableState === "true") url.searchParams.set("disableState", "true");
11833
- if (disableZipCode === "true")
11834
- url.searchParams.set("disableZipCode", "true");
11835
- if (paymentCurrency)
11836
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
11837
- if (showCurrencySelector)
11838
- url.searchParams.set(
11839
- "showCurrencySelector",
11840
- String(showCurrencySelector)
11841
- );
11842
- if (paymentAmount)
11843
- url.searchParams.set("paymentAmount", String(paymentAmount));
11844
- if (showDiscounts)
11845
- url.searchParams.set("showDiscounts", String(showDiscounts));
11846
- for (const [key, value] of Object.entries(queryParams || {})) {
11847
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
11848
- url.searchParams.set(key, String(value));
11849
- }
11850
- }
11851
- return url.toString();
11852
- }
11853
- const dyn = data;
11854
- const {
11855
- product_id,
11856
- product_cart,
11857
- quantity,
11858
- billing,
11859
- customer,
11860
- addons,
11861
- metadata,
11862
- allowed_payment_method_types,
11863
- billing_currency,
11864
- discount_code,
11865
- on_demand,
11866
- return_url: bodyReturnUrl,
11867
- show_saved_payment_methods,
11868
- tax_id,
11869
- trial_period_days
11870
- } = dyn;
11871
- const dodopayments = new DodoPayments({
11872
- bearerToken,
11873
- environment
11874
- });
11875
- let isSubscription = false;
11876
- let productIdToFetch = product_id;
11877
- if (!product_id && product_cart && product_cart.length > 0) {
11878
- productIdToFetch = product_cart[0].product_id;
11879
- }
11880
- if (!productIdToFetch)
11881
- throw new Error(
11882
- "Missing required field: product_id or product_cart[0].product_id"
11883
- );
11884
- let product;
11885
- try {
11886
- product = await dodopayments.products.retrieve(productIdToFetch);
11887
- } catch (err) {
11888
- console.error(err);
11889
- throw new Error("Product not found");
11890
- }
11891
- isSubscription = Boolean(product.is_recurring);
11892
- if (isSubscription && !product_id)
11893
- throw new Error("Missing required field: product_id for subscription");
11894
- if (!billing) throw new Error("Missing required field: billing");
11895
- if (!customer) throw new Error("Missing required field: customer");
11896
- if (isSubscription) {
11897
- const subscriptionPayload = {
11898
- billing,
11899
- customer,
11900
- product_id,
11901
- quantity: quantity ? Number(quantity) : 1
11902
- };
11903
- if (metadata) subscriptionPayload.metadata = metadata;
11904
- if (discount_code) subscriptionPayload.discount_code = discount_code;
11905
- if (addons) subscriptionPayload.addons = addons;
11906
- if (allowed_payment_method_types)
11907
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
11908
- if (billing_currency)
11909
- subscriptionPayload.billing_currency = billing_currency;
11910
- if (on_demand) subscriptionPayload.on_demand = on_demand;
11911
- subscriptionPayload.payment_link = true;
11912
- if (bodyReturnUrl) {
11913
- subscriptionPayload.return_url = bodyReturnUrl;
11914
- } else if (returnUrl) {
11915
- subscriptionPayload.return_url = returnUrl;
11916
- }
11917
- if (show_saved_payment_methods)
11918
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
11919
- if (tax_id) subscriptionPayload.tax_id = tax_id;
11920
- if (trial_period_days)
11921
- subscriptionPayload.trial_period_days = trial_period_days;
11922
- let subscription;
11923
- try {
11924
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
11925
- } catch (err) {
11926
- console.error("Error when creating subscription", err);
11927
- throw new Error(err instanceof Error ? err.message : String(err));
11928
- }
11929
- if (!subscription || !subscription.payment_link) {
11930
- throw new Error(
11931
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
11932
- );
11933
- }
11934
- return subscription.payment_link;
11935
- } else {
11936
- let cart = product_cart;
11937
- if (!cart && product_id) {
11938
- cart = [
11939
- { product_id, quantity: quantity ? Number(quantity) : 1 }
11940
- ];
11941
- }
11942
- if (!cart || cart.length === 0)
11943
- throw new Error("Missing required field: product_cart or product_id");
11944
- const paymentPayload = {
11945
- billing,
11946
- customer,
11947
- product_cart: cart
11948
- };
11949
- if (metadata) paymentPayload.metadata = metadata;
11950
- paymentPayload.payment_link = true;
11951
- if (allowed_payment_method_types)
11952
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
11953
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
11954
- if (discount_code) paymentPayload.discount_code = discount_code;
11955
- if (bodyReturnUrl) {
11956
- paymentPayload.return_url = bodyReturnUrl;
11957
- } else if (returnUrl) {
11958
- paymentPayload.return_url = returnUrl;
11959
- }
11960
- if (show_saved_payment_methods)
11961
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
11962
- if (tax_id) paymentPayload.tax_id = tax_id;
11963
- let payment;
11964
- try {
11965
- payment = await dodopayments.payments.create(paymentPayload);
11966
- } catch (err) {
11967
- console.error("Error when creating payment link", err);
11968
- throw new Error(err instanceof Error ? err.message : String(err));
11969
- }
11970
- if (!payment || !payment.payment_link) {
11971
- throw new Error(
11972
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
11973
- );
11974
- }
11975
- return payment.payment_link;
11976
- }
11307
+ base64$1.decodedLength = function (s) {
11308
+ return stdCoder.decodedLength(s);
11977
11309
  };
11978
11310
 
11979
- const Checkout = (config) => {
11980
- const getHandler = async (req) => {
11981
- const { searchParams } = new URL(req.url);
11982
- const queryParams = Object.fromEntries(searchParams);
11983
- if (!queryParams.productId) {
11984
- return new serverExports.NextResponse("Please provide productId query parameter", {
11985
- status: 400,
11986
- });
11987
- }
11988
- const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
11989
- if (!success) {
11990
- if (error.errors.some((e) => e.path.toString() === "productId")) {
11991
- return new serverExports.NextResponse("Please provide productId query parameter", {
11992
- status: 400,
11993
- });
11994
- }
11995
- return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
11996
- status: 400,
11997
- });
11998
- }
11999
- let url = "";
12000
- try {
12001
- url = await buildCheckoutUrl({ queryParams: data, ...config });
12002
- }
12003
- catch (error) {
12004
- return new serverExports.NextResponse(error.message, { status: 400 });
12005
- }
12006
- return serverExports.NextResponse.json({ checkout_url: url });
12007
- };
12008
- const postHandler = async (req) => {
12009
- let body;
12010
- try {
12011
- body = await req.json();
12012
- }
12013
- catch (e) {
12014
- return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
12015
- }
12016
- if (config.type === "dynamic") {
12017
- // Handle dynamic checkout
12018
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
12019
- if (!success) {
12020
- return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
12021
- status: 400,
12022
- });
12023
- }
12024
- let url = "";
12025
- try {
12026
- url = await buildCheckoutUrl({
12027
- body: data,
12028
- ...config,
12029
- type: "dynamic",
12030
- });
12031
- }
12032
- catch (error) {
12033
- return new serverExports.NextResponse(error.message, { status: 400 });
12034
- }
12035
- return serverExports.NextResponse.json({ checkout_url: url });
12036
- }
12037
- else {
12038
- // Handle checkout session
12039
- const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12040
- if (!success) {
12041
- return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12042
- status: 400,
12043
- });
12044
- }
12045
- let url = "";
12046
- try {
12047
- url = await buildCheckoutUrl({
12048
- sessionPayload: data,
12049
- ...config,
12050
- type: "session",
12051
- });
12052
- }
12053
- catch (error) {
12054
- return new serverExports.NextResponse(error.message, { status: 400 });
12055
- }
12056
- return serverExports.NextResponse.json({ checkout_url: url });
12057
- }
12058
- };
12059
- return (req) => {
12060
- if (req.method === "POST") {
12061
- return postHandler(req);
12062
- }
12063
- return getHandler(req);
12064
- };
12065
- };
12066
-
12067
- var dist = {};
12068
-
12069
- var timing_safe_equal = {};
12070
-
12071
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
12072
- timing_safe_equal.timingSafeEqual = void 0;
12073
- function assert(expr, msg = "") {
12074
- if (!expr) {
12075
- throw new Error(msg);
12076
- }
12077
- }
12078
- function timingSafeEqual(a, b) {
12079
- if (a.byteLength !== b.byteLength) {
12080
- return false;
12081
- }
12082
- if (!(a instanceof DataView)) {
12083
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
12084
- }
12085
- if (!(b instanceof DataView)) {
12086
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
12087
- }
12088
- assert(a instanceof DataView);
12089
- assert(b instanceof DataView);
12090
- const length = a.byteLength;
12091
- let out = 0;
12092
- let i = -1;
12093
- while (++i < length) {
12094
- out |= a.getUint8(i) ^ b.getUint8(i);
12095
- }
12096
- return out === 0;
12097
- }
12098
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
12099
-
12100
- var base64$1 = {};
12101
-
12102
- // Copyright (C) 2016 Dmitry Chestnykh
12103
- // MIT License. See LICENSE file for details.
12104
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
12105
- var extendStatics = function (d, b) {
12106
- extendStatics = Object.setPrototypeOf ||
12107
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12108
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12109
- return extendStatics(d, b);
12110
- };
12111
- return function (d, b) {
12112
- extendStatics(d, b);
12113
- function __() { this.constructor = d; }
12114
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12115
- };
12116
- })();
12117
- Object.defineProperty(base64$1, "__esModule", { value: true });
12118
- /**
12119
- * Package base64 implements Base64 encoding and decoding.
12120
- */
12121
- // Invalid character used in decoding to indicate
12122
- // that the character to decode is out of range of
12123
- // alphabet and cannot be decoded.
12124
- var INVALID_BYTE = 256;
12125
- /**
12126
- * Implements standard Base64 encoding.
12127
- *
12128
- * Operates in constant time.
12129
- */
12130
- var Coder = /** @class */ (function () {
12131
- // TODO(dchest): methods to encode chunk-by-chunk.
12132
- function Coder(_paddingCharacter) {
12133
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
12134
- this._paddingCharacter = _paddingCharacter;
12135
- }
12136
- Coder.prototype.encodedLength = function (length) {
12137
- if (!this._paddingCharacter) {
12138
- return (length * 8 + 5) / 6 | 0;
12139
- }
12140
- return (length + 2) / 3 * 4 | 0;
12141
- };
12142
- Coder.prototype.encode = function (data) {
12143
- var out = "";
12144
- var i = 0;
12145
- for (; i < data.length - 2; i += 3) {
12146
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
12147
- out += this._encodeByte((c >>> 3 * 6) & 63);
12148
- out += this._encodeByte((c >>> 2 * 6) & 63);
12149
- out += this._encodeByte((c >>> 1 * 6) & 63);
12150
- out += this._encodeByte((c >>> 0 * 6) & 63);
12151
- }
12152
- var left = data.length - i;
12153
- if (left > 0) {
12154
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
12155
- out += this._encodeByte((c >>> 3 * 6) & 63);
12156
- out += this._encodeByte((c >>> 2 * 6) & 63);
12157
- if (left === 2) {
12158
- out += this._encodeByte((c >>> 1 * 6) & 63);
12159
- }
12160
- else {
12161
- out += this._paddingCharacter || "";
12162
- }
12163
- out += this._paddingCharacter || "";
12164
- }
12165
- return out;
12166
- };
12167
- Coder.prototype.maxDecodedLength = function (length) {
12168
- if (!this._paddingCharacter) {
12169
- return (length * 6 + 7) / 8 | 0;
12170
- }
12171
- return length / 4 * 3 | 0;
12172
- };
12173
- Coder.prototype.decodedLength = function (s) {
12174
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
12175
- };
12176
- Coder.prototype.decode = function (s) {
12177
- if (s.length === 0) {
12178
- return new Uint8Array(0);
12179
- }
12180
- var paddingLength = this._getPaddingLength(s);
12181
- var length = s.length - paddingLength;
12182
- var out = new Uint8Array(this.maxDecodedLength(length));
12183
- var op = 0;
12184
- var i = 0;
12185
- var haveBad = 0;
12186
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
12187
- for (; i < length - 4; i += 4) {
12188
- v0 = this._decodeChar(s.charCodeAt(i + 0));
12189
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12190
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12191
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12192
- out[op++] = (v0 << 2) | (v1 >>> 4);
12193
- out[op++] = (v1 << 4) | (v2 >>> 2);
12194
- out[op++] = (v2 << 6) | v3;
12195
- haveBad |= v0 & INVALID_BYTE;
12196
- haveBad |= v1 & INVALID_BYTE;
12197
- haveBad |= v2 & INVALID_BYTE;
12198
- haveBad |= v3 & INVALID_BYTE;
12199
- }
12200
- if (i < length - 1) {
12201
- v0 = this._decodeChar(s.charCodeAt(i));
12202
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12203
- out[op++] = (v0 << 2) | (v1 >>> 4);
12204
- haveBad |= v0 & INVALID_BYTE;
12205
- haveBad |= v1 & INVALID_BYTE;
12206
- }
12207
- if (i < length - 2) {
12208
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12209
- out[op++] = (v1 << 4) | (v2 >>> 2);
12210
- haveBad |= v2 & INVALID_BYTE;
12211
- }
12212
- if (i < length - 3) {
12213
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12214
- out[op++] = (v2 << 6) | v3;
12215
- haveBad |= v3 & INVALID_BYTE;
12216
- }
12217
- if (haveBad !== 0) {
12218
- throw new Error("Base64Coder: incorrect characters for decoding");
12219
- }
12220
- return out;
12221
- };
12222
- // Standard encoding have the following encoded/decoded ranges,
12223
- // which we need to convert between.
12224
- //
12225
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
12226
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12227
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
12228
- //
12229
- // Encode 6 bits in b into a new character.
12230
- Coder.prototype._encodeByte = function (b) {
12231
- // Encoding uses constant time operations as follows:
12232
- //
12233
- // 1. Define comparison of A with B using (A - B) >>> 8:
12234
- // if A > B, then result is positive integer
12235
- // if A <= B, then result is 0
12236
- //
12237
- // 2. Define selection of C or 0 using bitwise AND: X & C:
12238
- // if X == 0, then result is 0
12239
- // if X != 0, then result is C
12240
- //
12241
- // 3. Start with the smallest comparison (b >= 0), which is always
12242
- // true, so set the result to the starting ASCII value (65).
12243
- //
12244
- // 4. Continue comparing b to higher ASCII values, and selecting
12245
- // zero if comparison isn't true, otherwise selecting a value
12246
- // to add to result, which:
12247
- //
12248
- // a) undoes the previous addition
12249
- // b) provides new value to add
12250
- //
12251
- var result = b;
12252
- // b >= 0
12253
- result += 65;
12254
- // b > 25
12255
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12256
- // b > 51
12257
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12258
- // b > 61
12259
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
12260
- // b > 62
12261
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
12262
- return String.fromCharCode(result);
12263
- };
12264
- // Decode a character code into a byte.
12265
- // Must return 256 if character is out of alphabet range.
12266
- Coder.prototype._decodeChar = function (c) {
12267
- // Decoding works similar to encoding: using the same comparison
12268
- // function, but now it works on ranges: result is always incremented
12269
- // by value, but this value becomes zero if the range is not
12270
- // satisfied.
12271
- //
12272
- // Decoding starts with invalid value, 256, which is then
12273
- // subtracted when the range is satisfied. If none of the ranges
12274
- // apply, the function returns 256, which is then checked by
12275
- // the caller to throw error.
12276
- var result = INVALID_BYTE; // start with invalid character
12277
- // c == 43 (c > 42 and c < 44)
12278
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
12279
- // c == 47 (c > 46 and c < 48)
12280
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
12281
- // c > 47 and c < 58
12282
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12283
- // c > 64 and c < 91
12284
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12285
- // c > 96 and c < 123
12286
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12287
- return result;
12288
- };
12289
- Coder.prototype._getPaddingLength = function (s) {
12290
- var paddingLength = 0;
12291
- if (this._paddingCharacter) {
12292
- for (var i = s.length - 1; i >= 0; i--) {
12293
- if (s[i] !== this._paddingCharacter) {
12294
- break;
12295
- }
12296
- paddingLength++;
12297
- }
12298
- if (s.length < 4 || paddingLength > 2) {
12299
- throw new Error("Base64Coder: incorrect padding");
12300
- }
12301
- }
12302
- return paddingLength;
12303
- };
12304
- return Coder;
12305
- }());
12306
- base64$1.Coder = Coder;
12307
- var stdCoder = new Coder();
12308
- function encode(data) {
12309
- return stdCoder.encode(data);
12310
- }
12311
- base64$1.encode = encode;
12312
- function decode(s) {
12313
- return stdCoder.decode(s);
12314
- }
12315
- base64$1.decode = decode;
12316
- /**
12317
- * Implements URL-safe Base64 encoding.
12318
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
12319
- *
12320
- * Operates in constant time.
12321
- */
12322
- var URLSafeCoder = /** @class */ (function (_super) {
12323
- __extends(URLSafeCoder, _super);
12324
- function URLSafeCoder() {
12325
- return _super !== null && _super.apply(this, arguments) || this;
12326
- }
12327
- // URL-safe encoding have the following encoded/decoded ranges:
12328
- //
12329
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
12330
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12331
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
12332
- //
12333
- URLSafeCoder.prototype._encodeByte = function (b) {
12334
- var result = b;
12335
- // b >= 0
12336
- result += 65;
12337
- // b > 25
12338
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12339
- // b > 51
12340
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12341
- // b > 61
12342
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
12343
- // b > 62
12344
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
12345
- return String.fromCharCode(result);
12346
- };
12347
- URLSafeCoder.prototype._decodeChar = function (c) {
12348
- var result = INVALID_BYTE;
12349
- // c == 45 (c > 44 and c < 46)
12350
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
12351
- // c == 95 (c > 94 and c < 96)
12352
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
12353
- // c > 47 and c < 58
12354
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12355
- // c > 64 and c < 91
12356
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12357
- // c > 96 and c < 123
12358
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12359
- return result;
12360
- };
12361
- return URLSafeCoder;
12362
- }(Coder));
12363
- base64$1.URLSafeCoder = URLSafeCoder;
12364
- var urlSafeCoder = new URLSafeCoder();
12365
- function encodeURLSafe(data) {
12366
- return urlSafeCoder.encode(data);
12367
- }
12368
- base64$1.encodeURLSafe = encodeURLSafe;
12369
- function decodeURLSafe(s) {
12370
- return urlSafeCoder.decode(s);
12371
- }
12372
- base64$1.decodeURLSafe = decodeURLSafe;
12373
- base64$1.encodedLength = function (length) {
12374
- return stdCoder.encodedLength(length);
12375
- };
12376
- base64$1.maxDecodedLength = function (length) {
12377
- return stdCoder.maxDecodedLength(length);
12378
- };
12379
- base64$1.decodedLength = function (s) {
12380
- return stdCoder.decodedLength(s);
12381
- };
12382
-
12383
- var sha256$1 = {exports: {}};
11311
+ var sha256$1 = {exports: {}};
12384
11312
 
12385
11313
  (function (module) {
12386
11314
  (function (root, factory) {
@@ -12822,96 +11750,1219 @@ class ExtendableError extends Error {
12822
11750
  this.name = "ExtendableError";
12823
11751
  this.stack = new Error(message).stack;
12824
11752
  }
12825
- }
12826
- class WebhookVerificationError extends ExtendableError {
12827
- constructor(message) {
12828
- super(message);
12829
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
12830
- this.name = "WebhookVerificationError";
11753
+ }
11754
+ class WebhookVerificationError extends ExtendableError {
11755
+ constructor(message) {
11756
+ super(message);
11757
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
11758
+ this.name = "WebhookVerificationError";
11759
+ }
11760
+ }
11761
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
11762
+ class Webhook {
11763
+ constructor(secret, options) {
11764
+ if (!secret) {
11765
+ throw new Error("Secret can't be empty.");
11766
+ }
11767
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
11768
+ if (secret instanceof Uint8Array) {
11769
+ this.key = secret;
11770
+ }
11771
+ else {
11772
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
11773
+ }
11774
+ }
11775
+ else {
11776
+ if (typeof secret !== "string") {
11777
+ throw new Error("Expected secret to be of type string");
11778
+ }
11779
+ if (secret.startsWith(Webhook.prefix)) {
11780
+ secret = secret.substring(Webhook.prefix.length);
11781
+ }
11782
+ this.key = base64.decode(secret);
11783
+ }
11784
+ }
11785
+ verify(payload, headers_) {
11786
+ const headers = {};
11787
+ for (const key of Object.keys(headers_)) {
11788
+ headers[key.toLowerCase()] = headers_[key];
11789
+ }
11790
+ const msgId = headers["webhook-id"];
11791
+ const msgSignature = headers["webhook-signature"];
11792
+ const msgTimestamp = headers["webhook-timestamp"];
11793
+ if (!msgSignature || !msgId || !msgTimestamp) {
11794
+ throw new WebhookVerificationError("Missing required headers");
11795
+ }
11796
+ const timestamp = this.verifyTimestamp(msgTimestamp);
11797
+ const computedSignature = this.sign(msgId, timestamp, payload);
11798
+ const expectedSignature = computedSignature.split(",")[1];
11799
+ const passedSignatures = msgSignature.split(" ");
11800
+ const encoder = new globalThis.TextEncoder();
11801
+ for (const versionedSignature of passedSignatures) {
11802
+ const [version, signature] = versionedSignature.split(",");
11803
+ if (version !== "v1") {
11804
+ continue;
11805
+ }
11806
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
11807
+ return JSON.parse(payload.toString());
11808
+ }
11809
+ }
11810
+ throw new WebhookVerificationError("No matching signature found");
11811
+ }
11812
+ sign(msgId, timestamp, payload) {
11813
+ if (typeof payload === "string") ;
11814
+ else if (payload.constructor.name === "Buffer") {
11815
+ payload = payload.toString();
11816
+ }
11817
+ else {
11818
+ throw new Error("Expected payload to be of type string or Buffer.");
11819
+ }
11820
+ const encoder = new TextEncoder();
11821
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
11822
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
11823
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
11824
+ return `v1,${expectedSignature}`;
11825
+ }
11826
+ verifyTimestamp(timestampHeader) {
11827
+ const now = Math.floor(Date.now() / 1000);
11828
+ const timestamp = parseInt(timestampHeader, 10);
11829
+ if (isNaN(timestamp)) {
11830
+ throw new WebhookVerificationError("Invalid Signature Headers");
11831
+ }
11832
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
11833
+ throw new WebhookVerificationError("Message timestamp too old");
11834
+ }
11835
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
11836
+ throw new WebhookVerificationError("Message timestamp too new");
11837
+ }
11838
+ return new Date(timestamp * 1000);
11839
+ }
11840
+ }
11841
+ Webhook_1 = dist.Webhook = Webhook;
11842
+ Webhook.prefix = "whsec_";
11843
+
11844
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11845
+ let Webhooks$1 = class Webhooks extends APIResource {
11846
+ constructor() {
11847
+ super(...arguments);
11848
+ this.headers = new Headers$1(this._client);
11849
+ }
11850
+ /**
11851
+ * Create a new webhook
11852
+ */
11853
+ create(body, options) {
11854
+ return this._client.post('/webhooks', { body, ...options });
11855
+ }
11856
+ /**
11857
+ * Get a webhook by id
11858
+ */
11859
+ retrieve(webhookID, options) {
11860
+ return this._client.get(path `/webhooks/${webhookID}`, options);
11861
+ }
11862
+ /**
11863
+ * Patch a webhook by id
11864
+ */
11865
+ update(webhookID, body, options) {
11866
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11867
+ }
11868
+ /**
11869
+ * List all webhooks
11870
+ */
11871
+ list(query = {}, options) {
11872
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11873
+ }
11874
+ /**
11875
+ * Delete a webhook by id
11876
+ */
11877
+ delete(webhookID, options) {
11878
+ return this._client.delete(path `/webhooks/${webhookID}`, {
11879
+ ...options,
11880
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
11881
+ });
11882
+ }
11883
+ /**
11884
+ * Get webhook secret by id
11885
+ */
11886
+ retrieveSecret(webhookID, options) {
11887
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11888
+ }
11889
+ unsafeUnwrap(body) {
11890
+ return JSON.parse(body);
11891
+ }
11892
+ unwrap(body, { headers, key }) {
11893
+ if (headers !== undefined) {
11894
+ const keyStr = key === undefined ? this._client.webhookKey : key;
11895
+ if (keyStr === null)
11896
+ throw new Error('Webhook key must not be null in order to unwrap');
11897
+ const wh = new Webhook_1(keyStr);
11898
+ wh.verify(body, headers);
11899
+ }
11900
+ return JSON.parse(body);
11901
+ }
11902
+ };
11903
+ Webhooks$1.Headers = Headers$1;
11904
+
11905
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11906
+ /**
11907
+ * Read an environment variable.
11908
+ *
11909
+ * Trims beginning and trailing whitespace.
11910
+ *
11911
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11912
+ */
11913
+ const readEnv = (env) => {
11914
+ if (typeof globalThis.process !== 'undefined') {
11915
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
11916
+ }
11917
+ if (typeof globalThis.Deno !== 'undefined') {
11918
+ return globalThis.Deno.env?.get?.(env)?.trim();
11919
+ }
11920
+ return undefined;
11921
+ };
11922
+
11923
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11924
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11925
+ const environments = {
11926
+ live_mode: 'https://live.dodopayments.com',
11927
+ test_mode: 'https://test.dodopayments.com',
11928
+ };
11929
+ /**
11930
+ * API Client for interfacing with the Dodo Payments API.
11931
+ */
11932
+ class DodoPayments {
11933
+ /**
11934
+ * API Client for interfacing with the Dodo Payments API.
11935
+ *
11936
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11937
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
11938
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11939
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11940
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11941
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11942
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11943
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11944
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11945
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11946
+ */
11947
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
11948
+ _DodoPayments_instances.add(this);
11949
+ _DodoPayments_encoder.set(this, void 0);
11950
+ this.checkoutSessions = new CheckoutSessions(this);
11951
+ this.payments = new Payments(this);
11952
+ this.subscriptions = new Subscriptions(this);
11953
+ this.invoices = new Invoices(this);
11954
+ this.licenses = new Licenses(this);
11955
+ this.licenseKeys = new LicenseKeys(this);
11956
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
11957
+ this.customers = new Customers(this);
11958
+ this.refunds = new Refunds(this);
11959
+ this.disputes = new Disputes(this);
11960
+ this.payouts = new Payouts(this);
11961
+ this.products = new Products(this);
11962
+ this.misc = new Misc(this);
11963
+ this.discounts = new Discounts(this);
11964
+ this.addons = new Addons(this);
11965
+ this.brands = new Brands(this);
11966
+ this.webhooks = new Webhooks$1(this);
11967
+ this.webhookEvents = new WebhookEvents(this);
11968
+ this.usageEvents = new UsageEvents(this);
11969
+ this.meters = new Meters(this);
11970
+ if (bearerToken === undefined) {
11971
+ 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' }).");
11972
+ }
11973
+ const options = {
11974
+ bearerToken,
11975
+ webhookKey,
11976
+ ...opts,
11977
+ baseURL,
11978
+ environment: opts.environment ?? 'live_mode',
11979
+ };
11980
+ if (baseURL && opts.environment) {
11981
+ 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');
11982
+ }
11983
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11984
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11985
+ this.logger = options.logger ?? console;
11986
+ const defaultLogLevel = 'warn';
11987
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
11988
+ this.logLevel = defaultLogLevel;
11989
+ this.logLevel =
11990
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11991
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11992
+ defaultLogLevel;
11993
+ this.fetchOptions = options.fetchOptions;
11994
+ this.maxRetries = options.maxRetries ?? 2;
11995
+ this.fetch = options.fetch ?? getDefaultFetch();
11996
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11997
+ this._options = options;
11998
+ this.bearerToken = bearerToken;
11999
+ this.webhookKey = webhookKey;
12000
+ }
12001
+ /**
12002
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
12003
+ */
12004
+ withOptions(options) {
12005
+ const client = new this.constructor({
12006
+ ...this._options,
12007
+ environment: options.environment ? options.environment : undefined,
12008
+ baseURL: options.environment ? undefined : this.baseURL,
12009
+ maxRetries: this.maxRetries,
12010
+ timeout: this.timeout,
12011
+ logger: this.logger,
12012
+ logLevel: this.logLevel,
12013
+ fetch: this.fetch,
12014
+ fetchOptions: this.fetchOptions,
12015
+ bearerToken: this.bearerToken,
12016
+ webhookKey: this.webhookKey,
12017
+ ...options,
12018
+ });
12019
+ return client;
12020
+ }
12021
+ defaultQuery() {
12022
+ return this._options.defaultQuery;
12023
+ }
12024
+ validateHeaders({ values, nulls }) {
12025
+ return;
12026
+ }
12027
+ async authHeaders(opts) {
12028
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
12029
+ }
12030
+ /**
12031
+ * Basic re-implementation of `qs.stringify` for primitive types.
12032
+ */
12033
+ stringifyQuery(query) {
12034
+ return Object.entries(query)
12035
+ .filter(([_, value]) => typeof value !== 'undefined')
12036
+ .map(([key, value]) => {
12037
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
12038
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
12039
+ }
12040
+ if (value === null) {
12041
+ return `${encodeURIComponent(key)}=`;
12042
+ }
12043
+ 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.`);
12044
+ })
12045
+ .join('&');
12046
+ }
12047
+ getUserAgent() {
12048
+ return `${this.constructor.name}/JS ${VERSION}`;
12049
+ }
12050
+ defaultIdempotencyKey() {
12051
+ return `stainless-node-retry-${uuid4()}`;
12052
+ }
12053
+ makeStatusError(status, error, message, headers) {
12054
+ return APIError.generate(status, error, message, headers);
12055
+ }
12056
+ buildURL(path, query, defaultBaseURL) {
12057
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
12058
+ const url = isAbsoluteURL(path) ?
12059
+ new URL(path)
12060
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
12061
+ const defaultQuery = this.defaultQuery();
12062
+ if (!isEmptyObj(defaultQuery)) {
12063
+ query = { ...defaultQuery, ...query };
12064
+ }
12065
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
12066
+ url.search = this.stringifyQuery(query);
12067
+ }
12068
+ return url.toString();
12069
+ }
12070
+ /**
12071
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
12072
+ */
12073
+ async prepareOptions(options) { }
12074
+ /**
12075
+ * Used as a callback for mutating the given `RequestInit` object.
12076
+ *
12077
+ * This is useful for cases where you want to add certain headers based off of
12078
+ * the request properties, e.g. `method` or `url`.
12079
+ */
12080
+ async prepareRequest(request, { url, options }) { }
12081
+ get(path, opts) {
12082
+ return this.methodRequest('get', path, opts);
12083
+ }
12084
+ post(path, opts) {
12085
+ return this.methodRequest('post', path, opts);
12086
+ }
12087
+ patch(path, opts) {
12088
+ return this.methodRequest('patch', path, opts);
12089
+ }
12090
+ put(path, opts) {
12091
+ return this.methodRequest('put', path, opts);
12092
+ }
12093
+ delete(path, opts) {
12094
+ return this.methodRequest('delete', path, opts);
12095
+ }
12096
+ methodRequest(method, path, opts) {
12097
+ return this.request(Promise.resolve(opts).then((opts) => {
12098
+ return { method, path, ...opts };
12099
+ }));
12100
+ }
12101
+ request(options, remainingRetries = null) {
12102
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
12103
+ }
12104
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
12105
+ const options = await optionsInput;
12106
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12107
+ if (retriesRemaining == null) {
12108
+ retriesRemaining = maxRetries;
12109
+ }
12110
+ await this.prepareOptions(options);
12111
+ const { req, url, timeout } = await this.buildRequest(options, {
12112
+ retryCount: maxRetries - retriesRemaining,
12113
+ });
12114
+ await this.prepareRequest(req, { url, options });
12115
+ /** Not an API request ID, just for correlating local log entries. */
12116
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
12117
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
12118
+ const startTime = Date.now();
12119
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
12120
+ retryOfRequestLogID,
12121
+ method: options.method,
12122
+ url,
12123
+ options,
12124
+ headers: req.headers,
12125
+ }));
12126
+ if (options.signal?.aborted) {
12127
+ throw new APIUserAbortError();
12128
+ }
12129
+ const controller = new AbortController();
12130
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
12131
+ const headersTime = Date.now();
12132
+ if (response instanceof globalThis.Error) {
12133
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12134
+ if (options.signal?.aborted) {
12135
+ throw new APIUserAbortError();
12136
+ }
12137
+ // detect native connection timeout errors
12138
+ // 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)"
12139
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
12140
+ // others do not provide enough information to distinguish timeouts from other connection errors
12141
+ const isTimeout = isAbortError(response) ||
12142
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
12143
+ if (retriesRemaining) {
12144
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
12145
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
12146
+ retryOfRequestLogID,
12147
+ url,
12148
+ durationMs: headersTime - startTime,
12149
+ message: response.message,
12150
+ }));
12151
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
12152
+ }
12153
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
12154
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
12155
+ retryOfRequestLogID,
12156
+ url,
12157
+ durationMs: headersTime - startTime,
12158
+ message: response.message,
12159
+ }));
12160
+ if (isTimeout) {
12161
+ throw new APIConnectionTimeoutError();
12162
+ }
12163
+ throw new APIConnectionError({ cause: response });
12164
+ }
12165
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
12166
+ if (!response.ok) {
12167
+ const shouldRetry = await this.shouldRetry(response);
12168
+ if (retriesRemaining && shouldRetry) {
12169
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12170
+ // We don't need the body of this response.
12171
+ await CancelReadableStream(response.body);
12172
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12173
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12174
+ retryOfRequestLogID,
12175
+ url: response.url,
12176
+ status: response.status,
12177
+ headers: response.headers,
12178
+ durationMs: headersTime - startTime,
12179
+ }));
12180
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
12181
+ }
12182
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
12183
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12184
+ const errText = await response.text().catch((err) => castToError(err).message);
12185
+ const errJSON = safeJSON(errText);
12186
+ const errMessage = errJSON ? undefined : errText;
12187
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12188
+ retryOfRequestLogID,
12189
+ url: response.url,
12190
+ status: response.status,
12191
+ headers: response.headers,
12192
+ message: errMessage,
12193
+ durationMs: Date.now() - startTime,
12194
+ }));
12195
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
12196
+ throw err;
12197
+ }
12198
+ loggerFor(this).info(responseInfo);
12199
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
12200
+ retryOfRequestLogID,
12201
+ url: response.url,
12202
+ status: response.status,
12203
+ headers: response.headers,
12204
+ durationMs: headersTime - startTime,
12205
+ }));
12206
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
12207
+ }
12208
+ getAPIList(path, Page, opts) {
12209
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
12210
+ }
12211
+ requestAPIList(Page, options) {
12212
+ const request = this.makeRequest(options, null, undefined);
12213
+ return new PagePromise(this, request, Page);
12214
+ }
12215
+ async fetchWithTimeout(url, init, ms, controller) {
12216
+ const { signal, method, ...options } = init || {};
12217
+ if (signal)
12218
+ signal.addEventListener('abort', () => controller.abort());
12219
+ const timeout = setTimeout(() => controller.abort(), ms);
12220
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
12221
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
12222
+ const fetchOptions = {
12223
+ signal: controller.signal,
12224
+ ...(isReadableBody ? { duplex: 'half' } : {}),
12225
+ method: 'GET',
12226
+ ...options,
12227
+ };
12228
+ if (method) {
12229
+ // Custom methods like 'patch' need to be uppercased
12230
+ // See https://github.com/nodejs/undici/issues/2294
12231
+ fetchOptions.method = method.toUpperCase();
12232
+ }
12233
+ try {
12234
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
12235
+ return await this.fetch.call(undefined, url, fetchOptions);
12236
+ }
12237
+ finally {
12238
+ clearTimeout(timeout);
12239
+ }
12240
+ }
12241
+ async shouldRetry(response) {
12242
+ // Note this is not a standard header.
12243
+ const shouldRetryHeader = response.headers.get('x-should-retry');
12244
+ // If the server explicitly says whether or not to retry, obey.
12245
+ if (shouldRetryHeader === 'true')
12246
+ return true;
12247
+ if (shouldRetryHeader === 'false')
12248
+ return false;
12249
+ // Retry on request timeouts.
12250
+ if (response.status === 408)
12251
+ return true;
12252
+ // Retry on lock timeouts.
12253
+ if (response.status === 409)
12254
+ return true;
12255
+ // Retry on rate limits.
12256
+ if (response.status === 429)
12257
+ return true;
12258
+ // Retry internal errors.
12259
+ if (response.status >= 500)
12260
+ return true;
12261
+ return false;
12262
+ }
12263
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
12264
+ let timeoutMillis;
12265
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
12266
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
12267
+ if (retryAfterMillisHeader) {
12268
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
12269
+ if (!Number.isNaN(timeoutMs)) {
12270
+ timeoutMillis = timeoutMs;
12271
+ }
12272
+ }
12273
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
12274
+ const retryAfterHeader = responseHeaders?.get('retry-after');
12275
+ if (retryAfterHeader && !timeoutMillis) {
12276
+ const timeoutSeconds = parseFloat(retryAfterHeader);
12277
+ if (!Number.isNaN(timeoutSeconds)) {
12278
+ timeoutMillis = timeoutSeconds * 1000;
12279
+ }
12280
+ else {
12281
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
12282
+ }
12283
+ }
12284
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
12285
+ // just do what it says, but otherwise calculate a default
12286
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
12287
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12288
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
12289
+ }
12290
+ await sleep(timeoutMillis);
12291
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
12292
+ }
12293
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
12294
+ const initialRetryDelay = 0.5;
12295
+ const maxRetryDelay = 8.0;
12296
+ const numRetries = maxRetries - retriesRemaining;
12297
+ // Apply exponential backoff, but not more than the max.
12298
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
12299
+ // Apply some jitter, take up to at most 25 percent of the retry time.
12300
+ const jitter = 1 - Math.random() * 0.25;
12301
+ return sleepSeconds * jitter * 1000;
12302
+ }
12303
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
12304
+ const options = { ...inputOptions };
12305
+ const { method, path, query, defaultBaseURL } = options;
12306
+ const url = this.buildURL(path, query, defaultBaseURL);
12307
+ if ('timeout' in options)
12308
+ validatePositiveInteger('timeout', options.timeout);
12309
+ options.timeout = options.timeout ?? this.timeout;
12310
+ const { bodyHeaders, body } = this.buildBody({ options });
12311
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
12312
+ const req = {
12313
+ method,
12314
+ headers: reqHeaders,
12315
+ ...(options.signal && { signal: options.signal }),
12316
+ ...(globalThis.ReadableStream &&
12317
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
12318
+ ...(body && { body }),
12319
+ ...(this.fetchOptions ?? {}),
12320
+ ...(options.fetchOptions ?? {}),
12321
+ };
12322
+ return { req, url, timeout: options.timeout };
12323
+ }
12324
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
12325
+ let idempotencyHeaders = {};
12326
+ if (this.idempotencyHeader && method !== 'get') {
12327
+ if (!options.idempotencyKey)
12328
+ options.idempotencyKey = this.defaultIdempotencyKey();
12329
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
12330
+ }
12331
+ const headers = buildHeaders([
12332
+ idempotencyHeaders,
12333
+ {
12334
+ Accept: 'application/json',
12335
+ 'User-Agent': this.getUserAgent(),
12336
+ 'X-Stainless-Retry-Count': String(retryCount),
12337
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
12338
+ ...getPlatformHeaders(),
12339
+ },
12340
+ await this.authHeaders(options),
12341
+ this._options.defaultHeaders,
12342
+ bodyHeaders,
12343
+ options.headers,
12344
+ ]);
12345
+ this.validateHeaders(headers);
12346
+ return headers.values;
12347
+ }
12348
+ buildBody({ options: { body, headers: rawHeaders } }) {
12349
+ if (!body) {
12350
+ return { bodyHeaders: undefined, body: undefined };
12351
+ }
12352
+ const headers = buildHeaders([rawHeaders]);
12353
+ if (
12354
+ // Pass raw type verbatim
12355
+ ArrayBuffer.isView(body) ||
12356
+ body instanceof ArrayBuffer ||
12357
+ body instanceof DataView ||
12358
+ (typeof body === 'string' &&
12359
+ // Preserve legacy string encoding behavior for now
12360
+ headers.values.has('content-type')) ||
12361
+ // `Blob` is superset of `File`
12362
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
12363
+ // `FormData` -> `multipart/form-data`
12364
+ body instanceof FormData ||
12365
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
12366
+ body instanceof URLSearchParams ||
12367
+ // Send chunked stream (each chunk has own `length`)
12368
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
12369
+ return { bodyHeaders: undefined, body: body };
12370
+ }
12371
+ else if (typeof body === 'object' &&
12372
+ (Symbol.asyncIterator in body ||
12373
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
12374
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
12375
+ }
12376
+ else {
12377
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
12378
+ }
12379
+ }
12380
+ }
12381
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
12382
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
12383
+ };
12384
+ DodoPayments.DodoPayments = _a;
12385
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
12386
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
12387
+ DodoPayments.APIError = APIError;
12388
+ DodoPayments.APIConnectionError = APIConnectionError;
12389
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
12390
+ DodoPayments.APIUserAbortError = APIUserAbortError;
12391
+ DodoPayments.NotFoundError = NotFoundError;
12392
+ DodoPayments.ConflictError = ConflictError;
12393
+ DodoPayments.RateLimitError = RateLimitError;
12394
+ DodoPayments.BadRequestError = BadRequestError;
12395
+ DodoPayments.AuthenticationError = AuthenticationError;
12396
+ DodoPayments.InternalServerError = InternalServerError;
12397
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
12398
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
12399
+ DodoPayments.toFile = toFile;
12400
+ DodoPayments.CheckoutSessions = CheckoutSessions;
12401
+ DodoPayments.Payments = Payments;
12402
+ DodoPayments.Subscriptions = Subscriptions;
12403
+ DodoPayments.Invoices = Invoices;
12404
+ DodoPayments.Licenses = Licenses;
12405
+ DodoPayments.LicenseKeys = LicenseKeys;
12406
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
12407
+ DodoPayments.Customers = Customers;
12408
+ DodoPayments.Refunds = Refunds;
12409
+ DodoPayments.Disputes = Disputes;
12410
+ DodoPayments.Payouts = Payouts;
12411
+ DodoPayments.Products = Products;
12412
+ DodoPayments.Misc = Misc;
12413
+ DodoPayments.Discounts = Discounts;
12414
+ DodoPayments.Addons = Addons;
12415
+ DodoPayments.Brands = Brands;
12416
+ DodoPayments.Webhooks = Webhooks$1;
12417
+ DodoPayments.WebhookEvents = WebhookEvents;
12418
+ DodoPayments.UsageEvents = UsageEvents;
12419
+ DodoPayments.Meters = Meters;
12420
+
12421
+ // src/checkout/checkout.ts
12422
+ var checkoutQuerySchema = objectType({
12423
+ productId: stringType(),
12424
+ quantity: stringType().optional(),
12425
+ // Customer fields
12426
+ fullName: stringType().optional(),
12427
+ firstName: stringType().optional(),
12428
+ lastName: stringType().optional(),
12429
+ email: stringType().optional(),
12430
+ country: stringType().optional(),
12431
+ addressLine: stringType().optional(),
12432
+ city: stringType().optional(),
12433
+ state: stringType().optional(),
12434
+ zipCode: stringType().optional(),
12435
+ // Disable flags
12436
+ disableFullName: stringType().optional(),
12437
+ disableFirstName: stringType().optional(),
12438
+ disableLastName: stringType().optional(),
12439
+ disableEmail: stringType().optional(),
12440
+ disableCountry: stringType().optional(),
12441
+ disableAddressLine: stringType().optional(),
12442
+ disableCity: stringType().optional(),
12443
+ disableState: stringType().optional(),
12444
+ disableZipCode: stringType().optional(),
12445
+ // Advanced controls
12446
+ paymentCurrency: stringType().optional(),
12447
+ showCurrencySelector: stringType().optional(),
12448
+ paymentAmount: stringType().optional(),
12449
+ showDiscounts: stringType().optional()
12450
+ // Metadata (allow any key starting with metadata_)
12451
+ // We'll handle metadata separately in the handler
12452
+ }).catchall(unknownType());
12453
+ var dynamicCheckoutBodySchema = objectType({
12454
+ // For subscription
12455
+ product_id: stringType().optional(),
12456
+ quantity: numberType().optional(),
12457
+ // For one-time payment
12458
+ product_cart: arrayType(
12459
+ objectType({
12460
+ product_id: stringType(),
12461
+ quantity: numberType()
12462
+ })
12463
+ ).optional(),
12464
+ // Common fields
12465
+ billing: objectType({
12466
+ city: stringType(),
12467
+ country: stringType(),
12468
+ state: stringType(),
12469
+ street: stringType(),
12470
+ zipcode: stringType()
12471
+ }),
12472
+ customer: objectType({
12473
+ customer_id: stringType().optional(),
12474
+ email: stringType().optional(),
12475
+ name: stringType().optional()
12476
+ }),
12477
+ discount_id: stringType().optional(),
12478
+ addons: arrayType(
12479
+ objectType({
12480
+ addon_id: stringType(),
12481
+ quantity: numberType()
12482
+ })
12483
+ ).optional(),
12484
+ metadata: recordType(stringType(), stringType()).optional(),
12485
+ currency: stringType().optional()
12486
+ // Allow any additional fields (for future compatibility)
12487
+ }).catchall(unknownType());
12488
+ var checkoutSessionProductCartItemSchema = objectType({
12489
+ product_id: stringType().min(1, "Product ID is required"),
12490
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
12491
+ addons: arrayType(
12492
+ objectType({
12493
+ addon_id: stringType(),
12494
+ quantity: numberType().int().nonnegative()
12495
+ })
12496
+ ).optional(),
12497
+ amount: numberType().int().nonnegative(
12498
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
12499
+ ).optional()
12500
+ });
12501
+ var checkoutSessionCustomerSchema = unionType([
12502
+ objectType({
12503
+ email: stringType().email(),
12504
+ name: stringType().min(1).optional(),
12505
+ phone_number: stringType().optional()
12506
+ }),
12507
+ objectType({
12508
+ customer_id: stringType()
12509
+ })
12510
+ ]).optional();
12511
+ var checkoutSessionBillingAddressSchema = objectType({
12512
+ street: stringType().optional(),
12513
+ city: stringType().optional(),
12514
+ state: stringType().optional(),
12515
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
12516
+ zipcode: stringType().optional()
12517
+ }).optional();
12518
+ var paymentMethodTypeSchema = enumType([
12519
+ "credit",
12520
+ "debit",
12521
+ "upi_collect",
12522
+ "upi_intent",
12523
+ "apple_pay",
12524
+ "cashapp",
12525
+ "google_pay",
12526
+ "multibanco",
12527
+ "bancontact_card",
12528
+ "eps",
12529
+ "ideal",
12530
+ "przelewy24",
12531
+ "paypal",
12532
+ "affirm",
12533
+ "klarna",
12534
+ "sepa",
12535
+ "ach",
12536
+ "amazon_pay",
12537
+ "afterpay_clearpay"
12538
+ ]);
12539
+ var checkoutSessionCustomizationSchema = objectType({
12540
+ theme: enumType(["light", "dark", "system"]).optional(),
12541
+ show_order_details: booleanType().optional(),
12542
+ show_on_demand_tag: booleanType().optional(),
12543
+ force_language: stringType().optional()
12544
+ }).optional();
12545
+ var checkoutSessionFeatureFlagsSchema = objectType({
12546
+ allow_currency_selection: booleanType().optional(),
12547
+ allow_discount_code: booleanType().optional(),
12548
+ allow_phone_number_collection: booleanType().optional(),
12549
+ allow_tax_id: booleanType().optional(),
12550
+ always_create_new_customer: booleanType().optional()
12551
+ }).optional();
12552
+ var checkoutSessionOnDemandSchema = objectType({
12553
+ mandate_only: booleanType(),
12554
+ product_price: numberType().int().optional(),
12555
+ product_currency: stringType().length(3).optional(),
12556
+ product_description: stringType().optional(),
12557
+ adaptive_currency_fees_inclusive: booleanType().optional()
12558
+ }).optional();
12559
+ var checkoutSessionSubscriptionDataSchema = objectType({
12560
+ trial_period_days: numberType().int().nonnegative().optional(),
12561
+ on_demand: checkoutSessionOnDemandSchema
12562
+ }).optional();
12563
+ var checkoutSessionPayloadSchema = objectType({
12564
+ // Required fields
12565
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
12566
+ // Optional fields
12567
+ customer: checkoutSessionCustomerSchema,
12568
+ billing_address: checkoutSessionBillingAddressSchema,
12569
+ return_url: stringType().url().optional(),
12570
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
12571
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
12572
+ show_saved_payment_methods: booleanType().optional(),
12573
+ confirm: booleanType().optional(),
12574
+ discount_code: stringType().optional(),
12575
+ metadata: recordType(stringType(), stringType()).optional(),
12576
+ customization: checkoutSessionCustomizationSchema,
12577
+ feature_flags: checkoutSessionFeatureFlagsSchema,
12578
+ subscription_data: checkoutSessionSubscriptionDataSchema,
12579
+ force_3ds: booleanType().optional()
12580
+ });
12581
+ var checkoutSessionResponseSchema = objectType({
12582
+ session_id: stringType().min(1, "Session ID is required"),
12583
+ checkout_url: stringType().url("Invalid checkout URL")
12584
+ });
12585
+ var createCheckoutSession = async (payload, config) => {
12586
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
12587
+ if (!validation.success) {
12588
+ throw new Error(
12589
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12590
+ );
12591
+ }
12592
+ const dodopayments = new DodoPayments({
12593
+ bearerToken: config.bearerToken,
12594
+ environment: config.environment
12595
+ });
12596
+ try {
12597
+ const sdkPayload = {
12598
+ ...validation.data,
12599
+ ...validation.data.billing_address && {
12600
+ billing_address: {
12601
+ ...validation.data.billing_address,
12602
+ country: validation.data.billing_address.country
12603
+ }
12604
+ }
12605
+ };
12606
+ const session = await dodopayments.checkoutSessions.create(
12607
+ sdkPayload
12608
+ );
12609
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
12610
+ if (!responseValidation.success) {
12611
+ throw new Error(
12612
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12613
+ );
12614
+ }
12615
+ return responseValidation.data;
12616
+ } catch (error) {
12617
+ if (error instanceof Error) {
12618
+ console.error("Dodo Payments Checkout Session API Error:", {
12619
+ message: error.message,
12620
+ payload: validation.data,
12621
+ config: {
12622
+ environment: config.environment,
12623
+ hasBearerToken: !!config.bearerToken
12624
+ }
12625
+ });
12626
+ throw new Error(`Failed to create checkout session: ${error.message}`);
12627
+ }
12628
+ console.error("Unknown error creating checkout session:", error);
12629
+ throw new Error(
12630
+ "Failed to create checkout session due to an unknown error"
12631
+ );
12632
+ }
12633
+ };
12634
+ var buildCheckoutUrl = async ({
12635
+ queryParams,
12636
+ body,
12637
+ sessionPayload,
12638
+ returnUrl,
12639
+ bearerToken,
12640
+ environment,
12641
+ type = "static"
12642
+ }) => {
12643
+ if (type === "session") {
12644
+ if (!sessionPayload) {
12645
+ throw new Error("sessionPayload is required when type is 'session'");
12646
+ }
12647
+ const session = await createCheckoutSession(sessionPayload, {
12648
+ bearerToken,
12649
+ environment
12650
+ });
12651
+ return session.checkout_url;
12652
+ }
12653
+ const inputData = type === "dynamic" ? body : queryParams;
12654
+ let parseResult;
12655
+ if (type === "dynamic") {
12656
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
12657
+ } else {
12658
+ parseResult = checkoutQuerySchema.safeParse(inputData);
12659
+ }
12660
+ const { success, data, error } = parseResult;
12661
+ if (!success) {
12662
+ throw new Error(
12663
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
12664
+ ${error.message}`
12665
+ );
12666
+ }
12667
+ if (type !== "dynamic") {
12668
+ const {
12669
+ productId,
12670
+ quantity: quantity2,
12671
+ fullName,
12672
+ firstName,
12673
+ lastName,
12674
+ email,
12675
+ country,
12676
+ addressLine,
12677
+ city,
12678
+ state,
12679
+ zipCode,
12680
+ disableFullName,
12681
+ disableFirstName,
12682
+ disableLastName,
12683
+ disableEmail,
12684
+ disableCountry,
12685
+ disableAddressLine,
12686
+ disableCity,
12687
+ disableState,
12688
+ disableZipCode,
12689
+ paymentCurrency,
12690
+ showCurrencySelector,
12691
+ paymentAmount,
12692
+ showDiscounts
12693
+ // metadata handled below
12694
+ } = data;
12695
+ const dodopayments2 = new DodoPayments({
12696
+ bearerToken,
12697
+ environment
12698
+ });
12699
+ if (!productId) throw new Error("Missing required field: productId");
12700
+ try {
12701
+ await dodopayments2.products.retrieve(productId);
12702
+ } catch (err) {
12703
+ console.error(err);
12704
+ throw new Error("Product not found");
12705
+ }
12706
+ const url = new URL(
12707
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
12708
+ );
12709
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
12710
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
12711
+ if (fullName) url.searchParams.set("fullName", String(fullName));
12712
+ if (firstName) url.searchParams.set("firstName", String(firstName));
12713
+ if (lastName) url.searchParams.set("lastName", String(lastName));
12714
+ if (email) url.searchParams.set("email", String(email));
12715
+ if (country) url.searchParams.set("country", String(country));
12716
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
12717
+ if (city) url.searchParams.set("city", String(city));
12718
+ if (state) url.searchParams.set("state", String(state));
12719
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
12720
+ if (disableFullName === "true")
12721
+ url.searchParams.set("disableFullName", "true");
12722
+ if (disableFirstName === "true")
12723
+ url.searchParams.set("disableFirstName", "true");
12724
+ if (disableLastName === "true")
12725
+ url.searchParams.set("disableLastName", "true");
12726
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
12727
+ if (disableCountry === "true")
12728
+ url.searchParams.set("disableCountry", "true");
12729
+ if (disableAddressLine === "true")
12730
+ url.searchParams.set("disableAddressLine", "true");
12731
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
12732
+ if (disableState === "true") url.searchParams.set("disableState", "true");
12733
+ if (disableZipCode === "true")
12734
+ url.searchParams.set("disableZipCode", "true");
12735
+ if (paymentCurrency)
12736
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
12737
+ if (showCurrencySelector)
12738
+ url.searchParams.set(
12739
+ "showCurrencySelector",
12740
+ String(showCurrencySelector)
12741
+ );
12742
+ if (paymentAmount)
12743
+ url.searchParams.set("paymentAmount", String(paymentAmount));
12744
+ if (showDiscounts)
12745
+ url.searchParams.set("showDiscounts", String(showDiscounts));
12746
+ for (const [key, value] of Object.entries(queryParams || {})) {
12747
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
12748
+ url.searchParams.set(key, String(value));
12749
+ }
12750
+ }
12751
+ return url.toString();
12752
+ }
12753
+ const dyn = data;
12754
+ const {
12755
+ product_id,
12756
+ product_cart,
12757
+ quantity,
12758
+ billing,
12759
+ customer,
12760
+ addons,
12761
+ metadata,
12762
+ allowed_payment_method_types,
12763
+ billing_currency,
12764
+ discount_code,
12765
+ on_demand,
12766
+ return_url: bodyReturnUrl,
12767
+ show_saved_payment_methods,
12768
+ tax_id,
12769
+ trial_period_days
12770
+ } = dyn;
12771
+ const dodopayments = new DodoPayments({
12772
+ bearerToken,
12773
+ environment
12774
+ });
12775
+ let isSubscription = false;
12776
+ let productIdToFetch = product_id;
12777
+ if (!product_id && product_cart && product_cart.length > 0) {
12778
+ productIdToFetch = product_cart[0].product_id;
12779
+ }
12780
+ if (!productIdToFetch)
12781
+ throw new Error(
12782
+ "Missing required field: product_id or product_cart[0].product_id"
12783
+ );
12784
+ let product;
12785
+ try {
12786
+ product = await dodopayments.products.retrieve(productIdToFetch);
12787
+ } catch (err) {
12788
+ console.error(err);
12789
+ throw new Error("Product not found");
12790
+ }
12791
+ isSubscription = Boolean(product.is_recurring);
12792
+ if (isSubscription && !product_id)
12793
+ throw new Error("Missing required field: product_id for subscription");
12794
+ if (!billing) throw new Error("Missing required field: billing");
12795
+ if (!customer) throw new Error("Missing required field: customer");
12796
+ if (isSubscription) {
12797
+ const subscriptionPayload = {
12798
+ billing,
12799
+ customer,
12800
+ product_id,
12801
+ quantity: quantity ? Number(quantity) : 1
12802
+ };
12803
+ if (metadata) subscriptionPayload.metadata = metadata;
12804
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
12805
+ if (addons) subscriptionPayload.addons = addons;
12806
+ if (allowed_payment_method_types)
12807
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
12808
+ if (billing_currency)
12809
+ subscriptionPayload.billing_currency = billing_currency;
12810
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
12811
+ subscriptionPayload.payment_link = true;
12812
+ if (bodyReturnUrl) {
12813
+ subscriptionPayload.return_url = bodyReturnUrl;
12814
+ } else if (returnUrl) {
12815
+ subscriptionPayload.return_url = returnUrl;
12816
+ }
12817
+ if (show_saved_payment_methods)
12818
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
12819
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
12820
+ if (trial_period_days)
12821
+ subscriptionPayload.trial_period_days = trial_period_days;
12822
+ let subscription;
12823
+ try {
12824
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
12825
+ } catch (err) {
12826
+ console.error("Error when creating subscription", err);
12827
+ throw new Error(err instanceof Error ? err.message : String(err));
12831
12828
  }
12832
- }
12833
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
12834
- class Webhook {
12835
- constructor(secret, options) {
12836
- if (!secret) {
12837
- throw new Error("Secret can't be empty.");
12829
+ if (!subscription || !subscription.payment_link) {
12830
+ throw new Error(
12831
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
12832
+ );
12833
+ }
12834
+ return subscription.payment_link;
12835
+ } else {
12836
+ let cart = product_cart;
12837
+ if (!cart && product_id) {
12838
+ cart = [
12839
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
12840
+ ];
12841
+ }
12842
+ if (!cart || cart.length === 0)
12843
+ throw new Error("Missing required field: product_cart or product_id");
12844
+ const paymentPayload = {
12845
+ billing,
12846
+ customer,
12847
+ product_cart: cart
12848
+ };
12849
+ if (metadata) paymentPayload.metadata = metadata;
12850
+ paymentPayload.payment_link = true;
12851
+ if (allowed_payment_method_types)
12852
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
12853
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
12854
+ if (discount_code) paymentPayload.discount_code = discount_code;
12855
+ if (bodyReturnUrl) {
12856
+ paymentPayload.return_url = bodyReturnUrl;
12857
+ } else if (returnUrl) {
12858
+ paymentPayload.return_url = returnUrl;
12859
+ }
12860
+ if (show_saved_payment_methods)
12861
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
12862
+ if (tax_id) paymentPayload.tax_id = tax_id;
12863
+ let payment;
12864
+ try {
12865
+ payment = await dodopayments.payments.create(paymentPayload);
12866
+ } catch (err) {
12867
+ console.error("Error when creating payment link", err);
12868
+ throw new Error(err instanceof Error ? err.message : String(err));
12869
+ }
12870
+ if (!payment || !payment.payment_link) {
12871
+ throw new Error(
12872
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
12873
+ );
12874
+ }
12875
+ return payment.payment_link;
12876
+ }
12877
+ };
12878
+
12879
+ const Checkout = (config) => {
12880
+ const getHandler = async (req) => {
12881
+ const { searchParams } = new URL(req.url);
12882
+ const queryParams = Object.fromEntries(searchParams);
12883
+ if (!queryParams.productId) {
12884
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12885
+ status: 400,
12886
+ });
12838
12887
  }
12839
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
12840
- if (secret instanceof Uint8Array) {
12841
- this.key = secret;
12842
- }
12843
- else {
12844
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
12888
+ const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
12889
+ if (!success) {
12890
+ if (error.errors.some((e) => e.path.toString() === "productId")) {
12891
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12892
+ status: 400,
12893
+ });
12845
12894
  }
12895
+ return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
12896
+ status: 400,
12897
+ });
12846
12898
  }
12847
- else {
12848
- if (typeof secret !== "string") {
12849
- throw new Error("Expected secret to be of type string");
12850
- }
12851
- if (secret.startsWith(Webhook.prefix)) {
12852
- secret = secret.substring(Webhook.prefix.length);
12853
- }
12854
- this.key = base64.decode(secret);
12899
+ let url = "";
12900
+ try {
12901
+ url = await buildCheckoutUrl({ queryParams: data, ...config });
12855
12902
  }
12856
- }
12857
- verify(payload, headers_) {
12858
- const headers = {};
12859
- for (const key of Object.keys(headers_)) {
12860
- headers[key.toLowerCase()] = headers_[key];
12903
+ catch (error) {
12904
+ return new serverExports.NextResponse(error.message, { status: 400 });
12861
12905
  }
12862
- const msgId = headers["webhook-id"];
12863
- const msgSignature = headers["webhook-signature"];
12864
- const msgTimestamp = headers["webhook-timestamp"];
12865
- if (!msgSignature || !msgId || !msgTimestamp) {
12866
- throw new WebhookVerificationError("Missing required headers");
12906
+ return serverExports.NextResponse.json({ checkout_url: url });
12907
+ };
12908
+ const postHandler = async (req) => {
12909
+ let body;
12910
+ try {
12911
+ body = await req.json();
12867
12912
  }
12868
- const timestamp = this.verifyTimestamp(msgTimestamp);
12869
- const computedSignature = this.sign(msgId, timestamp, payload);
12870
- const expectedSignature = computedSignature.split(",")[1];
12871
- const passedSignatures = msgSignature.split(" ");
12872
- const encoder = new globalThis.TextEncoder();
12873
- for (const versionedSignature of passedSignatures) {
12874
- const [version, signature] = versionedSignature.split(",");
12875
- if (version !== "v1") {
12876
- continue;
12913
+ catch (e) {
12914
+ return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
12915
+ }
12916
+ if (config.type === "dynamic") {
12917
+ // Handle dynamic checkout
12918
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
12919
+ if (!success) {
12920
+ return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
12921
+ status: 400,
12922
+ });
12877
12923
  }
12878
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
12879
- return JSON.parse(payload.toString());
12924
+ let url = "";
12925
+ try {
12926
+ url = await buildCheckoutUrl({
12927
+ body: data,
12928
+ ...config,
12929
+ type: "dynamic",
12930
+ });
12880
12931
  }
12881
- }
12882
- throw new WebhookVerificationError("No matching signature found");
12883
- }
12884
- sign(msgId, timestamp, payload) {
12885
- if (typeof payload === "string") ;
12886
- else if (payload.constructor.name === "Buffer") {
12887
- payload = payload.toString();
12932
+ catch (error) {
12933
+ return new serverExports.NextResponse(error.message, { status: 400 });
12934
+ }
12935
+ return serverExports.NextResponse.json({ checkout_url: url });
12888
12936
  }
12889
12937
  else {
12890
- throw new Error("Expected payload to be of type string or Buffer.");
12891
- }
12892
- const encoder = new TextEncoder();
12893
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
12894
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
12895
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
12896
- return `v1,${expectedSignature}`;
12897
- }
12898
- verifyTimestamp(timestampHeader) {
12899
- const now = Math.floor(Date.now() / 1000);
12900
- const timestamp = parseInt(timestampHeader, 10);
12901
- if (isNaN(timestamp)) {
12902
- throw new WebhookVerificationError("Invalid Signature Headers");
12903
- }
12904
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
12905
- throw new WebhookVerificationError("Message timestamp too old");
12938
+ // Handle checkout session
12939
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12940
+ if (!success) {
12941
+ return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12942
+ status: 400,
12943
+ });
12944
+ }
12945
+ let url = "";
12946
+ try {
12947
+ url = await buildCheckoutUrl({
12948
+ sessionPayload: data,
12949
+ ...config,
12950
+ type: "session",
12951
+ });
12952
+ }
12953
+ catch (error) {
12954
+ return new serverExports.NextResponse(error.message, { status: 400 });
12955
+ }
12956
+ return serverExports.NextResponse.json({ checkout_url: url });
12906
12957
  }
12907
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
12908
- throw new WebhookVerificationError("Message timestamp too new");
12958
+ };
12959
+ return (req) => {
12960
+ if (req.method === "POST") {
12961
+ return postHandler(req);
12909
12962
  }
12910
- return new Date(timestamp * 1000);
12911
- }
12912
- }
12913
- Webhook_1 = dist.Webhook = Webhook;
12914
- Webhook.prefix = "whsec_";
12963
+ return getHandler(req);
12964
+ };
12965
+ };
12915
12966
 
12916
12967
  // src/schemas/webhook.ts
12917
12968
  var PaymentSchema = objectType({