@tagadapay/headless-sdk 1.17.0 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/core/modules/customer.d.ts +26 -4
- package/dist/core/modules/customer.d.ts.map +1 -1
- package/dist/core/modules/customer.js +50 -16
- package/dist/core/modules/customer.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/provider.d.ts +13 -2
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +35 -7
- package/dist/react/provider.js.map +1 -1
- package/dist/tagada-headless-commerce.min.js +2 -2
- package/dist/tagada-headless-commerce.min.js.map +4 -4
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +3 -3
- package/dist/tagada-headless.js +4 -4
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +1 -1
- package/dist/tagada-pixels.min.js +1 -1
- package/package.json +4 -1
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.18.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -787,10 +787,10 @@ var TagadaHeadlessBundle = (() => {
|
|
|
787
787
|
|
|
788
788
|
// src/core/version.ts
|
|
789
789
|
var SDK_NAME = "headless";
|
|
790
|
-
var SDK_VERSION = "1.
|
|
790
|
+
var SDK_VERSION = "1.18.0";
|
|
791
791
|
|
|
792
792
|
// src/core/modules/track.ts
|
|
793
|
-
var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.
|
|
793
|
+
var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-pixels.min.js";
|
|
794
794
|
function loadScript(src, isReady) {
|
|
795
795
|
if (isReady())
|
|
796
796
|
return Promise.resolve();
|
|
@@ -2061,7 +2061,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
2061
2061
|
|
|
2062
2062
|
// src/core/modules/lazyCommerce.ts
|
|
2063
2063
|
var script = typeof document === "undefined" ? null : document.currentScript;
|
|
2064
|
-
var url = (script == null ? void 0 : script.src) ? new URL("tagada-headless-commerce.min.js", script.src).href : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.
|
|
2064
|
+
var url = (script == null ? void 0 : script.src) ? new URL("tagada-headless-commerce.min.js", script.src).href : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-headless-commerce.min.js";
|
|
2065
2065
|
var loading;
|
|
2066
2066
|
function loadCommerce() {
|
|
2067
2067
|
if (window.TagadaHeadlessCommerce)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.18.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessBundle=(()=>{var xe=Object.create;var Y=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var re=(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 Le=(i,e)=>{for(var t in e)Y(i,t,{get:e[t],enumerable:!0})},me=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _e(e))!Ee.call(i,r)&&r!==t&&Y(i,r,{get:()=>e[r],enumerable:!(n=Te(e,r))||n.enumerable});return i};var se=(i,e,t)=>(t=i!=null?xe(Ne(i)):{},me(e||!i||!i.__esModule?Y(t,"default",{value:i,enumerable:!0}):t,i)),De=i=>me(Y({},"__esModule",{value:!0}),i);var nt={};Le(nt,{AVAILABLE_LANGUAGES:()=>G,CatalogModule:()=>U,CheckoutModule:()=>I,CurrencyUtils:()=>x,CustomerModule:()=>A,CustomerPortalModule:()=>R,ExperimentsModule:()=>q,FunnelModule:()=>O,GoogleAutocompleteCore:()=>K,HeadlessClient:()=>H,HttpClient:()=>S,ISODataCore:()=>J,OffersModule:()=>b,PaymentModule:()=>D,RxModule:()=>F,TagadaAuthError:()=>_,TagadaError:()=>y,TagadaNetworkError:()=>k,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>W,TagadaRateLimitError:()=>E,TagadaValidationError:()=>N,TrackModule:()=>L,createHeadlessClient:()=>Se,ensureGeoDataLoaded:()=>B,formatMoney:()=>pe,getCountries:()=>$,getStatesForCountry:()=>z,isLanguageLoaded:()=>V,loadGoogleMapsScript:()=>ue,parseTokensFromUrl:()=>he});var y=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},_=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},N=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}},w=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},E=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},W=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}},k=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ge={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},S=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??ge[e]??ge.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:s={},params:o,token:a,signal:d}=t,c=`${this.baseUrl}${e}`;if(o){let h=new URLSearchParams;for(let[P,v]of Object.entries(o))v!==void 0&&h.set(P,String(v));let f=h.toString();f&&(c+=`?${f}`)}let g={"Content-Type":"application/json",...s},u=a??this.apiKey??((m=this.getToken)==null?void 0:m.call(this));u&&(g["x-cms-token"]=u);let p=new AbortController,l=setTimeout(()=>p.abort(),this.timeout);try{let h=await fetch(c,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(l),h.ok){let f=await h.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(h,e),new y("Unexpected error","unknown",h.status)}catch(h){throw clearTimeout(l),h instanceof y?h:h instanceof DOMException&&h.name==="AbortError"?new k(`Request to ${e} timed out after ${this.timeout}ms.`):new k(h instanceof Error?h.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=Me(n.data),s=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new _(s);case 404:throw new w(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new N(s,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new E(a)}default:throw new y(s,"api_error",e.status,n)}}};function Me(i){if(i&&typeof i=="object")return i;if(typeof i!="string")return{};try{let e=JSON.parse(i);return e&&typeof e=="object"?e:{}}catch{return{}}}var I=class i{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,d;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.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}),o=this.normalizeSession(s);this._currentSession=o;try{(d=this.onSession)==null||d.call(this,o)}catch{}return o}async createSession(e){var d,c,g;let t=e.items.map(u=>({variantId:u.variantId,priceId:u.priceId,...u.sellingPlanId!==void 0?{sellingPlanId:u.sellingPlanId}:{},...u.trialDays!==void 0?{trialDays:u.trialDays}:{},...u.trialPrice!==void 0?{trialPrice:u.trialPrice}:{},quantity:u.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(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),a=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:a,customerId:s.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,s=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:s.checkoutToken,sessionToken:s.sessionToken}),d=`${o}${t}?${a.toString()}`;return{...s,url:d}}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,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},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??{},o=r??n,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:s,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 n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),s=n??r??{},o=r??n,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:s,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Ue({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??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(u=>{let p=u.price,l=u.variant??(p==null?void 0:p.variant)??{},m=u.product??l.product??{},h=(p==null?void 0:p.currencyOptions)??{},f=(a?h[a]:void 0)??h[Object.keys(h)[0]],P=(f==null?void 0:f.amount)??0;return{id:u.id,variantId:u.variantId,priceId:u.priceId,productName:m.name??"",variantName:l.name??"",quantity:u.quantity??1,unitAmount:P,totalAmount:P*(u.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),c=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"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((u,p)=>u+(p.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,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}},he=I.parseTokensFromUrl;function Ue(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 Q(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 fe(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 fe(n)?n:void 0}function fe(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var ie="headless",oe="1.17.0";var ye="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-pixels.min.js";function ke(i,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=i,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function Oe(){if(typeof window>"u")return null;if(ye){let i=window;return i.TagadaPixels?i.TagadaPixels:(await ke(ye,()=>!!i.TagadaPixels),i.TagadaPixels??null)}return await import("../../pixels/index.js")}var Pe="__tgd_track",Fe="__tgd_aid",qe="__tgd_sid",ve=50,$e=2e3,we=1e3,He=64;function X(i){if(!(!Array.isArray(i)||i.length===0))return i.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ce(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var Ke={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function ae(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function je(i){let e={};for(let t of i){let{provider:n,id:r,idKey:s,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[s]:r,events:t.events??{}})}return e}var L=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Pe)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Pe,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,s=Date.now(),o=this.lastStep.get(r);o!==void 0&&s-o<we||(this.remember(r,s),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:s,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=Ke[e],s=`${r??e}_${ae()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:s,props:Ce(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:s}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...Ce(t)??{},step_id:n,pixel_event_id:s})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=we&&this.lastStep.delete(n);for(;this.lastStep.size>=He;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var s;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(s=n.items)==null?void 0:s.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ie,version:oe},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),s=window;return typeof((e=s.tgd)==null?void 0:e.init)!="function"&&await ke(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=s.tgd)==null?void 0:o.init)=="function"}),typeof((t=s.tgd)==null?void 0:t.init)!="function"?null:(s.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),s.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await Oe();if(n===null)return null;let r=n.createPixelEngine({pixels:je(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:s=>this.onPixelSignal(s)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(s=>s.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=ve){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),$e))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let s=ae();return n.setItem(t,s),s}catch{return ae()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,ve),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ie,version:oe},anonymousId:this.identifier("local",Fe),sessionId:this.identifier("session",qe),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Ge=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Be(i){var o;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:Ge.has(t),integrationId:e?void 0:i.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof s=="string"?s:void 0,metadata:i.metadata??void 0}}var D=class{constructor(e,t,n,r,s,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=s;this.onSignal=o;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`),o={...(s==null?void 0:s.config)??{}};return this.lastPaymentSetup=o,o}catch(s){if(!(s instanceof w))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(Be):(t==null?void 0:t.methods)??[],r={};for(let s of n){let o=s.provider&&s.provider!==s.method?`${s.method}:${s.provider}`:s.method;r[o]=s}return r}async getExpressMethods(e,t){var s,o,a,d,c,g,u,p,l,m;let n=await this.getPaymentSetup(e,t),r={};for(let[h,f]of Object.entries(n)){if(!f.enabled)continue;if(h.startsWith("express_checkout:")&&f.methods){let T={available:!0,processorId:f.processorId,publishableKey:f.publishableKey,metadata:f.metadata};if((s=f.methods.apple_pay)!=null&&s.enabled){let Re=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...T,type:"apple_pay",available:!!Re}}(d=f.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((c=this.onSignal)==null||c.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...T,type:"google_pay"}),(g=f.methods.link)!=null&&g.enabled&&(r.link={...T,type:"link"}),(u=f.methods.klarna_express)!=null&&u.enabled&&(r.klarna={...T,type:"klarna_express"});continue}if(!f.express)continue;let P=f.method,v={type:P,available:!0,processorId:f.processorId,publishableKey:f.publishableKey,metadata:f.metadata};if(P==="apple_pay"||f.type==="apple_pay"){let T=typeof window<"u"&&"ApplePaySession"in window&&((l=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:l.call(p));r.applePay={...v,available:!!T}}else P==="google_pay"||f.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((m=this.onSignal)==null||m.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=v):P==="paypal"?r.paypal=v:P==="klarna"||P==="klarna_express"?r.klarna=v:P==="link"&&(r.link=v)}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 a,d,c,g,u,p,l,m,h;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Q(e.shippingContact),billingAddress:Q(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.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:((u=e.shippingContact)==null?void 0:u.givenName)??((p=e.billingContact)==null?void 0:p.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((m=e.billingContact)==null?void 0:m.familyName)});let t=e.merchantRegistrationId??((h=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:h.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let s=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(s,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,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 o;for(let a of Object.values(s??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.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 o,a,d,c;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Z(e.shippingAddress),billingAddress:Z(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.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,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return n.status==="succeeded"?(this.emitPaid((s=e.order)==null?void 0:s.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.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"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||s!=="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(g=>d.delete(g));let c=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(c?"?"+c:""))}catch{}}return a}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 o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,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,o;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:((o=n==null?void 0:n.method)==null?void 0:o.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,o;let n=(o=(s=e.requireActionData)==null?void 0:s.metadata)==null?void 0:o.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 a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.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){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,s=Date.now(),o=0;for(;Date.now()-s<r;){let d;try{d=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(c=>setTimeout(c,n));continue}if(d.status==="succeeded"||d.status==="pending"&&d.subStatus==="authorized")return d.status==="succeeded"&&this.emitPaid((a=d.order)==null?void 0:a.id,d),{status:"succeeded",payment:d,order:d.order};if(d.status==="failed"||d.status==="declined")return{status:"failed",error:d.status,payment:d};if(d.requireAction&&d.requireAction!=="none"&&d.requireActionData&&!d.requireActionData.processed)return this.handlePaymentAction(d,{});await new Promise(c=>setTimeout(c,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}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:X(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var C=typeof document>"u"?null:document.currentScript,ze=C!=null&&C.src?new URL("tagada-headless-commerce.min.js",C.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-headless-commerce.min.js",ee;function M(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(ee||(ee=new Promise((i,e)=>{let t=document.createElement("script");t.src=ze,t.async=!0,C!=null&&C.nonce&&(t.nonce=C.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?i(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(i=>{throw ee=void 0,i})),ee)}var b=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])b.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var A=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])A.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var R=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])R.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var U=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 O=class{constructor(e,t,n,r,s){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=s}async navigate(e){var a,d;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"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let s=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(d=this.onFunnelSession)==null||d.call(this,s)}catch{}return{url:await this.runNavigate({funnelSessionId:s,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:s}}async ensureCmsSession(e,t,n){var o,a,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:((o=n.customer)==null?void 0:o.locale)??Ve(),userAgent:Je(),queryCurrency:((a=n.customer)==null?void 0:a.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 u,p,l,m;let{funnelSessionId:t,stepId:n,session:r,input:s,currentUrl:o}=e,a=r.items.map(h=>({variantId:h.variantId,priceId:h.priceId,quantity:h.quantity})),d=s.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),c={email:((u=s.customer)==null?void 0:u.email)??((p=r.customer)==null?void 0:p.email),currency:((l=s.customer)==null?void 0:l.currency)??r.currency,locale:(m=s.customer)==null?void 0:m.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:c,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function Ve(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Je(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var F=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}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 q=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,s;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((s=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:s.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,s;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((s=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:s.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var H=class{constructor(e){let t=e.environment??"production",n=S.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new S({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new L(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new q(()=>this.track.core(),this.config.bootstrap);let r=s=>{this._sessionToken=s};this.checkout=new I(this.http,this.config.storeId,r,s=>this.track.noteCheckout({checkoutSessionId:s.id,amount:s.totals.total,currency:s.totals.currency,items:X(s.items)})),this.payment=new D(this.http,this.config.storeId,t,this.checkout,s=>this.track.notePaid(s),(s,o)=>this.track.noteSignal("wallet_unavailable",s,o)),this.offers=new b(this.http,this.config.storeId,this.payment),this.customer=new A(this.http,this.config.storeId),this.portal=new R(this.http,this.config.storeId,r),this.catalog=new U(this.http,this.config.storeId),this.funnel=new O(this.http,this.config.storeId,this.checkout,this.config.accountId,s=>this.track.noteFunnelSession(s)),this.rx=new F(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Se(i){return new H(i)}var Ie=!1,be=!1,te=[];function de(){be=!0;for(let i of te)i();te.length=0}function ue(i,e={}){var t,n;return be||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(de(),Promise.resolve()):Ie?new Promise(r=>te.push(r)):(Ie=!0,new Promise((r,s)=>{if(te.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var g,u;(u=(g=window.google)==null?void 0:g.maps)!=null&&u.places?de():setTimeout(c,100)};c();return}let a=new URLSearchParams({key:i,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=()=>de(),d.onerror=()=>s(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var K=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(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,d)=>{var c,g,u;o(d===((u=(g=(c=window.google)==null?void 0:c.maps)==null?void 0:g.places)==null?void 0:u.PlacesServiceStatus.OK)&&a?a:[])})})}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"]},(o,a)=>{var d,c,g;s(a===((g=(c=(d=window.google)==null?void 0:d.maps)==null?void 0:c.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",s="",o="",a="",d="",c="",g="";for(let l of e.address_components??[]){let m=l.types;m.includes("subpremise")&&(t.subpremise=l.long_name),m.includes("street_number")&&(t.streetNumber=l.long_name),m.includes("premise")&&(n=l.long_name),m.includes("route")&&(t.route=l.long_name),m.includes("neighborhood")&&(r=l.long_name),m.includes("sublocality_level_5")&&(s=l.long_name),m.includes("sublocality_level_4")&&(o=l.long_name),m.includes("sublocality_level_3")&&(a=l.long_name),m.includes("sublocality_level_2")&&(d=l.long_name),m.includes("sublocality_level_1")&&(c=l.long_name),m.includes("locality")&&(t.locality=l.long_name),m.includes("postal_town")&&(g=l.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),m.includes("country")&&(t.country=l.short_name),m.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 u=t.streetNumber||n,p=t.route||s||o||a||r;if(t.subpremise&&u&&p)t.fullStreetAddress=`${t.subpremise}/${u} ${p}`;else if(u&&p)if(n&&o&&a){let l=`${a}-${o}-${n}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${u} ${p}`;else p?t.fullStreetAddress=p:u&&(t.fullStreetAddress=u);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 Ae="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",G=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],j=new Map,ne=new Map,ce=new Map,le=new Map;async function Ye(i){let e=j.get(i);if(e)return e;let t=ce.get(i);return t||(t=(async()=>{let n=`${Ae}/${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 j.set(i,s),ce.delete(i),s})(),ce.set(i,t),t)}async function We(i){let e=ne.get(i);if(e)return e;let t=le.get(i);return t||(t=(async()=>{let n=`${Ae}/${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 ne.set(i,s),le.delete(i),s})(),le.set(i,t),t)}function Qe(i){return j.get(i)||j.get("en")||{}}function Ze(i){return ne.get(i)||ne.get("en")||{}}async function B(i="en"){await Promise.all([Ye(i),We(i)])}var $=(i="en")=>{let e=Qe(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))},z=(i,e="en")=>{let n=Ze(e)[i];return n?n.map(([r,s])=>({code:r,name:s,countryCode:i})).sort((r,s)=>r.name.localeCompare(s.name)):[]};function V(i){return j.has(i)}var J=class i{static ensureLoaded(e="en"){return B(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 z(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 o=s.find(a=>a.iso===e);return o||(o=s.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=s.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=s.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return V(e)}static getAvailableLanguages(){return G}};var Xe={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"},et={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"},tt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),x=class i{static getSymbol(e){return Xe[e]??e}static getName(e){return et[e]??e}static getDecimalPlaces(e){return tt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function pe(i,e="USD",t="en-US"){let n=x.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`${x.getSymbol(e)}${r.toFixed(n)}`}}return De(nt);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var xe=Object.create;var Y=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var re=(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 Le=(i,e)=>{for(var t in e)Y(i,t,{get:e[t],enumerable:!0})},me=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _e(e))!Ee.call(i,r)&&r!==t&&Y(i,r,{get:()=>e[r],enumerable:!(n=Te(e,r))||n.enumerable});return i};var se=(i,e,t)=>(t=i!=null?xe(Ne(i)):{},me(e||!i||!i.__esModule?Y(t,"default",{value:i,enumerable:!0}):t,i)),De=i=>me(Y({},"__esModule",{value:!0}),i);var nt={};Le(nt,{AVAILABLE_LANGUAGES:()=>G,CatalogModule:()=>U,CheckoutModule:()=>I,CurrencyUtils:()=>x,CustomerModule:()=>A,CustomerPortalModule:()=>R,ExperimentsModule:()=>q,FunnelModule:()=>O,GoogleAutocompleteCore:()=>K,HeadlessClient:()=>H,HttpClient:()=>S,ISODataCore:()=>J,OffersModule:()=>b,PaymentModule:()=>D,RxModule:()=>F,TagadaAuthError:()=>_,TagadaError:()=>y,TagadaNetworkError:()=>k,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>W,TagadaRateLimitError:()=>E,TagadaValidationError:()=>N,TrackModule:()=>L,createHeadlessClient:()=>Se,ensureGeoDataLoaded:()=>B,formatMoney:()=>pe,getCountries:()=>$,getStatesForCountry:()=>z,isLanguageLoaded:()=>V,loadGoogleMapsScript:()=>ue,parseTokensFromUrl:()=>he});var y=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},_=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},N=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}},w=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},E=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},W=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}},k=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ge={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},S=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??ge[e]??ge.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:s={},params:o,token:a,signal:d}=t,c=`${this.baseUrl}${e}`;if(o){let h=new URLSearchParams;for(let[P,v]of Object.entries(o))v!==void 0&&h.set(P,String(v));let f=h.toString();f&&(c+=`?${f}`)}let g={"Content-Type":"application/json",...s},u=a??this.apiKey??((m=this.getToken)==null?void 0:m.call(this));u&&(g["x-cms-token"]=u);let p=new AbortController,l=setTimeout(()=>p.abort(),this.timeout);try{let h=await fetch(c,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(l),h.ok){let f=await h.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(h,e),new y("Unexpected error","unknown",h.status)}catch(h){throw clearTimeout(l),h instanceof y?h:h instanceof DOMException&&h.name==="AbortError"?new k(`Request to ${e} timed out after ${this.timeout}ms.`):new k(h instanceof Error?h.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=Me(n.data),s=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new _(s);case 404:throw new w(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new N(s,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new E(a)}default:throw new y(s,"api_error",e.status,n)}}};function Me(i){if(i&&typeof i=="object")return i;if(typeof i!="string")return{};try{let e=JSON.parse(i);return e&&typeof e=="object"?e:{}}catch{return{}}}var I=class i{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,d;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.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}),o=this.normalizeSession(s);this._currentSession=o;try{(d=this.onSession)==null||d.call(this,o)}catch{}return o}async createSession(e){var d,c,g;let t=e.items.map(u=>({variantId:u.variantId,priceId:u.priceId,...u.sellingPlanId!==void 0?{sellingPlanId:u.sellingPlanId}:{},...u.trialDays!==void 0?{trialDays:u.trialDays}:{},...u.trialPrice!==void 0?{trialPrice:u.trialPrice}:{},quantity:u.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(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),a=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:a,customerId:s.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,s=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:s.checkoutToken,sessionToken:s.sessionToken}),d=`${o}${t}?${a.toString()}`;return{...s,url:d}}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,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},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??{},o=r??n,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:s,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 n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),s=n??r??{},o=r??n,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:s,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Ue({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??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(u=>{let p=u.price,l=u.variant??(p==null?void 0:p.variant)??{},m=u.product??l.product??{},h=(p==null?void 0:p.currencyOptions)??{},f=(a?h[a]:void 0)??h[Object.keys(h)[0]],P=(f==null?void 0:f.amount)??0;return{id:u.id,variantId:u.variantId,priceId:u.priceId,productName:m.name??"",variantName:l.name??"",quantity:u.quantity??1,unitAmount:P,totalAmount:P*(u.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),c=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"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((u,p)=>u+(p.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,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}},he=I.parseTokensFromUrl;function Ue(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 Q(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 fe(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 fe(n)?n:void 0}function fe(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var ie="headless",oe="1.18.0";var ye="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-pixels.min.js";function ke(i,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=i,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function Oe(){if(typeof window>"u")return null;if(ye){let i=window;return i.TagadaPixels?i.TagadaPixels:(await ke(ye,()=>!!i.TagadaPixels),i.TagadaPixels??null)}return await import("../../pixels/index.js")}var Pe="__tgd_track",Fe="__tgd_aid",qe="__tgd_sid",ve=50,$e=2e3,we=1e3,He=64;function X(i){if(!(!Array.isArray(i)||i.length===0))return i.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ce(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var Ke={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function ae(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function je(i){let e={};for(let t of i){let{provider:n,id:r,idKey:s,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[s]:r,events:t.events??{}})}return e}var L=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Pe)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Pe,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,s=Date.now(),o=this.lastStep.get(r);o!==void 0&&s-o<we||(this.remember(r,s),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:s,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=Ke[e],s=`${r??e}_${ae()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:s,props:Ce(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:s}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...Ce(t)??{},step_id:n,pixel_event_id:s})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=we&&this.lastStep.delete(n);for(;this.lastStep.size>=He;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var s;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(s=n.items)==null?void 0:s.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ie,version:oe},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),s=window;return typeof((e=s.tgd)==null?void 0:e.init)!="function"&&await ke(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=s.tgd)==null?void 0:o.init)=="function"}),typeof((t=s.tgd)==null?void 0:t.init)!="function"?null:(s.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),s.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await Oe();if(n===null)return null;let r=n.createPixelEngine({pixels:je(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:s=>this.onPixelSignal(s)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(s=>s.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=ve){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),$e))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let s=ae();return n.setItem(t,s),s}catch{return ae()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,ve),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ie,version:oe},anonymousId:this.identifier("local",Fe),sessionId:this.identifier("session",qe),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Ge=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Be(i){var o;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:Ge.has(t),integrationId:e?void 0:i.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof s=="string"?s:void 0,metadata:i.metadata??void 0}}var D=class{constructor(e,t,n,r,s,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=s;this.onSignal=o;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`),o={...(s==null?void 0:s.config)??{}};return this.lastPaymentSetup=o,o}catch(s){if(!(s instanceof w))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(Be):(t==null?void 0:t.methods)??[],r={};for(let s of n){let o=s.provider&&s.provider!==s.method?`${s.method}:${s.provider}`:s.method;r[o]=s}return r}async getExpressMethods(e,t){var s,o,a,d,c,g,u,p,l,m;let n=await this.getPaymentSetup(e,t),r={};for(let[h,f]of Object.entries(n)){if(!f.enabled)continue;if(h.startsWith("express_checkout:")&&f.methods){let T={available:!0,processorId:f.processorId,publishableKey:f.publishableKey,metadata:f.metadata};if((s=f.methods.apple_pay)!=null&&s.enabled){let Re=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...T,type:"apple_pay",available:!!Re}}(d=f.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((c=this.onSignal)==null||c.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...T,type:"google_pay"}),(g=f.methods.link)!=null&&g.enabled&&(r.link={...T,type:"link"}),(u=f.methods.klarna_express)!=null&&u.enabled&&(r.klarna={...T,type:"klarna_express"});continue}if(!f.express)continue;let P=f.method,v={type:P,available:!0,processorId:f.processorId,publishableKey:f.publishableKey,metadata:f.metadata};if(P==="apple_pay"||f.type==="apple_pay"){let T=typeof window<"u"&&"ApplePaySession"in window&&((l=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:l.call(p));r.applePay={...v,available:!!T}}else P==="google_pay"||f.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((m=this.onSignal)==null||m.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=v):P==="paypal"?r.paypal=v:P==="klarna"||P==="klarna_express"?r.klarna=v:P==="link"&&(r.link=v)}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 a,d,c,g,u,p,l,m,h;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Q(e.shippingContact),billingAddress:Q(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.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:((u=e.shippingContact)==null?void 0:u.givenName)??((p=e.billingContact)==null?void 0:p.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((m=e.billingContact)==null?void 0:m.familyName)});let t=e.merchantRegistrationId??((h=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:h.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let s=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(s,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,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 o;for(let a of Object.values(s??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.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 o,a,d,c;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:Z(e.shippingAddress),billingAddress:Z(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.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,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return n.status==="succeeded"?(this.emitPaid((s=e.order)==null?void 0:s.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.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"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||s!=="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(g=>d.delete(g));let c=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(c?"?"+c:""))}catch{}}return a}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 o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,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,o;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:((o=n==null?void 0:n.method)==null?void 0:o.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,o;let n=(o=(s=e.requireActionData)==null?void 0:s.metadata)==null?void 0:o.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 a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.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){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,s=Date.now(),o=0;for(;Date.now()-s<r;){let d;try{d=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(c=>setTimeout(c,n));continue}if(d.status==="succeeded"||d.status==="pending"&&d.subStatus==="authorized")return d.status==="succeeded"&&this.emitPaid((a=d.order)==null?void 0:a.id,d),{status:"succeeded",payment:d,order:d.order};if(d.status==="failed"||d.status==="declined")return{status:"failed",error:d.status,payment:d};if(d.requireAction&&d.requireAction!=="none"&&d.requireActionData&&!d.requireActionData.processed)return this.handlePaymentAction(d,{});await new Promise(c=>setTimeout(c,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}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:X(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var C=typeof document>"u"?null:document.currentScript,ze=C!=null&&C.src?new URL("tagada-headless-commerce.min.js",C.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-headless-commerce.min.js",ee;function M(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(ee||(ee=new Promise((i,e)=>{let t=document.createElement("script");t.src=ze,t.async=!0,C!=null&&C.nonce&&(t.nonce=C.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?i(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(i=>{throw ee=void 0,i})),ee)}var b=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])b.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var A=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])A.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var R=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=M().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let i of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])R.prototype[i]=function(...e){return this.load().then(t=>t[i](...e))};var U=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 O=class{constructor(e,t,n,r,s){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=s}async navigate(e){var a,d;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"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let s=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(d=this.onFunnelSession)==null||d.call(this,s)}catch{}return{url:await this.runNavigate({funnelSessionId:s,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:s}}async ensureCmsSession(e,t,n){var o,a,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:((o=n.customer)==null?void 0:o.locale)??Ve(),userAgent:Je(),queryCurrency:((a=n.customer)==null?void 0:a.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 u,p,l,m;let{funnelSessionId:t,stepId:n,session:r,input:s,currentUrl:o}=e,a=r.items.map(h=>({variantId:h.variantId,priceId:h.priceId,quantity:h.quantity})),d=s.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),c={email:((u=s.customer)==null?void 0:u.email)??((p=r.customer)==null?void 0:p.email),currency:((l=s.customer)==null?void 0:l.currency)??r.currency,locale:(m=s.customer)==null?void 0:m.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:c,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function Ve(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Je(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var F=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}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 q=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,s;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((s=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:s.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,s;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((s=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:s.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var H=class{constructor(e){let t=e.environment??"production",n=S.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new S({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new L(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new q(()=>this.track.core(),this.config.bootstrap);let r=s=>{this._sessionToken=s};this.checkout=new I(this.http,this.config.storeId,r,s=>this.track.noteCheckout({checkoutSessionId:s.id,amount:s.totals.total,currency:s.totals.currency,items:X(s.items)})),this.payment=new D(this.http,this.config.storeId,t,this.checkout,s=>this.track.notePaid(s),(s,o)=>this.track.noteSignal("wallet_unavailable",s,o)),this.offers=new b(this.http,this.config.storeId,this.payment),this.customer=new A(this.http,this.config.storeId),this.portal=new R(this.http,this.config.storeId,r),this.catalog=new U(this.http,this.config.storeId),this.funnel=new O(this.http,this.config.storeId,this.checkout,this.config.accountId,s=>this.track.noteFunnelSession(s)),this.rx=new F(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Se(i){return new H(i)}var Ie=!1,be=!1,te=[];function de(){be=!0;for(let i of te)i();te.length=0}function ue(i,e={}){var t,n;return be||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(de(),Promise.resolve()):Ie?new Promise(r=>te.push(r)):(Ie=!0,new Promise((r,s)=>{if(te.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var g,u;(u=(g=window.google)==null?void 0:g.maps)!=null&&u.places?de():setTimeout(c,100)};c();return}let a=new URLSearchParams({key:i,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=()=>de(),d.onerror=()=>s(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var K=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(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,d)=>{var c,g,u;o(d===((u=(g=(c=window.google)==null?void 0:c.maps)==null?void 0:g.places)==null?void 0:u.PlacesServiceStatus.OK)&&a?a:[])})})}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"]},(o,a)=>{var d,c,g;s(a===((g=(c=(d=window.google)==null?void 0:d.maps)==null?void 0:c.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",s="",o="",a="",d="",c="",g="";for(let l of e.address_components??[]){let m=l.types;m.includes("subpremise")&&(t.subpremise=l.long_name),m.includes("street_number")&&(t.streetNumber=l.long_name),m.includes("premise")&&(n=l.long_name),m.includes("route")&&(t.route=l.long_name),m.includes("neighborhood")&&(r=l.long_name),m.includes("sublocality_level_5")&&(s=l.long_name),m.includes("sublocality_level_4")&&(o=l.long_name),m.includes("sublocality_level_3")&&(a=l.long_name),m.includes("sublocality_level_2")&&(d=l.long_name),m.includes("sublocality_level_1")&&(c=l.long_name),m.includes("locality")&&(t.locality=l.long_name),m.includes("postal_town")&&(g=l.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),m.includes("country")&&(t.country=l.short_name),m.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 u=t.streetNumber||n,p=t.route||s||o||a||r;if(t.subpremise&&u&&p)t.fullStreetAddress=`${t.subpremise}/${u} ${p}`;else if(u&&p)if(n&&o&&a){let l=`${a}-${o}-${n}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${u} ${p}`;else p?t.fullStreetAddress=p:u&&(t.fullStreetAddress=u);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 Ae="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",G=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],j=new Map,ne=new Map,ce=new Map,le=new Map;async function Ye(i){let e=j.get(i);if(e)return e;let t=ce.get(i);return t||(t=(async()=>{let n=`${Ae}/${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 j.set(i,s),ce.delete(i),s})(),ce.set(i,t),t)}async function We(i){let e=ne.get(i);if(e)return e;let t=le.get(i);return t||(t=(async()=>{let n=`${Ae}/${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 ne.set(i,s),le.delete(i),s})(),le.set(i,t),t)}function Qe(i){return j.get(i)||j.get("en")||{}}function Ze(i){return ne.get(i)||ne.get("en")||{}}async function B(i="en"){await Promise.all([Ye(i),We(i)])}var $=(i="en")=>{let e=Qe(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))},z=(i,e="en")=>{let n=Ze(e)[i];return n?n.map(([r,s])=>({code:r,name:s,countryCode:i})).sort((r,s)=>r.name.localeCompare(s.name)):[]};function V(i){return j.has(i)}var J=class i{static ensureLoaded(e="en"){return B(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 z(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 o=s.find(a=>a.iso===e);return o||(o=s.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=s.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=s.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return V(e)}static getAvailableLanguages(){return G}};var Xe={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"},et={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"},tt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),x=class i{static getSymbol(e){return Xe[e]??e}static getName(e){return et[e]??e}static getDecimalPlaces(e){return tt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function pe(i,e="USD",t="en-US"){let n=x.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`${x.getSymbol(e)}${r.toFixed(n)}`}}return De(nt);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|