@tagadapay/headless-sdk 1.9.0 → 1.13.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 (40) hide show
  1. package/README.md +233 -216
  2. package/dist/core/index.d.ts +1 -0
  3. package/dist/core/index.d.ts.map +1 -1
  4. package/dist/core/index.js +1 -0
  5. package/dist/core/index.js.map +1 -1
  6. package/dist/core/modules/checkout.d.ts +15 -0
  7. package/dist/core/modules/checkout.d.ts.map +1 -1
  8. package/dist/core/modules/checkout.js +14 -0
  9. package/dist/core/modules/checkout.js.map +1 -1
  10. package/dist/core/modules/customer.d.ts +28 -2
  11. package/dist/core/modules/customer.d.ts.map +1 -1
  12. package/dist/core/modules/customer.js +40 -6
  13. package/dist/core/modules/customer.js.map +1 -1
  14. package/dist/core/modules/payment.d.ts +35 -0
  15. package/dist/core/modules/payment.d.ts.map +1 -1
  16. package/dist/core/modules/payment.js +70 -2
  17. package/dist/core/modules/payment.js.map +1 -1
  18. package/dist/core/types.d.ts +9 -0
  19. package/dist/core/types.d.ts.map +1 -1
  20. package/dist/react/hooks/useCheckout.d.ts +23 -0
  21. package/dist/react/hooks/useCheckout.d.ts.map +1 -1
  22. package/dist/react/hooks/useCheckout.js +12 -0
  23. package/dist/react/hooks/useCheckout.js.map +1 -1
  24. package/dist/react/hooks/useOrder.d.ts +60 -0
  25. package/dist/react/hooks/useOrder.d.ts.map +1 -0
  26. package/dist/react/hooks/useOrder.js +103 -0
  27. package/dist/react/hooks/useOrder.js.map +1 -0
  28. package/dist/react/hooks/usePayment.d.ts +4 -0
  29. package/dist/react/hooks/usePayment.d.ts.map +1 -1
  30. package/dist/react/hooks/usePayment.js.map +1 -1
  31. package/dist/react/index.d.ts +3 -0
  32. package/dist/react/index.d.ts.map +1 -1
  33. package/dist/react/index.js +3 -0
  34. package/dist/react/index.js.map +1 -1
  35. package/dist/tagada-headless-react.min.js +2 -2
  36. package/dist/tagada-headless-react.min.js.map +4 -4
  37. package/dist/tagada-headless.js +115 -12
  38. package/dist/tagada-headless.min.js +2 -2
  39. package/dist/tagada-headless.min.js.map +3 -3
  40. package/package.json +79 -79
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.9.0
2
+ * @tagadapay/headless-sdk v1.13.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
@@ -69,7 +69,8 @@ var TagadaHeadlessBundle = (() => {
69
69
  getCountries: () => getCountries,
70
70
  getStatesForCountry: () => getStatesForCountry,
71
71
  isLanguageLoaded: () => isLanguageLoaded,
72
- loadGoogleMapsScript: () => loadGoogleMapsScript
72
+ loadGoogleMapsScript: () => loadGoogleMapsScript,
73
+ parseTokensFromUrl: () => parseTokensFromUrl
73
74
  });
74
75
 
75
76
  // src/core/errors.ts
@@ -235,7 +236,7 @@ var TagadaHeadlessBundle = (() => {
235
236
  };
236
237
 
237
238
  // src/core/modules/checkout.ts
238
- var CheckoutModule = class {
239
+ var CheckoutModule = class _CheckoutModule {
239
240
  constructor(http, storeId, onTokenChange) {
240
241
  this.http = http;
241
242
  this.storeId = storeId;
@@ -405,6 +406,10 @@ var TagadaHeadlessBundle = (() => {
405
406
  const sessionToken = parsed.searchParams.get("sessionToken") ?? parsed.searchParams.get("token") ?? "";
406
407
  return { checkoutToken, sessionToken };
407
408
  }
409
+ /** Instance alias of {@link CheckoutModule.parseTokensFromUrl}. */
410
+ parseTokensFromUrl(url) {
411
+ return _CheckoutModule.parseTokensFromUrl(url);
412
+ }
408
413
  /**
409
414
  * Add or update cart items on an existing session (upsert by product).
410
415
  *
@@ -689,6 +694,7 @@ var TagadaHeadlessBundle = (() => {
689
694
  return Object.values(out).some((v) => v !== void 0 && v !== "") ? out : void 0;
690
695
  }
691
696
  };
697
+ var parseTokensFromUrl = CheckoutModule.parseTokensFromUrl;
692
698
  function stripEmpty(obj) {
693
699
  const result = {};
694
700
  for (const [k, v] of Object.entries(obj)) {
@@ -746,6 +752,12 @@ var TagadaHeadlessBundle = (() => {
746
752
  this.storeId = storeId;
747
753
  this.environment = environment;
748
754
  this.checkout = checkout;
755
+ /**
756
+ * Last payment setup seen by `getPaymentSetup` — lets `processApplePay`
757
+ * resolve the domain's Apple Pay registration (BYOK / platform-integrator)
758
+ * without a second network round-trip inside Apple's authorization window.
759
+ */
760
+ this.lastPaymentSetup = null;
749
761
  }
750
762
  // ---------------------------------------------------------------------------
751
763
  // Discovery: what payment methods are available?
@@ -762,10 +774,12 @@ var TagadaHeadlessBundle = (() => {
762
774
  */
763
775
  async getPaymentSetup(checkoutSessionId, opts) {
764
776
  if (opts == null ? void 0 : opts.paymentSetupConfig) {
777
+ this.lastPaymentSetup = opts.paymentSetupConfig;
765
778
  return opts.paymentSetupConfig;
766
779
  }
767
780
  const injected = this.readInjectedStepConfig();
768
781
  if (injected) {
782
+ this.lastPaymentSetup = injected;
769
783
  return injected;
770
784
  }
771
785
  const methods = await this.http.get(
@@ -777,6 +791,7 @@ var TagadaHeadlessBundle = (() => {
777
791
  const key = m.provider ? `${m.method}:${m.provider}` : m.method;
778
792
  config[key] = m;
779
793
  }
794
+ this.lastPaymentSetup = config;
780
795
  return config;
781
796
  }
782
797
  /**
@@ -1035,7 +1050,7 @@ var TagadaHeadlessBundle = (() => {
1035
1050
  * };
1036
1051
  */
1037
1052
  async processApplePay(opts) {
1038
- var _a, _b, _c, _d, _e, _f, _g, _h;
1053
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1039
1054
  await this.syncWalletContact(opts.checkoutSessionId, {
1040
1055
  shippingAddress: applePayContactToAddress(opts.shippingContact),
1041
1056
  billingAddress: applePayContactToAddress(opts.billingContact),
@@ -1044,10 +1059,14 @@ var TagadaHeadlessBundle = (() => {
1044
1059
  firstName: ((_e = opts.shippingContact) == null ? void 0 : _e.givenName) ?? ((_f = opts.billingContact) == null ? void 0 : _f.givenName),
1045
1060
  lastName: ((_g = opts.shippingContact) == null ? void 0 : _g.familyName) ?? ((_h = opts.billingContact) == null ? void 0 : _h.familyName)
1046
1061
  });
1062
+ const merchantRegistrationId = opts.merchantRegistrationId ?? ((_i = await this.resolveApplePayRegistration(opts.checkoutSessionId)) == null ? void 0 : _i.merchantRegistrationId);
1047
1063
  const coreJs = await this.loadCoreJs();
1048
1064
  const tokenizer = new coreJs.Tokenizer({ environment: this.environment });
1049
1065
  await tokenizer.initialize();
1050
- const { tagadaToken } = await tokenizer.tokenizeApplePay(opts.applePayToken);
1066
+ const rawToken = await tokenizer.tokenizeApplePay(opts.applePayToken, merchantRegistrationId);
1067
+ const tagadaToken = btoa(
1068
+ JSON.stringify(coreJs.createTagadaDigitalWalletToken(rawToken, "apple_pay"))
1069
+ );
1051
1070
  return this.pay({
1052
1071
  checkoutSessionId: opts.checkoutSessionId,
1053
1072
  tagadaToken,
@@ -1057,6 +1076,52 @@ var TagadaHeadlessBundle = (() => {
1057
1076
  isExpress: true
1058
1077
  });
1059
1078
  }
1079
+ /**
1080
+ * Resolve the Apple Pay registration binding for the domain the page is
1081
+ * served from. Both merchant-certificate (BYOK) and platform-integrator
1082
+ * (PPIID) Apple Pay attach a domain-keyed `applePayByok` map to the
1083
+ * `apple_pay` method's metadata; a hit means every Basis Theory call —
1084
+ * merchant session AND tokenization — must carry that
1085
+ * `merchant_registration_id`. A miss (the default) means legacy platform
1086
+ * Apple Pay: omit the id and behavior is unchanged.
1087
+ *
1088
+ * Sources, in order: the Tagada routing injection, the last payment setup
1089
+ * seen by `getPaymentSetup`, then one API fetch when a `checkoutSessionId`
1090
+ * is given and no setup was ever loaded.
1091
+ *
1092
+ * Use `displayName` (when present) as the `display_name` of the Basis
1093
+ * Theory merchant session.
1094
+ */
1095
+ async resolveApplePayRegistration(checkoutSessionId) {
1096
+ if (typeof window === "undefined")
1097
+ return null;
1098
+ let host = window.location.hostname.toLowerCase().split(":")[0];
1099
+ if (host.startsWith("www."))
1100
+ host = host.slice(4);
1101
+ const fromConfig = (setup) => {
1102
+ var _a;
1103
+ for (const entry of Object.values(setup ?? {})) {
1104
+ const map = (_a = entry == null ? void 0 : entry.metadata) == null ? void 0 : _a.applePayByok;
1105
+ if (!map || typeof map !== "object")
1106
+ continue;
1107
+ const hit = map[host];
1108
+ if (hit == null ? void 0 : hit.merchantRegistrationId) {
1109
+ return { merchantRegistrationId: hit.merchantRegistrationId, displayName: hit.displayName };
1110
+ }
1111
+ }
1112
+ return null;
1113
+ };
1114
+ const local = fromConfig(this.readInjectedStepConfig()) ?? fromConfig(this.lastPaymentSetup);
1115
+ if (local)
1116
+ return local;
1117
+ if (this.lastPaymentSetup || this.readInjectedStepConfig() || !checkoutSessionId)
1118
+ return null;
1119
+ try {
1120
+ return fromConfig(await this.getPaymentSetup(checkoutSessionId));
1121
+ } catch {
1122
+ return null;
1123
+ }
1124
+ }
1060
1125
  /**
1061
1126
  * Process a Google Pay payment.
1062
1127
  * Tokenizes the Google Pay token and processes payment in one call.
@@ -1077,7 +1142,10 @@ var TagadaHeadlessBundle = (() => {
1077
1142
  const coreJs = await this.loadCoreJs();
1078
1143
  const tokenizer = new coreJs.Tokenizer({ environment: this.environment });
1079
1144
  await tokenizer.initialize();
1080
- const { tagadaToken } = await tokenizer.tokenizeGooglePay(opts.googlePayToken);
1145
+ const rawToken = await tokenizer.tokenizeGooglePay(opts.googlePayToken);
1146
+ const tagadaToken = btoa(
1147
+ JSON.stringify(coreJs.createTagadaDigitalWalletToken(rawToken, "google_pay"))
1148
+ );
1081
1149
  return this.pay({
1082
1150
  checkoutSessionId: opts.checkoutSessionId,
1083
1151
  tagadaToken,
@@ -1660,12 +1728,47 @@ var TagadaHeadlessBundle = (() => {
1660
1728
  { params: { storeId: this.storeId, limit: opts == null ? void 0 : opts.limit, offset: opts == null ? void 0 : opts.offset } }
1661
1729
  );
1662
1730
  }
1663
- /** Get a single order by ID. */
1664
- async getOrder(orderId) {
1665
- const res = await this.http.get(`/api/v1/orders/${orderId}`, {
1666
- params: { storeId: this.storeId }
1667
- });
1668
- return res.order;
1731
+ /**
1732
+ * Get a single order by ID.
1733
+ *
1734
+ * **Thank-you pages:** accepted one-click upsells create *child orders*
1735
+ * (`metadata.mainOrderId` = this order's id) that land asynchronously —
1736
+ * the first fetch right after an accept usually misses them. Pass
1737
+ * `waitForRelatedOrders: true` to poll until `order.relatedOrders` is
1738
+ * non-empty or the timeout elapses. On timeout the latest snapshot is
1739
+ * returned (never throws), so an order with no accepted upsell simply
1740
+ * comes back with an empty `relatedOrders` after `timeoutMs`.
1741
+ *
1742
+ * @example
1743
+ * ```ts
1744
+ * // Thank-you page: show the main order AND the upsells
1745
+ * const order = await tagada.customer.getOrder(orderId, {
1746
+ * waitForRelatedOrders: true,
1747
+ * });
1748
+ * renderOrders([order, ...(order.relatedOrders ?? [])]);
1749
+ * ```
1750
+ */
1751
+ async getOrder(orderId, opts) {
1752
+ var _a, _b;
1753
+ const fetchOrder = async () => {
1754
+ const res = await this.http.get(`/api/v1/orders/${orderId}`, {
1755
+ params: { storeId: this.storeId }
1756
+ });
1757
+ return res.order;
1758
+ };
1759
+ let order = await fetchOrder();
1760
+ if (!(opts == null ? void 0 : opts.waitForRelatedOrders) || ((_a = order.relatedOrders) == null ? void 0 : _a.length))
1761
+ return order;
1762
+ const timeoutMs = opts.timeoutMs ?? 8e3;
1763
+ const intervalMs = opts.intervalMs ?? 2e3;
1764
+ const deadline = Date.now() + timeoutMs;
1765
+ while (Date.now() < deadline) {
1766
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));
1767
+ order = await fetchOrder();
1768
+ if ((_b = order.relatedOrders) == null ? void 0 : _b.length)
1769
+ return order;
1770
+ }
1771
+ return order;
1669
1772
  }
1670
1773
  /** List subscriptions for a customer. */
1671
1774
  async getSubscriptions(customerId) {
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.9.0
2
+ * @tagadapay/headless-sdk v1.13.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessBundle=(()=>{var ue=Object.create;var j=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var ee=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ge=(s,e)=>{for(var t in e)j(s,t,{get:e[t],enumerable:!0})},te=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of le(e))!pe.call(s,n)&&n!==t&&j(s,n,{get:()=>e[n],enumerable:!(r=ce(e,n))||r.enumerable});return s};var re=(s,e,t)=>(t=s!=null?ue(me(s)):{},te(e||!s||!s.__esModule?j(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>te(j({},"__esModule",{value:!0}),s);var be={};ge(be,{AVAILABLE_LANGUAGES:()=>M,CatalogModule:()=>N,CheckoutModule:()=>b,CurrencyUtils:()=>C,CustomerModule:()=>T,FunnelModule:()=>L,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>U,HttpClient:()=>w,ISODataCore:()=>G,OffersModule:()=>x,PaymentModule:()=>R,RxModule:()=>_,TagadaAuthError:()=>k,TagadaError:()=>y,TagadaNetworkError:()=>P,TagadaNotFoundError:()=>S,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>A,TagadaValidationError:()=>v,createHeadlessClient:()=>ie,ensureGeoDataLoaded:()=>$,formatMoney:()=>X,getCountries:()=>O,getStatesForCountry:()=>q,isLanguageLoaded:()=>F,loadGoogleMapsScript:()=>W});var y=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},k=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},v=class extends y{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},S=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},A=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},K=class extends y{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}},P=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},w=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??ne[e]??ne.production}async request(e,t={}){var u;let{method:r="GET",body:n,headers:i={},params:o,token:a,signal:d}=t,m=`${this.baseUrl}${e}`;if(o){let p=new URLSearchParams;for(let[I,H]of Object.entries(o))H!==void 0&&p.set(I,String(H));let f=p.toString();f&&(m+=`?${f}`)}let h={"Content-Type":"application/json",...i},c=a??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));c&&(h["x-cms-token"]=c);let g=new AbortController,l=setTimeout(()=>g.abort(),this.timeout);try{let p=await fetch(m,{method:r,headers:h,body:n!=null?JSON.stringify(n):void 0,signal:d??g.signal});if(clearTimeout(l),p.ok){let f=await p.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(p,e),new y("Unexpected error","unknown",p.status)}catch(p){throw clearTimeout(l),p instanceof y?p:p instanceof DOMException&&p.name==="AbortError"?new P(`Request to ${e} timed out after ${this.timeout}ms.`):new P(p instanceof Error?p.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 n=r.data??{},i=r.message??r.error??(typeof n.message=="string"?n.message:void 0)??(typeof r.data=="string"?r.data:void 0)??`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new k(i);case 404:throw new S(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new v(i,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new A(a)}default:throw new y(i,"api_error",e.status,r)}}};var b=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(i);return this._currentSession=o,o}async createSession(e){var d;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 n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);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&&((d=this.onTokenChange)==null||d.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let t=await this.createSession({items:e.items,currency:e.currency,returnUrl:e.returnUrl,customerEmail:e.customerEmail,customerFirstName:e.customerFirstName,customerLastName:e.customerLastName}),r=e.origin??(typeof window<"u"?window.location.origin:""),n=e.checkoutPath??"/checkout",i=new URLSearchParams({checkoutToken:t.checkoutToken,sessionToken:t.sessionToken}),o=`${r}${n}?${i.toString()}`;return{...t,url:o}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{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),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??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),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??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 ye({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??[]).map(r=>this.normalizeShippingRate(r))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}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??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(h=n.currency??t.selectedPresentmentCurrency)==null?void 0:h.toUpperCase(),d=i.map(c=>{let g=c.price,l=c.variant??(g==null?void 0:g.variant)??{},u=c.product??l.product??{},p=(g==null?void 0:g.currencyOptions)??{},f=(a?p[a]:void 0)??p[Object.keys(p)[0]],I=(f==null?void 0:f.amount)??0;return{id:c.id,variantId:c.variantId,priceId:c.priceId,productName:u.name??"",variantName:l.name??"",quantity:c.quantity??1,unitAmount:I,totalAmount:I*(c.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??u.imageUrl??""}}),m=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:d,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??m.reduce((c,g)=>c+(g.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(n=>n!==void 0&&n!=="")?r:void 0}};function ye(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function B(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return se(e)?e:void 0}function z(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return se(r)?r:void 0}function se(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var R=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.environment=r;this.checkout=n}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return t.paymentSetupConfig;let r=this.readInjectedStepConfig();if(r)return r;let n=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),i={};for(let o of n.methods??[]){let a=o.provider?`${o.method}:${o.provider}`:o.method;i[a]=o}return i}async getExpressMethods(e,t){var i,o,a,d,m,h,c,g;let r=await this.getPaymentSetup(e,t),n={};for(let[l,u]of Object.entries(r)){if(!u.enabled)continue;if(l.startsWith("express_checkout:")&&u.methods){let I={available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if((i=u.methods.apple_pay)!=null&&i.enabled){let H=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...I,type:"apple_pay",available:!!H}}(d=u.methods.google_pay)!=null&&d.enabled&&(n.googlePay={...I,type:"google_pay"}),(m=u.methods.link)!=null&&m.enabled&&(n.link={...I,type:"link"}),(h=u.methods.klarna_express)!=null&&h.enabled&&(n.klarna={...I,type:"klarna_express"});continue}if(!u.express)continue;let p=u.method,f={type:p,available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if(p==="apple_pay"||u.type==="apple_pay"){let I=typeof window<"u"&&"ApplePaySession"in window&&((g=(c=window.ApplePaySession)==null?void 0:c.canMakePayments)==null?void 0:g.call(c));n.applePay={...f,available:!!I}}else p==="google_pay"||u.type==="google_pay"?n.googlePay=f:p==="paypal"?n.paypal=f:p==="klarna"||p==="klarna_express"?n.klarna=f:p==="link"&&(n.link=f)}return n}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(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.getProvider().getProviderName()),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,returnUrl:e.returnUrl})}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,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress:r,billingAddress:n}=t;if(!r&&!n)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:r,billingAddress:n})}async processApplePay(e){var i,o,a,d,m,h,c,g;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:B(e.shippingContact),billingAddress:B(e.billingContact),email:((i=e.shippingContact)==null?void 0:i.emailAddress)??((o=e.billingContact)==null?void 0:o.emailAddress),phone:((a=e.shippingContact)==null?void 0:a.phoneNumber)??((d=e.billingContact)==null?void 0:d.phoneNumber),firstName:((m=e.shippingContact)==null?void 0:m.givenName)??((h=e.billingContact)==null?void 0:h.givenName),lastName:((c=e.shippingContact)==null?void 0:c.familyName)??((g=e.billingContact)==null?void 0:g.familyName)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){var i,o,a,d;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:z(e.shippingAddress),billingAddress:z(e.billingAddress),email:e.email??((i=e.shippingAddress)==null?void 0:i.emailAddress)??((o=e.billingAddress)==null?void 0:o.emailAddress),phone:((a=e.shippingAddress)==null?void 0:a.phoneNumber)??((d=e.billingAddress)==null?void 0:d.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,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){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?{status:"succeeded",payment:r,order:e.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((i=r.requireActionData)==null?void 0:i.message)||((o=r.requireActionData)==null?void 0:o.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(h=>d.delete(h));let m=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(m?"?"+m:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){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 ${n}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,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,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 n;try{n=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 n.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,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<n;){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(d=>setTimeout(d,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(d=>setTimeout(d,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 x=class{constructor(e,t,r){this.http=e;this.storeId=t;this.payment=r}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 processOfferPayment(e){if(!this.payment)throw new Error("OffersModule: no PaymentModule injected. Use createHeadlessClient() instead of constructing OffersModule directly.");let t=e.returnUrl??(typeof window<"u"?window.location.href:void 0),r=await this.payPreviewedOffer({...e,returnUrl:t});return this.payment.finalize({payment:r.payment,order:r.order},{returnUrl:t})}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 T=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 N=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.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 L=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n}async navigate(e){var a;let t=this.checkout.getCurrentSession();if(!t)throw new y("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new y("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var o,a,d;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=r.customer)==null?void 0:o.locale)??fe(),userAgent:Ie(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(d=r.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var c,g,l,u;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:o}=e,a=n.items.map(p=>({variantId:p.variantId,priceId:p.priceId,quantity:p.quantity})),d=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),m={email:((c=i.customer)==null?void 0:c.email)??((g=n.customer)==null?void 0:g.email),currency:((l=i.customer)==null?void 0:l.currency)??n.currency,locale:(u=i.customer)==null?void 0:u.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:a,customer:m,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function fe(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ie(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var _=class{constructor(e){this.http=e}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async getQuestionsForProduct(e){return this.http.get("/api/public/v1/rx/questions-for-product",{params:{productId:e}})}};var U=class{constructor(e){let t=e.environment??"production",r=w.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new w({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=i=>{this._sessionToken=i};this.checkout=new b(this.http,this.config.storeId,n),this.payment=new R(this.http,this.config.storeId,t,this.checkout),this.offers=new x(this.http,this.config.storeId,this.payment),this.customer=new T(this.http,this.config.storeId),this.catalog=new N(this.http,this.config.storeId),this.funnel=new L(this.http,this.config.storeId,this.checkout,this.config.accountId),this.rx=new _(this.http)}setSessionToken(e){this._sessionToken=e}};function ie(s){return new U(s)}var oe=!1,ae=!1,J=[];function Q(){ae=!0;for(let s of J)s();J.length=0}function W(s,e={}){var t,r;return ae||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(Q(),Promise.resolve()):oe?new Promise(n=>J.push(n)):(oe=!0,new Promise((n,i)=>{if(J.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let m=()=>{var h,c;(c=(h=window.google)==null?void 0:h.maps)!=null&&c.places?Q():setTimeout(m,100)};m();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${a}`,d.async=!0,d.defer=!0,d.onload=()=>Q(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var E=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.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,d)=>{var m,h,c;o(d===((c=(h=(m=window.google)==null?void 0:m.maps)==null?void 0:h.places)==null?void 0:c.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.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 d,m,h;i(a===((h=(m=(d=window.google)==null?void 0:d.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="",n="",i="",o="",a="",d="",m="",h="";for(let l of e.address_components??[]){let u=l.types;u.includes("subpremise")&&(t.subpremise=l.long_name),u.includes("street_number")&&(t.streetNumber=l.long_name),u.includes("premise")&&(r=l.long_name),u.includes("route")&&(t.route=l.long_name),u.includes("neighborhood")&&(n=l.long_name),u.includes("sublocality_level_5")&&(i=l.long_name),u.includes("sublocality_level_4")&&(o=l.long_name),u.includes("sublocality_level_3")&&(a=l.long_name),u.includes("sublocality_level_2")&&(d=l.long_name),u.includes("sublocality_level_1")&&(m=l.long_name),u.includes("locality")&&(t.locality=l.long_name),u.includes("postal_town")&&(h=l.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),u.includes("country")&&(t.country=l.short_name),u.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=h||d||m||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let c=t.streetNumber||r,g=t.route||i||o||a||n;if(t.subpremise&&c&&g)t.fullStreetAddress=`${t.subpremise}/${c} ${g}`;else if(c&&g)if(r&&o&&a){let l=`${a}-${o}-${r}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${c} ${g}`;else g?t.fullStreetAddress=g:c&&(t.fullStreetAddress=c);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var de="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",M=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],D=new Map,V=new Map,Y=new Map,Z=new Map;async function Pe(s){let e=D.get(s);if(e)return e;let t=Y.get(s);return t||(t=(async()=>{let r=`${de}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return D.set(s,i),Y.delete(s),i})(),Y.set(s,t),t)}async function we(s){let e=V.get(s);if(e)return e;let t=Z.get(s);return t||(t=(async()=>{let r=`${de}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return V.set(s,i),Z.delete(s),i})(),Z.set(s,t),t)}function Ce(s){return D.get(s)||D.get("en")||{}}function ke(s){return V.get(s)||V.get("en")||{}}async function $(s="en"){await Promise.all([Pe(s),we(s)])}var O=(s="en")=>{let e=Ce(s);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))},q=(s,e="en")=>{let r=ke(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function F(s){return D.has(s)}var G=class s{static ensureLoaded(e="en"){return $(e)}static getCountries(e="en"){let t=O(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return O(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return q(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);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 F(e)}static getAvailableLanguages(){return M}};var ve={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"},Se={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"},Ae=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),C=class s{static getSymbol(e){return ve[e]??e}static getName(e){return Se[e]??e}static getDecimalPlaces(e){return Ae.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function X(s,e="USD",t="en-US"){let r=C.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${C.getSymbol(e)}${n.toFixed(r)}`}}return he(be);})();
6
+ "use strict";var TagadaHeadlessBundle=(()=>{var ce=Object.create;var j=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var ee=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var he=(s,e)=>{for(var t in e)j(s,t,{get:e[t],enumerable:!0})},te=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!ge.call(s,n)&&n!==t&&j(s,n,{get:()=>e[n],enumerable:!(r=le(e,n))||r.enumerable});return s};var re=(s,e,t)=>(t=s!=null?ce(pe(s)):{},te(e||!s||!s.__esModule?j(t,"default",{value:s,enumerable:!0}):t,s)),ye=s=>te(j({},"__esModule",{value:!0}),s);var be={};he(be,{AVAILABLE_LANGUAGES:()=>M,CatalogModule:()=>N,CheckoutModule:()=>C,CurrencyUtils:()=>k,CustomerModule:()=>T,FunnelModule:()=>L,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>U,HttpClient:()=>w,ISODataCore:()=>G,OffersModule:()=>x,PaymentModule:()=>b,RxModule:()=>O,TagadaAuthError:()=>S,TagadaError:()=>y,TagadaNetworkError:()=>I,TagadaNotFoundError:()=>A,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>R,TagadaValidationError:()=>v,createHeadlessClient:()=>oe,ensureGeoDataLoaded:()=>$,formatMoney:()=>X,getCountries:()=>_,getStatesForCountry:()=>F,isLanguageLoaded:()=>q,loadGoogleMapsScript:()=>Q,parseTokensFromUrl:()=>se});var y=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},S=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},v=class extends y{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},A=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},R=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},K=class extends y{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 y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},w=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??ne[e]??ne.production}async request(e,t={}){var u;let{method:r="GET",body:n,headers:i={},params:a,token:o,signal:d}=t,c=`${this.baseUrl}${e}`;if(a){let p=new URLSearchParams;for(let[P,H]of Object.entries(a))H!==void 0&&p.set(P,String(H));let f=p.toString();f&&(c+=`?${f}`)}let g={"Content-Type":"application/json",...i},m=o??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));m&&(g["x-cms-token"]=m);let h=new AbortController,l=setTimeout(()=>h.abort(),this.timeout);try{let p=await fetch(c,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:d??h.signal});if(clearTimeout(l),p.ok){let f=await p.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(p,e),new y("Unexpected error","unknown",p.status)}catch(p){throw clearTimeout(l),p instanceof y?p:p instanceof DOMException&&p.name==="AbortError"?new I(`Request to ${e} timed out after ${this.timeout}ms.`):new I(p instanceof Error?p.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 n=r.data??{},i=r.message??r.error??(typeof n.message=="string"?n.message:void 0)??(typeof r.data=="string"?r.data:void 0)??`Request failed: ${e.status} ${e.statusText} on ${t}`,a=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new S(i);case 404:throw new A(t,"");case 422:{let o=Array.isArray(r.errors)?r.errors:[];throw new v(i,o,a,r)}case 429:{let o=Number(e.headers.get("Retry-After")??"1")*1e3;throw new R(o)}default:throw new y(i,"api_error",e.status,r)}}};var C=class s{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var o;t&&(this.sessionToken=t,(o=this.onTokenChange)==null||o.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),a=this.normalizeSession(i);return this._currentSession=a,a}async createSession(e){var d;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl);let n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);let i=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((d=this.onTokenChange)==null||d.call(this,o)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:o,customerId:i.customerId}}async createSessionUrl(e){let t=await this.createSession({items:e.items,currency:e.currency,returnUrl:e.returnUrl,customerEmail:e.customerEmail,customerFirstName:e.customerFirstName,customerLastName:e.customerLastName}),r=e.origin??(typeof window<"u"?window.location.origin:""),n=e.checkoutPath??"/checkout",i=new URLSearchParams({checkoutToken:t.checkoutToken,sessionToken:t.sessionToken}),a=`${r}${n}?${i.toString()}`;return{...t,url:a}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{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),n=this.mapAddress(t.billingAddress),i=r??n??{},a=n??r,o=!!(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:a??{},differentBillingAddress:o},{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),n=this.mapAddress(t.billingAddress),i=r??n??{},a=n??r,o=!!(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:a??{},differentBillingAddress:o},{token:this.sessionToken})}mapAddress(e){if(e)return fe({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??[]).map(r=>this.normalizeShippingRate(r))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}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 g;let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],a=t.customer,o=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=i.map(m=>{let h=m.price,l=m.variant??(h==null?void 0:h.variant)??{},u=m.product??l.product??{},p=(h==null?void 0:h.currencyOptions)??{},f=(o?p[o]:void 0)??p[Object.keys(p)[0]],P=(f==null?void 0:f.amount)??0;return{id:m.id,variantId:m.variantId,priceId:m.priceId,productName:u.name??"",variantName:l.name??"",quantity:m.quantity??1,unitAmount:P,totalAmount:P*(m.quantity??1),currency:o??"USD",imageUrl:l.imageUrl??u.imageUrl??""}}),c=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:o??"USD",items:d,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??c.reduce((m,h)=>m+(h.amount??0),0),currency:o??"USD"},customer:a?{id:a.id,email:a.email,firstName:a.firstName,lastName:a.lastName,phone:a.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(n=>n!==void 0&&n!=="")?r:void 0}},se=C.parseTokensFromUrl;function fe(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function B(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return ie(e)?e:void 0}function z(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return ie(r)?r:void 0}function ie(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var b=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;this.lastPaymentSetup=null}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let r=this.readInjectedStepConfig();if(r)return this.lastPaymentSetup=r,r;let n=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),i={};for(let a of n.methods??[]){let o=a.provider?`${a.method}:${a.provider}`:a.method;i[o]=a}return this.lastPaymentSetup=i,i}async getExpressMethods(e,t){var i,a,o,d,c,g,m,h;let r=await this.getPaymentSetup(e,t),n={};for(let[l,u]of Object.entries(r)){if(!u.enabled)continue;if(l.startsWith("express_checkout:")&&u.methods){let P={available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if((i=u.methods.apple_pay)!=null&&i.enabled){let H=typeof window<"u"&&"ApplePaySession"in window&&((o=(a=window.ApplePaySession)==null?void 0:a.canMakePayments)==null?void 0:o.call(a));n.applePay={...P,type:"apple_pay",available:!!H}}(d=u.methods.google_pay)!=null&&d.enabled&&(n.googlePay={...P,type:"google_pay"}),(c=u.methods.link)!=null&&c.enabled&&(n.link={...P,type:"link"}),(g=u.methods.klarna_express)!=null&&g.enabled&&(n.klarna={...P,type:"klarna_express"});continue}if(!u.express)continue;let p=u.method,f={type:p,available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if(p==="apple_pay"||u.type==="apple_pay"){let P=typeof window<"u"&&"ApplePaySession"in window&&((h=(m=window.ApplePaySession)==null?void 0:m.canMakePayments)==null?void 0:h.call(m));n.applePay={...f,available:!!P}}else p==="google_pay"||u.type==="google_pay"?n.googlePay=f:p==="paypal"?n.paypal=f:p==="klarna"||p==="klarna_express"?n.klarna=f:p==="link"&&(n.link=f)}return n}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(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.getProvider().getProviderName()),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,returnUrl:e.returnUrl})}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,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress:r,billingAddress:n}=t;if(!r&&!n)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:r,billingAddress:n})}async processApplePay(e){var o,d,c,g,m,h,l,u,p;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:B(e.shippingContact),billingAddress:B(e.billingContact),email:((o=e.shippingContact)==null?void 0:o.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((c=e.shippingContact)==null?void 0:c.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((m=e.shippingContact)==null?void 0:m.givenName)??((h=e.billingContact)==null?void 0:h.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((u=e.billingContact)==null?void 0:u.familyName)});let t=e.merchantRegistrationId??((p=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:p.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),a=btoa(JSON.stringify(r.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:a,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let r=i=>{var a;for(let o of Object.values(i??{})){let d=(a=o==null?void 0:o.metadata)==null?void 0:a.applePayByok;if(!d||typeof d!="object")continue;let c=d[t];if(c!=null&&c.merchantRegistrationId)return{merchantRegistrationId:c.merchantRegistrationId,displayName:c.displayName}}return null},n=r(this.readInjectedStepConfig())??r(this.lastPaymentSetup);if(n)return n;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return r(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var a,o,d,c;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:z(e.shippingAddress),billingAddress:z(e.billingAddress),email:e.email??((a=e.shippingAddress)==null?void 0:a.emailAddress)??((o=e.billingAddress)==null?void 0:o.emailAddress),phone:((d=e.shippingAddress)==null?void 0:d.phoneNumber)??((c=e.billingAddress)==null?void 0:c.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,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){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,a;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?{status:"succeeded",payment:r,order:e.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((i=r.requireActionData)==null?void 0:i.message)||((a=r.requireActionData)==null?void 0:a.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),a=r.searchParams.get("paymentId");if(n!=="requireAction"||i!=="completed"||!a)return null;let o=await this.resumeAfterRedirect(a);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>d.delete(g));let c=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(c?"?"+c:""))}catch{}}return o}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let a=await this.getPaymentStatus(e);if(a.status==="succeeded"||a.status==="failed"||a.status==="declined")return a;await new Promise(o=>setTimeout(o,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}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,a;let r=(i=t.metadata)==null?void 0:i.redirect,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,method:((a=r==null?void 0:r.method)==null?void 0:a.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,a;let r=(a=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:a.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let n;try{n=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 o=new n.ThreedsManager({provider:"basis_theory"});return await o.initialize({apiKey:void 0}),await o.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,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),a=0;for(;Date.now()-i<n;){let o;try{o=await this.getPaymentStatus(e),a=0}catch{if(a++,a>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(d=>setTimeout(d,r));continue}if(o.status==="succeeded"||o.status==="pending"&&o.subStatus==="authorized")return{status:"succeeded",payment:o,order:o.order};if(o.status==="failed"||o.status==="declined")return{status:"failed",error:o.status,payment:o};if(o.requireAction&&o.requireAction!=="none"&&o.requireActionData&&!o.requireActionData.processed)return this.handlePaymentAction(o,{});await new Promise(d=>setTimeout(d,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 x=class{constructor(e,t,r){this.http=e;this.storeId=t;this.payment=r}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 a of e.ids)r.push(`ids=${encodeURIComponent(a)}`);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 processOfferPayment(e){if(!this.payment)throw new Error("OffersModule: no PaymentModule injected. Use createHeadlessClient() instead of constructing OffersModule directly.");let t=e.returnUrl??(typeof window<"u"?window.location.href:void 0),r=await this.payPreviewedOffer({...e,returnUrl:t});return this.payment.finalize({payment:r.payment,order:r.order},{returnUrl:t})}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 T=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,t){var d,c;let r=async()=>(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order,n=await r();if(!(t!=null&&t.waitForRelatedOrders)||(d=n.relatedOrders)!=null&&d.length)return n;let i=t.timeoutMs??8e3,a=t.intervalMs??2e3,o=Date.now()+i;for(;Date.now()<o;)if(await new Promise(g=>setTimeout(g,Math.min(a,Math.max(0,o-Date.now())))),n=await r(),(c=n.relatedOrders)!=null&&c.length)return n;return n}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 N=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.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 L=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n}async navigate(e){var o;let t=this.checkout.getCurrentSession();if(!t)throw new y("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new y("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(o=globalThis.location)==null?void 0:o.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var a,o,d;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((a=r.customer)==null?void 0:a.locale)??Pe(),userAgent:Ie(),queryCurrency:((o=r.customer)==null?void 0:o.currency)??e.currency,queryLocale:(d=r.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var m,h,l,u;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:a}=e,o=n.items.map(p=>({variantId:p.variantId,priceId:p.priceId,quantity:p.quantity})),d=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),c={email:((m=i.customer)==null?void 0:m.email)??((h=n.customer)==null?void 0:h.email),currency:((l=i.customer)==null?void 0:l.currency)??n.currency,locale:(u=i.customer)==null?void 0:u.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:a,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:o,customer:c,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function Pe(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ie(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var O=class{constructor(e){this.http=e}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async getQuestionsForProduct(e){return this.http.get("/api/public/v1/rx/questions-for-product",{params:{productId:e}})}};var U=class{constructor(e){let t=e.environment??"production",r=w.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new w({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=i=>{this._sessionToken=i};this.checkout=new C(this.http,this.config.storeId,n),this.payment=new b(this.http,this.config.storeId,t,this.checkout),this.offers=new x(this.http,this.config.storeId,this.payment),this.customer=new T(this.http,this.config.storeId),this.catalog=new N(this.http,this.config.storeId),this.funnel=new L(this.http,this.config.storeId,this.checkout,this.config.accountId),this.rx=new O(this.http)}setSessionToken(e){this._sessionToken=e}};function oe(s){return new U(s)}var ae=!1,de=!1,J=[];function V(){de=!0;for(let s of J)s();J.length=0}function Q(s,e={}){var t,r;return de||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(V(),Promise.resolve()):ae?new Promise(n=>J.push(n)):(ae=!0,new Promise((n,i)=>{if(J.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var g,m;(m=(g=window.google)==null?void 0:g.maps)!=null&&m.places?V():setTimeout(c,100)};c();return}let o=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&o.set("language",e.language),e.region&&o.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${o}`,d.async=!0,d.defer=!0,d.onload=()=>V(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var E=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(a=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(o,d)=>{var c,g,m;a(d===((m=(g=(c=window.google)==null?void 0:c.maps)==null?void 0:g.places)==null?void 0:m.PlacesServiceStatus.OK)&&o?o:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.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"]},(a,o)=>{var d,c,g;i(o===((g=(c=(d=window.google)==null?void 0:d.maps)==null?void 0:c.places)==null?void 0:g.PlacesServiceStatus.OK)&&a?a:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",a="",o="",d="",c="",g="";for(let l of e.address_components??[]){let u=l.types;u.includes("subpremise")&&(t.subpremise=l.long_name),u.includes("street_number")&&(t.streetNumber=l.long_name),u.includes("premise")&&(r=l.long_name),u.includes("route")&&(t.route=l.long_name),u.includes("neighborhood")&&(n=l.long_name),u.includes("sublocality_level_5")&&(i=l.long_name),u.includes("sublocality_level_4")&&(a=l.long_name),u.includes("sublocality_level_3")&&(o=l.long_name),u.includes("sublocality_level_2")&&(d=l.long_name),u.includes("sublocality_level_1")&&(c=l.long_name),u.includes("locality")&&(t.locality=l.long_name),u.includes("postal_town")&&(g=l.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),u.includes("country")&&(t.country=l.short_name),u.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=g||d||c||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let m=t.streetNumber||r,h=t.route||i||a||o||n;if(t.subpremise&&m&&h)t.fullStreetAddress=`${t.subpremise}/${m} ${h}`;else if(m&&h)if(r&&a&&o){let l=`${o}-${a}-${r}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${m} ${h}`;else h?t.fullStreetAddress=h:m&&(t.fullStreetAddress=m);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var ue="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",M=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],D=new Map,W=new Map,Y=new Map,Z=new Map;async function we(s){let e=D.get(s);if(e)return e;let t=Y.get(s);return t||(t=(async()=>{let r=`${ue}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return D.set(s,i),Y.delete(s),i})(),Y.set(s,t),t)}async function Ce(s){let e=W.get(s);if(e)return e;let t=Z.get(s);return t||(t=(async()=>{let r=`${ue}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return W.set(s,i),Z.delete(s),i})(),Z.set(s,t),t)}function ke(s){return D.get(s)||D.get("en")||{}}function Se(s){return W.get(s)||W.get("en")||{}}async function $(s="en"){await Promise.all([we(s),Ce(s)])}var _=(s="en")=>{let e=ke(s);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))},F=(s,e="en")=>{let r=Se(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function q(s){return D.has(s)}var G=class s{static ensureLoaded(e="en"){return $(e)}static getCountries(e="en"){let t=_(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return _(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return F(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);if(i.length===0)return null;let a=i.find(o=>o.iso===e);return a||(a=i.find(o=>o.name.toLowerCase()===e.toLowerCase()),a)||(a=i.find(o=>o.name.toLowerCase()===t.toLowerCase()),a)?a:(a=i.find(o=>o.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(o.name.toLowerCase())),a??null)}static isLanguageLoaded(e){return q(e)}static getAvailableLanguages(){return M}};var ve={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"},Ae={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"},Re=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),k=class s{static getSymbol(e){return ve[e]??e}static getName(e){return Ae[e]??e}static getDecimalPlaces(e){return Re.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function X(s,e="USD",t="en-US"){let r=k.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${k.getSymbol(e)}${n.toFixed(r)}`}}return ye(be);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
8
8
  //# sourceMappingURL=tagada-headless.min.js.map