@tagadapay/headless-sdk 1.7.0 → 1.8.0

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.
Files changed (81) hide show
  1. package/dist/core/client.d.ts +7 -0
  2. package/dist/core/client.js +2 -0
  3. package/dist/core/index.d.ts +2 -0
  4. package/dist/core/index.js +1 -0
  5. package/dist/core/modules/checkout.d.ts +11 -5
  6. package/dist/core/modules/checkout.js +17 -6
  7. package/dist/core/modules/rx.d.ts +162 -0
  8. package/dist/core/modules/rx.js +46 -0
  9. package/dist/react/hooks/useCheckout.js +11 -2
  10. package/dist/react/hooks/useRx.d.ts +64 -0
  11. package/dist/react/hooks/useRx.js +145 -0
  12. package/dist/react/index.d.ts +2 -0
  13. package/dist/react/index.js +1 -0
  14. package/package.json +4 -10
  15. package/dist/core/client.d.ts.map +0 -1
  16. package/dist/core/client.js.map +0 -1
  17. package/dist/core/errors.d.ts.map +0 -1
  18. package/dist/core/errors.js.map +0 -1
  19. package/dist/core/helpers/autocomplete.d.ts.map +0 -1
  20. package/dist/core/helpers/autocomplete.js.map +0 -1
  21. package/dist/core/helpers/countries.d.ts.map +0 -1
  22. package/dist/core/helpers/countries.js.map +0 -1
  23. package/dist/core/helpers/currency.d.ts.map +0 -1
  24. package/dist/core/helpers/currency.js.map +0 -1
  25. package/dist/core/helpers/index.d.ts.map +0 -1
  26. package/dist/core/helpers/index.js.map +0 -1
  27. package/dist/core/helpers/iso3166.d.ts.map +0 -1
  28. package/dist/core/helpers/iso3166.js.map +0 -1
  29. package/dist/core/http.d.ts.map +0 -1
  30. package/dist/core/http.js.map +0 -1
  31. package/dist/core/index.d.ts.map +0 -1
  32. package/dist/core/index.js.map +0 -1
  33. package/dist/core/modules/catalog.d.ts.map +0 -1
  34. package/dist/core/modules/catalog.js.map +0 -1
  35. package/dist/core/modules/checkout.d.ts.map +0 -1
  36. package/dist/core/modules/checkout.js.map +0 -1
  37. package/dist/core/modules/customer.d.ts.map +0 -1
  38. package/dist/core/modules/customer.js.map +0 -1
  39. package/dist/core/modules/funnel.d.ts.map +0 -1
  40. package/dist/core/modules/funnel.js.map +0 -1
  41. package/dist/core/modules/offers.d.ts.map +0 -1
  42. package/dist/core/modules/offers.js.map +0 -1
  43. package/dist/core/modules/payment.d.ts.map +0 -1
  44. package/dist/core/modules/payment.js.map +0 -1
  45. package/dist/core/types.d.ts.map +0 -1
  46. package/dist/core/types.js.map +0 -1
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index.js.map +0 -1
  49. package/dist/react/hooks/useCatalog.d.ts.map +0 -1
  50. package/dist/react/hooks/useCatalog.js.map +0 -1
  51. package/dist/react/hooks/useCheckout.d.ts.map +0 -1
  52. package/dist/react/hooks/useCheckout.js.map +0 -1
  53. package/dist/react/hooks/useCustomer.d.ts.map +0 -1
  54. package/dist/react/hooks/useCustomer.js.map +0 -1
  55. package/dist/react/hooks/useGoogleAutocomplete.d.ts.map +0 -1
  56. package/dist/react/hooks/useGoogleAutocomplete.js.map +0 -1
  57. package/dist/react/hooks/useISOData.d.ts.map +0 -1
  58. package/dist/react/hooks/useISOData.js.map +0 -1
  59. package/dist/react/hooks/useOffers.d.ts.map +0 -1
  60. package/dist/react/hooks/useOffers.js.map +0 -1
  61. package/dist/react/hooks/usePayment.d.ts.map +0 -1
  62. package/dist/react/hooks/usePayment.js.map +0 -1
  63. package/dist/react/index.d.ts.map +0 -1
  64. package/dist/react/index.js.map +0 -1
  65. package/dist/react/internal/redirectGuard.d.ts.map +0 -1
  66. package/dist/react/internal/redirectGuard.js.map +0 -1
  67. package/dist/react/provider.d.ts.map +0 -1
  68. package/dist/react/provider.js.map +0 -1
  69. package/dist/stripe/StripeExpressButton.d.ts.map +0 -1
  70. package/dist/stripe/StripeExpressButton.js.map +0 -1
  71. package/dist/stripe/StripeExpressCheckout.d.ts.map +0 -1
  72. package/dist/stripe/StripeExpressCheckout.js.map +0 -1
  73. package/dist/stripe/index.d.ts.map +0 -1
  74. package/dist/stripe/index.js.map +0 -1
  75. package/dist/stripe/useStripeExpress.d.ts.map +0 -1
  76. package/dist/stripe/useStripeExpress.js.map +0 -1
  77. package/dist/tagada-headless-react.min.js +0 -8
  78. package/dist/tagada-headless-react.min.js.map +0 -7
  79. package/dist/tagada-headless.js +0 -2229
  80. package/dist/tagada-headless.min.js +0 -8
  81. package/dist/tagada-headless.min.js.map +0 -7
@@ -1,2229 +0,0 @@
1
- /**
2
- * @tagadapay/headless-sdk v1.7.0
3
- * Headless checkout, payments, offers, and CRM
4
- * @license MIT
5
- */
6
- "use strict";
7
- var TagadaHeadlessBundle = (() => {
8
- var __create = Object.create;
9
- var __defProp = Object.defineProperty;
10
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
- var __getOwnPropNames = Object.getOwnPropertyNames;
12
- var __getProtoOf = Object.getPrototypeOf;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
15
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
16
- }) : x)(function(x) {
17
- if (typeof require !== "undefined")
18
- return require.apply(this, arguments);
19
- throw Error('Dynamic require of "' + x + '" is not supported');
20
- });
21
- var __export = (target, all) => {
22
- for (var name in all)
23
- __defProp(target, name, { get: all[name], enumerable: true });
24
- };
25
- var __copyProps = (to, from, except, desc) => {
26
- if (from && typeof from === "object" || typeof from === "function") {
27
- for (let key of __getOwnPropNames(from))
28
- if (!__hasOwnProp.call(to, key) && key !== except)
29
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
- }
31
- return to;
32
- };
33
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
- // If the importer is in node compatibility mode or this is not an ESM
35
- // file that has been converted to a CommonJS file using a Babel-
36
- // compatible transform (i.e. "__esModule" has not been set), then set
37
- // "default" to the CommonJS "module.exports" for node compatibility.
38
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
- mod
40
- ));
41
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
42
-
43
- // src/core/index.ts
44
- var core_exports = {};
45
- __export(core_exports, {
46
- AVAILABLE_LANGUAGES: () => AVAILABLE_LANGUAGES,
47
- CatalogModule: () => CatalogModule,
48
- CheckoutModule: () => CheckoutModule,
49
- CurrencyUtils: () => CurrencyUtils,
50
- CustomerModule: () => CustomerModule,
51
- FunnelModule: () => FunnelModule,
52
- GoogleAutocompleteCore: () => GoogleAutocompleteCore,
53
- HeadlessClient: () => HeadlessClient,
54
- HttpClient: () => HttpClient,
55
- ISODataCore: () => ISODataCore,
56
- OffersModule: () => OffersModule,
57
- PaymentModule: () => PaymentModule,
58
- TagadaAuthError: () => TagadaAuthError,
59
- TagadaError: () => TagadaError,
60
- TagadaNetworkError: () => TagadaNetworkError,
61
- TagadaNotFoundError: () => TagadaNotFoundError,
62
- TagadaPaymentError: () => TagadaPaymentError,
63
- TagadaRateLimitError: () => TagadaRateLimitError,
64
- TagadaValidationError: () => TagadaValidationError,
65
- createHeadlessClient: () => createHeadlessClient,
66
- ensureGeoDataLoaded: () => ensureGeoDataLoaded,
67
- formatMoney: () => formatMoney,
68
- getCountries: () => getCountries,
69
- getStatesForCountry: () => getStatesForCountry,
70
- isLanguageLoaded: () => isLanguageLoaded,
71
- loadGoogleMapsScript: () => loadGoogleMapsScript
72
- });
73
-
74
- // src/core/errors.ts
75
- var TagadaError = class extends Error {
76
- constructor(message, code, statusCode, details) {
77
- super(message);
78
- this.name = "TagadaError";
79
- this.code = code;
80
- this.statusCode = statusCode;
81
- this.details = details;
82
- }
83
- };
84
- var TagadaAuthError = class extends TagadaError {
85
- constructor(message = "Authentication failed. Check your API key or checkout token.") {
86
- super(message, "auth_error", 401);
87
- this.name = "TagadaAuthError";
88
- }
89
- };
90
- var TagadaValidationError = class extends TagadaError {
91
- constructor(message, errors = []) {
92
- super(message, "validation_error", 422, { errors });
93
- this.name = "TagadaValidationError";
94
- this.errors = errors;
95
- }
96
- };
97
- var TagadaNotFoundError = class extends TagadaError {
98
- constructor(resource, id) {
99
- super(`${resource} "${id}" not found.`, "not_found", 404);
100
- this.name = "TagadaNotFoundError";
101
- }
102
- };
103
- var TagadaRateLimitError = class extends TagadaError {
104
- constructor(retryAfterMs = 1e3) {
105
- super(`Rate limited. Retry after ${retryAfterMs}ms.`, "rate_limit", 429);
106
- this.name = "TagadaRateLimitError";
107
- this.retryAfterMs = retryAfterMs;
108
- }
109
- };
110
- var TagadaPaymentError = class extends TagadaError {
111
- constructor(message, opts) {
112
- super(message, "payment_error", void 0, opts == null ? void 0 : opts.details);
113
- this.name = "TagadaPaymentError";
114
- this.paymentId = opts == null ? void 0 : opts.paymentId;
115
- this.requireAction = opts == null ? void 0 : opts.requireAction;
116
- }
117
- };
118
- var TagadaNetworkError = class extends TagadaError {
119
- constructor(message = "Network request failed. Check your connection.") {
120
- super(message, "network_error");
121
- this.name = "TagadaNetworkError";
122
- }
123
- };
124
-
125
- // src/core/http.ts
126
- var BASE_URLS = {
127
- production: "https://api.tagada.io",
128
- development: "https://api.tagada.dev",
129
- local: "http://localhost:3000"
130
- };
131
- var HttpClient = class {
132
- constructor(config) {
133
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
134
- this.timeout = config.timeout;
135
- this.apiKey = config.apiKey;
136
- this.getToken = config.getToken;
137
- }
138
- static resolveBaseUrl(environment, override) {
139
- return override ?? BASE_URLS[environment] ?? BASE_URLS.production;
140
- }
141
- async request(path, options = {}) {
142
- var _a;
143
- const { method = "GET", body, headers = {}, params, token, signal } = options;
144
- let url = `${this.baseUrl}${path}`;
145
- if (params) {
146
- const qs = new URLSearchParams();
147
- for (const [k, v] of Object.entries(params)) {
148
- if (v !== void 0)
149
- qs.set(k, String(v));
150
- }
151
- const str = qs.toString();
152
- if (str)
153
- url += `?${str}`;
154
- }
155
- const reqHeaders = {
156
- "Content-Type": "application/json",
157
- ...headers
158
- };
159
- const authToken = token ?? this.apiKey ?? ((_a = this.getToken) == null ? void 0 : _a.call(this));
160
- if (authToken) {
161
- reqHeaders["x-cms-token"] = authToken;
162
- }
163
- const controller = new AbortController();
164
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
165
- try {
166
- const res = await fetch(url, {
167
- method,
168
- headers: reqHeaders,
169
- body: body != null ? JSON.stringify(body) : void 0,
170
- signal: signal ?? controller.signal
171
- });
172
- clearTimeout(timeoutId);
173
- if (res.ok) {
174
- const text = await res.text();
175
- return text ? JSON.parse(text) : {};
176
- }
177
- await this.handleErrorResponse(res, path);
178
- throw new TagadaError("Unexpected error", "unknown", res.status);
179
- } catch (err) {
180
- clearTimeout(timeoutId);
181
- if (err instanceof TagadaError)
182
- throw err;
183
- if (err instanceof DOMException && err.name === "AbortError") {
184
- throw new TagadaNetworkError(`Request to ${path} timed out after ${this.timeout}ms.`);
185
- }
186
- throw new TagadaNetworkError(
187
- err instanceof Error ? err.message : "Network request failed."
188
- );
189
- }
190
- }
191
- get(path, options) {
192
- return this.request(path, { ...options, method: "GET" });
193
- }
194
- post(path, body, options) {
195
- return this.request(path, { ...options, method: "POST", body });
196
- }
197
- patch(path, body, options) {
198
- return this.request(path, { ...options, method: "PATCH", body });
199
- }
200
- put(path, body, options) {
201
- return this.request(path, { ...options, method: "PUT", body });
202
- }
203
- delete(path, options) {
204
- return this.request(path, { ...options, method: "DELETE" });
205
- }
206
- async handleErrorResponse(res, path) {
207
- let parsed = {};
208
- try {
209
- parsed = await res.json();
210
- } catch {
211
- }
212
- const msg = parsed.message ?? parsed.error ?? `Request failed: ${res.status} ${res.statusText} on ${path}`;
213
- switch (res.status) {
214
- case 401:
215
- case 403:
216
- throw new TagadaAuthError(msg);
217
- case 404:
218
- throw new TagadaNotFoundError(path, "");
219
- case 422: {
220
- const fieldErrors = Array.isArray(parsed.errors) ? parsed.errors : [];
221
- throw new TagadaValidationError(msg, fieldErrors);
222
- }
223
- case 429: {
224
- const retryAfter = Number(res.headers.get("Retry-After") ?? "1") * 1e3;
225
- throw new TagadaRateLimitError(retryAfter);
226
- }
227
- default:
228
- throw new TagadaError(msg, "api_error", res.status, parsed);
229
- }
230
- }
231
- };
232
-
233
- // src/core/modules/checkout.ts
234
- var CheckoutModule = class {
235
- constructor(http, storeId, onTokenChange) {
236
- this.http = http;
237
- this.storeId = storeId;
238
- this.onTokenChange = onTokenChange;
239
- }
240
- /**
241
- * Returns the most recently loaded `CheckoutSession`, if any.
242
- *
243
- * Populated by `loadSession()`. Returns `undefined` if the SDK has not
244
- * loaded a session yet. Used by `funnel.navigate()` to source the cart.
245
- */
246
- getCurrentSession() {
247
- return this._currentSession;
248
- }
249
- /**
250
- * Load an existing checkout session by its checkout token.
251
- *
252
- * @param checkoutToken The checkout token (from URL param `checkoutToken`).
253
- * @param sessionToken The JWT session token (from URL param `token`). Required for auth.
254
- * @param opts.currency Optional presentment currency override (e.g. 'EUR').
255
- * Only applied when the session has no currency set yet (first load).
256
- * Once set, currency is locked to the session and this param is ignored.
257
- *
258
- * Both `checkoutToken` and `sessionToken` come from the redirect URL returned by `createSession()`.
259
- * Example URL: `/checkout?checkoutToken=abc123&token=eyJ...`
260
- */
261
- async loadSession(checkoutToken, sessionToken, opts) {
262
- var _a;
263
- if (sessionToken) {
264
- this.sessionToken = sessionToken;
265
- (_a = this.onTokenChange) == null ? void 0 : _a.call(this, sessionToken);
266
- }
267
- const params = { skipAsyncWait: "false" };
268
- if (opts == null ? void 0 : opts.currency) {
269
- params.currency = opts.currency;
270
- }
271
- const raw = await this.http.get(
272
- `/api/v1/checkout-sessions/${checkoutToken}/v2`,
273
- {
274
- params,
275
- token: this.sessionToken
276
- }
277
- );
278
- const session = this.normalizeSession(raw);
279
- this._currentSession = session;
280
- return session;
281
- }
282
- /**
283
- * Create a new checkout session.
284
- *
285
- * Returns a `checkoutToken` and `sessionToken` (JWT) needed for all subsequent calls.
286
- * Also returns a `checkoutUrl` (the full Tagada-hosted checkout URL, for reference).
287
- */
288
- async createSession(opts) {
289
- var _a;
290
- const lineItems = opts.items.map((i) => ({
291
- variantId: i.variantId,
292
- priceId: i.priceId,
293
- quantity: i.quantity
294
- }));
295
- const body = {
296
- storeId: this.storeId,
297
- lineItems
298
- };
299
- if (opts.returnUrl)
300
- body.returnUrl = opts.returnUrl;
301
- const customerData = {};
302
- if (opts.currency)
303
- customerData.currency = opts.currency;
304
- if (opts.customerEmail) {
305
- customerData.email = opts.customerEmail;
306
- customerData.firstName = opts.customerFirstName;
307
- customerData.lastName = opts.customerLastName;
308
- }
309
- if (Object.keys(customerData).length > 0) {
310
- body.customer = customerData;
311
- }
312
- const res = await this.http.post("/api/v1/checkout/session/init", body);
313
- const url = new URL(res.checkoutUrl);
314
- const sessionToken = url.searchParams.get("token") ?? "";
315
- this.sessionToken = sessionToken;
316
- if (sessionToken)
317
- (_a = this.onTokenChange) == null ? void 0 : _a.call(this, sessionToken);
318
- return {
319
- checkoutUrl: res.checkoutUrl,
320
- checkoutToken: res.checkoutToken,
321
- sessionToken,
322
- customerId: res.customerId
323
- };
324
- }
325
- /**
326
- * Create a session and produce a self-hosted redirect URL.
327
- *
328
- * Convenience wrapper around `createSession()`. Builds a URL of the
329
- * form `${origin}${checkoutPath}?checkoutToken=...&sessionToken=...`
330
- * that you can navigate to from a Cart page. The receiving page reads
331
- * the params via {@link CheckoutModule.parseTokensFromUrl} and calls
332
- * {@link CheckoutModule.loadSession}.
333
- *
334
- * For Tagada-hosted checkouts use the `checkoutUrl` returned by
335
- * `createSession()` directly — this helper is for **self-hosted**
336
- * checkout pages.
337
- *
338
- * @example
339
- * ```ts
340
- * const { url } = await tagada.checkout.createSessionUrl({
341
- * items: [{ variantId, quantity: 1 }],
342
- * checkoutPath: '/checkout',
343
- * });
344
- * window.location.href = url;
345
- * ```
346
- */
347
- async createSessionUrl(opts) {
348
- const session = await this.createSession({
349
- items: opts.items,
350
- currency: opts.currency,
351
- returnUrl: opts.returnUrl,
352
- customerEmail: opts.customerEmail,
353
- customerFirstName: opts.customerFirstName,
354
- customerLastName: opts.customerLastName
355
- });
356
- const origin = opts.origin ?? (typeof window !== "undefined" ? window.location.origin : "");
357
- const checkoutPath = opts.checkoutPath ?? "/checkout";
358
- const params = new URLSearchParams({
359
- checkoutToken: session.checkoutToken,
360
- sessionToken: session.sessionToken
361
- });
362
- const url = `${origin}${checkoutPath}?${params.toString()}`;
363
- return { ...session, url };
364
- }
365
- /**
366
- * Read `checkoutToken` and session token from a URL.
367
- *
368
- * Recognizes both the SDK convention (`?sessionToken=`) and the
369
- * Tagada-hosted convention (`?token=`), so the same checkout page
370
- * works whether the user came from `createSessionUrl()` or directly
371
- * from a Tagada-hosted redirect.
372
- *
373
- * Returns `null` if `checkoutToken` is missing.
374
- *
375
- * @example
376
- * ```ts
377
- * const tokens = CheckoutModule.parseTokensFromUrl();
378
- * if (!tokens) {
379
- * window.location.href = '/cart';
380
- * return;
381
- * }
382
- * const session = await tagada.checkout.loadSession(
383
- * tokens.checkoutToken,
384
- * tokens.sessionToken,
385
- * );
386
- * ```
387
- */
388
- static parseTokensFromUrl(url) {
389
- if (typeof url === "undefined" && typeof window === "undefined")
390
- return null;
391
- const href = url ?? window.location.href;
392
- let parsed;
393
- try {
394
- parsed = new URL(href);
395
- } catch {
396
- return null;
397
- }
398
- const checkoutToken = parsed.searchParams.get("checkoutToken");
399
- if (!checkoutToken)
400
- return null;
401
- const sessionToken = parsed.searchParams.get("sessionToken") ?? parsed.searchParams.get("token") ?? "";
402
- return { checkoutToken, sessionToken };
403
- }
404
- /**
405
- * Replace the cart items for an existing session.
406
- *
407
- * Returns a server-side mutation summary (counts of created/updated rows).
408
- * It does NOT return the updated `CheckoutSession` — the underlying
409
- * `POST /checkout-sessions/:id/line-items` endpoint never has and the
410
- * previous typing was a lie that quietly assigned `{ success, updated, ... }`
411
- * into a `CheckoutSession` slot in `useCheckout`.
412
- *
413
- * Call `loadSession()` after this if you need the refreshed session
414
- * (the React `useCheckout` hook does this for you).
415
- */
416
- async updateCart(sessionId, items) {
417
- return this.http.post(
418
- `/api/v1/checkout-sessions/${sessionId}/line-items`,
419
- { items },
420
- { token: this.sessionToken }
421
- );
422
- }
423
- /**
424
- * Update customer identity (email, name, phone).
425
- *
426
- * Call this before `updateAddress()` — the SDK remembers the values and
427
- * includes them automatically when addresses are submitted.
428
- *
429
- * If you prefer a single call, use `updateCustomerAndAddress()` instead.
430
- */
431
- async updateCustomer(sessionId, customer) {
432
- if (customer.email)
433
- this.customerEmail = customer.email;
434
- if (customer.firstName)
435
- this.customerFirstName = customer.firstName;
436
- if (customer.lastName)
437
- this.customerLastName = customer.lastName;
438
- if (customer.phone)
439
- this.customerPhone = customer.phone;
440
- }
441
- /**
442
- * Update shipping and/or billing address on the session.
443
- *
444
- * Automatically includes customer name/phone stored from `updateCustomer()`.
445
- * Uses the same atomic API call as the production checkout, so email,
446
- * customer name, and addresses are all persisted together.
447
- *
448
- * **Shipped products**: pass `shippingAddress`. If `billingAddress` is omitted,
449
- * the shipping address is automatically used as billing.
450
- *
451
- * **Digital products**: pass only `billingAddress` (no shipping needed).
452
- *
453
- * @example
454
- * // Shipped product — billing = shipping automatically
455
- * await checkout.updateAddress(sessionId, {
456
- * shippingAddress: { line1: '10 Rue de la Paix', city: 'Paris', postalCode: '75002', country: 'FR' },
457
- * });
458
- *
459
- * @example
460
- * // Digital product — billing only
461
- * await checkout.updateAddress(sessionId, {
462
- * billingAddress: { country: 'FR' },
463
- * });
464
- */
465
- async updateAddress(sessionId, addresses) {
466
- const shipping = this.mapAddress(addresses.shippingAddress);
467
- const billing = this.mapAddress(addresses.billingAddress);
468
- const effectiveShipping = shipping ?? billing ?? {};
469
- const effectiveBilling = billing ?? shipping;
470
- const differentBilling = !!(addresses.billingAddress && addresses.shippingAddress);
471
- await this.http.post(
472
- `/api/v1/checkout-sessions/${sessionId}/customer-and-session-info`,
473
- {
474
- checkoutSessionId: sessionId,
475
- customerData: {
476
- email: this.customerEmail
477
- },
478
- shippingAddress: effectiveShipping,
479
- billingAddress: effectiveBilling ?? {},
480
- differentBillingAddress: differentBilling
481
- },
482
- { token: this.sessionToken }
483
- );
484
- }
485
- /**
486
- * Set customer info + addresses in one call (mirrors production checkout).
487
- *
488
- * Equivalent to calling `updateCustomer()` then `updateAddress()`, but
489
- * in a single network request.
490
- */
491
- async updateCustomerAndAddress(sessionId, data) {
492
- if (data.customer.email)
493
- this.customerEmail = data.customer.email;
494
- if (data.customer.firstName)
495
- this.customerFirstName = data.customer.firstName;
496
- if (data.customer.lastName)
497
- this.customerLastName = data.customer.lastName;
498
- if (data.customer.phone)
499
- this.customerPhone = data.customer.phone;
500
- const shipping = this.mapAddress(data.shippingAddress);
501
- const billing = this.mapAddress(data.billingAddress);
502
- const effectiveShipping = shipping ?? billing ?? {};
503
- const effectiveBilling = billing ?? shipping;
504
- const differentBilling = !!(data.billingAddress && data.shippingAddress);
505
- await this.http.post(
506
- `/api/v1/checkout-sessions/${sessionId}/customer-and-session-info`,
507
- {
508
- checkoutSessionId: sessionId,
509
- customerData: {
510
- email: this.customerEmail
511
- },
512
- shippingAddress: effectiveShipping,
513
- billingAddress: effectiveBilling ?? {},
514
- differentBillingAddress: differentBilling
515
- },
516
- { token: this.sessionToken }
517
- );
518
- }
519
- /** Map an SDK Address to the API shape, injecting stored customer fields. */
520
- mapAddress(a) {
521
- if (!a)
522
- return void 0;
523
- return stripEmpty({
524
- firstName: a.firstName ?? this.customerFirstName,
525
- lastName: a.lastName ?? this.customerLastName,
526
- phone: a.phone ?? this.customerPhone,
527
- address1: a.line1,
528
- address2: a.line2,
529
- city: a.city,
530
- state: a.state,
531
- postal: a.postalCode,
532
- country: a.country
533
- });
534
- }
535
- /** Apply a promotion code to the session. */
536
- async applyPromoCode(sessionId, code) {
537
- await this.http.post(
538
- `/api/v1/checkout-sessions/${sessionId}/promotions/apply`,
539
- { checkoutSessionId: sessionId, code },
540
- { token: this.sessionToken }
541
- );
542
- }
543
- /** Remove a promotion from the session by promotion ID. */
544
- async removePromoCode(sessionId, promotionId) {
545
- const promoId = promotionId ?? "default";
546
- await this.http.delete(
547
- `/api/v1/checkout-sessions/${sessionId}/promotions/${promoId}`,
548
- { token: this.sessionToken }
549
- );
550
- }
551
- /**
552
- * Fetch available shipping rates for the session's address.
553
- * Only relevant for **shipped products** — digital products can skip this step.
554
- *
555
- * Requires a shipping address to be set first via `updateAddress()`.
556
- * Returns an empty array if no rates are configured or address is missing.
557
- */
558
- async getShippingRates(sessionId) {
559
- const res = await this.http.get(
560
- `/api/v1/checkout-sessions/${sessionId}/shipping-rates`,
561
- { token: this.sessionToken }
562
- );
563
- return (res.rates ?? []).map((r) => this.normalizeShippingRate(r));
564
- }
565
- /**
566
- * Normalize the v1 rates payload (`shippingRateName`, `estimatedDeliveryTime`)
567
- * to the SDK's `ShippingRate` shape (`name`, `estimatedDays`). Without
568
- * this the consumer's UI shows blank rate names — the demo's "Delivery"
569
- * radios were rendering only the price, no label.
570
- */
571
- normalizeShippingRate(r) {
572
- return {
573
- id: r.id,
574
- name: r.name ?? r.shippingRateName ?? "",
575
- description: r.description ?? void 0,
576
- amount: r.amount ?? 0,
577
- currency: r.currency ?? "USD",
578
- estimatedDays: r.estimatedDays ?? r.estimatedDeliveryTime ?? void 0
579
- };
580
- }
581
- /**
582
- * Select a shipping rate for the session.
583
- * Only relevant for **shipped products** — digital products can skip this step.
584
- */
585
- async selectShippingRate(sessionId, rateId) {
586
- await this.http.post(
587
- `/api/v1/checkout-sessions/${sessionId}/shipping-rate`,
588
- { checkoutSessionId: sessionId, shippingRateId: rateId },
589
- { token: this.sessionToken }
590
- );
591
- }
592
- /**
593
- * Normalize the raw v2 API response into a cleaner CheckoutSession shape.
594
- * The raw response has nested `checkoutSession` + `summary` -- we flatten it.
595
- */
596
- normalizeSession(raw) {
597
- var _a;
598
- const cs = raw.checkoutSession;
599
- const orderSummaries = cs.orderSummaries ?? [];
600
- const summary = raw.summary ?? cs.summary ?? orderSummaries[0] ?? {};
601
- const lineItems = cs.sessionLineItems ?? [];
602
- const customer = cs.customer;
603
- const sessionCurrency = (_a = summary.currency ?? cs.selectedPresentmentCurrency) == null ? void 0 : _a.toUpperCase();
604
- const items = lineItems.map((li) => {
605
- const price = li.price;
606
- const variant = li.variant ?? (price == null ? void 0 : price.variant) ?? {};
607
- const product = li.product ?? variant.product ?? {};
608
- const currencyOpts = (price == null ? void 0 : price.currencyOptions) ?? {};
609
- const priceEntry = (sessionCurrency ? currencyOpts[sessionCurrency] : void 0) ?? currencyOpts[Object.keys(currencyOpts)[0]];
610
- const amount = (priceEntry == null ? void 0 : priceEntry.amount) ?? 0;
611
- return {
612
- id: li.id,
613
- variantId: li.variantId,
614
- priceId: li.priceId,
615
- productName: product.name ?? "",
616
- variantName: variant.name ?? "",
617
- quantity: li.quantity ?? 1,
618
- unitAmount: amount,
619
- totalAmount: amount * (li.quantity ?? 1),
620
- currency: sessionCurrency ?? "USD",
621
- imageUrl: variant.imageUrl ?? product.imageUrl ?? ""
622
- };
623
- });
624
- const summaryItems = summary.items ?? [];
625
- return {
626
- id: cs.id,
627
- storeId: cs.storeId,
628
- checkoutToken: cs.checkoutToken,
629
- currency: sessionCurrency ?? "USD",
630
- items,
631
- totals: {
632
- subtotal: summary.subtotalAmount ?? 0,
633
- discount: summary.totalPromotionAmount ?? 0,
634
- shipping: summary.shippingCost ?? 0,
635
- tax: summary.totalTaxAmount ?? 0,
636
- total: summary.totalAmount ?? summaryItems.reduce((s, i) => s + (i.amount ?? 0), 0),
637
- currency: sessionCurrency ?? "USD"
638
- },
639
- customer: customer ? {
640
- id: customer.id,
641
- email: customer.email,
642
- firstName: customer.firstName,
643
- lastName: customer.lastName,
644
- phone: customer.phone
645
- } : void 0,
646
- shippingAddress: this.normalizeAddress(cs.shippingAddress),
647
- billingAddress: this.normalizeAddress(cs.billingAddress),
648
- selectedShippingRateId: cs.shippingRateId ?? null,
649
- metadata: cs.metadata
650
- };
651
- }
652
- /**
653
- * Map the raw API address shape (`address1`, `address2`, `postal`) onto
654
- * the SDK's `Address` shape (`line1`, `line2`, `postalCode`). Without
655
- * this, `session.shippingAddress.line1` is silently undefined after a
656
- * reload — the type was lying about the actual key names — which is
657
- * what makes the demo lose form state on refresh.
658
- */
659
- normalizeAddress(raw) {
660
- if (!raw || typeof raw !== "object")
661
- return void 0;
662
- const a = raw;
663
- const out = {
664
- firstName: a.firstName,
665
- lastName: a.lastName,
666
- line1: a.line1 ?? a.address1,
667
- line2: a.line2 ?? a.address2,
668
- city: a.city,
669
- state: a.state,
670
- postalCode: a.postalCode ?? a.postal,
671
- country: a.country,
672
- phone: a.phone
673
- };
674
- return Object.values(out).some((v) => v !== void 0 && v !== "") ? out : void 0;
675
- }
676
- };
677
- function stripEmpty(obj) {
678
- const result = {};
679
- for (const [k, v] of Object.entries(obj)) {
680
- if (v !== void 0 && v !== null && v !== "") {
681
- result[k] = v;
682
- }
683
- }
684
- return Object.keys(result).length > 0 ? result : void 0;
685
- }
686
-
687
- // src/core/modules/payment.ts
688
- var PaymentModule = class {
689
- constructor(http, storeId, environment) {
690
- this.http = http;
691
- this.storeId = storeId;
692
- this.environment = environment;
693
- }
694
- // ---------------------------------------------------------------------------
695
- // Discovery: what payment methods are available?
696
- // ---------------------------------------------------------------------------
697
- /**
698
- * Get the full payment setup config for a checkout session.
699
- * Returns a map of payment methods with their configuration
700
- * (card, apple_pay, google_pay, klarna, etc.).
701
- *
702
- * Priority chain:
703
- * 1. Explicit `paymentSetupConfig` parameter (developer override)
704
- * 2. `window.__TGD_STEP_CONFIG__` injection (Tagada routing infra)
705
- * 3. API fallback (`GET /api/v1/payment-methods`)
706
- */
707
- async getPaymentSetup(checkoutSessionId, opts) {
708
- if (opts == null ? void 0 : opts.paymentSetupConfig) {
709
- return opts.paymentSetupConfig;
710
- }
711
- const injected = this.readInjectedStepConfig();
712
- if (injected) {
713
- return injected;
714
- }
715
- const methods = await this.http.get(
716
- "/api/v1/payment-methods",
717
- { params: { checkoutSessionId } }
718
- );
719
- const config = {};
720
- for (const m of methods.methods ?? []) {
721
- const key = m.provider ? `${m.method}:${m.provider}` : m.method;
722
- config[key] = m;
723
- }
724
- return config;
725
- }
726
- /**
727
- * Get express payment methods (Apple Pay, Google Pay, PayPal, etc.)
728
- * filtered to only those available in the current browser.
729
- */
730
- async getExpressMethods(checkoutSessionId, opts) {
731
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
732
- const setup = await this.getPaymentSetup(checkoutSessionId, opts);
733
- const result = {};
734
- for (const [key, config] of Object.entries(setup)) {
735
- if (!config.enabled)
736
- continue;
737
- if (key.startsWith("express_checkout:") && config.methods) {
738
- const base2 = {
739
- available: true,
740
- processorId: config.processorId,
741
- publishableKey: config.publishableKey,
742
- metadata: config.metadata
743
- };
744
- if ((_a = config.methods.apple_pay) == null ? void 0 : _a.enabled) {
745
- const hasApplePay = typeof window !== "undefined" && "ApplePaySession" in window && ((_c = (_b = window.ApplePaySession) == null ? void 0 : _b.canMakePayments) == null ? void 0 : _c.call(_b));
746
- result.applePay = { ...base2, type: "apple_pay", available: !!hasApplePay };
747
- }
748
- if ((_d = config.methods.google_pay) == null ? void 0 : _d.enabled) {
749
- result.googlePay = { ...base2, type: "google_pay" };
750
- }
751
- if ((_e = config.methods.paypal) == null ? void 0 : _e.enabled) {
752
- result.paypal = { ...base2, type: "paypal" };
753
- }
754
- if ((_f = config.methods.link) == null ? void 0 : _f.enabled) {
755
- result.link = { ...base2, type: "link" };
756
- }
757
- if ((_g = config.methods.klarna_express) == null ? void 0 : _g.enabled) {
758
- result.klarna = { ...base2, type: "klarna_express" };
759
- }
760
- continue;
761
- }
762
- if (!config.express)
763
- continue;
764
- const method = config.method;
765
- const base = {
766
- type: method,
767
- available: true,
768
- processorId: config.processorId,
769
- publishableKey: config.publishableKey,
770
- metadata: config.metadata
771
- };
772
- if (method === "apple_pay" || config.type === "apple_pay") {
773
- const hasApplePay = typeof window !== "undefined" && "ApplePaySession" in window && ((_i = (_h = window.ApplePaySession) == null ? void 0 : _h.canMakePayments) == null ? void 0 : _i.call(_h));
774
- result.applePay = { ...base, available: !!hasApplePay };
775
- } else if (method === "google_pay" || config.type === "google_pay") {
776
- result.googlePay = base;
777
- } else if (method === "paypal") {
778
- result.paypal = base;
779
- } else if (method === "klarna" || method === "klarna_express") {
780
- result.klarna = base;
781
- } else if (method === "link") {
782
- result.link = base;
783
- }
784
- }
785
- return result;
786
- }
787
- /**
788
- * Get store-level payment config (3DS flags, default flow ID, etc.).
789
- */
790
- async getStoreConfig() {
791
- const res = await this.http.get(
792
- "/api/v1/checkout/config",
793
- { params: { storeId: this.storeId } }
794
- );
795
- return res.config ?? res;
796
- }
797
- /**
798
- * Convenience: return only enabled payment method keys.
799
- */
800
- async getEnabledMethods(checkoutSessionId, opts) {
801
- const setup = await this.getPaymentSetup(checkoutSessionId, opts);
802
- return Object.entries(setup).filter(([, c]) => c.enabled).map(([key]) => key);
803
- }
804
- // ---------------------------------------------------------------------------
805
- // Tokenization (delegates to @tagadapay/core-js if available)
806
- // ---------------------------------------------------------------------------
807
- /**
808
- * Tokenize a card using @tagadapay/core-js.
809
- * Requires `@tagadapay/core-js` to be installed as a peer dependency.
810
- *
811
- * Card data is sent directly to Basis Theory for tokenization and never
812
- * reaches TagadaPay servers. The returned `tagadaToken` is safe to pass
813
- * to the TagadaPay API.
814
- *
815
- * **PCI note:** Using this method means card data passes through your
816
- * JavaScript environment. You are responsible for PCI DSS SAQ-A-EP
817
- * compliance. See https://docs.tagada.io/developer-tools/headless-sdk/pci-compliance
818
- *
819
- * @returns tagadaToken (base64 string) and rawToken with SCA metadata.
820
- */
821
- async tokenizeCard(card) {
822
- const coreJs = await this.loadCoreJs();
823
- const tokenizer = new coreJs.Tokenizer({ environment: this.environment });
824
- await tokenizer.initialize();
825
- const sanitized = {
826
- cardNumber: card.cardNumber,
827
- expiryDate: card.expiryDate,
828
- cvc: card.cvc
829
- };
830
- if (card.cardholderName)
831
- sanitized.cardholderName = card.cardholderName;
832
- const rawToken = await tokenizer.tokenizeCardRaw(sanitized);
833
- const tagadaToken = coreJs.createTagadaToken(
834
- rawToken,
835
- tokenizer.getProvider().getProviderName()
836
- );
837
- return { tagadaToken, rawToken };
838
- }
839
- // ---------------------------------------------------------------------------
840
- // Instrument creation
841
- // ---------------------------------------------------------------------------
842
- /**
843
- * Create a reusable payment instrument from a TagadaToken.
844
- * Session-authenticated (uses the checkout session JWT).
845
- */
846
- async createInstrument(opts) {
847
- return this.http.post("/api/v1/payment/create-instrument-from-token", {
848
- tagadaToken: opts.tagadaToken
849
- });
850
- }
851
- // ---------------------------------------------------------------------------
852
- // 3DS
853
- // ---------------------------------------------------------------------------
854
- /**
855
- * Create a 3DS session on the TagadaPay backend.
856
- * This persists the session so the processor can use it during payment.
857
- */
858
- async create3dsSession(opts) {
859
- return this.http.post("/api/public/v1/threeds/create-session", {
860
- provider: opts.provider ?? "basis_theory",
861
- storeId: this.storeId,
862
- paymentInstrumentId: opts.paymentInstrumentId,
863
- sessionData: opts.sessionData
864
- });
865
- }
866
- // ---------------------------------------------------------------------------
867
- // Payment processing
868
- // ---------------------------------------------------------------------------
869
- /**
870
- * High-level pay: single API call that decodes tagadaToken server-side,
871
- * creates the payment instrument, and processes payment.
872
- *
873
- * Also accepts `paymentInstrumentId` directly for pre-created instruments.
874
- */
875
- async pay(opts) {
876
- if (opts.tagadaToken && !opts.paymentInstrumentId) {
877
- return this.http.post("/api/v1/payment/pay-with-token", {
878
- tagadaToken: opts.tagadaToken,
879
- checkoutSessionId: opts.checkoutSessionId,
880
- returnUrl: opts.returnUrl,
881
- paymentFlowId: opts.paymentFlowId,
882
- processorId: opts.processorId,
883
- paymentMethod: opts.paymentMethod,
884
- isExpress: opts.isExpress,
885
- metadata: opts.metadata
886
- });
887
- }
888
- return this.http.post("/api/public/v1/checkout/pay-v2", {
889
- checkoutSessionId: opts.checkoutSessionId,
890
- paymentInstrumentId: opts.paymentInstrumentId,
891
- storeId: this.storeId,
892
- paymentFlowId: opts.paymentFlowId,
893
- threedsSessionId: opts.threedsSessionId,
894
- processorId: opts.processorId,
895
- paymentMethod: opts.paymentMethod,
896
- isExpress: opts.isExpress,
897
- metadata: opts.metadata
898
- });
899
- }
900
- /**
901
- * Low-level pay: process payment with an existing instrument or for APM/express flows
902
- * where no instrument is needed (redirect-based methods).
903
- */
904
- async payDirect(opts) {
905
- return this.http.post("/api/public/v1/checkout/pay-v2", {
906
- checkoutSessionId: opts.checkoutSessionId,
907
- paymentInstrumentId: opts.paymentInstrumentId ?? "",
908
- storeId: this.storeId,
909
- paymentFlowId: opts.paymentFlowId,
910
- processorId: opts.processorId,
911
- paymentMethod: opts.paymentMethod,
912
- isExpress: opts.isExpress,
913
- threedsSessionId: opts.threedsSessionId
914
- });
915
- }
916
- /**
917
- * Process an Apple Pay payment.
918
- * Tokenizes the Apple Pay token and processes payment in one call.
919
- */
920
- async processApplePay(opts) {
921
- const coreJs = await this.loadCoreJs();
922
- const tokenizer = new coreJs.Tokenizer({ environment: this.environment });
923
- await tokenizer.initialize();
924
- const { tagadaToken } = await tokenizer.tokenizeApplePay(opts.applePayToken);
925
- return this.pay({
926
- checkoutSessionId: opts.checkoutSessionId,
927
- tagadaToken,
928
- paymentFlowId: opts.paymentFlowId,
929
- processorId: opts.processorId,
930
- paymentMethod: "apple_pay",
931
- isExpress: true
932
- });
933
- }
934
- /**
935
- * Process a Google Pay payment.
936
- * Tokenizes the Google Pay token and processes payment in one call.
937
- */
938
- async processGooglePay(opts) {
939
- const coreJs = await this.loadCoreJs();
940
- const tokenizer = new coreJs.Tokenizer({ environment: this.environment });
941
- await tokenizer.initialize();
942
- const { tagadaToken } = await tokenizer.tokenizeGooglePay(opts.googlePayToken);
943
- return this.pay({
944
- checkoutSessionId: opts.checkoutSessionId,
945
- tagadaToken,
946
- paymentFlowId: opts.paymentFlowId,
947
- processorId: opts.processorId,
948
- paymentMethod: "google_pay",
949
- isExpress: true
950
- });
951
- }
952
- /**
953
- * Process an APM payment (Klarna, iDEAL, etc.) via redirect.
954
- * These typically don't require a payment instrument -- the processor handles the redirect.
955
- */
956
- async processApm(opts) {
957
- return this.payDirect({
958
- checkoutSessionId: opts.checkoutSessionId,
959
- paymentMethod: opts.paymentMethod,
960
- processorId: opts.processorId,
961
- paymentFlowId: opts.paymentFlowId
962
- });
963
- }
964
- /**
965
- * Initiate a Stripe Express Checkout payment (Apple Pay, Google Pay, Link, etc.).
966
- *
967
- * Calls `pay-v2` with `isExpress: true`, which returns a `clientSecret` in
968
- * `payment.requireActionData.metadata.stripeExpressCheckout.clientSecret`.
969
- * The caller must then call `stripe.confirmPayment()` with that secret.
970
- *
971
- * Used by the `StripeExpressCheckout` class and `useStripeExpress` hook.
972
- * Not typically called directly — use the Stripe integration classes instead.
973
- */
974
- async processStripeExpress(opts) {
975
- return this.payDirect({
976
- checkoutSessionId: opts.checkoutSessionId,
977
- processorId: opts.processorId,
978
- paymentMethod: opts.paymentMethod,
979
- isExpress: true
980
- });
981
- }
982
- // ---------------------------------------------------------------------------
983
- // High-level orchestrator — the ONE function beginners should call
984
- // ---------------------------------------------------------------------------
985
- /**
986
- * Process a payment end-to-end: pay, handle 3DS / redirects, poll until done.
987
- *
988
- * This is the **recommended** way to process payments. It wraps `pay()`, detects
989
- * `requireAction`, runs 3DS challenges (if `@tagadapay/core-js` is installed),
990
- * and polls until a terminal status.
991
- *
992
- * Returns a discriminated union so you can pattern-match on `result.status`:
993
- *
994
- * @example
995
- * ```ts
996
- * const result = await payment.processPayment({
997
- * checkoutSessionId: session.id,
998
- * tagadaToken,
999
- * });
1000
- *
1001
- * switch (result.status) {
1002
- * case 'succeeded':
1003
- * console.log('Paid!', result.payment.id);
1004
- * break;
1005
- * case 'requires_redirect':
1006
- * // In browser: window.location.href = result.redirectUrl
1007
- * // The React hook handles this automatically.
1008
- * break;
1009
- * case 'failed':
1010
- * console.error(result.error);
1011
- * break;
1012
- * }
1013
- * ```
1014
- */
1015
- async processPayment(opts) {
1016
- if (!opts.returnUrl && typeof window !== "undefined") {
1017
- opts = { ...opts, returnUrl: window.location.href };
1018
- }
1019
- const payResult = await this.pay(opts);
1020
- return this.finalize(payResult, { returnUrl: opts.returnUrl });
1021
- }
1022
- /**
1023
- * Resolve a raw `PayResult` (from any pay endpoint — `pay()`, `payDirect()`,
1024
- * `processApplePay()`, `offers.payPreviewedOffer()`, …) into a typed
1025
- * `ProcessPaymentResult` (`succeeded` / `requires_redirect` / `failed`
1026
- * / `pending`).
1027
- *
1028
- * Handles 3DS routing (modal challenge via core-js, or bank redirect)
1029
- * and async polling until the payment reaches a terminal status.
1030
- *
1031
- * This is the same logic `processPayment()` runs after `pay()` — exposed
1032
- * so callers (and the offers module) that already have a raw `PayResult`
1033
- * don't need to re-pay.
1034
- */
1035
- async finalize(input, opts) {
1036
- var _a, _b;
1037
- const payment = input.payment;
1038
- const returnUrl = (opts == null ? void 0 : opts.returnUrl) ?? (typeof window !== "undefined" ? window.location.href : void 0);
1039
- if (payment.status === "succeeded") {
1040
- return { status: "succeeded", payment, order: input.order };
1041
- }
1042
- if (payment.status === "failed" || payment.status === "declined") {
1043
- const msg = ((_a = payment.requireActionData) == null ? void 0 : _a.message) || ((_b = payment.requireActionData) == null ? void 0 : _b.errorCode) || `Payment ${payment.status}`;
1044
- return { status: "failed", error: msg, payment };
1045
- }
1046
- if (payment.requireAction && payment.requireAction !== "none" && payment.requireActionData) {
1047
- return this.handlePaymentAction(payment, { returnUrl });
1048
- }
1049
- return this.pollUntilDone(payment.id);
1050
- }
1051
- /**
1052
- * Resume a payment after the user returns from a redirect (3DS, processor auth, APM).
1053
- *
1054
- * Called automatically by `usePayment()` in React when it detects return-URL params.
1055
- * You can also call it manually in non-React apps.
1056
- */
1057
- async resumeAfterRedirect(paymentId) {
1058
- return this.pollUntilDone(paymentId);
1059
- }
1060
- /**
1061
- * Detect a return from a 3DS / processor redirect by inspecting the
1062
- * current page URL, then poll the payment to completion.
1063
- *
1064
- * The post-3DS URL convention used by Tagada-routed processors is
1065
- * `?paymentAction=requireAction&paymentActionStatus=completed&paymentId=pay_xxx`.
1066
- * If those params are present, this method polls the payment, cleans the
1067
- * URL (so a refresh doesn't re-trigger), and returns the resolved
1068
- * `ProcessPaymentResult`. Otherwise it returns `null`.
1069
- *
1070
- * Use this in vanilla apps as the first thing on page load. The React
1071
- * `usePayment` hook does the same automatically — don't call this when
1072
- * also using `usePayment`, you'll double-poll.
1073
- *
1074
- * @example
1075
- * ```ts
1076
- * const tagada = createHeadlessClient({ storeId, environment });
1077
- *
1078
- * const resumed = await tagada.payment.maybeResumeFromUrl();
1079
- * if (resumed?.status === 'succeeded') {
1080
- * window.location.href = `/thank-you?orderId=${resumed.order?.id}`;
1081
- * return;
1082
- * }
1083
- * if (resumed?.status === 'failed') {
1084
- * showError(resumed.error);
1085
- * return;
1086
- * }
1087
- * // No 3DS return — render the normal page.
1088
- * ```
1089
- */
1090
- async maybeResumeFromUrl(opts) {
1091
- if (typeof window === "undefined" && !(opts == null ? void 0 : opts.url))
1092
- return null;
1093
- const href = (opts == null ? void 0 : opts.url) ?? window.location.href;
1094
- let url;
1095
- try {
1096
- url = new URL(href);
1097
- } catch {
1098
- return null;
1099
- }
1100
- const action = url.searchParams.get("paymentAction");
1101
- const actionStatus = url.searchParams.get("paymentActionStatus");
1102
- const paymentId = url.searchParams.get("paymentId");
1103
- if (action !== "requireAction" || actionStatus !== "completed" || !paymentId) {
1104
- return null;
1105
- }
1106
- const result = await this.resumeAfterRedirect(paymentId);
1107
- if ((opts == null ? void 0 : opts.cleanUrl) !== false && typeof window !== "undefined" && !(opts == null ? void 0 : opts.url)) {
1108
- const cleanParams = new URLSearchParams(window.location.search);
1109
- [
1110
- "paymentAction",
1111
- "paymentActionStatus",
1112
- "paymentId",
1113
- "payment_intent",
1114
- "payment_intent_client_secret",
1115
- "source_type",
1116
- "redirect_status",
1117
- "sessionId"
1118
- ].forEach((k) => cleanParams.delete(k));
1119
- const search = cleanParams.toString();
1120
- try {
1121
- window.history.replaceState(
1122
- {},
1123
- document.title,
1124
- window.location.pathname + (search ? "?" + search : "")
1125
- );
1126
- } catch {
1127
- }
1128
- }
1129
- return result;
1130
- }
1131
- // ---------------------------------------------------------------------------
1132
- // Status polling
1133
- // ---------------------------------------------------------------------------
1134
- /** Get current status of a payment. */
1135
- async getPaymentStatus(paymentId) {
1136
- return this.http.get(`/api/v1/payments/${paymentId}`);
1137
- }
1138
- /**
1139
- * Poll a payment until it reaches a terminal status.
1140
- * Returns the final status or throws on timeout.
1141
- */
1142
- async pollPaymentStatus(paymentId, opts) {
1143
- const interval = (opts == null ? void 0 : opts.intervalMs) ?? 1500;
1144
- const timeout = (opts == null ? void 0 : opts.timeoutMs) ?? 6e4;
1145
- const start = Date.now();
1146
- while (Date.now() - start < timeout) {
1147
- const status = await this.getPaymentStatus(paymentId);
1148
- if (status.status === "succeeded" || status.status === "failed" || status.status === "declined") {
1149
- return status;
1150
- }
1151
- await new Promise((r) => setTimeout(r, interval));
1152
- }
1153
- throw new Error(`Payment ${paymentId} did not reach terminal status within ${timeout}ms.`);
1154
- }
1155
- /** Finalize a payment after a 3DS challenge completes. */
1156
- async completeAfter3ds(paymentId) {
1157
- return this.http.post("/api/v1/payments/complete-after-3ds", {
1158
- paymentId
1159
- });
1160
- }
1161
- /** Tell the server this action has been seen / is being processed. */
1162
- async markActionProcessed(paymentId) {
1163
- try {
1164
- await this.http.post("/api/v1/payments/require-action/processed", {
1165
- paymentId
1166
- });
1167
- } catch {
1168
- }
1169
- }
1170
- // ---------------------------------------------------------------------------
1171
- // Internal: action routing
1172
- // ---------------------------------------------------------------------------
1173
- /**
1174
- * Route a payment action to the appropriate handler.
1175
- * Returns `requires_redirect` for browser-level redirects,
1176
- * or attempts 3DS inline and polls to completion.
1177
- */
1178
- async handlePaymentAction(payment, opts) {
1179
- const actionData = payment.requireActionData;
1180
- await this.markActionProcessed(payment.id);
1181
- const actionType = actionData.type;
1182
- switch (actionType) {
1183
- case "threeds_auth":
1184
- return this.handleThreedsAuth(payment, opts);
1185
- case "processor_auth":
1186
- case "redirect_to_payment":
1187
- return this.extractRedirect(payment, actionData);
1188
- case "redirect":
1189
- return this.extractRedirect(payment, actionData);
1190
- case "error":
1191
- return {
1192
- status: "failed",
1193
- error: actionData.message || actionData.errorCode || "Payment failed",
1194
- payment
1195
- };
1196
- default:
1197
- return this.extractRedirect(payment, actionData);
1198
- }
1199
- }
1200
- /**
1201
- * Extract redirect info from actionData.
1202
- * Works for processor_auth (GET or POST), redirect, and any unknown type with a URL.
1203
- */
1204
- extractRedirect(payment, actionData) {
1205
- var _a, _b;
1206
- const redirect = (_a = actionData.metadata) == null ? void 0 : _a.redirect;
1207
- const url = (redirect == null ? void 0 : redirect.redirectUrl) || actionData.redirectUrl;
1208
- if (!url) {
1209
- return {
1210
- status: "failed",
1211
- error: `Payment requires action (${actionData.type}) but no redirect URL was provided`,
1212
- payment
1213
- };
1214
- }
1215
- return {
1216
- status: "requires_redirect",
1217
- redirectUrl: url,
1218
- method: ((_b = redirect == null ? void 0 : redirect.method) == null ? void 0 : _b.toUpperCase()) || "GET",
1219
- postData: redirect == null ? void 0 : redirect.data,
1220
- paymentId: payment.id
1221
- };
1222
- }
1223
- /**
1224
- * Run a 3DS challenge using @tagadapay/core-js.
1225
- * If core-js is not installed, falls back to redirect.
1226
- */
1227
- async handleThreedsAuth(payment, opts) {
1228
- var _a, _b;
1229
- const session = (_b = (_a = payment.requireActionData) == null ? void 0 : _a.metadata) == null ? void 0 : _b.threedsSession;
1230
- if (!(session == null ? void 0 : session.externalSessionId)) {
1231
- return this.extractRedirect(payment, payment.requireActionData);
1232
- }
1233
- let coreJs;
1234
- try {
1235
- coreJs = await import("@tagadapay/core-js");
1236
- } catch {
1237
- if (session.acsChallengeUrl) {
1238
- return {
1239
- status: "requires_redirect",
1240
- redirectUrl: session.acsChallengeUrl,
1241
- paymentId: payment.id
1242
- };
1243
- }
1244
- return this.extractRedirect(payment, payment.requireActionData);
1245
- }
1246
- try {
1247
- const manager = new coreJs.ThreedsManager({ provider: "basis_theory" });
1248
- await manager.initialize({ apiKey: void 0 });
1249
- await manager.startChallenge({
1250
- sessionId: session.externalSessionId,
1251
- acsChallengeUrl: session.acsChallengeUrl,
1252
- acsTransactionId: session.acsTransID,
1253
- threeDSVersion: session.messageVersion
1254
- });
1255
- await this.completeAfter3ds(payment.id);
1256
- return this.pollUntilDone(payment.id);
1257
- } catch {
1258
- if (session.acsChallengeUrl) {
1259
- return {
1260
- status: "requires_redirect",
1261
- redirectUrl: session.acsChallengeUrl,
1262
- paymentId: payment.id
1263
- };
1264
- }
1265
- return {
1266
- status: "failed",
1267
- error: "3D Secure authentication failed",
1268
- payment
1269
- };
1270
- }
1271
- }
1272
- /**
1273
- * Poll until the payment reaches a terminal status, then return a ProcessPaymentResult.
1274
- * Also handles new requireAction that may appear during polling.
1275
- */
1276
- async pollUntilDone(paymentId, opts) {
1277
- const interval = (opts == null ? void 0 : opts.intervalMs) ?? 1500;
1278
- const timeout = (opts == null ? void 0 : opts.timeoutMs) ?? 6e4;
1279
- const start = Date.now();
1280
- let consecutiveErrors = 0;
1281
- while (Date.now() - start < timeout) {
1282
- let status;
1283
- try {
1284
- status = await this.getPaymentStatus(paymentId);
1285
- consecutiveErrors = 0;
1286
- } catch {
1287
- consecutiveErrors++;
1288
- if (consecutiveErrors >= 3) {
1289
- return { status: "failed", error: "Payment verification failed due to network errors" };
1290
- }
1291
- await new Promise((r) => setTimeout(r, interval));
1292
- continue;
1293
- }
1294
- if (status.status === "succeeded" || status.status === "pending" && status.subStatus === "authorized") {
1295
- return { status: "succeeded", payment: status, order: status.order };
1296
- }
1297
- if (status.status === "failed" || status.status === "declined") {
1298
- return { status: "failed", error: status.status, payment: status };
1299
- }
1300
- if (status.requireAction && status.requireAction !== "none" && status.requireActionData && !status.requireActionData.processed) {
1301
- return this.handlePaymentAction(
1302
- status,
1303
- {}
1304
- );
1305
- }
1306
- await new Promise((r) => setTimeout(r, interval));
1307
- }
1308
- return { status: "pending", paymentId };
1309
- }
1310
- // ---------------------------------------------------------------------------
1311
- // Internal helpers
1312
- // ---------------------------------------------------------------------------
1313
- /**
1314
- * Read paymentSetupConfig from the Tagada routing injection.
1315
- * Only available when running on Tagada infra (not on external hosting like Vercel).
1316
- */
1317
- readInjectedStepConfig() {
1318
- if (typeof window === "undefined")
1319
- return null;
1320
- const raw = window.__TGD_STEP_CONFIG__;
1321
- if (!raw)
1322
- return null;
1323
- try {
1324
- const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
1325
- return (parsed == null ? void 0 : parsed.paymentSetupConfig) ?? null;
1326
- } catch {
1327
- return null;
1328
- }
1329
- }
1330
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1331
- async loadCoreJs() {
1332
- try {
1333
- return await import("@tagadapay/core-js");
1334
- } catch {
1335
- throw new Error(
1336
- "This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js"
1337
- );
1338
- }
1339
- }
1340
- };
1341
-
1342
- // src/core/modules/offers.ts
1343
- var OffersModule = class {
1344
- constructor(http, storeId, payment) {
1345
- this.http = http;
1346
- this.storeId = storeId;
1347
- this.payment = payment;
1348
- }
1349
- // ---------------------------------------------------------------------------
1350
- // Offer loading
1351
- // ---------------------------------------------------------------------------
1352
- /** Get a single offer by ID. */
1353
- async getOffer(offerId) {
1354
- return this.http.get(`/api/v1/offers/${offerId}`);
1355
- }
1356
- /** List offers for the current store. Optionally filter by type or a set of IDs. */
1357
- async listOffers(opts) {
1358
- var _a;
1359
- let url = `/api/v1/stores/${this.storeId}/offers`;
1360
- const queryParts = [];
1361
- if (opts == null ? void 0 : opts.type)
1362
- queryParts.push(`type=${encodeURIComponent(opts.type)}`);
1363
- if ((_a = opts == null ? void 0 : opts.ids) == null ? void 0 : _a.length) {
1364
- for (const id of opts.ids)
1365
- queryParts.push(`ids=${encodeURIComponent(id)}`);
1366
- }
1367
- if (queryParts.length)
1368
- url += `?${queryParts.join("&")}`;
1369
- const res = await this.http.get(url);
1370
- return res.offers ?? [];
1371
- }
1372
- // ---------------------------------------------------------------------------
1373
- // Preview & pay (one-click upsell flow from plugin-sdk)
1374
- // ---------------------------------------------------------------------------
1375
- /** Preview offer pricing. Returns line items with amounts and totals. */
1376
- async previewOffer(opts) {
1377
- return this.http.post(`/api/v1/offers/${opts.offerId}/preview`, {
1378
- offerId: opts.offerId,
1379
- currency: opts.currency ?? "",
1380
- lineItems: opts.lineItems
1381
- });
1382
- }
1383
- /**
1384
- * Pay a previously previewed offer (one-click charge).
1385
- * Used after a main order so the stored payment instrument is reused.
1386
- *
1387
- * **Low-level API.** Returns the raw `OfferPayResult` — `requireAction`,
1388
- * polling, and 3DS redirects are NOT handled. For most cases, use
1389
- * {@link processOfferPayment} which orchestrates the full lifecycle.
1390
- */
1391
- async payPreviewedOffer(opts) {
1392
- return this.http.post(`/api/v1/offers/${opts.offerId}/pay-preview`, {
1393
- offerId: opts.offerId,
1394
- currency: opts.currency ?? "",
1395
- lineItems: opts.lineItems,
1396
- returnUrl: opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : ""),
1397
- mainOrderId: opts.mainOrderId,
1398
- paymentInstrumentId: opts.paymentInstrumentId
1399
- });
1400
- }
1401
- /**
1402
- * One-click upsell with full lifecycle handling.
1403
- *
1404
- * Like `payment.processPayment()` but for previewed offers: charges the
1405
- * stored instrument from `mainOrderId`, runs any 3DS challenge or bank
1406
- * redirect, polls until terminal, and returns a typed
1407
- * `ProcessPaymentResult` (`succeeded` / `requires_redirect` /
1408
- * `failed` / `pending`).
1409
- *
1410
- * Use this instead of the lower-level `payPreviewedOffer()` whenever you
1411
- * don't need to inspect the raw `OfferPayResult` shape — which is most
1412
- * of the time.
1413
- *
1414
- * @example
1415
- * ```ts
1416
- * const result = await tagada.offers.processOfferPayment({
1417
- * offerId: 'offer_xxx',
1418
- * mainOrderId: order.id,
1419
- * returnUrl: window.location.href,
1420
- * });
1421
- *
1422
- * switch (result.status) {
1423
- * case 'succeeded':
1424
- * window.location.href = '/upsell-2';
1425
- * break;
1426
- * case 'requires_redirect':
1427
- * window.location.href = result.redirectUrl;
1428
- * break;
1429
- * case 'failed':
1430
- * showError(result.error);
1431
- * break;
1432
- * }
1433
- * ```
1434
- */
1435
- async processOfferPayment(opts) {
1436
- if (!this.payment) {
1437
- throw new Error(
1438
- "OffersModule: no PaymentModule injected. Use createHeadlessClient() instead of constructing OffersModule directly."
1439
- );
1440
- }
1441
- const returnUrl = opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : void 0);
1442
- const payResult = await this.payPreviewedOffer({ ...opts, returnUrl });
1443
- return this.payment.finalize(
1444
- { payment: payResult.payment, order: payResult.order },
1445
- { returnUrl }
1446
- );
1447
- }
1448
- // ---------------------------------------------------------------------------
1449
- // Order bumps (checkout-session scoped)
1450
- // ---------------------------------------------------------------------------
1451
- /** Toggle an order bump on/off within a checkout session. */
1452
- async toggleOrderBump(opts) {
1453
- return this.http.post(
1454
- `/api/v1/checkout-sessions/${opts.checkoutSessionId}/toggle-order-bump`,
1455
- {
1456
- orderBumpOfferId: opts.orderBumpOfferId,
1457
- selected: opts.selected
1458
- }
1459
- );
1460
- }
1461
- // ---------------------------------------------------------------------------
1462
- // Post-purchase offers (order-scoped)
1463
- // ---------------------------------------------------------------------------
1464
- /** List post-purchase offers for an order. */
1465
- async listPostPurchaseOffers(orderId) {
1466
- const res = await this.http.get(`/api/v1/post-purchase/${orderId}/offers`);
1467
- return Array.isArray(res) ? res : [];
1468
- }
1469
- /** Accept a post-purchase offer. */
1470
- async acceptPostPurchaseOffer(opts) {
1471
- return this.http.post(
1472
- `/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/accept`,
1473
- { items: opts.items ?? [] }
1474
- );
1475
- }
1476
- /** Decline a post-purchase offer. */
1477
- async declinePostPurchaseOffer(opts) {
1478
- return this.http.post(
1479
- `/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/decline`
1480
- );
1481
- }
1482
- };
1483
-
1484
- // src/core/modules/customer.ts
1485
- var CustomerModule = class {
1486
- constructor(http, storeId) {
1487
- this.http = http;
1488
- this.storeId = storeId;
1489
- }
1490
- /** Get customer profile by ID. */
1491
- async getProfile(customerId) {
1492
- const res = await this.http.get(
1493
- `/api/v1/customers/${customerId}`,
1494
- { params: { storeId: this.storeId } }
1495
- );
1496
- return res.customer;
1497
- }
1498
- /** Get customer profile by email. */
1499
- async getByEmail(email) {
1500
- try {
1501
- const res = await this.http.get(
1502
- "/api/v1/customers/by-email",
1503
- { params: { email, storeId: this.storeId } }
1504
- );
1505
- return res.customer;
1506
- } catch {
1507
- return null;
1508
- }
1509
- }
1510
- /** Update customer profile fields. */
1511
- async updateProfile(customerId, data) {
1512
- const res = await this.http.patch(
1513
- `/api/v1/customers/${customerId}`,
1514
- { storeId: this.storeId, ...data }
1515
- );
1516
- return res.customer;
1517
- }
1518
- /** List orders for a customer. */
1519
- async getOrders(customerId, opts) {
1520
- return this.http.get(
1521
- `/api/v1/customers/${customerId}/orders`,
1522
- { params: { storeId: this.storeId, limit: opts == null ? void 0 : opts.limit, offset: opts == null ? void 0 : opts.offset } }
1523
- );
1524
- }
1525
- /** Get a single order by ID. */
1526
- async getOrder(orderId) {
1527
- const res = await this.http.get(`/api/v1/orders/${orderId}`, {
1528
- params: { storeId: this.storeId }
1529
- });
1530
- return res.order;
1531
- }
1532
- /** List subscriptions for a customer. */
1533
- async getSubscriptions(customerId) {
1534
- const res = await this.http.get(
1535
- `/api/v1/customers/${customerId}/subscriptions`,
1536
- { params: { storeId: this.storeId } }
1537
- );
1538
- return res.subscriptions;
1539
- }
1540
- /** Get a single subscription by ID. */
1541
- async getSubscription(subscriptionId) {
1542
- const res = await this.http.get(
1543
- `/api/v1/subscriptions/${subscriptionId}`,
1544
- { params: { storeId: this.storeId } }
1545
- );
1546
- return res.subscription;
1547
- }
1548
- };
1549
-
1550
- // src/core/modules/catalog.ts
1551
- var CatalogModule = class {
1552
- constructor(http, storeId) {
1553
- this.http = http;
1554
- this.storeId = storeId;
1555
- }
1556
- /**
1557
- * List all active products for the store, including variants and prices.
1558
- *
1559
- * @param opts.productIds Optional filter to specific product IDs.
1560
- * @param opts.variantIds Optional filter to products containing these variant IDs.
1561
- */
1562
- async getProducts(opts) {
1563
- var _a, _b;
1564
- const body = {
1565
- storeId: this.storeId,
1566
- includeVariants: true,
1567
- includePrices: true
1568
- };
1569
- if ((_a = opts == null ? void 0 : opts.productIds) == null ? void 0 : _a.length)
1570
- body.productIds = opts.productIds;
1571
- if ((_b = opts == null ? void 0 : opts.variantIds) == null ? void 0 : _b.length)
1572
- body.variantIds = opts.variantIds;
1573
- const res = await this.http.post(
1574
- "/api/v1/products",
1575
- body
1576
- );
1577
- return res.items ?? [];
1578
- }
1579
- /**
1580
- * Get a single product by ID.
1581
- */
1582
- async getProduct(productId) {
1583
- const items = await this.getProducts({ productIds: [productId] });
1584
- return items[0] ?? null;
1585
- }
1586
- };
1587
-
1588
- // src/core/modules/funnel.ts
1589
- var FunnelModule = class {
1590
- constructor(http, storeId, checkout, accountId) {
1591
- this.http = http;
1592
- this.storeId = storeId;
1593
- this.checkout = checkout;
1594
- this.accountId = accountId;
1595
- }
1596
- async navigate(input) {
1597
- var _a;
1598
- const session = this.checkout.getCurrentSession();
1599
- if (!session) {
1600
- throw new TagadaError(
1601
- "No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).",
1602
- "no_cart_loaded"
1603
- );
1604
- }
1605
- const accountId = input.accountId ?? this.accountId;
1606
- if (!accountId) {
1607
- throw new TagadaError(
1608
- "accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.",
1609
- "missing_account_id"
1610
- );
1611
- }
1612
- const currentUrl = input.currentUrl ?? (typeof globalThis !== "undefined" ? (_a = globalThis.location) == null ? void 0 : _a.href : void 0);
1613
- await this.ensureCmsSession(session, accountId, input);
1614
- const funnelSessionId = await this.initializeFunnel({
1615
- funnelId: input.funnelId,
1616
- stepId: input.stepId,
1617
- accountId,
1618
- currentUrl
1619
- });
1620
- const url = await this.runNavigate({
1621
- funnelSessionId,
1622
- stepId: input.stepId,
1623
- session,
1624
- input,
1625
- currentUrl
1626
- });
1627
- return { url, funnelSessionId };
1628
- }
1629
- // -------------------------------------------------------------------------
1630
- // Internals
1631
- // -------------------------------------------------------------------------
1632
- async ensureCmsSession(session, accountId, input) {
1633
- var _a, _b, _c;
1634
- if (this._cmsToken && this._cmsSessionId && this._cmsCustomerId)
1635
- return;
1636
- const anon = await this.http.post(
1637
- "/api/v1/cms/session/anonymous",
1638
- { storeId: this.storeId, role: "anonymous", draft: false }
1639
- );
1640
- this._cmsToken = anon.token;
1641
- this._cmsSessionId = anon.sessionId;
1642
- const init = await this.http.post(
1643
- "/api/v1/cms/session/v2/init",
1644
- {
1645
- storeId: this.storeId,
1646
- accountId,
1647
- customerId: "anon_placeholder",
1648
- browserLocale: ((_a = input.customer) == null ? void 0 : _a.locale) ?? defaultLocale(),
1649
- userAgent: defaultUserAgent(),
1650
- queryCurrency: ((_b = input.customer) == null ? void 0 : _b.currency) ?? session.currency,
1651
- queryLocale: (_c = input.customer) == null ? void 0 : _c.locale
1652
- },
1653
- { token: this._cmsToken }
1654
- );
1655
- this._cmsCustomerId = init.customer.id;
1656
- }
1657
- async initializeFunnel(args) {
1658
- const res = await this.http.post(
1659
- "/api/v1/funnel/initialize",
1660
- {
1661
- cmsSession: {
1662
- customerId: this._cmsCustomerId,
1663
- sessionId: this._cmsSessionId,
1664
- storeId: this.storeId,
1665
- accountId: args.accountId
1666
- },
1667
- funnelId: args.funnelId,
1668
- entryStepId: args.stepId,
1669
- funnelStepId: args.stepId,
1670
- currentUrl: args.currentUrl,
1671
- draft: false
1672
- },
1673
- { token: this._cmsToken }
1674
- );
1675
- return res.context.sessionId;
1676
- }
1677
- async runNavigate(args) {
1678
- var _a, _b, _c, _d;
1679
- const { funnelSessionId, stepId, session, input, currentUrl } = args;
1680
- const lineItems = session.items.map((i) => ({
1681
- variantId: i.variantId,
1682
- priceId: i.priceId,
1683
- quantity: i.quantity
1684
- }));
1685
- const discountCodes = input.discountCodes ?? (session.promotionCode ? [session.promotionCode] : void 0);
1686
- const customer = {
1687
- email: ((_a = input.customer) == null ? void 0 : _a.email) ?? ((_b = session.customer) == null ? void 0 : _b.email),
1688
- currency: ((_c = input.customer) == null ? void 0 : _c.currency) ?? session.currency,
1689
- locale: (_d = input.customer) == null ? void 0 : _d.locale
1690
- };
1691
- const res = await this.http.post(
1692
- "/api/v1/funnel/navigate",
1693
- {
1694
- sessionId: funnelSessionId,
1695
- currentUrl,
1696
- funnelStepId: stepId,
1697
- fireAndForget: false,
1698
- event: {
1699
- type: "INIT_CHECKOUT",
1700
- data: {
1701
- checkoutInit: {
1702
- cartToken: session.id,
1703
- lineItems,
1704
- customer,
1705
- returnUrl: input.returnUrl,
1706
- storeId: this.storeId,
1707
- metadata: input.metadata,
1708
- discountCodes
1709
- }
1710
- }
1711
- }
1712
- },
1713
- { token: this._cmsToken }
1714
- );
1715
- return res.result.url;
1716
- }
1717
- };
1718
- function defaultLocale() {
1719
- if (typeof navigator !== "undefined" && navigator.language)
1720
- return navigator.language;
1721
- return "en-US";
1722
- }
1723
- function defaultUserAgent() {
1724
- if (typeof navigator !== "undefined" && navigator.userAgent)
1725
- return navigator.userAgent;
1726
- return "tagadapay-headless-sdk";
1727
- }
1728
-
1729
- // src/core/client.ts
1730
- var HeadlessClient = class {
1731
- constructor(config) {
1732
- const environment = config.environment ?? "production";
1733
- const baseUrl = HttpClient.resolveBaseUrl(environment, config.baseUrl);
1734
- this.config = {
1735
- ...config,
1736
- environment,
1737
- baseUrl,
1738
- timeout: config.timeout ?? 3e4
1739
- };
1740
- this.http = new HttpClient({
1741
- baseUrl,
1742
- timeout: this.config.timeout,
1743
- apiKey: config.apiKey,
1744
- getToken: () => this._sessionToken
1745
- });
1746
- const setToken = (token) => {
1747
- this._sessionToken = token;
1748
- };
1749
- this.checkout = new CheckoutModule(this.http, this.config.storeId, setToken);
1750
- this.payment = new PaymentModule(this.http, this.config.storeId, environment);
1751
- this.offers = new OffersModule(this.http, this.config.storeId, this.payment);
1752
- this.customer = new CustomerModule(this.http, this.config.storeId);
1753
- this.catalog = new CatalogModule(this.http, this.config.storeId);
1754
- this.funnel = new FunnelModule(
1755
- this.http,
1756
- this.config.storeId,
1757
- this.checkout,
1758
- this.config.accountId
1759
- );
1760
- }
1761
- /** Manually set the session token (e.g. from URL params on page load). */
1762
- setSessionToken(token) {
1763
- this._sessionToken = token;
1764
- }
1765
- };
1766
- function createHeadlessClient(config) {
1767
- return new HeadlessClient(config);
1768
- }
1769
-
1770
- // src/core/helpers/autocomplete.ts
1771
- var scriptInjected = false;
1772
- var scriptReady = false;
1773
- var readyCallbacks = [];
1774
- function onScriptReady() {
1775
- scriptReady = true;
1776
- for (const cb of readyCallbacks)
1777
- cb();
1778
- readyCallbacks.length = 0;
1779
- }
1780
- function loadGoogleMapsScript(apiKey, opts = {}) {
1781
- var _a, _b;
1782
- if (scriptReady || ((_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places)) {
1783
- onScriptReady();
1784
- return Promise.resolve();
1785
- }
1786
- if (scriptInjected) {
1787
- return new Promise((resolve) => readyCallbacks.push(resolve));
1788
- }
1789
- scriptInjected = true;
1790
- return new Promise((resolve, reject) => {
1791
- readyCallbacks.push(resolve);
1792
- const existing = document.querySelector('script[src*="maps.googleapis.com"]');
1793
- if (existing) {
1794
- const poll = () => {
1795
- var _a2, _b2;
1796
- if ((_b2 = (_a2 = window.google) == null ? void 0 : _a2.maps) == null ? void 0 : _b2.places) {
1797
- onScriptReady();
1798
- } else {
1799
- setTimeout(poll, 100);
1800
- }
1801
- };
1802
- poll();
1803
- return;
1804
- }
1805
- const params = new URLSearchParams({
1806
- key: apiKey,
1807
- libraries: "places",
1808
- v: opts.version ?? "weekly"
1809
- });
1810
- if (opts.language)
1811
- params.set("language", opts.language);
1812
- if (opts.region)
1813
- params.set("region", opts.region);
1814
- const script = document.createElement("script");
1815
- script.src = `https://maps.googleapis.com/maps/api/js?${params}`;
1816
- script.async = true;
1817
- script.defer = true;
1818
- script.onload = () => onScriptReady();
1819
- script.onerror = () => reject(new Error("Failed to load Google Maps script"));
1820
- document.head.appendChild(script);
1821
- });
1822
- }
1823
- var GoogleAutocompleteCore = class _GoogleAutocompleteCore {
1824
- /** Search for address predictions. */
1825
- static async searchPlaces(input, options = {}) {
1826
- var _a, _b;
1827
- if (!((_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places) || !input.trim())
1828
- return [];
1829
- const service = new window.google.maps.places.AutocompleteService();
1830
- return new Promise((resolve) => {
1831
- service.getPlacePredictions(
1832
- { input, types: options.types ?? ["address"], componentRestrictions: options.componentRestrictions },
1833
- (predictions, status) => {
1834
- var _a2, _b2, _c;
1835
- resolve(status === ((_c = (_b2 = (_a2 = window.google) == null ? void 0 : _a2.maps) == null ? void 0 : _b2.places) == null ? void 0 : _c.PlacesServiceStatus.OK) && predictions ? predictions : []);
1836
- }
1837
- );
1838
- });
1839
- }
1840
- /** Get full place details by place_id. */
1841
- static async getPlaceDetails(placeId) {
1842
- var _a, _b;
1843
- if (!((_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places))
1844
- return null;
1845
- const svc = new window.google.maps.places.PlacesService(document.createElement("div"));
1846
- return new Promise((resolve) => {
1847
- svc.getDetails(
1848
- { placeId, fields: ["place_id", "formatted_address", "address_components", "geometry"] },
1849
- (place, status) => {
1850
- var _a2, _b2, _c;
1851
- resolve(status === ((_c = (_b2 = (_a2 = window.google) == null ? void 0 : _a2.maps) == null ? void 0 : _b2.places) == null ? void 0 : _c.PlacesServiceStatus.OK) && place ? place : null);
1852
- }
1853
- );
1854
- });
1855
- }
1856
- /** Extract structured address fields from a Google PlaceDetails result. */
1857
- static extractAddressComponents(place) {
1858
- const out = {
1859
- subpremise: "",
1860
- streetNumber: "",
1861
- route: "",
1862
- locality: "",
1863
- administrativeAreaLevel1: "",
1864
- administrativeAreaLevel1Long: "",
1865
- administrativeAreaLevel2: "",
1866
- administrativeAreaLevel2Long: "",
1867
- country: "",
1868
- postalCode: "",
1869
- fullStreetAddress: ""
1870
- };
1871
- let premise = "";
1872
- let neighborhood = "";
1873
- let sublocality5 = "", sublocality4 = "", sublocality3 = "", sublocality2 = "", sublocality1 = "";
1874
- let postalTown = "";
1875
- for (const c of place.address_components ?? []) {
1876
- const t = c.types;
1877
- if (t.includes("subpremise"))
1878
- out.subpremise = c.long_name;
1879
- if (t.includes("street_number"))
1880
- out.streetNumber = c.long_name;
1881
- if (t.includes("premise"))
1882
- premise = c.long_name;
1883
- if (t.includes("route"))
1884
- out.route = c.long_name;
1885
- if (t.includes("neighborhood"))
1886
- neighborhood = c.long_name;
1887
- if (t.includes("sublocality_level_5"))
1888
- sublocality5 = c.long_name;
1889
- if (t.includes("sublocality_level_4"))
1890
- sublocality4 = c.long_name;
1891
- if (t.includes("sublocality_level_3"))
1892
- sublocality3 = c.long_name;
1893
- if (t.includes("sublocality_level_2"))
1894
- sublocality2 = c.long_name;
1895
- if (t.includes("sublocality_level_1"))
1896
- sublocality1 = c.long_name;
1897
- if (t.includes("locality"))
1898
- out.locality = c.long_name;
1899
- if (t.includes("postal_town"))
1900
- postalTown = c.long_name;
1901
- if (t.includes("administrative_area_level_2")) {
1902
- out.administrativeAreaLevel2 = c.short_name;
1903
- out.administrativeAreaLevel2Long = c.long_name;
1904
- }
1905
- if (t.includes("administrative_area_level_1")) {
1906
- out.administrativeAreaLevel1 = c.short_name;
1907
- out.administrativeAreaLevel1Long = c.long_name;
1908
- }
1909
- if (t.includes("country"))
1910
- out.country = c.short_name;
1911
- if (t.includes("postal_code"))
1912
- out.postalCode = c.long_name;
1913
- }
1914
- if (!out.locality)
1915
- out.locality = postalTown || sublocality2 || sublocality1 || "";
1916
- if (!out.administrativeAreaLevel1 && out.administrativeAreaLevel2) {
1917
- out.administrativeAreaLevel1 = out.administrativeAreaLevel2Long || out.administrativeAreaLevel2;
1918
- out.administrativeAreaLevel1Long = out.administrativeAreaLevel2Long;
1919
- }
1920
- const buildingNumber = out.streetNumber || premise;
1921
- const streetName = out.route || sublocality5 || sublocality4 || sublocality3 || neighborhood;
1922
- if (out.subpremise && buildingNumber && streetName) {
1923
- out.fullStreetAddress = `${out.subpremise}/${buildingNumber} ${streetName}`;
1924
- } else if (buildingNumber && streetName) {
1925
- if (premise && sublocality4 && sublocality3) {
1926
- let addr = `${sublocality3}-${sublocality4}-${premise}`;
1927
- if (sublocality2)
1928
- addr = `${addr} ${sublocality2}`;
1929
- out.fullStreetAddress = addr;
1930
- } else {
1931
- out.fullStreetAddress = `${buildingNumber} ${streetName}`;
1932
- }
1933
- } else if (streetName) {
1934
- out.fullStreetAddress = streetName;
1935
- } else if (buildingNumber) {
1936
- out.fullStreetAddress = buildingNumber;
1937
- }
1938
- out.fullStreetAddress = out.fullStreetAddress.trim();
1939
- return out;
1940
- }
1941
- /** Shorthand: extract into the flat shape used by address forms. */
1942
- static extractFormattedAddress(place) {
1943
- const a = _GoogleAutocompleteCore.extractAddressComponents(place);
1944
- return {
1945
- address1: a.fullStreetAddress,
1946
- city: a.locality,
1947
- country: a.country,
1948
- state: a.administrativeAreaLevel1,
1949
- postal: a.postalCode
1950
- };
1951
- }
1952
- };
1953
-
1954
- // src/core/helpers/iso3166.ts
1955
- var GEODATA_CDN_BASE = "https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1";
1956
- var AVAILABLE_LANGUAGES = ["en", "ru", "de", "da", "fr", "es", "zh", "hi", "pt", "ja", "ar", "it", "he"];
1957
- var countriesCache = /* @__PURE__ */ new Map();
1958
- var regionsCache = /* @__PURE__ */ new Map();
1959
- var inflightCountries = /* @__PURE__ */ new Map();
1960
- var inflightRegions = /* @__PURE__ */ new Map();
1961
- async function fetchCountriesRaw(language) {
1962
- const cached = countriesCache.get(language);
1963
- if (cached)
1964
- return cached;
1965
- let inflight = inflightCountries.get(language);
1966
- if (inflight)
1967
- return inflight;
1968
- inflight = (async () => {
1969
- const url = `${GEODATA_CDN_BASE}/${language}/countries.json`;
1970
- const res = await fetch(url);
1971
- if (!res.ok)
1972
- throw new Error(`Geodata fetch failed: ${url} (${res.status})`);
1973
- const data = await res.json();
1974
- countriesCache.set(language, data);
1975
- inflightCountries.delete(language);
1976
- return data;
1977
- })();
1978
- inflightCountries.set(language, inflight);
1979
- return inflight;
1980
- }
1981
- async function fetchRegionsRaw(language) {
1982
- const cached = regionsCache.get(language);
1983
- if (cached)
1984
- return cached;
1985
- let inflight = inflightRegions.get(language);
1986
- if (inflight)
1987
- return inflight;
1988
- inflight = (async () => {
1989
- const url = `${GEODATA_CDN_BASE}/${language}/regions.json`;
1990
- const res = await fetch(url);
1991
- if (!res.ok)
1992
- throw new Error(`Geodata fetch failed: ${url} (${res.status})`);
1993
- const data = await res.json();
1994
- regionsCache.set(language, data);
1995
- inflightRegions.delete(language);
1996
- return data;
1997
- })();
1998
- inflightRegions.set(language, inflight);
1999
- return inflight;
2000
- }
2001
- function getCountriesCached(language) {
2002
- return countriesCache.get(language) || countriesCache.get("en") || {};
2003
- }
2004
- function getRegionsCached(language) {
2005
- return regionsCache.get(language) || regionsCache.get("en") || {};
2006
- }
2007
- async function ensureGeoDataLoaded(language = "en") {
2008
- await Promise.all([fetchCountriesRaw(language), fetchRegionsRaw(language)]);
2009
- }
2010
- var getCountries = (language = "en") => {
2011
- const raw = getCountriesCached(language);
2012
- return Object.entries(raw).map(([code, c]) => ({ code, name: c.n, iso3: c.i3, numeric: c.nu })).sort((a, b) => a.name.localeCompare(b.name));
2013
- };
2014
- var getStatesForCountry = (countryCode, language = "en") => {
2015
- const raw = getRegionsCached(language);
2016
- const tuples = raw[countryCode];
2017
- if (!tuples)
2018
- return [];
2019
- return tuples.map(([iso, name]) => ({ code: iso, name, countryCode })).sort((a, b) => a.name.localeCompare(b.name));
2020
- };
2021
- function isLanguageLoaded(language) {
2022
- return countriesCache.has(language);
2023
- }
2024
-
2025
- // src/core/helpers/countries.ts
2026
- var ISODataCore = class _ISODataCore {
2027
- /** Fetch countries + regions from CDN for a language. Call before sync getters. */
2028
- static ensureLoaded(language = "en") {
2029
- return ensureGeoDataLoaded(language);
2030
- }
2031
- /** Get all countries as a Record keyed by ISO code. */
2032
- static getCountries(language = "en") {
2033
- const arr = getCountries(language);
2034
- const result = {};
2035
- for (const c of arr) {
2036
- result[c.code] = { iso: c.code, iso3: c.iso3 ?? "", numeric: c.numeric ?? 0, name: c.name };
2037
- }
2038
- return result;
2039
- }
2040
- /** Get all countries as a sorted array of { value, label } for select inputs. */
2041
- static getCountryOptions(language = "en") {
2042
- return getCountries(language).map((c) => ({ value: c.code, label: c.name }));
2043
- }
2044
- /** Get regions/states for a country. */
2045
- static getRegions(countryCode, language = "en") {
2046
- return getStatesForCountry(countryCode, language).map((s) => ({ iso: s.code, name: s.name }));
2047
- }
2048
- /** Get regions as a sorted array of { value, label } for select inputs. */
2049
- static getRegionOptions(countryCode, language = "en") {
2050
- return _ISODataCore.getRegions(countryCode, language).map((r) => ({ value: r.iso, label: r.name }));
2051
- }
2052
- /** Find a specific region by ISO code. */
2053
- static findRegion(countryCode, regionCode, language = "en") {
2054
- return _ISODataCore.getRegions(countryCode, language).find((r) => r.iso === regionCode) ?? null;
2055
- }
2056
- /**
2057
- * Map a Google Places administrative_area to an ISO region.
2058
- * Tries exact ISO match, then name match, then partial match.
2059
- */
2060
- static mapGoogleToISO(googleState, googleStateLong, countryCode, language = "en") {
2061
- const regions = _ISODataCore.getRegions(countryCode, language);
2062
- if (regions.length === 0)
2063
- return null;
2064
- let match = regions.find((r) => r.iso === googleState);
2065
- if (match)
2066
- return match;
2067
- match = regions.find((r) => r.name.toLowerCase() === googleState.toLowerCase());
2068
- if (match)
2069
- return match;
2070
- match = regions.find((r) => r.name.toLowerCase() === googleStateLong.toLowerCase());
2071
- if (match)
2072
- return match;
2073
- match = regions.find(
2074
- (r) => r.name.toLowerCase().includes(googleStateLong.toLowerCase()) || googleStateLong.toLowerCase().includes(r.name.toLowerCase())
2075
- );
2076
- return match ?? null;
2077
- }
2078
- static isLanguageLoaded(language) {
2079
- return isLanguageLoaded(language);
2080
- }
2081
- static getAvailableLanguages() {
2082
- return AVAILABLE_LANGUAGES;
2083
- }
2084
- };
2085
-
2086
- // src/core/helpers/currency.ts
2087
- var SYMBOLS = {
2088
- USD: "$",
2089
- EUR: "\u20AC",
2090
- GBP: "\xA3",
2091
- JPY: "\xA5",
2092
- CAD: "C$",
2093
- AUD: "A$",
2094
- CHF: "CHF",
2095
- CNY: "\xA5",
2096
- SEK: "kr",
2097
- NOK: "kr",
2098
- DKK: "kr",
2099
- PLN: "z\u0142",
2100
- CZK: "K\u010D",
2101
- HUF: "Ft",
2102
- RON: "lei",
2103
- BGN: "\u043B\u0432",
2104
- HRK: "kn",
2105
- RUB: "\u20BD",
2106
- UAH: "\u20B4",
2107
- TRY: "\u20BA",
2108
- BRL: "R$",
2109
- MXN: "$",
2110
- ZAR: "R",
2111
- INR: "\u20B9",
2112
- KRW: "\u20A9",
2113
- THB: "\u0E3F",
2114
- VND: "\u20AB",
2115
- IDR: "Rp",
2116
- MYR: "RM",
2117
- SGD: "S$",
2118
- PHP: "\u20B1",
2119
- TWD: "NT$",
2120
- HKD: "HK$",
2121
- ILS: "\u20AA",
2122
- AED: "\u062F.\u0625",
2123
- SAR: "\u0631.\u0633",
2124
- QAR: "\u0631.\u0642",
2125
- KWD: "\u062F.\u0643",
2126
- BHD: "\u062F.\u0628",
2127
- OMR: "\u0631.\u0639.",
2128
- EGP: "\xA3",
2129
- NGN: "\u20A6",
2130
- KES: "KSh",
2131
- GHS: "\u20B5",
2132
- COP: "$",
2133
- ARS: "$",
2134
- CLP: "$",
2135
- PEN: "S/",
2136
- CRC: "\u20A1",
2137
- DOP: "RD$",
2138
- JMD: "J$",
2139
- BOB: "Bs",
2140
- PYG: "\u20B2",
2141
- GTQ: "Q",
2142
- NIO: "C$",
2143
- PAB: "B/.",
2144
- PKR: "\u20A8",
2145
- BDT: "\u09F3",
2146
- LKR: "\u20A8",
2147
- NPR: "\u20A8",
2148
- GEL: "\u20BE",
2149
- AMD: "\u058F",
2150
- AZN: "\u20BC",
2151
- KZT: "\u20B8"
2152
- };
2153
- var NAMES = {
2154
- USD: "US Dollar",
2155
- EUR: "Euro",
2156
- GBP: "British Pound",
2157
- JPY: "Japanese Yen",
2158
- CAD: "Canadian Dollar",
2159
- AUD: "Australian Dollar",
2160
- CHF: "Swiss Franc",
2161
- CNY: "Chinese Yuan",
2162
- SEK: "Swedish Krona",
2163
- NOK: "Norwegian Krone",
2164
- DKK: "Danish Krone",
2165
- PLN: "Polish Zloty",
2166
- CZK: "Czech Koruna",
2167
- HUF: "Hungarian Forint",
2168
- BRL: "Brazilian Real",
2169
- MXN: "Mexican Peso",
2170
- INR: "Indian Rupee",
2171
- KRW: "South Korean Won",
2172
- THB: "Thai Baht",
2173
- SGD: "Singapore Dollar",
2174
- HKD: "Hong Kong Dollar",
2175
- TWD: "Taiwan Dollar",
2176
- ILS: "Israeli Shekel",
2177
- AED: "UAE Dirham",
2178
- SAR: "Saudi Riyal",
2179
- ZAR: "South African Rand",
2180
- TRY: "Turkish Lira",
2181
- RUB: "Russian Ruble",
2182
- NGN: "Nigerian Naira"
2183
- };
2184
- var ZERO_DECIMAL = /* @__PURE__ */ new Set([
2185
- "JPY",
2186
- "KRW",
2187
- "VND",
2188
- "IDR",
2189
- "LAK",
2190
- "KHR",
2191
- "MMK",
2192
- "PYG"
2193
- ]);
2194
- var CurrencyUtils = class _CurrencyUtils {
2195
- static getSymbol(code) {
2196
- return SYMBOLS[code] ?? code;
2197
- }
2198
- static getName(code) {
2199
- return NAMES[code] ?? code;
2200
- }
2201
- static getDecimalPlaces(code) {
2202
- return ZERO_DECIMAL.has(code) ? 0 : 2;
2203
- }
2204
- static getCurrency(code) {
2205
- return {
2206
- code,
2207
- symbol: _CurrencyUtils.getSymbol(code),
2208
- name: _CurrencyUtils.getName(code),
2209
- decimalPlaces: _CurrencyUtils.getDecimalPlaces(code)
2210
- };
2211
- }
2212
- };
2213
- function formatMoney(amountMinorUnits, currencyCode = "USD", locale = "en-US") {
2214
- const decimals = CurrencyUtils.getDecimalPlaces(currencyCode);
2215
- const value = amountMinorUnits / (decimals === 0 ? 100 : Math.pow(10, decimals));
2216
- try {
2217
- return new Intl.NumberFormat(locale, {
2218
- style: "currency",
2219
- currency: currencyCode,
2220
- minimumFractionDigits: decimals,
2221
- maximumFractionDigits: decimals
2222
- }).format(value);
2223
- } catch {
2224
- return `${CurrencyUtils.getSymbol(currencyCode)}${value.toFixed(decimals)}`;
2225
- }
2226
- }
2227
- return __toCommonJS(core_exports);
2228
- })();
2229
- if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}