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