@tagadapay/headless-sdk 1.4.0 → 1.5.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.
- package/dist/core/client.d.ts +6 -0
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +6 -0
- package/dist/core/client.js.map +1 -1
- package/dist/core/http.js +2 -2
- package/dist/core/http.js.map +1 -1
- package/dist/core/modules/checkout.d.ts +42 -4
- package/dist/core/modules/checkout.d.ts.map +1 -1
- package/dist/core/modules/checkout.js +72 -20
- package/dist/core/modules/checkout.js.map +1 -1
- package/dist/core/modules/payment.d.ts +58 -3
- package/dist/core/modules/payment.d.ts.map +1 -1
- package/dist/core/modules/payment.js +111 -7
- package/dist/core/modules/payment.js.map +1 -1
- package/dist/core/types.d.ts +32 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/react/hooks/useCheckout.d.ts.map +1 -1
- package/dist/react/hooks/useCheckout.js +7 -3
- package/dist/react/hooks/useCheckout.js.map +1 -1
- package/dist/react/hooks/usePayment.d.ts +19 -3
- package/dist/react/hooks/usePayment.d.ts.map +1 -1
- package/dist/react/hooks/usePayment.js +8 -3
- package/dist/react/hooks/usePayment.js.map +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/stripe/StripeExpressButton.d.ts +30 -0
- package/dist/stripe/StripeExpressButton.d.ts.map +1 -0
- package/dist/stripe/StripeExpressButton.js +32 -0
- package/dist/stripe/StripeExpressButton.js.map +1 -0
- package/dist/stripe/StripeExpressCheckout.d.ts +98 -0
- package/dist/stripe/StripeExpressCheckout.d.ts.map +1 -0
- package/dist/stripe/StripeExpressCheckout.js +198 -0
- package/dist/stripe/StripeExpressCheckout.js.map +1 -0
- package/dist/stripe/index.d.ts +8 -0
- package/dist/stripe/index.d.ts.map +1 -0
- package/dist/stripe/index.js +15 -0
- package/dist/stripe/index.js.map +1 -0
- package/dist/stripe/useStripeExpress.d.ts +54 -0
- package/dist/stripe/useStripeExpress.d.ts.map +1 -0
- package/dist/stripe/useStripeExpress.js +126 -0
- package/dist/stripe/useStripeExpress.js.map +1 -0
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +3 -3
- package/dist/tagada-headless.js +163 -33
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +3 -3
- package/package.json +9 -3
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.5.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -123,8 +123,8 @@ var TagadaHeadlessBundle = (() => {
|
|
|
123
123
|
|
|
124
124
|
// src/core/http.ts
|
|
125
125
|
var BASE_URLS = {
|
|
126
|
-
production: "https://
|
|
127
|
-
development: "https://
|
|
126
|
+
production: "https://api.tagada.io",
|
|
127
|
+
development: "https://api.tagada.dev",
|
|
128
128
|
local: "http://localhost:3000"
|
|
129
129
|
};
|
|
130
130
|
var HttpClient = class {
|
|
@@ -241,20 +241,27 @@ var TagadaHeadlessBundle = (() => {
|
|
|
241
241
|
*
|
|
242
242
|
* @param checkoutToken The checkout token (from URL param `checkoutToken`).
|
|
243
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.
|
|
244
247
|
*
|
|
245
|
-
* Both
|
|
248
|
+
* Both `checkoutToken` and `sessionToken` come from the redirect URL returned by `createSession()`.
|
|
246
249
|
* Example URL: `/checkout?checkoutToken=abc123&token=eyJ...`
|
|
247
250
|
*/
|
|
248
|
-
async loadSession(checkoutToken, sessionToken) {
|
|
251
|
+
async loadSession(checkoutToken, sessionToken, opts) {
|
|
249
252
|
var _a;
|
|
250
253
|
if (sessionToken) {
|
|
251
254
|
this.sessionToken = sessionToken;
|
|
252
255
|
(_a = this.onTokenChange) == null ? void 0 : _a.call(this, sessionToken);
|
|
253
256
|
}
|
|
257
|
+
const params = { skipAsyncWait: "false" };
|
|
258
|
+
if (opts == null ? void 0 : opts.currency) {
|
|
259
|
+
params.currency = opts.currency;
|
|
260
|
+
}
|
|
254
261
|
const raw = await this.http.get(
|
|
255
262
|
`/api/v1/checkout-sessions/${checkoutToken}/v2`,
|
|
256
263
|
{
|
|
257
|
-
params
|
|
264
|
+
params,
|
|
258
265
|
token: this.sessionToken
|
|
259
266
|
}
|
|
260
267
|
);
|
|
@@ -277,17 +284,18 @@ var TagadaHeadlessBundle = (() => {
|
|
|
277
284
|
storeId: this.storeId,
|
|
278
285
|
lineItems
|
|
279
286
|
};
|
|
280
|
-
if (opts.currency)
|
|
281
|
-
body.currency = opts.currency;
|
|
282
287
|
if (opts.returnUrl)
|
|
283
288
|
body.returnUrl = opts.returnUrl;
|
|
289
|
+
const customerData = {};
|
|
290
|
+
if (opts.currency)
|
|
291
|
+
customerData.currency = opts.currency;
|
|
284
292
|
if (opts.customerEmail) {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
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;
|
|
291
299
|
}
|
|
292
300
|
const res = await this.http.post("/api/v1/checkout/session/init", body);
|
|
293
301
|
const url = new URL(res.checkoutUrl);
|
|
@@ -302,7 +310,18 @@ var TagadaHeadlessBundle = (() => {
|
|
|
302
310
|
customerId: res.customerId
|
|
303
311
|
};
|
|
304
312
|
}
|
|
305
|
-
/**
|
|
313
|
+
/**
|
|
314
|
+
* Replace the cart items for an existing session.
|
|
315
|
+
*
|
|
316
|
+
* Returns a server-side mutation summary (counts of created/updated rows).
|
|
317
|
+
* It does NOT return the updated `CheckoutSession` — the underlying
|
|
318
|
+
* `POST /checkout-sessions/:id/line-items` endpoint never has and the
|
|
319
|
+
* previous typing was a lie that quietly assigned `{ success, updated, ... }`
|
|
320
|
+
* into a `CheckoutSession` slot in `useCheckout`.
|
|
321
|
+
*
|
|
322
|
+
* Call `loadSession()` after this if you need the refreshed session
|
|
323
|
+
* (the React `useCheckout` hook does this for you).
|
|
324
|
+
*/
|
|
306
325
|
async updateCart(sessionId, items) {
|
|
307
326
|
return this.http.post(
|
|
308
327
|
`/api/v1/checkout-sessions/${sessionId}/line-items`,
|
|
@@ -468,17 +487,20 @@ var TagadaHeadlessBundle = (() => {
|
|
|
468
487
|
* The raw response has nested `checkoutSession` + `summary` -- we flatten it.
|
|
469
488
|
*/
|
|
470
489
|
normalizeSession(raw) {
|
|
490
|
+
var _a;
|
|
471
491
|
const cs = raw.checkoutSession;
|
|
472
492
|
const orderSummaries = cs.orderSummaries ?? [];
|
|
473
493
|
const summary = raw.summary ?? cs.summary ?? orderSummaries[0] ?? {};
|
|
474
494
|
const lineItems = cs.sessionLineItems ?? [];
|
|
475
495
|
const customer = cs.customer;
|
|
496
|
+
const sessionCurrency = (_a = summary.currency ?? cs.selectedPresentmentCurrency) == null ? void 0 : _a.toUpperCase();
|
|
476
497
|
const items = lineItems.map((li) => {
|
|
477
498
|
const price = li.price;
|
|
478
499
|
const variant = (price == null ? void 0 : price.variant) ?? {};
|
|
479
500
|
const product = variant.product ?? {};
|
|
480
501
|
const currencyOpts = (price == null ? void 0 : price.currencyOptions) ?? {};
|
|
481
|
-
const
|
|
502
|
+
const priceEntry = (sessionCurrency ? currencyOpts[sessionCurrency] : void 0) ?? currencyOpts[Object.keys(currencyOpts)[0]];
|
|
503
|
+
const amount = (priceEntry == null ? void 0 : priceEntry.amount) ?? 0;
|
|
482
504
|
return {
|
|
483
505
|
id: li.id,
|
|
484
506
|
variantId: li.variantId,
|
|
@@ -486,9 +508,9 @@ var TagadaHeadlessBundle = (() => {
|
|
|
486
508
|
productName: product.name ?? "",
|
|
487
509
|
variantName: variant.name ?? "",
|
|
488
510
|
quantity: li.quantity ?? 1,
|
|
489
|
-
unitAmount:
|
|
490
|
-
totalAmount:
|
|
491
|
-
currency:
|
|
511
|
+
unitAmount: amount,
|
|
512
|
+
totalAmount: amount * (li.quantity ?? 1),
|
|
513
|
+
currency: sessionCurrency ?? "USD",
|
|
492
514
|
imageUrl: variant.imageUrl ?? ""
|
|
493
515
|
};
|
|
494
516
|
});
|
|
@@ -497,7 +519,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
497
519
|
id: cs.id,
|
|
498
520
|
storeId: cs.storeId,
|
|
499
521
|
checkoutToken: cs.checkoutToken,
|
|
500
|
-
currency:
|
|
522
|
+
currency: sessionCurrency ?? "USD",
|
|
501
523
|
items,
|
|
502
524
|
totals: {
|
|
503
525
|
subtotal: summary.subtotalAmount ?? 0,
|
|
@@ -505,19 +527,45 @@ var TagadaHeadlessBundle = (() => {
|
|
|
505
527
|
shipping: summary.shippingCost ?? 0,
|
|
506
528
|
tax: summary.totalTaxAmount ?? 0,
|
|
507
529
|
total: summary.totalAmount ?? summaryItems.reduce((s, i) => s + (i.amount ?? 0), 0),
|
|
508
|
-
currency:
|
|
530
|
+
currency: sessionCurrency ?? "USD"
|
|
509
531
|
},
|
|
510
532
|
customer: customer ? {
|
|
511
533
|
id: customer.id,
|
|
512
534
|
email: customer.email,
|
|
513
535
|
firstName: customer.firstName,
|
|
514
|
-
lastName: customer.lastName
|
|
536
|
+
lastName: customer.lastName,
|
|
537
|
+
phone: customer.phone
|
|
515
538
|
} : void 0,
|
|
516
|
-
shippingAddress: cs.shippingAddress,
|
|
517
|
-
billingAddress: cs.billingAddress,
|
|
539
|
+
shippingAddress: this.normalizeAddress(cs.shippingAddress),
|
|
540
|
+
billingAddress: this.normalizeAddress(cs.billingAddress),
|
|
541
|
+
selectedShippingRateId: cs.shippingRateId ?? null,
|
|
518
542
|
metadata: cs.metadata
|
|
519
543
|
};
|
|
520
544
|
}
|
|
545
|
+
/**
|
|
546
|
+
* Map the raw API address shape (`address1`, `address2`, `postal`) onto
|
|
547
|
+
* the SDK's `Address` shape (`line1`, `line2`, `postalCode`). Without
|
|
548
|
+
* this, `session.shippingAddress.line1` is silently undefined after a
|
|
549
|
+
* reload — the type was lying about the actual key names — which is
|
|
550
|
+
* what makes the demo lose form state on refresh.
|
|
551
|
+
*/
|
|
552
|
+
normalizeAddress(raw) {
|
|
553
|
+
if (!raw || typeof raw !== "object")
|
|
554
|
+
return void 0;
|
|
555
|
+
const a = raw;
|
|
556
|
+
const out = {
|
|
557
|
+
firstName: a.firstName,
|
|
558
|
+
lastName: a.lastName,
|
|
559
|
+
line1: a.line1 ?? a.address1,
|
|
560
|
+
line2: a.line2 ?? a.address2,
|
|
561
|
+
city: a.city,
|
|
562
|
+
state: a.state,
|
|
563
|
+
postalCode: a.postalCode ?? a.postal,
|
|
564
|
+
country: a.country,
|
|
565
|
+
phone: a.phone
|
|
566
|
+
};
|
|
567
|
+
return Object.values(out).some((v) => v !== void 0 && v !== "") ? out : void 0;
|
|
568
|
+
}
|
|
521
569
|
};
|
|
522
570
|
function stripEmpty(obj) {
|
|
523
571
|
const result = {};
|
|
@@ -543,8 +591,20 @@ var TagadaHeadlessBundle = (() => {
|
|
|
543
591
|
* Get the full payment setup config for a checkout session.
|
|
544
592
|
* Returns a map of payment methods with their configuration
|
|
545
593
|
* (card, apple_pay, google_pay, klarna, etc.).
|
|
594
|
+
*
|
|
595
|
+
* Priority chain:
|
|
596
|
+
* 1. Explicit `paymentSetupConfig` parameter (developer override)
|
|
597
|
+
* 2. `window.__TGD_STEP_CONFIG__` injection (Tagada routing infra)
|
|
598
|
+
* 3. API fallback (`GET /api/v1/payment-methods`)
|
|
546
599
|
*/
|
|
547
|
-
async getPaymentSetup(checkoutSessionId) {
|
|
600
|
+
async getPaymentSetup(checkoutSessionId, opts) {
|
|
601
|
+
if (opts == null ? void 0 : opts.paymentSetupConfig) {
|
|
602
|
+
return opts.paymentSetupConfig;
|
|
603
|
+
}
|
|
604
|
+
const injected = this.readInjectedStepConfig();
|
|
605
|
+
if (injected) {
|
|
606
|
+
return injected;
|
|
607
|
+
}
|
|
548
608
|
const methods = await this.http.get(
|
|
549
609
|
"/api/v1/payment-methods",
|
|
550
610
|
{ params: { checkoutSessionId } }
|
|
@@ -560,12 +620,39 @@ var TagadaHeadlessBundle = (() => {
|
|
|
560
620
|
* Get express payment methods (Apple Pay, Google Pay, PayPal, etc.)
|
|
561
621
|
* filtered to only those available in the current browser.
|
|
562
622
|
*/
|
|
563
|
-
async getExpressMethods(checkoutSessionId) {
|
|
564
|
-
var _a, _b;
|
|
565
|
-
const setup = await this.getPaymentSetup(checkoutSessionId);
|
|
623
|
+
async getExpressMethods(checkoutSessionId, opts) {
|
|
624
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
625
|
+
const setup = await this.getPaymentSetup(checkoutSessionId, opts);
|
|
566
626
|
const result = {};
|
|
567
|
-
for (const [, config] of Object.entries(setup)) {
|
|
568
|
-
if (!config.enabled
|
|
627
|
+
for (const [key, config] of Object.entries(setup)) {
|
|
628
|
+
if (!config.enabled)
|
|
629
|
+
continue;
|
|
630
|
+
if (key.startsWith("express_checkout:") && config.methods) {
|
|
631
|
+
const base2 = {
|
|
632
|
+
available: true,
|
|
633
|
+
processorId: config.processorId,
|
|
634
|
+
publishableKey: config.publishableKey,
|
|
635
|
+
metadata: config.metadata
|
|
636
|
+
};
|
|
637
|
+
if ((_a = config.methods.apple_pay) == null ? void 0 : _a.enabled) {
|
|
638
|
+
const hasApplePay = typeof window !== "undefined" && "ApplePaySession" in window && ((_c = (_b = window.ApplePaySession) == null ? void 0 : _b.canMakePayments) == null ? void 0 : _c.call(_b));
|
|
639
|
+
result.applePay = { ...base2, type: "apple_pay", available: !!hasApplePay };
|
|
640
|
+
}
|
|
641
|
+
if ((_d = config.methods.google_pay) == null ? void 0 : _d.enabled) {
|
|
642
|
+
result.googlePay = { ...base2, type: "google_pay" };
|
|
643
|
+
}
|
|
644
|
+
if ((_e = config.methods.paypal) == null ? void 0 : _e.enabled) {
|
|
645
|
+
result.paypal = { ...base2, type: "paypal" };
|
|
646
|
+
}
|
|
647
|
+
if ((_f = config.methods.link) == null ? void 0 : _f.enabled) {
|
|
648
|
+
result.link = { ...base2, type: "link" };
|
|
649
|
+
}
|
|
650
|
+
if ((_g = config.methods.klarna_express) == null ? void 0 : _g.enabled) {
|
|
651
|
+
result.klarna = { ...base2, type: "klarna_express" };
|
|
652
|
+
}
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (!config.express)
|
|
569
656
|
continue;
|
|
570
657
|
const method = config.method;
|
|
571
658
|
const base = {
|
|
@@ -576,7 +663,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
576
663
|
metadata: config.metadata
|
|
577
664
|
};
|
|
578
665
|
if (method === "apple_pay" || config.type === "apple_pay") {
|
|
579
|
-
const hasApplePay = typeof window !== "undefined" && "ApplePaySession" in window && ((
|
|
666
|
+
const hasApplePay = typeof window !== "undefined" && "ApplePaySession" in window && ((_i = (_h = window.ApplePaySession) == null ? void 0 : _h.canMakePayments) == null ? void 0 : _i.call(_h));
|
|
580
667
|
result.applePay = { ...base, available: !!hasApplePay };
|
|
581
668
|
} else if (method === "google_pay" || config.type === "google_pay") {
|
|
582
669
|
result.googlePay = base;
|
|
@@ -603,8 +690,8 @@ var TagadaHeadlessBundle = (() => {
|
|
|
603
690
|
/**
|
|
604
691
|
* Convenience: return only enabled payment method keys.
|
|
605
692
|
*/
|
|
606
|
-
async getEnabledMethods(checkoutSessionId) {
|
|
607
|
-
const setup = await this.getPaymentSetup(checkoutSessionId);
|
|
693
|
+
async getEnabledMethods(checkoutSessionId, opts) {
|
|
694
|
+
const setup = await this.getPaymentSetup(checkoutSessionId, opts);
|
|
608
695
|
return Object.entries(setup).filter(([, c]) => c.enabled).map(([key]) => key);
|
|
609
696
|
}
|
|
610
697
|
// ---------------------------------------------------------------------------
|
|
@@ -614,6 +701,14 @@ var TagadaHeadlessBundle = (() => {
|
|
|
614
701
|
* Tokenize a card using @tagadapay/core-js.
|
|
615
702
|
* Requires `@tagadapay/core-js` to be installed as a peer dependency.
|
|
616
703
|
*
|
|
704
|
+
* Card data is sent directly to Basis Theory for tokenization and never
|
|
705
|
+
* reaches TagadaPay servers. The returned `tagadaToken` is safe to pass
|
|
706
|
+
* to the TagadaPay API.
|
|
707
|
+
*
|
|
708
|
+
* **PCI note:** Using this method means card data passes through your
|
|
709
|
+
* JavaScript environment. You are responsible for PCI DSS SAQ-A-EP
|
|
710
|
+
* compliance. See https://docs.tagada.io/developer-tools/headless-sdk/pci-compliance
|
|
711
|
+
*
|
|
617
712
|
* @returns tagadaToken (base64 string) and rawToken with SCA metadata.
|
|
618
713
|
*/
|
|
619
714
|
async tokenizeCard(card) {
|
|
@@ -758,6 +853,24 @@ var TagadaHeadlessBundle = (() => {
|
|
|
758
853
|
paymentFlowId: opts.paymentFlowId
|
|
759
854
|
});
|
|
760
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Initiate a Stripe Express Checkout payment (Apple Pay, Google Pay, Link, etc.).
|
|
858
|
+
*
|
|
859
|
+
* Calls `pay-v2` with `isExpress: true`, which returns a `clientSecret` in
|
|
860
|
+
* `payment.requireActionData.metadata.stripeExpressCheckout.clientSecret`.
|
|
861
|
+
* The caller must then call `stripe.confirmPayment()` with that secret.
|
|
862
|
+
*
|
|
863
|
+
* Used by the `StripeExpressCheckout` class and `useStripeExpress` hook.
|
|
864
|
+
* Not typically called directly — use the Stripe integration classes instead.
|
|
865
|
+
*/
|
|
866
|
+
async processStripeExpress(opts) {
|
|
867
|
+
return this.payDirect({
|
|
868
|
+
checkoutSessionId: opts.checkoutSessionId,
|
|
869
|
+
processorId: opts.processorId,
|
|
870
|
+
paymentMethod: opts.paymentMethod,
|
|
871
|
+
isExpress: true
|
|
872
|
+
});
|
|
873
|
+
}
|
|
761
874
|
// ---------------------------------------------------------------------------
|
|
762
875
|
// High-level orchestrator — the ONE function beginners should call
|
|
763
876
|
// ---------------------------------------------------------------------------
|
|
@@ -1001,6 +1114,23 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1001
1114
|
// ---------------------------------------------------------------------------
|
|
1002
1115
|
// Internal helpers
|
|
1003
1116
|
// ---------------------------------------------------------------------------
|
|
1117
|
+
/**
|
|
1118
|
+
* Read paymentSetupConfig from the Tagada routing injection.
|
|
1119
|
+
* Only available when running on Tagada infra (not on external hosting like Vercel).
|
|
1120
|
+
*/
|
|
1121
|
+
readInjectedStepConfig() {
|
|
1122
|
+
if (typeof window === "undefined")
|
|
1123
|
+
return null;
|
|
1124
|
+
const raw = window.__TGD_STEP_CONFIG__;
|
|
1125
|
+
if (!raw)
|
|
1126
|
+
return null;
|
|
1127
|
+
try {
|
|
1128
|
+
const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
1129
|
+
return (parsed == null ? void 0 : parsed.paymentSetupConfig) ?? null;
|
|
1130
|
+
} catch {
|
|
1131
|
+
return null;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1004
1134
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1005
1135
|
async loadCoreJs() {
|
|
1006
1136
|
try {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.5.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessBundle=(()=>{var ne=Object.create;var q=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ae=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var Y=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,e)=>{for(var t in e)q(n,t,{get:e[t],enumerable:!0})},W=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oe(e))!ce.call(n,s)&&s!==t&&q(n,s,{get:()=>e[s],enumerable:!(r=ie(e,s))||r.enumerable});return n};var Z=(n,e,t)=>(t=n!=null?ne(ae(n)):{},W(e||!n||!n.__esModule?q(t,"default",{value:n,enumerable:!0}):t,n)),de=n=>W(q({},"__esModule",{value:!0}),n);var we={};ue(we,{AVAILABLE_LANGUAGES:()=>N,CatalogModule:()=>T,CheckoutModule:()=>C,CurrencyUtils:()=>w,CustomerModule:()=>b,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>O,HttpClient:()=>P,ISODataCore:()=>M,OffersModule:()=>R,PaymentModule:()=>A,TagadaAuthError:()=>I,TagadaError:()=>h,TagadaNetworkError:()=>f,TagadaNotFoundError:()=>k,TagadaPaymentError:()=>G,TagadaRateLimitError:()=>S,TagadaValidationError:()=>v,createHeadlessClient:()=>X,ensureGeoDataLoaded:()=>_,formatMoney:()=>J,getCountries:()=>L,getStatesForCountry:()=>$,isLanguageLoaded:()=>U,loadGoogleMapsScript:()=>B});var h=class extends Error{constructor(e,t,r,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=s}},I=class extends h{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},v=class extends h{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},k=class extends h{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},S=class extends h{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},G=class extends h{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},f=class extends h{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var Q={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},P=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??Q[e]??Q.production}async request(e,t={}){var d;let{method:r="GET",body:s,headers:o={},params:i,token:a,signal:c}=t,l=`${this.baseUrl}${e}`;if(i){let g=new URLSearchParams;for(let[se,V]of Object.entries(i))V!==void 0&&g.set(se,String(V));let x=g.toString();x&&(l+=`?${x}`)}let m={"Content-Type":"application/json",...o},p=a??this.apiKey??((d=this.getToken)==null?void 0:d.call(this));p&&(m["x-cms-token"]=p);let y=new AbortController,u=setTimeout(()=>y.abort(),this.timeout);try{let g=await fetch(l,{method:r,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??y.signal});if(clearTimeout(u),g.ok){let x=await g.text();return x?JSON.parse(x):{}}throw await this.handleErrorResponse(g,e),new h("Unexpected error","unknown",g.status)}catch(g){throw clearTimeout(u),g instanceof h?g:g instanceof DOMException&&g.name==="AbortError"?new f(`Request to ${e} timed out after ${this.timeout}ms.`):new f(g instanceof Error?g.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let s=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new I(s);case 404:throw new k(t,"");case 422:{let o=Array.isArray(r.errors)?r.errors:[];throw new v(s,o)}case 429:{let o=Number(e.headers.get("Retry-After")??"1")*1e3;throw new S(o)}default:throw new h(s,"api_error",e.status,r)}}};var C=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let r=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(r)}async createSession(e){var a;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),r={storeId:this.storeId,lineItems:t};e.currency&&(r.currency=e.currency),e.returnUrl&&(r.returnUrl=e.returnUrl),e.customerEmail&&(r.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",r),i=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=i,i&&((a=this.onTokenChange)==null||a.call(this,i)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:i,customerId:s.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let r=this.mapAddress(t.shippingAddress),s=this.mapAddress(t.billingAddress),o=r??s??{},i=s??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:o,billingAddress:i??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let r=this.mapAddress(t.shippingAddress),s=this.mapAddress(t.billingAddress),o=r??s??{},i=s??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:o,billingAddress:i??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return le({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,r=t.orderSummaries??[],s=e.summary??t.summary??r[0]??{},o=t.sessionLineItems??[],i=t.customer,a=o.map(l=>{let m=l.price,p=(m==null?void 0:m.variant)??{},y=p.product??{},u=(m==null?void 0:m.currencyOptions)??{},d=u.USD??u[Object.keys(u)[0]];return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:y.name??"",variantName:p.name??"",quantity:l.quantity??1,unitAmount:(d==null?void 0:d.amount)??0,totalAmount:((d==null?void 0:d.amount)??0)*(l.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:p.imageUrl??""}}),c=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:a,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??c.reduce((l,m)=>l+(m.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:i?{id:i.id,email:i.email,firstName:i.firstName,lastName:i.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};function le(n){let e={};for(let[t,r]of Object.entries(n))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var A=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r={};for(let s of t.methods??[]){let o=s.provider?`${s.method}:${s.provider}`:s.method;r[o]=s}return r}async getExpressMethods(e){var s,o;let t=await this.getPaymentSetup(e),r={};for(let[,i]of Object.entries(t)){if(!i.enabled||!i.express)continue;let a=i.method,c={type:a,available:!0,processorId:i.processorId,publishableKey:i.publishableKey,metadata:i.metadata};if(a==="apple_pay"||i.type==="apple_pay"){let l=typeof window<"u"&&"ApplePaySession"in window&&((o=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:o.call(s));r.applePay={...c,available:!!l}}else a==="google_pay"||i.type==="google_pay"?r.googlePay=c:a==="paypal"?r.paypal=c:a==="klarna"||a==="klarna_express"?r.klarna=c:a==="link"&&(r.link=c)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[o,i]=await Promise.all([r.tokenizeCard(s),r.tokenizeCardRaw(s)]);return{tagadaToken:o,rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processPayment(e){var s,o;!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e),r=t.payment;return r.status==="succeeded"?{status:"succeeded",payment:r,order:t.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((s=r.requireActionData)==null?void 0:s.message)||((o=r.requireActionData)==null?void 0:o.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,e):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,o=Date.now();for(;Date.now()-o<s;){let i=await this.getPaymentStatus(e);if(i.status==="succeeded"||i.status==="failed"||i.status==="declined")return i;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var o,i;let r=(o=t.metadata)==null?void 0:o.redirect,s=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return s?{status:"requires_redirect",redirectUrl:s,method:((i=r==null?void 0:r.method)==null?void 0:i.toUpperCase())||"GET",postData:r==null?void 0:r.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var o,i;let r=(i=(o=e.requireActionData)==null?void 0:o.metadata)==null?void 0:i.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let s;try{s=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new s.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){let r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,o=Date.now(),i=0;for(;Date.now()-o<s;){let a;try{a=await this.getPaymentStatus(e),i=0}catch{if(i++,i>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(c=>setTimeout(c,r));continue}if(a.status==="succeeded"||a.status==="pending"&&a.subStatus==="authorized")return{status:"succeeded",payment:a,order:a.order};if(a.status==="failed"||a.status==="declined")return{status:"failed",error:a.status,payment:a};if(a.requireAction&&a.requireAction!=="none"&&a.requireActionData&&!a.requireActionData.processed)return this.handlePaymentAction(a,{});await new Promise(c=>setTimeout(c,r))}return{status:"pending",paymentId:e}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var R=class{constructor(e,t){this.http=e;this.storeId=t}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var o;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(o=e==null?void 0:e.ids)!=null&&o.length)for(let i of e.ids)r.push(`ids=${encodeURIComponent(i)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var b=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var T=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var s,o;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(s=e==null?void 0:e.productIds)!=null&&s.length&&(t.productIds=e.productIds),(o=e==null?void 0:e.variantIds)!=null&&o.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var O=class{constructor(e){let t=e.environment??"production",r=P.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new P({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=o=>{this._sessionToken=o};this.checkout=new C(this.http,this.config.storeId,s),this.payment=new A(this.http,this.config.storeId,t),this.offers=new R(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId),this.catalog=new T(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function X(n){return new O(n)}var ee=!1,te=!1,H=[];function F(){te=!0;for(let n of H)n();H.length=0}function B(n,e={}){var t,r;return te||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(F(),Promise.resolve()):ee?new Promise(s=>H.push(s)):(ee=!0,new Promise((s,o)=>{if(H.push(s),document.querySelector('script[src*="maps.googleapis.com"]')){let l=()=>{var m,p;(p=(m=window.google)==null?void 0:m.maps)!=null&&p.places?F():setTimeout(l,100)};l();return}let a=new URLSearchParams({key:n,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>F(),c.onerror=()=>o(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var E=class n{static async searchPlaces(e,t={}){var s,o;if(!((o=(s=window.google)==null?void 0:s.maps)!=null&&o.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(i=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var l,m,p;i(c===((p=(m=(l=window.google)==null?void 0:l.maps)==null?void 0:m.places)==null?void 0:p.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,s;if(!((s=(r=window.google)==null?void 0:r.maps)!=null&&s.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(o=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(i,a)=>{var c,l,m;o(a===((m=(l=(c=window.google)==null?void 0:c.maps)==null?void 0:l.places)==null?void 0:m.PlacesServiceStatus.OK)&&i?i:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",s="",o="",i="",a="",c="",l="",m="";for(let u of e.address_components??[]){let d=u.types;d.includes("subpremise")&&(t.subpremise=u.long_name),d.includes("street_number")&&(t.streetNumber=u.long_name),d.includes("premise")&&(r=u.long_name),d.includes("route")&&(t.route=u.long_name),d.includes("neighborhood")&&(s=u.long_name),d.includes("sublocality_level_5")&&(o=u.long_name),d.includes("sublocality_level_4")&&(i=u.long_name),d.includes("sublocality_level_3")&&(a=u.long_name),d.includes("sublocality_level_2")&&(c=u.long_name),d.includes("sublocality_level_1")&&(l=u.long_name),d.includes("locality")&&(t.locality=u.long_name),d.includes("postal_town")&&(m=u.long_name),d.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=u.short_name,t.administrativeAreaLevel2Long=u.long_name),d.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=u.short_name,t.administrativeAreaLevel1Long=u.long_name),d.includes("country")&&(t.country=u.short_name),d.includes("postal_code")&&(t.postalCode=u.long_name)}t.locality||(t.locality=m||c||l||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let p=t.streetNumber||r,y=t.route||o||i||a||s;if(t.subpremise&&p&&y)t.fullStreetAddress=`${t.subpremise}/${p} ${y}`;else if(p&&y)if(r&&i&&a){let u=`${a}-${i}-${r}`;c&&(u=`${u} ${c}`),t.fullStreetAddress=u}else t.fullStreetAddress=`${p} ${y}`;else y?t.fullStreetAddress=y:p&&(t.fullStreetAddress=p);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=n.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var re="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",N=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],D=new Map,K=new Map,j=new Map,z=new Map;async function me(n){let e=D.get(n);if(e)return e;let t=j.get(n);return t||(t=(async()=>{let r=`${re}/${n}/countries.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let o=await s.json();return D.set(n,o),j.delete(n),o})(),j.set(n,t),t)}async function pe(n){let e=K.get(n);if(e)return e;let t=z.get(n);return t||(t=(async()=>{let r=`${re}/${n}/regions.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let o=await s.json();return K.set(n,o),z.delete(n),o})(),z.set(n,t),t)}function ge(n){return D.get(n)||D.get("en")||{}}function he(n){return K.get(n)||K.get("en")||{}}async function _(n="en"){await Promise.all([me(n),pe(n)])}var L=(n="en")=>{let e=ge(n);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},$=(n,e="en")=>{let r=he(e)[n];return r?r.map(([s,o])=>({code:s,name:o,countryCode:n})).sort((s,o)=>s.name.localeCompare(o.name)):[]};function U(n){return D.has(n)}var M=class n{static ensureLoaded(e="en"){return _(e)}static getCountries(e="en"){let t=L(e),r={};for(let s of t)r[s.code]={iso:s.code,iso3:s.iso3??"",numeric:s.numeric??0,name:s.name};return r}static getCountryOptions(e="en"){return L(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return $(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return n.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return n.getRegions(e,r).find(s=>s.iso===t)??null}static mapGoogleToISO(e,t,r,s="en"){let o=n.getRegions(r,s);if(o.length===0)return null;let i=o.find(a=>a.iso===e);return i||(i=o.find(a=>a.name.toLowerCase()===e.toLowerCase()),i)||(i=o.find(a=>a.name.toLowerCase()===t.toLowerCase()),i)?i:(i=o.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),i??null)}static isLanguageLoaded(e){return U(e)}static getAvailableLanguages(){return N}};var ye={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},fe={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},Pe=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),w=class n{static getSymbol(e){return ye[e]??e}static getName(e){return fe[e]??e}static getDecimalPlaces(e){return Pe.has(e)?0:2}static getCurrency(e){return{code:e,symbol:n.getSymbol(e),name:n.getName(e),decimalPlaces:n.getDecimalPlaces(e)}}};function J(n,e="USD",t="en-US"){let r=w.getDecimalPlaces(e),s=n/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(s)}catch{return`${w.getSymbol(e)}${s.toFixed(r)}`}}return de(we);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var ie=Object.create;var H=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var W=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,e)=>{for(var t in e)H(n,t,{get:e[t],enumerable:!0})},Z=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ae(e))!de.call(n,s)&&s!==t&&H(n,s,{get:()=>e[s],enumerable:!(r=oe(e,s))||r.enumerable});return n};var Q=(n,e,t)=>(t=n!=null?ie(ce(n)):{},Z(e||!n||!n.__esModule?H(t,"default",{value:n,enumerable:!0}):t,n)),le=n=>Z(H({},"__esModule",{value:!0}),n);var Ie={};ue(Ie,{AVAILABLE_LANGUAGES:()=>$,CatalogModule:()=>O,CheckoutModule:()=>R,CurrencyUtils:()=>S,CustomerModule:()=>x,GoogleAutocompleteCore:()=>N,HeadlessClient:()=>D,HttpClient:()=>k,ISODataCore:()=>q,OffersModule:()=>L,PaymentModule:()=>T,TagadaAuthError:()=>v,TagadaError:()=>f,TagadaNetworkError:()=>I,TagadaNotFoundError:()=>A,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>b,TagadaValidationError:()=>C,createHeadlessClient:()=>ee,ensureGeoDataLoaded:()=>U,formatMoney:()=>Y,getCountries:()=>E,getStatesForCountry:()=>M,isLanguageLoaded:()=>G,loadGoogleMapsScript:()=>z});var f=class extends Error{constructor(e,t,r,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=s}},v=class extends f{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},C=class extends f{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},A=class extends f{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},b=class extends f{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},K=class extends f{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},I=class extends f{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var X={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},k=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??X[e]??X.production}async request(e,t={}){var g;let{method:r="GET",body:s,headers:i={},params:o,token:a,signal:u}=t,m=`${this.baseUrl}${e}`;if(o){let c=new URLSearchParams;for(let[P,w]of Object.entries(o))w!==void 0&&c.set(P,String(w));let y=c.toString();y&&(m+=`?${y}`)}let h={"Content-Type":"application/json",...i},l=a??this.apiKey??((g=this.getToken)==null?void 0:g.call(this));l&&(h["x-cms-token"]=l);let p=new AbortController,d=setTimeout(()=>p.abort(),this.timeout);try{let c=await fetch(m,{method:r,headers:h,body:s!=null?JSON.stringify(s):void 0,signal:u??p.signal});if(clearTimeout(d),c.ok){let y=await c.text();return y?JSON.parse(y):{}}throw await this.handleErrorResponse(c,e),new f("Unexpected error","unknown",c.status)}catch(c){throw clearTimeout(d),c instanceof f?c:c instanceof DOMException&&c.name==="AbortError"?new I(`Request to ${e} timed out after ${this.timeout}ms.`):new I(c instanceof Error?c.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let s=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new v(s);case 404:throw new A(t,"");case 422:{let i=Array.isArray(r.errors)?r.errors:[];throw new C(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new b(i)}default:throw new f(s,"api_error",e.status,r)}}};var R=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t,r){var o;t&&(this.sessionToken=t,(o=this.onTokenChange)==null||o.call(this,t));let s={skipAsyncWait:"false"};r!=null&&r.currency&&(s.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:s,token:this.sessionToken});return this.normalizeSession(i)}async createSession(e){var u;let t=e.items.map(m=>({variantId:m.variantId,priceId:m.priceId,quantity:m.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl);let s={};e.currency&&(s.currency=e.currency),e.customerEmail&&(s.email=e.customerEmail,s.firstName=e.customerFirstName,s.lastName=e.customerLastName),Object.keys(s).length>0&&(r.customer=s);let i=await this.http.post("/api/v1/checkout/session/init",r),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((u=this.onTokenChange)==null||u.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let r=this.mapAddress(t.shippingAddress),s=this.mapAddress(t.billingAddress),i=r??s??{},o=s??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let r=this.mapAddress(t.shippingAddress),s=this.mapAddress(t.billingAddress),i=r??s??{},o=s??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return me({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var h;let t=e.checkoutSession,r=t.orderSummaries??[],s=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(h=s.currency??t.selectedPresentmentCurrency)==null?void 0:h.toUpperCase(),u=i.map(l=>{let p=l.price,d=(p==null?void 0:p.variant)??{},g=d.product??{},c=(p==null?void 0:p.currencyOptions)??{},y=(a?c[a]:void 0)??c[Object.keys(c)[0]],P=(y==null?void 0:y.amount)??0;return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:g.name??"",variantName:d.name??"",quantity:l.quantity??1,unitAmount:P,totalAmount:P*(l.quantity??1),currency:a??"USD",imageUrl:d.imageUrl??""}}),m=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:u,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??m.reduce((l,p)=>l+(p.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,r={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(r).some(s=>s!==void 0&&s!=="")?r:void 0}};function me(n){let e={};for(let[t,r]of Object.entries(n))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var T=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return t.paymentSetupConfig;let r=this.readInjectedStepConfig();if(r)return r;let s=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),i={};for(let o of s.methods??[]){let a=o.provider?`${o.method}:${o.provider}`:o.method;i[a]=o}return i}async getExpressMethods(e,t){var i,o,a,u,m,h,l,p,d;let r=await this.getPaymentSetup(e,t),s={};for(let[g,c]of Object.entries(r)){if(!c.enabled)continue;if(g.startsWith("express_checkout:")&&c.methods){let w={available:!0,processorId:c.processorId,publishableKey:c.publishableKey,metadata:c.metadata};if((i=c.methods.apple_pay)!=null&&i.enabled){let ne=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));s.applePay={...w,type:"apple_pay",available:!!ne}}(u=c.methods.google_pay)!=null&&u.enabled&&(s.googlePay={...w,type:"google_pay"}),(m=c.methods.paypal)!=null&&m.enabled&&(s.paypal={...w,type:"paypal"}),(h=c.methods.link)!=null&&h.enabled&&(s.link={...w,type:"link"}),(l=c.methods.klarna_express)!=null&&l.enabled&&(s.klarna={...w,type:"klarna_express"});continue}if(!c.express)continue;let y=c.method,P={type:y,available:!0,processorId:c.processorId,publishableKey:c.publishableKey,metadata:c.metadata};if(y==="apple_pay"||c.type==="apple_pay"){let w=typeof window<"u"&&"ApplePaySession"in window&&((d=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:d.call(p));s.applePay={...P,available:!!w}}else y==="google_pay"||c.type==="google_pay"?s.googlePay=P:y==="paypal"?s.paypal=P:y==="klarna"||y==="klarna_express"?s.klarna=P:y==="link"&&(s.link=P)}return s}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let r=await this.getPaymentSetup(e,t);return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>s)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,o]=await Promise.all([r.tokenizeCard(s),r.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:o}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async processPayment(e){var s,i;!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e),r=t.payment;return r.status==="succeeded"?{status:"succeeded",payment:r,order:t.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((s=r.requireActionData)==null?void 0:s.message)||((i=r.requireActionData)==null?void 0:i.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,e):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var i,o;let r=(i=t.metadata)==null?void 0:i.redirect,s=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return s?{status:"requires_redirect",redirectUrl:s,method:((o=r==null?void 0:r.method)==null?void 0:o.toUpperCase())||"GET",postData:r==null?void 0:r.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let r=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let s;try{s=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new s.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){let r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<s;){let a;try{a=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,r));continue}if(a.status==="succeeded"||a.status==="pending"&&a.subStatus==="authorized")return{status:"succeeded",payment:a,order:a.order};if(a.status==="failed"||a.status==="declined")return{status:"failed",error:a.status,payment:a};if(a.requireAction&&a.requireAction!=="none"&&a.requireActionData&&!a.requireActionData.processed)return this.handlePaymentAction(a,{});await new Promise(u=>setTimeout(u,r))}return{status:"pending",paymentId:e}}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var L=class{constructor(e,t){this.http=e;this.storeId=t}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var i;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(i=e==null?void 0:e.ids)!=null&&i.length)for(let o of e.ids)r.push(`ids=${encodeURIComponent(o)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var x=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var O=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var s,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(s=e==null?void 0:e.productIds)!=null&&s.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var D=class{constructor(e){let t=e.environment??"production",r=k.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new k({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new R(this.http,this.config.storeId,s),this.payment=new T(this.http,this.config.storeId,t),this.offers=new L(this.http,this.config.storeId),this.customer=new x(this.http,this.config.storeId),this.catalog=new O(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function ee(n){return new D(n)}var te=!1,re=!1,F=[];function B(){re=!0;for(let n of F)n();F.length=0}function z(n,e={}){var t,r;return re||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(B(),Promise.resolve()):te?new Promise(s=>F.push(s)):(te=!0,new Promise((s,i)=>{if(F.push(s),document.querySelector('script[src*="maps.googleapis.com"]')){let m=()=>{var h,l;(l=(h=window.google)==null?void 0:h.maps)!=null&&l.places?B():setTimeout(m,100)};m();return}let a=new URLSearchParams({key:n,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let u=document.createElement("script");u.src=`https://maps.googleapis.com/maps/api/js?${a}`,u.async=!0,u.defer=!0,u.onload=()=>B(),u.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(u)}))}var N=class n{static async searchPlaces(e,t={}){var s,i;if(!((i=(s=window.google)==null?void 0:s.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,u)=>{var m,h,l;o(u===((l=(h=(m=window.google)==null?void 0:m.maps)==null?void 0:h.places)==null?void 0:l.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,s;if(!((s=(r=window.google)==null?void 0:r.maps)!=null&&s.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var u,m,h;i(a===((h=(m=(u=window.google)==null?void 0:u.maps)==null?void 0:m.places)==null?void 0:h.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",s="",i="",o="",a="",u="",m="",h="";for(let d of e.address_components??[]){let g=d.types;g.includes("subpremise")&&(t.subpremise=d.long_name),g.includes("street_number")&&(t.streetNumber=d.long_name),g.includes("premise")&&(r=d.long_name),g.includes("route")&&(t.route=d.long_name),g.includes("neighborhood")&&(s=d.long_name),g.includes("sublocality_level_5")&&(i=d.long_name),g.includes("sublocality_level_4")&&(o=d.long_name),g.includes("sublocality_level_3")&&(a=d.long_name),g.includes("sublocality_level_2")&&(u=d.long_name),g.includes("sublocality_level_1")&&(m=d.long_name),g.includes("locality")&&(t.locality=d.long_name),g.includes("postal_town")&&(h=d.long_name),g.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=d.short_name,t.administrativeAreaLevel2Long=d.long_name),g.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=d.short_name,t.administrativeAreaLevel1Long=d.long_name),g.includes("country")&&(t.country=d.short_name),g.includes("postal_code")&&(t.postalCode=d.long_name)}t.locality||(t.locality=h||u||m||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let l=t.streetNumber||r,p=t.route||i||o||a||s;if(t.subpremise&&l&&p)t.fullStreetAddress=`${t.subpremise}/${l} ${p}`;else if(l&&p)if(r&&o&&a){let d=`${a}-${o}-${r}`;u&&(d=`${d} ${u}`),t.fullStreetAddress=d}else t.fullStreetAddress=`${l} ${p}`;else p?t.fullStreetAddress=p:l&&(t.fullStreetAddress=l);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=n.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var se="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",$=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],_=new Map,j=new Map,J=new Map,V=new Map;async function pe(n){let e=_.get(n);if(e)return e;let t=J.get(n);return t||(t=(async()=>{let r=`${se}/${n}/countries.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let i=await s.json();return _.set(n,i),J.delete(n),i})(),J.set(n,t),t)}async function ge(n){let e=j.get(n);if(e)return e;let t=V.get(n);return t||(t=(async()=>{let r=`${se}/${n}/regions.json`,s=await fetch(r);if(!s.ok)throw new Error(`Geodata fetch failed: ${r} (${s.status})`);let i=await s.json();return j.set(n,i),V.delete(n),i})(),V.set(n,t),t)}function he(n){return _.get(n)||_.get("en")||{}}function ye(n){return j.get(n)||j.get("en")||{}}async function U(n="en"){await Promise.all([pe(n),ge(n)])}var E=(n="en")=>{let e=he(n);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},M=(n,e="en")=>{let r=ye(e)[n];return r?r.map(([s,i])=>({code:s,name:i,countryCode:n})).sort((s,i)=>s.name.localeCompare(i.name)):[]};function G(n){return _.has(n)}var q=class n{static ensureLoaded(e="en"){return U(e)}static getCountries(e="en"){let t=E(e),r={};for(let s of t)r[s.code]={iso:s.code,iso3:s.iso3??"",numeric:s.numeric??0,name:s.name};return r}static getCountryOptions(e="en"){return E(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return M(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return n.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return n.getRegions(e,r).find(s=>s.iso===t)??null}static mapGoogleToISO(e,t,r,s="en"){let i=n.getRegions(r,s);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return G(e)}static getAvailableLanguages(){return $}};var fe={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Pe={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},we=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),S=class n{static getSymbol(e){return fe[e]??e}static getName(e){return Pe[e]??e}static getDecimalPlaces(e){return we.has(e)?0:2}static getCurrency(e){return{code:e,symbol:n.getSymbol(e),name:n.getName(e),decimalPlaces:n.getDecimalPlaces(e)}}};function Y(n,e="USD",t="en-US"){let r=S.getDecimalPlaces(e),s=n/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(s)}catch{return`${S.getSymbol(e)}${s.toFixed(r)}`}}return le(Ie);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|