@tagadapay/headless-sdk 1.13.0 → 1.14.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.13.0
2
+ * @tagadapay/headless-sdk v1.14.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
@@ -291,7 +291,7 @@ var TagadaHeadlessBundle = (() => {
291
291
  * Also returns a `checkoutUrl` (the full Tagada-hosted checkout URL, for reference).
292
292
  */
293
293
  async createSession(opts) {
294
- var _a;
294
+ var _a, _b, _c;
295
295
  const lineItems = opts.items.map((i) => ({
296
296
  variantId: i.variantId,
297
297
  priceId: i.priceId,
@@ -303,6 +303,15 @@ var TagadaHeadlessBundle = (() => {
303
303
  };
304
304
  if (opts.returnUrl)
305
305
  body.returnUrl = opts.returnUrl;
306
+ if ((_a = opts.discountCodes) == null ? void 0 : _a.length)
307
+ body.discountCodes = opts.discountCodes;
308
+ if (opts.metadata && Object.keys(opts.metadata).length > 0)
309
+ body.metadata = opts.metadata;
310
+ if (opts.customerMetadata && Object.keys(opts.customerMetadata).length > 0) {
311
+ body.customerMetadata = opts.customerMetadata;
312
+ }
313
+ if ((_b = opts.customerTags) == null ? void 0 : _b.length)
314
+ body.customerTags = opts.customerTags;
306
315
  const customerData = {};
307
316
  if (opts.currency)
308
317
  customerData.currency = opts.currency;
@@ -319,7 +328,7 @@ var TagadaHeadlessBundle = (() => {
319
328
  const sessionToken = url.searchParams.get("token") ?? "";
320
329
  this.sessionToken = sessionToken;
321
330
  if (sessionToken)
322
- (_a = this.onTokenChange) == null ? void 0 : _a.call(this, sessionToken);
331
+ (_c = this.onTokenChange) == null ? void 0 : _c.call(this, sessionToken);
323
332
  return {
324
333
  checkoutUrl: res.checkoutUrl,
325
334
  checkoutToken: res.checkoutToken,
@@ -653,7 +662,11 @@ var TagadaHeadlessBundle = (() => {
653
662
  discount: summary.totalPromotionAmount ?? 0,
654
663
  shipping: summary.shippingCost ?? 0,
655
664
  tax: summary.totalTaxAmount ?? 0,
656
- total: summary.totalAmount ?? summaryItems.reduce((s, i) => s + (i.amount ?? 0), 0),
665
+ // `totalAdjustedAmount` is what gets charged (subtotal − discounts + shipping + tax).
666
+ // The raw adjuster summary also carries `totalAmount` = subtotal + shipping only —
667
+ // reading that first showed a pre-discount, pre-tax total (#TAG-2246). The legacy
668
+ // `orderSummaries[0]` shape only has `totalAmount`, already aliased to the adjusted total.
669
+ total: summary.totalAdjustedAmount ?? summary.totalAmount ?? summaryItems.reduce((s, i) => s + (i.amount ?? 0), 0),
657
670
  currency: sessionCurrency ?? "USD"
658
671
  },
659
672
  customer: customer ? {
@@ -746,6 +759,28 @@ var TagadaHeadlessBundle = (() => {
746
759
  }
747
760
 
748
761
  // src/core/modules/payment.ts
762
+ var EXPRESS_METHOD_TYPES = /* @__PURE__ */ new Set(["apple_pay", "google_pay", "paypal", "klarna", "klarna_express", "link"]);
763
+ function paymentMethodListEntryToConfig(entry) {
764
+ var _a;
765
+ const isCard = entry.type === "credit-card";
766
+ const method = isCard ? "card" : entry.type;
767
+ const settings = entry.settings ?? {};
768
+ const processors = settings.processors;
769
+ const publishableKey = settings.publishableKey;
770
+ return {
771
+ enabled: true,
772
+ method,
773
+ provider: isCard ? void 0 : entry.type,
774
+ type: isCard ? "card" : entry.type,
775
+ label: entry.title,
776
+ logoUrl: entry.iconUrl,
777
+ express: EXPRESS_METHOD_TYPES.has(method),
778
+ integrationId: isCard ? void 0 : entry.id,
779
+ processorId: (_a = processors == null ? void 0 : processors[0]) == null ? void 0 : _a.processorId,
780
+ publishableKey: typeof publishableKey === "string" ? publishableKey : void 0,
781
+ metadata: entry.metadata ?? void 0
782
+ };
783
+ }
749
784
  var PaymentModule = class {
750
785
  constructor(http, storeId, environment, checkout) {
751
786
  this.http = http;
@@ -782,16 +817,36 @@ var TagadaHeadlessBundle = (() => {
782
817
  this.lastPaymentSetup = injected;
783
818
  return injected;
784
819
  }
785
- const methods = await this.http.get(
786
- "/api/v1/payment-methods",
787
- { params: { checkoutSessionId } }
788
- );
820
+ try {
821
+ const res = await this.http.get(
822
+ `/api/v1/checkout-sessions/${checkoutSessionId}/payment-setup`
823
+ );
824
+ const config2 = { ...(res == null ? void 0 : res.config) ?? {} };
825
+ this.lastPaymentSetup = config2;
826
+ return config2;
827
+ } catch (err) {
828
+ if (!(err instanceof TagadaNotFoundError))
829
+ throw err;
830
+ }
831
+ const config = await this.getPaymentSetupFromPickerList(checkoutSessionId);
832
+ this.lastPaymentSetup = config;
833
+ return config;
834
+ }
835
+ /**
836
+ * Transitional fallback: `/api/v1/payment-methods` answers with a flat
837
+ * array of `{ id, type, title, iconUrl, default, settings, metadata }`
838
+ * picker rows (`type` = 'credit-card' or the integration provider). Map
839
+ * them to the setup-config shape. Only used when the backend does not
840
+ * serve `/checkout-sessions/:id/payment-setup` yet.
841
+ */
842
+ async getPaymentSetupFromPickerList(checkoutSessionId) {
843
+ const res = await this.http.get("/api/v1/payment-methods", { params: { checkoutSessionId } });
844
+ const entries = Array.isArray(res) ? res.map(paymentMethodListEntryToConfig) : (res == null ? void 0 : res.methods) ?? [];
789
845
  const config = {};
790
- for (const m of methods.methods ?? []) {
791
- const key = m.provider ? `${m.method}:${m.provider}` : m.method;
846
+ for (const m of entries) {
847
+ const key = m.provider && m.provider !== m.method ? `${m.method}:${m.provider}` : m.method;
792
848
  config[key] = m;
793
849
  }
794
- this.lastPaymentSetup = config;
795
850
  return config;
796
851
  }
797
852
  /**
@@ -2015,9 +2070,9 @@ var TagadaHeadlessBundle = (() => {
2015
2070
  * Fetch the network-authored intake questions for a product.
2016
2071
  * Empty `questions` means the storefront should use its local quiz.
2017
2072
  */
2018
- async getQuestionsForProduct(productId) {
2073
+ async getQuestionsForProduct(productId, variantId) {
2019
2074
  return this.http.get("/api/public/v1/rx/questions-for-product", {
2020
- params: { productId }
2075
+ params: variantId ? { productId, variantId } : { productId }
2021
2076
  });
2022
2077
  }
2023
2078
  };
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.13.0
2
+ * @tagadapay/headless-sdk v1.14.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
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);})();
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=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var he=(i,e)=>{for(var t in e)j(i,t,{get:e[t],enumerable:!0})},te=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of me(e))!ge.call(i,r)&&r!==t&&j(i,r,{get:()=>e[r],enumerable:!(n=le(e,r))||n.enumerable});return i};var ne=(i,e,t)=>(t=i!=null?ce(pe(i)):{},te(e||!i||!i.__esModule?j(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>te(j({},"__esModule",{value:!0}),i);var xe={};he(xe,{AVAILABLE_LANGUAGES:()=>D,CatalogModule:()=>N,CheckoutModule:()=>k,CurrencyUtils:()=>S,CustomerModule:()=>x,FunnelModule:()=>L,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>U,HttpClient:()=>C,ISODataCore:()=>G,OffersModule:()=>T,PaymentModule:()=>R,RxModule:()=>O,TagadaAuthError:()=>v,TagadaError:()=>y,TagadaNetworkError:()=>w,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>b,TagadaValidationError:()=>A,createHeadlessClient:()=>ae,ensureGeoDataLoaded:()=>$,formatMoney:()=>X,getCountries:()=>_,getStatesForCountry:()=>F,isLanguageLoaded:()=>q,loadGoogleMapsScript:()=>Y,parseTokensFromUrl:()=>se});var y=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},v=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},A=class extends y{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},I=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},b=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}},w=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var re={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},C=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??re[e]??re.production}async request(e,t={}){var u;let{method:n="GET",body:r,headers:s={},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",...s},l=o??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));l&&(g["x-cms-token"]=l);let h=new AbortController,m=setTimeout(()=>h.abort(),this.timeout);try{let p=await fetch(c,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??h.signal});if(clearTimeout(m),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(m),p instanceof y?p:p instanceof DOMException&&p.name==="AbortError"?new w(`Request to ${e} timed out after ${this.timeout}ms.`):new w(p instanceof Error?p.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let r=n.data??{},s=n.message??n.error??(typeof r.message=="string"?r.message:void 0)??(typeof n.data=="string"?n.data:void 0)??`Request failed: ${e.status} ${e.statusText} on ${t}`,a=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new v(s);case 404:throw new I(t,"");case 422:{let o=Array.isArray(n.errors)?n.errors:[];throw new A(s,o,a,n)}case 429:{let o=Number(e.headers.get("Retry-After")??"1")*1e3;throw new b(o)}default:throw new y(s,"api_error",e.status,n)}}};var k=class i{constructor(e,t,n){this.http=e;this.storeId=t;this.onTokenChange=n}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var o;t&&(this.sessionToken=t,(o=this.onTokenChange)==null||o.call(this,t));let r={skipAsyncWait:"false"};n!=null&&n.currency&&(r.currency=n.currency);let s=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),a=this.normalizeSession(s);return this._currentSession=a,a}async createSession(e){var d,c,g;let t=e.items.map(l=>({variantId:l.variantId,priceId:l.priceId,quantity:l.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),(d=e.discountCodes)!=null&&d.length&&(n.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(n.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(n.customerMetadata=e.customerMetadata),(c=e.customerTags)!=null&&c.length&&(n.customerTags=e.customerTags);let r={};e.currency&&(r.currency=e.currency),e.customerEmail&&(r.email=e.customerEmail,r.firstName=e.customerFirstName,r.lastName=e.customerLastName),Object.keys(r).length>0&&(n.customer=r);let s=await this.http.post("/api/v1/checkout/session/init",n),o=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((g=this.onTokenChange)==null||g.call(this,o)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:o,customerId:s.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}),n=e.origin??(typeof window<"u"?window.location.origin:""),r=e.checkoutPath??"/checkout",s=new URLSearchParams({checkoutToken:t.checkoutToken,sessionToken:t.sessionToken}),a=`${n}${r}?${s.toString()}`;return{...t,url:a}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("checkoutToken");if(!r)return null;let s=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:s}}parseTokensFromUrl(e){return i.parseTokensFromUrl(e)}async updateCart(e,t){let n=t.map(r=>({variantId:r.variantId,priceId:r.priceId,quantity:r.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:n},{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 n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),s=n??r??{},a=r??n,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:s,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 n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),s=n??r??{},a=r??n,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:s,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 n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}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,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},s=t.sessionLineItems??[],a=t.customer,o=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(l=>{let h=l.price,m=l.variant??(h==null?void 0:h.variant)??{},u=l.product??m.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:l.id,variantId:l.variantId,priceId:l.priceId,productName:u.name??"",variantName:m.name??"",quantity:l.quantity??1,unitAmount:P,totalAmount:P*(l.quantity??1),currency:o??"USD",imageUrl:m.imageUrl??u.imageUrl??""}}),c=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:o??"USD",items:d,totals:{subtotal:r.subtotalAmount??0,discount:r.totalPromotionAmount??0,shipping:r.shippingCost??0,tax:r.totalTaxAmount??0,total:r.totalAdjustedAmount??r.totalAmount??c.reduce((l,h)=>l+(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,n={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(n).some(r=>r!==void 0&&r!=="")?n:void 0}},se=k.parseTokensFromUrl;function fe(i){let e={};for(let[t,n]of Object.entries(i))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function B(i){var t,n;if(!i)return;let e={firstName:i.givenName,lastName:i.familyName,line1:(t=i.addressLines)==null?void 0:t[0],line2:(n=i.addressLines)==null?void 0:n[1],city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode,phone:i.phoneNumber};return ie(e)?e:void 0}function z(i){if(!i)return;let[e,...t]=(i.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:i.address1,line2:[i.address2,i.address3].filter(Boolean).join(" ")||void 0,city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode,phone:i.phoneNumber};return ie(n)?n:void 0}function ie(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var Pe=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Ie(i){var a;let e=i.type==="credit-card",t=e?"card":i.type,n=i.settings??{},r=n.processors,s=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:i.type,type:e?"card":i.type,label:i.title,logoUrl:i.iconUrl,express:Pe.has(t),integrationId:e?void 0:i.id,processorId:(a=r==null?void 0:r[0])==null?void 0:a.processorId,publishableKey:typeof s=="string"?s:void 0,metadata:i.metadata??void 0}}var R=class{constructor(e,t,n,r){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.lastPaymentSetup=null}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let n=this.readInjectedStepConfig();if(n)return this.lastPaymentSetup=n,n;try{let s=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),a={...(s==null?void 0:s.config)??{}};return this.lastPaymentSetup=a,a}catch(s){if(!(s instanceof I))throw s}let r=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=r,r}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n=Array.isArray(t)?t.map(Ie):(t==null?void 0:t.methods)??[],r={};for(let s of n){let a=s.provider&&s.provider!==s.method?`${s.method}:${s.provider}`:s.method;r[a]=s}return r}async getExpressMethods(e,t){var s,a,o,d,c,g,l,h;let n=await this.getPaymentSetup(e,t),r={};for(let[m,u]of Object.entries(n)){if(!u.enabled)continue;if(m.startsWith("express_checkout:")&&u.methods){let P={available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if((s=u.methods.apple_pay)!=null&&s.enabled){let H=typeof window<"u"&&"ApplePaySession"in window&&((o=(a=window.ApplePaySession)==null?void 0:a.canMakePayments)==null?void 0:o.call(a));r.applePay={...P,type:"apple_pay",available:!!H}}(d=u.methods.google_pay)!=null&&d.enabled&&(r.googlePay={...P,type:"google_pay"}),(c=u.methods.link)!=null&&c.enabled&&(r.link={...P,type:"link"}),(g=u.methods.klarna_express)!=null&&g.enabled&&(r.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=(l=window.ApplePaySession)==null?void 0:l.canMakePayments)==null?void 0:h.call(l));r.applePay={...f,available:!!P}}else p==="google_pay"||u.type==="google_pay"?r.googlePay=f:p==="paypal"?r.paypal=f:p==="klarna"||p==="klarna_express"?r.klarna=f:p==="link"&&(r.link=f)}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,t){let n=await this.getPaymentSetup(e,t);return Object.entries(n).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(r.cardholderName=e.cardholderName);let s=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(s,n.getProvider().getProviderName()),rawToken:s}}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:n,billingAddress:r}=t;if(!n&&!r)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 s={};t.email&&(s.email=t.email),t.phone&&(s.phone=t.phone),t.firstName&&(s.firstName=t.firstName),t.lastName&&(s.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:s,shippingAddress:n,billingAddress:r})}async processApplePay(e){var o,d,c,g,l,h,m,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:((l=e.shippingContact)==null?void 0:l.givenName)??((h=e.billingContact)==null?void 0:h.givenName),lastName:((m=e.shippingContact)==null?void 0:m.familyName)??((u=e.billingContact)==null?void 0:u.familyName)});let t=e.merchantRegistrationId??((p=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:p.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let s=await r.tokenizeApplePay(e.applePayToken,t),a=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(s,"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 n=s=>{var a;for(let o of Object.values(s??{})){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},r=n(this.readInjectedStepConfig())??n(this.lastPaymentSetup);if(r)return r;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return n(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(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),s=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));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){!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 s,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return n.status==="succeeded"?{status:"succeeded",payment:n,order:e.order}:n.status==="failed"||n.status==="declined"?{status:"failed",error:((s=n.requireActionData)==null?void 0:s.message)||((a=n.requireActionData)==null?void 0:a.errorCode)||`Payment ${n.status}`,payment:n}:n.requireAction&&n.requireAction!=="none"&&n.requireActionData?this.handlePaymentAction(n,{returnUrl:r}):this.pollUntilDone(n.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,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("paymentAction"),s=n.searchParams.get("paymentActionStatus"),a=n.searchParams.get("paymentId");if(r!=="requireAction"||s!=="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 n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,s=Date.now();for(;Date.now()-s<r;){let a=await this.getPaymentStatus(e);if(a.status==="succeeded"||a.status==="failed"||a.status==="declined")return a;await new Promise(o=>setTimeout(o,n))}throw new Error(`Payment ${e} did not reach terminal status within ${r}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 n=e.requireActionData;switch(await this.markActionProcessed(e.id),n.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,n);case"redirect":return this.extractRedirect(e,n);case"error":return{status:"failed",error:n.message||n.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,n)}}extractRedirect(e,t){var s,a;let n=(s=t.metadata)==null?void 0:s.redirect,r=(n==null?void 0:n.redirectUrl)||t.redirectUrl;return r?{status:"requires_redirect",redirectUrl:r,method:((a=n==null?void 0:n.method)==null?void 0:a.toUpperCase())||"GET",postData:n==null?void 0:n.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 s,a;let n=(a=(s=e.requireActionData)==null?void 0:s.metadata)==null?void 0:a.threedsSession;if(!(n!=null&&n.externalSessionId))return this.extractRedirect(e,e.requireActionData);let r;try{r=await import("@tagadapay/core-js")}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let o=new r.ThreedsManager({provider:"basis_theory"});return await o.initialize({apiKey:void 0}),await o.startChallenge({sessionId:n.externalSessionId,acsChallengeUrl:n.acsChallengeUrl,acsTransactionId:n.acsTransID,threeDSVersion:n.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,s=Date.now(),a=0;for(;Date.now()-s<r;){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,n));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,n))}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 T=class{constructor(e,t,n){this.http=e;this.storeId=t;this.payment=n}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var s;let t=`/api/v1/stores/${this.storeId}/offers`,n=[];if(e!=null&&e.type&&n.push(`type=${encodeURIComponent(e.type)}`),(s=e==null?void 0:e.ids)!=null&&s.length)for(let a of e.ids)n.push(`ids=${encodeURIComponent(a)}`);return n.length&&(t+=`?${n.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),n=await this.payPreviewedOffer({...e,returnUrl:t});return this.payment.finalize({payment:n.payment,order:n.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 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,t){var d,c;let n=async()=>(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order,r=await n();if(!(t!=null&&t.waitForRelatedOrders)||(d=r.relatedOrders)!=null&&d.length)return r;let s=t.timeoutMs??8e3,a=t.intervalMs??2e3,o=Date.now()+s;for(;Date.now()<o;)if(await new Promise(g=>setTimeout(g,Math.min(a,Math.max(0,o-Date.now())))),r=await n(),(c=r.relatedOrders)!=null&&c.length)return r;return r}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 r,s;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(s=e==null?void 0:e.variantIds)!=null&&s.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,n,r){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r}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 n=e.accountId??this.accountId;if(!n)throw new y("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let r=e.currentUrl??(typeof globalThis<"u"?(o=globalThis.location)==null?void 0:o.href:void 0);await this.ensureCmsSession(t,n,e);let s=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});return{url:await this.runNavigate({funnelSessionId:s,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:s}}async ensureCmsSession(e,t,n){var a,o,d;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let r=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=r.token,this._cmsSessionId=r.sessionId;let s=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((a=n.customer)==null?void 0:a.locale)??we(),userAgent:Ce(),queryCurrency:((o=n.customer)==null?void 0:o.currency)??e.currency,queryLocale:(d=n.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=s.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 l,h,m,u;let{funnelSessionId:t,stepId:n,session:r,input:s,currentUrl:a}=e,o=r.items.map(p=>({variantId:p.variantId,priceId:p.priceId,quantity:p.quantity})),d=s.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),c={email:((l=s.customer)==null?void 0:l.email)??((h=r.customer)==null?void 0:h.email),currency:((m=s.customer)==null?void 0:m.currency)??r.currency,locale:(u=s.customer)==null?void 0:u.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:a,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:o,customer:c,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function we(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ce(){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,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var U=class{constructor(e){let t=e.environment??"production",n=C.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new C({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let r=s=>{this._sessionToken=s};this.checkout=new k(this.http,this.config.storeId,r),this.payment=new R(this.http,this.config.storeId,t,this.checkout),this.offers=new T(this.http,this.config.storeId,this.payment),this.customer=new x(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 ae(i){return new U(i)}var oe=!1,de=!1,J=[];function V(){de=!0;for(let i of J)i();J.length=0}function Y(i,e={}){var t,n;return de||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(V(),Promise.resolve()):oe?new Promise(r=>J.push(r)):(oe=!0,new Promise((r,s)=>{if(J.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var g,l;(l=(g=window.google)==null?void 0:g.maps)!=null&&l.places?V():setTimeout(c,100)};c();return}let o=new URLSearchParams({key:i,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=()=>s(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var E=class i{static async searchPlaces(e,t={}){var r,s;if(!((s=(r=window.google)==null?void 0:r.maps)!=null&&s.places)||!e.trim())return[];let n=new window.google.maps.places.AutocompleteService;return new Promise(a=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(o,d)=>{var c,g,l;a(d===((l=(g=(c=window.google)==null?void 0:c.maps)==null?void 0:g.places)==null?void 0:l.PlacesServiceStatus.OK)&&o?o:[])})})}static async getPlaceDetails(e){var n,r;if(!((r=(n=window.google)==null?void 0:n.maps)!=null&&r.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(s=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(a,o)=>{var d,c,g;s(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:""},n="",r="",s="",a="",o="",d="",c="",g="";for(let m of e.address_components??[]){let u=m.types;u.includes("subpremise")&&(t.subpremise=m.long_name),u.includes("street_number")&&(t.streetNumber=m.long_name),u.includes("premise")&&(n=m.long_name),u.includes("route")&&(t.route=m.long_name),u.includes("neighborhood")&&(r=m.long_name),u.includes("sublocality_level_5")&&(s=m.long_name),u.includes("sublocality_level_4")&&(a=m.long_name),u.includes("sublocality_level_3")&&(o=m.long_name),u.includes("sublocality_level_2")&&(d=m.long_name),u.includes("sublocality_level_1")&&(c=m.long_name),u.includes("locality")&&(t.locality=m.long_name),u.includes("postal_town")&&(g=m.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=m.short_name,t.administrativeAreaLevel2Long=m.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=m.short_name,t.administrativeAreaLevel1Long=m.long_name),u.includes("country")&&(t.country=m.short_name),u.includes("postal_code")&&(t.postalCode=m.long_name)}t.locality||(t.locality=g||d||c||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let l=t.streetNumber||n,h=t.route||s||a||o||r;if(t.subpremise&&l&&h)t.fullStreetAddress=`${t.subpremise}/${l} ${h}`;else if(l&&h)if(n&&a&&o){let m=`${o}-${a}-${n}`;d&&(m=`${m} ${d}`),t.fullStreetAddress=m}else t.fullStreetAddress=`${l} ${h}`;else h?t.fullStreetAddress=h:l&&(t.fullStreetAddress=l);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=i.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",D=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],M=new Map,W=new Map,Q=new Map,Z=new Map;async function ke(i){let e=M.get(i);if(e)return e;let t=Q.get(i);return t||(t=(async()=>{let n=`${ue}/${i}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let s=await r.json();return M.set(i,s),Q.delete(i),s})(),Q.set(i,t),t)}async function Se(i){let e=W.get(i);if(e)return e;let t=Z.get(i);return t||(t=(async()=>{let n=`${ue}/${i}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let s=await r.json();return W.set(i,s),Z.delete(i),s})(),Z.set(i,t),t)}function ve(i){return M.get(i)||M.get("en")||{}}function Ae(i){return W.get(i)||W.get("en")||{}}async function $(i="en"){await Promise.all([ke(i),Se(i)])}var _=(i="en")=>{let e=ve(i);return Object.entries(e).map(([t,n])=>({code:t,name:n.n,iso3:n.i3,numeric:n.nu})).sort((t,n)=>t.name.localeCompare(n.name))},F=(i,e="en")=>{let n=Ae(e)[i];return n?n.map(([r,s])=>({code:r,name:s,countryCode:i})).sort((r,s)=>r.name.localeCompare(s.name)):[]};function q(i){return M.has(i)}var G=class i{static ensureLoaded(e="en"){return $(e)}static getCountries(e="en"){let t=_(e),n={};for(let r of t)n[r.code]={iso:r.code,iso3:r.iso3??"",numeric:r.numeric??0,name:r.name};return n}static getCountryOptions(e="en"){return _(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return F(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return i.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return i.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let s=i.getRegions(n,r);if(s.length===0)return null;let a=s.find(o=>o.iso===e);return a||(a=s.find(o=>o.name.toLowerCase()===e.toLowerCase()),a)||(a=s.find(o=>o.name.toLowerCase()===t.toLowerCase()),a)?a:(a=s.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 D}};var be={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"},Re={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"},Te=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),S=class i{static getSymbol(e){return be[e]??e}static getName(e){return Re[e]??e}static getDecimalPlaces(e){return Te.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function X(i,e="USD",t="en-US"){let n=S.getDecimalPlaces(e),r=i/(n===0?100:Math.pow(10,n));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(r)}catch{return`${S.getSymbol(e)}${r.toFixed(n)}`}}return ye(xe);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
8
8
  //# sourceMappingURL=tagada-headless.min.js.map