@dodopayments/sveltekit 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -94,7 +94,7 @@ function error(status, body) {
94
94
 
95
95
  new TextEncoder();
96
96
 
97
- const VERSION = '1.42.0'; // x-release-please-version
97
+ const VERSION = '1.51.2'; // x-release-please-version
98
98
 
99
99
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
100
100
  class DodoPaymentsError extends Error {
@@ -1238,6 +1238,46 @@ class DefaultPageNumberPagination extends AbstractPage {
1238
1238
  return { params: { page_number: currentPage + 1 } };
1239
1239
  }
1240
1240
  }
1241
+ class CursorPagePagination extends AbstractPage {
1242
+ constructor(client, response, body, options) {
1243
+ super(client, response, body, options);
1244
+ this.data = body.data || [];
1245
+ this.iterator = body.iterator || '';
1246
+ this.done = body.done || false;
1247
+ }
1248
+ getPaginatedItems() {
1249
+ return this.data ?? [];
1250
+ }
1251
+ hasNextPage() {
1252
+ if (this.done === false) {
1253
+ return false;
1254
+ }
1255
+ return super.hasNextPage();
1256
+ }
1257
+ // @deprecated Please use `nextPageInfo()` instead
1258
+ nextPageParams() {
1259
+ const info = this.nextPageInfo();
1260
+ if (!info)
1261
+ return null;
1262
+ if ('params' in info)
1263
+ return info.params;
1264
+ const params = Object.fromEntries(info.url.searchParams);
1265
+ if (!Object.keys(params).length)
1266
+ return null;
1267
+ return params;
1268
+ }
1269
+ nextPageInfo() {
1270
+ const cursor = this.iterator;
1271
+ if (!cursor) {
1272
+ return null;
1273
+ }
1274
+ return {
1275
+ params: {
1276
+ iterator: cursor,
1277
+ },
1278
+ };
1279
+ }
1280
+ }
1241
1281
 
1242
1282
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1243
1283
  class APIResource {
@@ -1296,6 +1336,13 @@ class Brands extends APIResource {
1296
1336
  }
1297
1337
  }
1298
1338
 
1339
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1340
+ class CheckoutSessions extends APIResource {
1341
+ create(body, options) {
1342
+ return this._client.post('/checkouts', { body, ...options });
1343
+ }
1344
+ }
1345
+
1299
1346
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1300
1347
  let CustomerPortal$1 = class CustomerPortal extends APIResource {
1301
1348
  create(customerId, params = {}, options) {
@@ -1701,26 +1748,79 @@ Subscriptions.SubscriptionListResponsesDefaultPageNumberPagination =
1701
1748
  SubscriptionListResponsesDefaultPageNumberPagination;
1702
1749
 
1703
1750
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1704
- class WebhookEvents extends APIResource {
1751
+ let Headers$1 = class Headers extends APIResource {
1705
1752
  /**
1706
- * @deprecated
1753
+ * Get a webhook by id
1707
1754
  */
1708
- retrieve(webhookEventId, options) {
1709
- return this._client.get(`/webhook_events/${webhookEventId}`, options);
1755
+ retrieve(webhookId, options) {
1756
+ return this._client.get(`/webhooks/${webhookId}/headers`, options);
1757
+ }
1758
+ /**
1759
+ * Patch a webhook by id
1760
+ */
1761
+ update(webhookId, body, options) {
1762
+ return this._client.patch(`/webhooks/${webhookId}/headers`, {
1763
+ body,
1764
+ ...options,
1765
+ headers: { Accept: '*/*', ...options?.headers },
1766
+ });
1767
+ }
1768
+ };
1769
+
1770
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1771
+ let Webhooks$1 = class Webhooks extends APIResource {
1772
+ constructor() {
1773
+ super(...arguments);
1774
+ this.headers = new Headers$1(this._client);
1775
+ }
1776
+ /**
1777
+ * Create a new webhook
1778
+ */
1779
+ create(body, options) {
1780
+ return this._client.post('/webhooks', { body, ...options });
1781
+ }
1782
+ /**
1783
+ * Get a webhook by id
1784
+ */
1785
+ retrieve(webhookId, options) {
1786
+ return this._client.get(`/webhooks/${webhookId}`, options);
1787
+ }
1788
+ /**
1789
+ * Patch a webhook by id
1790
+ */
1791
+ update(webhookId, body, options) {
1792
+ return this._client.patch(`/webhooks/${webhookId}`, { body, ...options });
1710
1793
  }
1711
1794
  list(query = {}, options) {
1712
1795
  if (isRequestOptions(query)) {
1713
1796
  return this.list({}, query);
1714
1797
  }
1715
- return this._client.getAPIList('/webhook_events', WebhookEventsDefaultPageNumberPagination, {
1716
- query,
1798
+ return this._client.getAPIList('/webhooks', WebhookDetailsCursorPagePagination, { query, ...options });
1799
+ }
1800
+ /**
1801
+ * Delete a webhook by id
1802
+ */
1803
+ delete(webhookId, options) {
1804
+ return this._client.delete(`/webhooks/${webhookId}`, {
1717
1805
  ...options,
1806
+ headers: { Accept: '*/*', ...options?.headers },
1718
1807
  });
1719
1808
  }
1809
+ /**
1810
+ * Get webhook secret by id
1811
+ */
1812
+ retrieveSecret(webhookId, options) {
1813
+ return this._client.get(`/webhooks/${webhookId}/secret`, options);
1814
+ }
1815
+ };
1816
+ class WebhookDetailsCursorPagePagination extends CursorPagePagination {
1720
1817
  }
1721
- class WebhookEventsDefaultPageNumberPagination extends DefaultPageNumberPagination {
1818
+ Webhooks$1.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1819
+ Webhooks$1.Headers = Headers$1;
1820
+
1821
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1822
+ class WebhookEvents extends APIResource {
1722
1823
  }
1723
- WebhookEvents.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1724
1824
 
1725
1825
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1726
1826
  var _DodoPayments_instances, _a;
@@ -1767,6 +1867,7 @@ class DodoPayments extends APIClient {
1767
1867
  fetch: options.fetch,
1768
1868
  });
1769
1869
  _DodoPayments_instances.add(this);
1870
+ this.checkoutSessions = new CheckoutSessions(this);
1770
1871
  this.payments = new Payments(this);
1771
1872
  this.subscriptions = new Subscriptions(this);
1772
1873
  this.invoices = new Invoices(this);
@@ -1783,6 +1884,7 @@ class DodoPayments extends APIClient {
1783
1884
  this.discounts = new Discounts(this);
1784
1885
  this.addons = new Addons(this);
1785
1886
  this.brands = new Brands(this);
1887
+ this.webhooks = new Webhooks$1(this);
1786
1888
  this._options = options;
1787
1889
  this.bearerToken = bearerToken;
1788
1890
  }
@@ -1817,6 +1919,7 @@ DodoPayments.PermissionDeniedError = PermissionDeniedError;
1817
1919
  DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
1818
1920
  DodoPayments.toFile = toFile;
1819
1921
  DodoPayments.fileFromPath = fileFromPath;
1922
+ DodoPayments.CheckoutSessions = CheckoutSessions;
1820
1923
  DodoPayments.Payments = Payments;
1821
1924
  DodoPayments.PaymentListResponsesDefaultPageNumberPagination =
1822
1925
  PaymentListResponsesDefaultPageNumberPagination;
@@ -1839,7 +1942,6 @@ DodoPayments.DisputeListResponsesDefaultPageNumberPagination =
1839
1942
  DodoPayments.Payouts = Payouts;
1840
1943
  DodoPayments.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
1841
1944
  DodoPayments.WebhookEvents = WebhookEvents;
1842
- DodoPayments.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1843
1945
  DodoPayments.Products = Products;
1844
1946
  DodoPayments.ProductListResponsesDefaultPageNumberPagination =
1845
1947
  ProductListResponsesDefaultPageNumberPagination;
@@ -1849,7 +1951,20 @@ DodoPayments.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPa
1849
1951
  DodoPayments.Addons = Addons;
1850
1952
  DodoPayments.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
1851
1953
  DodoPayments.Brands = Brands;
1954
+ DodoPayments.Webhooks = Webhooks$1;
1955
+ DodoPayments.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1852
1956
 
1957
+ var __assign = (undefined && undefined.__assign) || function () {
1958
+ __assign = Object.assign || function(t) {
1959
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1960
+ s = arguments[i];
1961
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1962
+ t[p] = s[p];
1963
+ }
1964
+ return t;
1965
+ };
1966
+ return __assign.apply(this, arguments);
1967
+ };
1853
1968
  var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1854
1969
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1855
1970
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -1886,7 +2001,8 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
1886
2001
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1887
2002
  }
1888
2003
  };
1889
- var checkoutQuerySchema = z.object({
2004
+ var checkoutQuerySchema = z
2005
+ .object({
1890
2006
  productId: z.string(),
1891
2007
  quantity: z.string().optional(),
1892
2008
  // Customer fields
@@ -1916,7 +2032,8 @@ var checkoutQuerySchema = z.object({
1916
2032
  showDiscounts: z.string().optional(),
1917
2033
  // Metadata (allow any key starting with metadata_)
1918
2034
  // We'll handle metadata separately in the handler
1919
- }).catchall(z.unknown());
2035
+ })
2036
+ .catchall(z.unknown());
1920
2037
  // Add Zod schema for dynamic checkout body
1921
2038
  var dynamicCheckoutBodySchema = z
1922
2039
  .object({
@@ -1955,12 +2072,192 @@ var dynamicCheckoutBodySchema = z
1955
2072
  // Allow any additional fields (for future compatibility)
1956
2073
  })
1957
2074
  .catchall(z.unknown());
2075
+ // ========================================
2076
+ // CHECKOUT SESSIONS SCHEMAS & TYPES
2077
+ // ========================================
2078
+ // Product cart item schema for checkout sessions
2079
+ var checkoutSessionProductCartItemSchema = z.object({
2080
+ product_id: z.string().min(1, "Product ID is required"),
2081
+ quantity: z.number().int().positive("Quantity must be a positive integer"),
2082
+ });
2083
+ // Customer information schema for checkout sessions
2084
+ var checkoutSessionCustomerSchema = z
2085
+ .object({
2086
+ email: z.string().email().optional(),
2087
+ name: z.string().min(1).optional(),
2088
+ phone_number: z.string().optional(),
2089
+ })
2090
+ .optional();
2091
+ // Billing address schema for checkout sessions
2092
+ var checkoutSessionBillingAddressSchema = z
2093
+ .object({
2094
+ street: z.string().optional(),
2095
+ city: z.string().optional(),
2096
+ state: z.string().optional(),
2097
+ country: z.string().length(2, "Country must be a 2-letter ISO code"),
2098
+ zipcode: z.string().optional(),
2099
+ })
2100
+ .optional();
2101
+ // Payment method types enum based on Dodo Payments documentation
2102
+ var paymentMethodTypeSchema = z.enum([
2103
+ "credit",
2104
+ "debit",
2105
+ "upi_collect",
2106
+ "upi_intent",
2107
+ "apple_pay",
2108
+ "google_pay",
2109
+ "amazon_pay",
2110
+ "klarna",
2111
+ "affirm",
2112
+ "afterpay_clearpay",
2113
+ "sepa",
2114
+ "ach",
2115
+ ]);
2116
+ // Customization options schema
2117
+ var checkoutSessionCustomizationSchema = z
2118
+ .object({
2119
+ theme: z.enum(["light", "dark", "system"]).optional(),
2120
+ show_order_details: z.boolean().optional(),
2121
+ show_on_demand_tag: z.boolean().optional(),
2122
+ })
2123
+ .optional();
2124
+ // Feature flags schema
2125
+ var checkoutSessionFeatureFlagsSchema = z
2126
+ .object({
2127
+ allow_currency_selection: z.boolean().optional(),
2128
+ allow_discount_code: z.boolean().optional(),
2129
+ allow_phone_number_collection: z.boolean().optional(),
2130
+ allow_tax_id: z.boolean().optional(),
2131
+ always_create_new_customer: z.boolean().optional(),
2132
+ })
2133
+ .optional();
2134
+ // Subscription data schema
2135
+ var checkoutSessionSubscriptionDataSchema = z
2136
+ .object({
2137
+ trial_period_days: z.number().int().nonnegative().optional(),
2138
+ })
2139
+ .optional();
2140
+ // Main checkout session payload schema
2141
+ var checkoutSessionPayloadSchema = z.object({
2142
+ // Required fields
2143
+ product_cart: z
2144
+ .array(checkoutSessionProductCartItemSchema)
2145
+ .min(1, "At least one product is required"),
2146
+ // Optional fields
2147
+ customer: checkoutSessionCustomerSchema,
2148
+ billing_address: checkoutSessionBillingAddressSchema,
2149
+ return_url: z.string().url().optional(),
2150
+ allowed_payment_method_types: z.array(paymentMethodTypeSchema).optional(),
2151
+ billing_currency: z
2152
+ .string()
2153
+ .length(3, "Currency must be a 3-letter ISO code")
2154
+ .optional(),
2155
+ show_saved_payment_methods: z.boolean().optional(),
2156
+ confirm: z.boolean().optional(),
2157
+ discount_code: z.string().optional(),
2158
+ metadata: z.record(z.string(), z.string()).optional(),
2159
+ customization: checkoutSessionCustomizationSchema,
2160
+ feature_flags: checkoutSessionFeatureFlagsSchema,
2161
+ subscription_data: checkoutSessionSubscriptionDataSchema,
2162
+ });
2163
+ // Checkout session response schema
2164
+ var checkoutSessionResponseSchema = z.object({
2165
+ session_id: z.string().min(1, "Session ID is required"),
2166
+ checkout_url: z.string().url("Invalid checkout URL"),
2167
+ });
2168
+ /**
2169
+ * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
2170
+ * This function provides a clean, type-safe interface to the Checkout Sessions API.
2171
+ *
2172
+ * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
2173
+ * @param config - Dodo Payments client configuration (bearerToken, environment)
2174
+ * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
2175
+ *
2176
+ * @throws {Error} When payload validation fails or API request fails
2177
+ *
2178
+ * @example
2179
+ * ```typescript
2180
+ * const session = await createCheckoutSession({
2181
+ * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
2182
+ * customer: { email: 'customer@example.com' },
2183
+ * return_url: 'https://yoursite.com/success'
2184
+ * }, {
2185
+ * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
2186
+ * environment: 'test_mode'
2187
+ * });
2188
+ *
2189
+ * ```
2190
+ */
2191
+ var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
2192
+ var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
2193
+ return __generator$1(this, function (_a) {
2194
+ switch (_a.label) {
2195
+ case 0:
2196
+ validation = checkoutSessionPayloadSchema.safeParse(payload);
2197
+ if (!validation.success) {
2198
+ throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
2199
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2200
+ .join(", ")));
2201
+ }
2202
+ dodopayments = new DodoPayments({
2203
+ bearerToken: config.bearerToken,
2204
+ environment: config.environment,
2205
+ });
2206
+ _a.label = 1;
2207
+ case 1:
2208
+ _a.trys.push([1, 3, , 4]);
2209
+ sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
2210
+ billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
2211
+ }));
2212
+ return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
2213
+ case 2:
2214
+ session = _a.sent();
2215
+ responseValidation = checkoutSessionResponseSchema.safeParse(session);
2216
+ if (!responseValidation.success) {
2217
+ throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
2218
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2219
+ .join(", ")));
2220
+ }
2221
+ return [2 /*return*/, responseValidation.data];
2222
+ case 3:
2223
+ error_1 = _a.sent();
2224
+ if (error_1 instanceof Error) {
2225
+ console.error("Dodo Payments Checkout Session API Error:", {
2226
+ message: error_1.message,
2227
+ payload: validation.data,
2228
+ config: {
2229
+ environment: config.environment,
2230
+ hasBearerToken: !!config.bearerToken,
2231
+ },
2232
+ });
2233
+ // Re-throw with a more user-friendly message
2234
+ throw new Error("Failed to create checkout session: ".concat(error_1.message));
2235
+ }
2236
+ // Handle non-Error objects
2237
+ console.error("Unknown error creating checkout session:", error_1);
2238
+ throw new Error("Failed to create checkout session due to an unknown error");
2239
+ case 4: return [2 /*return*/];
2240
+ }
2241
+ });
2242
+ }); };
1958
2243
  var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
1959
- var inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
1960
- var queryParams = _b.queryParams, body = _b.body, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
2244
+ var session, inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
2245
+ var queryParams = _b.queryParams, body = _b.body, sessionPayload = _b.sessionPayload, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
1961
2246
  return __generator$1(this, function (_g) {
1962
2247
  switch (_g.label) {
1963
2248
  case 0:
2249
+ if (!(type === "session")) return [3 /*break*/, 2];
2250
+ if (!sessionPayload) {
2251
+ throw new Error("sessionPayload is required when type is 'session'");
2252
+ }
2253
+ return [4 /*yield*/, createCheckoutSession(sessionPayload, {
2254
+ bearerToken: bearerToken,
2255
+ environment: environment,
2256
+ })];
2257
+ case 1:
2258
+ session = _g.sent();
2259
+ return [2 /*return*/, session.checkout_url];
2260
+ case 2:
1964
2261
  inputData = type === "dynamic" ? body : queryParams;
1965
2262
  if (type === "dynamic") {
1966
2263
  parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
@@ -1972,7 +2269,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1972
2269
  if (!success) {
1973
2270
  throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
1974
2271
  }
1975
- if (!(type !== "dynamic")) return [3 /*break*/, 5];
2272
+ if (!(type !== "dynamic")) return [3 /*break*/, 7];
1976
2273
  _c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
1977
2274
  dodopayments_1 = new DodoPayments({
1978
2275
  bearerToken: bearerToken,
@@ -1981,18 +2278,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1981
2278
  // Check that the product exists for this merchant
1982
2279
  if (!productId)
1983
2280
  throw new Error("Missing required field: productId");
1984
- _g.label = 1;
1985
- case 1:
1986
- _g.trys.push([1, 3, , 4]);
2281
+ _g.label = 3;
2282
+ case 3:
2283
+ _g.trys.push([3, 5, , 6]);
1987
2284
  return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
1988
- case 2:
2285
+ case 4:
1989
2286
  _g.sent();
1990
- return [3 /*break*/, 4];
1991
- case 3:
2287
+ return [3 /*break*/, 6];
2288
+ case 5:
1992
2289
  err_1 = _g.sent();
1993
2290
  console.error(err_1);
1994
2291
  throw new Error("Product not found");
1995
- case 4:
2292
+ case 6:
1996
2293
  url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
1997
2294
  url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
1998
2295
  if (returnUrl)
@@ -2052,7 +2349,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2052
2349
  }
2053
2350
  }
2054
2351
  return [2 /*return*/, url.toString()];
2055
- case 5:
2352
+ case 7:
2056
2353
  dyn = data;
2057
2354
  product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
2058
2355
  dodopayments = new DodoPayments({
@@ -2066,18 +2363,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2066
2363
  }
2067
2364
  if (!productIdToFetch)
2068
2365
  throw new Error("Missing required field: product_id or product_cart[0].product_id");
2069
- _g.label = 6;
2070
- case 6:
2071
- _g.trys.push([6, 8, , 9]);
2366
+ _g.label = 8;
2367
+ case 8:
2368
+ _g.trys.push([8, 10, , 11]);
2072
2369
  return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
2073
- case 7:
2370
+ case 9:
2074
2371
  product = _g.sent();
2075
- return [3 /*break*/, 9];
2076
- case 8:
2372
+ return [3 /*break*/, 11];
2373
+ case 10:
2077
2374
  err_2 = _g.sent();
2078
2375
  console.error(err_2);
2079
2376
  throw new Error("Product not found");
2080
- case 9:
2377
+ case 11:
2081
2378
  isSubscription = Boolean(product.is_recurring);
2082
2379
  // Required field validation
2083
2380
  if (isSubscription && !product_id)
@@ -2086,7 +2383,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2086
2383
  throw new Error("Missing required field: billing");
2087
2384
  if (!customer)
2088
2385
  throw new Error("Missing required field: customer");
2089
- if (!isSubscription) return [3 /*break*/, 14];
2386
+ if (!isSubscription) return [3 /*break*/, 16];
2090
2387
  subscriptionPayload = {
2091
2388
  billing: billing,
2092
2389
  customer: customer,
@@ -2122,24 +2419,24 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2122
2419
  if (trial_period_days)
2123
2420
  subscriptionPayload.trial_period_days = trial_period_days;
2124
2421
  subscription = void 0;
2125
- _g.label = 10;
2126
- case 10:
2127
- _g.trys.push([10, 12, , 13]);
2422
+ _g.label = 12;
2423
+ case 12:
2424
+ _g.trys.push([12, 14, , 15]);
2128
2425
  return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
2129
- case 11:
2426
+ case 13:
2130
2427
  subscription =
2131
2428
  _g.sent();
2132
- return [3 /*break*/, 13];
2133
- case 12:
2429
+ return [3 /*break*/, 15];
2430
+ case 14:
2134
2431
  err_3 = _g.sent();
2135
2432
  console.error("Error when creating subscription", err_3);
2136
2433
  throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
2137
- case 13:
2434
+ case 15:
2138
2435
  if (!subscription || !subscription.payment_link) {
2139
2436
  throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
2140
2437
  }
2141
2438
  return [2 /*return*/, subscription.payment_link];
2142
- case 14:
2439
+ case 16:
2143
2440
  cart = product_cart;
2144
2441
  if (!cart && product_id) {
2145
2442
  cart = [
@@ -2175,18 +2472,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2175
2472
  if (tax_id)
2176
2473
  paymentPayload.tax_id = tax_id;
2177
2474
  payment = void 0;
2178
- _g.label = 15;
2179
- case 15:
2180
- _g.trys.push([15, 17, , 18]);
2475
+ _g.label = 17;
2476
+ case 17:
2477
+ _g.trys.push([17, 19, , 20]);
2181
2478
  return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
2182
- case 16:
2479
+ case 18:
2183
2480
  payment = _g.sent();
2184
- return [3 /*break*/, 18];
2185
- case 17:
2481
+ return [3 /*break*/, 20];
2482
+ case 19:
2186
2483
  err_4 = _g.sent();
2187
2484
  console.error("Error when creating payment link", err_4);
2188
2485
  throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
2189
- case 18:
2486
+ case 20:
2190
2487
  if (!payment || !payment.payment_link) {
2191
2488
  throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
2192
2489
  }
@@ -2216,10 +2513,7 @@ const Checkout = (config) => {
2216
2513
  catch (err) {
2217
2514
  throw error(400, err.message);
2218
2515
  }
2219
- return new Response(null, {
2220
- status: 302,
2221
- headers: { Location: urlStr },
2222
- });
2516
+ return Response.json({ checkout_url: urlStr });
2223
2517
  };
2224
2518
  const postHandler = async (event) => {
2225
2519
  let body;
@@ -2229,21 +2523,44 @@ const Checkout = (config) => {
2229
2523
  catch (e) {
2230
2524
  throw error(400, "Invalid JSON body");
2231
2525
  }
2232
- const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
2233
- if (!success) {
2234
- throw error(400, `Invalid request body.\n ${zodError.message}`);
2235
- }
2236
- let urlStr = "";
2237
- try {
2238
- urlStr = await buildCheckoutUrl({ body: data, ...config });
2526
+ if (config.type === "dynamic") {
2527
+ // Handle dynamic checkout
2528
+ const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
2529
+ if (!success) {
2530
+ throw error(400, `Invalid request body.\n ${zodError.message}`);
2531
+ }
2532
+ let urlStr = "";
2533
+ try {
2534
+ urlStr = await buildCheckoutUrl({
2535
+ body: data,
2536
+ ...config,
2537
+ type: "dynamic",
2538
+ });
2539
+ }
2540
+ catch (err) {
2541
+ throw error(400, err.message);
2542
+ }
2543
+ return Response.json({ checkout_url: urlStr });
2239
2544
  }
2240
- catch (err) {
2241
- throw error(400, err.message);
2545
+ else {
2546
+ // Handle checkout session
2547
+ const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
2548
+ if (!success) {
2549
+ throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
2550
+ }
2551
+ let urlStr = "";
2552
+ try {
2553
+ urlStr = await buildCheckoutUrl({
2554
+ sessionPayload: data,
2555
+ ...config,
2556
+ type: "session",
2557
+ });
2558
+ }
2559
+ catch (err) {
2560
+ throw error(400, err.message);
2561
+ }
2562
+ return Response.json({ checkout_url: urlStr });
2242
2563
  }
2243
- return new Response(null, {
2244
- status: 302,
2245
- headers: { Location: urlStr },
2246
- });
2247
2564
  };
2248
2565
  // SvelteKit expects named exports for HTTP verbs
2249
2566
  return {