@tagadapay/headless-sdk 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.19.0
2
+ * @tagadapay/headless-sdk v1.20.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
@@ -789,10 +789,10 @@ var TagadaHeadlessBundle = (() => {
789
789
 
790
790
  // src/core/version.ts
791
791
  var SDK_NAME = "headless";
792
- var SDK_VERSION = "1.19.0";
792
+ var SDK_VERSION = "1.20.0";
793
793
 
794
794
  // src/core/modules/track.ts
795
- var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.19.0/dist/tagada-pixels.min.js";
795
+ var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.0/dist/tagada-pixels.min.js";
796
796
  function loadScript(src, isReady) {
797
797
  if (isReady())
798
798
  return Promise.resolve();
@@ -1211,6 +1211,28 @@ var TagadaHeadlessBundle = (() => {
1211
1211
  metadata: entry.metadata ?? void 0
1212
1212
  };
1213
1213
  }
1214
+ function loadStripeJs() {
1215
+ if (typeof window === "undefined")
1216
+ return Promise.reject(new Error("Stripe Radar needs a browser"));
1217
+ const fromPage = () => window.Stripe;
1218
+ const loaded = fromPage();
1219
+ if (loaded)
1220
+ return Promise.resolve(loaded);
1221
+ return new Promise((resolve, reject) => {
1222
+ const script2 = document.createElement("script");
1223
+ script2.src = "https://js.stripe.com/v3/";
1224
+ script2.async = true;
1225
+ script2.onload = () => {
1226
+ const stripe = fromPage();
1227
+ if (stripe)
1228
+ resolve(stripe);
1229
+ else
1230
+ reject(new Error("Stripe.js loaded without window.Stripe"));
1231
+ };
1232
+ script2.onerror = () => reject(new Error("Failed to load Stripe.js"));
1233
+ document.head.appendChild(script2);
1234
+ });
1235
+ }
1214
1236
  var PaymentModule = class {
1215
1237
  constructor(http, storeId, environment, checkout, onPaid, onSignal) {
1216
1238
  this.http = http;
@@ -1887,6 +1909,8 @@ var TagadaHeadlessBundle = (() => {
1887
1909
  return this.extractRedirect(payment, actionData);
1888
1910
  case "redirect":
1889
1911
  return this.extractRedirect(payment, actionData);
1912
+ case "stripe_radar":
1913
+ return this.handleStripeRadar(payment);
1890
1914
  case "error":
1891
1915
  return {
1892
1916
  status: "failed",
@@ -1969,6 +1993,34 @@ var TagadaHeadlessBundle = (() => {
1969
1993
  };
1970
1994
  }
1971
1995
  }
1996
+ /**
1997
+ * Stripe Radar: the processor holds the charge until the browser sends a Radar
1998
+ * session. Create it with Stripe.js, save it, resume the payment, then poll.
1999
+ */
2000
+ async handleStripeRadar(payment) {
2001
+ var _a, _b;
2002
+ const radar = (_b = (_a = payment.requireActionData) == null ? void 0 : _a.metadata) == null ? void 0 : _b.radar;
2003
+ if (!(radar == null ? void 0 : radar.publishableKey)) {
2004
+ return { status: "failed", error: "Stripe Radar configuration missing", payment };
2005
+ }
2006
+ try {
2007
+ const Stripe = await loadStripeJs();
2008
+ const { radarSession, error } = await Stripe(radar.publishableKey).createRadarSession();
2009
+ if (error || !radarSession) {
2010
+ throw new Error((error == null ? void 0 : error.message) || "No Radar session returned by Stripe");
2011
+ }
2012
+ await this.http.post("/api/v1/radar-sessions", {
2013
+ orderId: radar.orderId,
2014
+ paymentId: payment.id,
2015
+ stripeRadarSessionId: radarSession.id,
2016
+ stripeRadarSessionData: radarSession
2017
+ });
2018
+ await this.completeAfter3ds(payment.id);
2019
+ return this.pollUntilDone(payment.id);
2020
+ } catch (e) {
2021
+ return { status: "failed", error: e instanceof Error ? e.message : "Stripe Radar failed", payment };
2022
+ }
2023
+ }
1972
2024
  /**
1973
2025
  * Poll until the payment reaches a terminal status, then return a ProcessPaymentResult.
1974
2026
  * Also handles new requireAction that may appear during polling.
@@ -2063,7 +2115,7 @@ var TagadaHeadlessBundle = (() => {
2063
2115
 
2064
2116
  // src/core/modules/lazyCommerce.ts
2065
2117
  var script = typeof document === "undefined" ? null : document.currentScript;
2066
- 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.19.0/dist/tagada-headless-commerce.min.js";
2118
+ 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.20.0/dist/tagada-headless-commerce.min.js";
2067
2119
  var loading;
2068
2120
  function loadCommerce() {
2069
2121
  if (window.TagadaHeadlessCommerce)
@@ -2422,6 +2474,19 @@ var TagadaHeadlessBundle = (() => {
2422
2474
  input
2423
2475
  );
2424
2476
  }
2477
+ /**
2478
+ * Resume an unfinished intake from `(orderId, checkoutToken)` alone: the
2479
+ * patient paid (card on hold) but the identity collected at checkout is
2480
+ * gone (tab closed, recovery email link, other device). Returns the Rx
2481
+ * line (`productId`, `variantId`) and the basics on the order; ask date of
2482
+ * birth and sex at birth again, render the questionnaire, then
2483
+ * `submitCase`. `{ caseExists: true }` means a case is already in: show
2484
+ * `getCasesForOrder`. Fails with 401 on a wrong token, 404 when the order
2485
+ * has no Rx line.
2486
+ */
2487
+ async getIntakeContext(input) {
2488
+ return this.http.post("/api/public/v1/rx/intake/context", input);
2489
+ }
2425
2490
  /**
2426
2491
  * Submit a fresh clinical case for a freshly-paid order. PHI is
2427
2492
  * forwarded to the clinical network and never persisted on
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.19.0
2
+ * @tagadapay/headless-sdk v1.20.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessBundle=(()=>{var Ne=Object.create;var Q=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var se=(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 Oe=(i,e)=>{for(var t in e)Q(i,t,{get:e[t],enumerable:!0})},he=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Le(e))!Me.call(i,r)&&r!==t&&Q(i,r,{get:()=>e[r],enumerable:!(n=Ee(e,r))||n.enumerable});return i};var ie=(i,e,t)=>(t=i!=null?Ne(De(i)):{},he(e||!i||!i.__esModule?Q(t,"default",{value:i,enumerable:!0}):t,i)),Ue=i=>he(Q({},"__esModule",{value:!0}),i);var it={};Oe(it,{AVAILABLE_LANGUAGES:()=>G,CatalogModule:()=>O,CheckoutModule:()=>I,CurrencyUtils:()=>A,CustomerModule:()=>x,CustomerPortalModule:()=>R,ExperimentsModule:()=>F,FunnelModule:()=>U,GoogleAutocompleteCore:()=>K,HeadlessClient:()=>H,HttpClient:()=>S,ISODataCore:()=>J,OffersModule:()=>b,PaymentModule:()=>D,RxModule:()=>q,TagadaAuthError:()=>_,TagadaError:()=>y,TagadaNetworkError:()=>C,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>Y,TagadaRateLimitError:()=>E,TagadaValidationError:()=>N,TrackModule:()=>L,createHeadlessClient:()=>xe,ensureGeoDataLoaded:()=>B,formatMoney:()=>ge,getCountries:()=>$,getStatesForCountry:()=>V,isLanguageLoaded:()=>z,isQuestionActive:()=>ue,loadGoogleMapsScript:()=>ce,parseTokensFromUrl:()=>ye,toIntakeAnswers:()=>be});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}},Y=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}},C=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var fe={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??fe[e]??fe.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:s={},params:o,token:a,signal:d}=t,l=`${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&&(l+=`?${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,c=setTimeout(()=>p.abort(),this.timeout);try{let h=await fetch(l,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(c),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(c),h instanceof y?h:h instanceof DOMException&&h.name==="AbortError"?new C(`Request to ${e} timed out after ${this.timeout}ms.`):new C(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=qe(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 qe(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,l,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),(l=e.customerTags)!=null&&l.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 Fe({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},s=t.sessionLineItems??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(u=>{let p=u.price,c=u.variant??(p==null?void 0:p.variant)??{},m=u.product??c.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:c.name??"",quantity:u.quantity??1,unitAmount:P,totalAmount:P*(u.quantity??1),currency:a??"USD",imageUrl:c.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),l=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??l.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}},ye=I.parseTokensFromUrl;function Fe(i){let e={};for(let[t,n]of Object.entries(i))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function W(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 Pe(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 Pe(n)?n:void 0}function Pe(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var oe="headless",ae="1.19.0";var ve="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.19.0/dist/tagada-pixels.min.js";function Ie(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 $e(){if(typeof window>"u")return null;if(ve){let i=window;return i.TagadaPixels?i.TagadaPixels:(await Ie(ve,()=>!!i.TagadaPixels),i.TagadaPixels??null)}return await import("../../pixels/index.js")}var we="__tgd_track",He="__tgd_aid",Ke="__tgd_sid",ke=50,je=2e3,Ce=1e3,Ge=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 Se(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 Be={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function de(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Ve(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(we)??"").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(we,`${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<Ce||(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=Be[e],s=`${r??e}_${de()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:s,props:Se(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,{...Se(t)??{},step_id:n,pixel_event_id:s})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=Ce&&this.lastStep.delete(n);for(;this.lastStep.size>=Ge;){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:oe,version:ae},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 Ie(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 $e();if(n===null)return null;let r=n.createPixelEngine({pixels:Ve(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>=ke){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),je))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let s=de();return n.setItem(t,s),s}catch{return de()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,ke),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:oe,version:ae},anonymousId:this.identifier("local",He),sessionId:this.identifier("session",Ke),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 ze=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Je(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:ze.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(Je):(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,l,g,u,p,c,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 _e=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:!!_e}}(d=f.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((l=this.onSignal)==null||l.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&&((c=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:c.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,l,g,u,p,c,m,h;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:W(e.shippingContact),billingAddress:W(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((l=e.shippingContact)==null?void 0:l.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:((c=e.shippingContact)==null?void 0:c.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 l=d[t];if(l!=null&&l.merchantRegistrationId)return{merchantRegistrationId:l.merchantRegistrationId,displayName:l.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,l;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)??((l=e.billingAddress)==null?void 0:l.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 l=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(l?"?"+l:""))}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(l=>setTimeout(l,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(l=>setTimeout(l,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 k=typeof document>"u"?null:document.currentScript,Qe=k!=null&&k.src?new URL("tagada-headless-commerce.min.js",k.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.19.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=Qe,t.async=!0,k!=null&&k.nonce&&(t.nonce=k.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 x=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"])x.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 O=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 U=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)??Ye(),userAgent:We(),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,c,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),l={email:((u=s.customer)==null?void 0:u.email)??((p=r.customer)==null?void 0:p.email),currency:((c=s.customer)==null?void 0:c.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:l,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function Ye(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function We(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var te=(i,e)=>e!==null&&String(i).trim().toLowerCase()===e.trim().toLowerCase();function ue(i,e,t={}){if(i.visible===!1||i.type==="file")return!1;let n=i.rules??[];return n.length===0?!0:n.some(r=>{let s=o=>{if(o.basedOn==="state")return te(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return te(t.sexAtBirth??"",o.answer);if(o.basedOn==="question"&&o.questionId){let a=e[o.questionId];return a===void 0?!1:Array.isArray(a)?a.some(d=>te(d,o.answer)):te(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(s):r.requirements.some(s)})}function be(i,e,t={}){let n=[];for(let r of i){if(r.visible===!1){r.defaultValue&&n.push({questionId:r.title,question:r.title,value:r.defaultValue,type:"string"});continue}if(!ue(r,e,t))continue;let s=e[r.externalQuestionId];s===void 0||typeof s=="string"&&s.trim()===""||n.push({questionId:r.title,question:r.title,value:s,type:r.type==="number"?"number":r.type==="boolean"?"boolean":"string",...r.options.length>0?{displayedOptions:r.options.map(o=>o.label)}:{}})}return n}var q=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 validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",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 F=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 F(()=>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 x(this.http,this.config.storeId),this.portal=new R(this.http,this.config.storeId,r),this.catalog=new O(this.http,this.config.storeId),this.funnel=new U(this.http,this.config.storeId,this.checkout,this.config.accountId,s=>this.track.noteFunnelSession(s)),this.rx=new q(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function xe(i){return new H(i)}var Re=!1,Ae=!1,ne=[];function le(){Ae=!0;for(let i of ne)i();ne.length=0}function ce(i,e={}){var t,n;return Ae||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(le(),Promise.resolve()):Re?new Promise(r=>ne.push(r)):(Re=!0,new Promise((r,s)=>{if(ne.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let l=()=>{var g,u;(u=(g=window.google)==null?void 0:g.maps)!=null&&u.places?le():setTimeout(l,100)};l();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=()=>le(),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 l,g,u;o(d===((u=(g=(l=window.google)==null?void 0:l.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,l,g;s(a===((g=(l=(d=window.google)==null?void 0:d.maps)==null?void 0:l.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="",l="",g="";for(let c of e.address_components??[]){let m=c.types;m.includes("subpremise")&&(t.subpremise=c.long_name),m.includes("street_number")&&(t.streetNumber=c.long_name),m.includes("premise")&&(n=c.long_name),m.includes("route")&&(t.route=c.long_name),m.includes("neighborhood")&&(r=c.long_name),m.includes("sublocality_level_5")&&(s=c.long_name),m.includes("sublocality_level_4")&&(o=c.long_name),m.includes("sublocality_level_3")&&(a=c.long_name),m.includes("sublocality_level_2")&&(d=c.long_name),m.includes("sublocality_level_1")&&(l=c.long_name),m.includes("locality")&&(t.locality=c.long_name),m.includes("postal_town")&&(g=c.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=c.short_name,t.administrativeAreaLevel2Long=c.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=c.short_name,t.administrativeAreaLevel1Long=c.long_name),m.includes("country")&&(t.country=c.short_name),m.includes("postal_code")&&(t.postalCode=c.long_name)}t.locality||(t.locality=g||d||l||""),!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 c=`${a}-${o}-${n}`;d&&(c=`${c} ${d}`),t.fullStreetAddress=c}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 Te="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,re=new Map,pe=new Map,me=new Map;async function Ze(i){let e=j.get(i);if(e)return e;let t=pe.get(i);return t||(t=(async()=>{let n=`${Te}/${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),pe.delete(i),s})(),pe.set(i,t),t)}async function Xe(i){let e=re.get(i);if(e)return e;let t=me.get(i);return t||(t=(async()=>{let n=`${Te}/${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 re.set(i,s),me.delete(i),s})(),me.set(i,t),t)}function et(i){return j.get(i)||j.get("en")||{}}function tt(i){return re.get(i)||re.get("en")||{}}async function B(i="en"){await Promise.all([Ze(i),Xe(i)])}var $=(i="en")=>{let e=et(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))},V=(i,e="en")=>{let n=tt(e)[i];return n?n.map(([r,s])=>({code:r,name:s,countryCode:i})).sort((r,s)=>r.name.localeCompare(s.name)):[]};function z(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 V(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 z(e)}static getAvailableLanguages(){return G}};var nt={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"},rt={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"},st=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),A=class i{static getSymbol(e){return nt[e]??e}static getName(e){return rt[e]??e}static getDecimalPlaces(e){return st.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function ge(i,e="USD",t="en-US"){let n=A.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`${A.getSymbol(e)}${r.toFixed(n)}`}}return Ue(it);})();
6
+ "use strict";var TagadaHeadlessBundle=(()=>{var Ne=Object.create;var Q=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var se=(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 Oe=(i,e)=>{for(var t in e)Q(i,t,{get:e[t],enumerable:!0})},he=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Le(e))!Me.call(i,r)&&r!==t&&Q(i,r,{get:()=>e[r],enumerable:!(n=Ee(e,r))||n.enumerable});return i};var ie=(i,e,t)=>(t=i!=null?Ne(De(i)):{},he(e||!i||!i.__esModule?Q(t,"default",{value:i,enumerable:!0}):t,i)),Ue=i=>he(Q({},"__esModule",{value:!0}),i);var ot={};Oe(ot,{AVAILABLE_LANGUAGES:()=>G,CatalogModule:()=>O,CheckoutModule:()=>I,CurrencyUtils:()=>A,CustomerModule:()=>x,CustomerPortalModule:()=>R,ExperimentsModule:()=>F,FunnelModule:()=>U,GoogleAutocompleteCore:()=>j,HeadlessClient:()=>K,HttpClient:()=>S,ISODataCore:()=>J,OffersModule:()=>b,PaymentModule:()=>D,RxModule:()=>q,TagadaAuthError:()=>_,TagadaError:()=>y,TagadaNetworkError:()=>C,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>Y,TagadaRateLimitError:()=>E,TagadaValidationError:()=>N,TrackModule:()=>L,createHeadlessClient:()=>xe,ensureGeoDataLoaded:()=>B,formatMoney:()=>ge,getCountries:()=>$,getStatesForCountry:()=>V,isLanguageLoaded:()=>z,isQuestionActive:()=>ue,loadGoogleMapsScript:()=>ce,parseTokensFromUrl:()=>ye,toIntakeAnswers:()=>be});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}},Y=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}},C=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var fe={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??fe[e]??fe.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:s={},params:o,token:a,signal:d}=t,l=`${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&&(l+=`?${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,c=setTimeout(()=>p.abort(),this.timeout);try{let h=await fetch(l,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(c),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(c),h instanceof y?h:h instanceof DOMException&&h.name==="AbortError"?new C(`Request to ${e} timed out after ${this.timeout}ms.`):new C(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=qe(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 qe(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,l,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),(l=e.customerTags)!=null&&l.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 Fe({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},s=t.sessionLineItems??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(u=>{let p=u.price,c=u.variant??(p==null?void 0:p.variant)??{},m=u.product??c.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:c.name??"",quantity:u.quantity??1,unitAmount:P,totalAmount:P*(u.quantity??1),currency:a??"USD",imageUrl:c.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),l=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??l.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}},ye=I.parseTokensFromUrl;function Fe(i){let e={};for(let[t,n]of Object.entries(i))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function W(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 Pe(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 Pe(n)?n:void 0}function Pe(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var oe="headless",ae="1.20.0";var ve="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.0/dist/tagada-pixels.min.js";function Ie(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 $e(){if(typeof window>"u")return null;if(ve){let i=window;return i.TagadaPixels?i.TagadaPixels:(await Ie(ve,()=>!!i.TagadaPixels),i.TagadaPixels??null)}return await import("../../pixels/index.js")}var we="__tgd_track",Ke="__tgd_aid",je="__tgd_sid",ke=50,He=2e3,Ce=1e3,Ge=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 Se(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 Be={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function de(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Ve(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(we)??"").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(we,`${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<Ce||(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=Be[e],s=`${r??e}_${de()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:s,props:Se(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,{...Se(t)??{},step_id:n,pixel_event_id:s})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=Ce&&this.lastStep.delete(n);for(;this.lastStep.size>=Ge;){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:oe,version:ae},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 Ie(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 $e();if(n===null)return null;let r=n.createPixelEngine({pixels:Ve(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>=ke){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),He))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let s=de();return n.setItem(t,s),s}catch{return de()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,ke),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:oe,version:ae},anonymousId:this.identifier("local",Ke),sessionId:this.identifier("session",je),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 ze=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Je(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:ze.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}}function Qe(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let i=()=>window.Stripe,e=i();return e?Promise.resolve(e):new Promise((t,n)=>{let r=document.createElement("script");r.src="https://js.stripe.com/v3/",r.async=!0,r.onload=()=>{let s=i();s?t(s):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}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(Je):(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,l,g,u,p,c,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 _e=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:!!_e}}(d=f.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((l=this.onSignal)==null||l.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&&((c=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:c.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,l,g,u,p,c,m,h;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:W(e.shippingContact),billingAddress:W(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((l=e.shippingContact)==null?void 0:l.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:((c=e.shippingContact)==null?void 0:c.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 l=d[t];if(l!=null&&l.merchantRegistrationId)return{merchantRegistrationId:l.merchantRegistrationId,displayName:l.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,l;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)??((l=e.billingAddress)==null?void 0:l.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 l=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(l?"?"+l:""))}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"stripe_radar":return this.handleStripeRadar(e);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 handleStripeRadar(e){var n,r;let t=(r=(n=e.requireActionData)==null?void 0:n.metadata)==null?void 0:r.radar;if(!(t!=null&&t.publishableKey))return{status:"failed",error:"Stripe Radar configuration missing",payment:e};try{let s=await Qe(),{radarSession:o,error:a}=await s(t.publishableKey).createRadarSession();if(a||!o)throw new Error((a==null?void 0:a.message)||"No Radar session returned by Stripe");return await this.http.post("/api/v1/radar-sessions",{orderId:t.orderId,paymentId:e.id,stripeRadarSessionId:o.id,stripeRadarSessionData:o}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch(s){return{status:"failed",error:s instanceof Error?s.message:"Stripe Radar 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(l=>setTimeout(l,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(l=>setTimeout(l,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 k=typeof document>"u"?null:document.currentScript,Ye=k!=null&&k.src?new URL("tagada-headless-commerce.min.js",k.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.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=Ye,t.async=!0,k!=null&&k.nonce&&(t.nonce=k.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 x=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"])x.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 O=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 U=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)??We(),userAgent:Ze(),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,c,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),l={email:((u=s.customer)==null?void 0:u.email)??((p=r.customer)==null?void 0:p.email),currency:((c=s.customer)==null?void 0:c.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:l,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function We(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ze(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var te=(i,e)=>e!==null&&String(i).trim().toLowerCase()===e.trim().toLowerCase();function ue(i,e,t={}){if(i.visible===!1||i.type==="file")return!1;let n=i.rules??[];return n.length===0?!0:n.some(r=>{let s=o=>{if(o.basedOn==="state")return te(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return te(t.sexAtBirth??"",o.answer);if(o.basedOn==="question"&&o.questionId){let a=e[o.questionId];return a===void 0?!1:Array.isArray(a)?a.some(d=>te(d,o.answer)):te(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(s):r.requirements.some(s)})}function be(i,e,t={}){let n=[];for(let r of i){if(r.visible===!1){r.defaultValue&&n.push({questionId:r.title,question:r.title,value:r.defaultValue,type:"string"});continue}if(!ue(r,e,t))continue;let s=e[r.externalQuestionId];s===void 0||typeof s=="string"&&s.trim()===""||n.push({questionId:r.title,question:r.title,value:s,type:r.type==="number"?"number":r.type==="boolean"?"boolean":"string",...r.options.length>0?{displayedOptions:r.options.map(o=>o.label)}:{}})}return n}var q=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 getIntakeContext(e){return this.http.post("/api/public/v1/rx/intake/context",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",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 F=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 K=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 F(()=>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 x(this.http,this.config.storeId),this.portal=new R(this.http,this.config.storeId,r),this.catalog=new O(this.http,this.config.storeId),this.funnel=new U(this.http,this.config.storeId,this.checkout,this.config.accountId,s=>this.track.noteFunnelSession(s)),this.rx=new q(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function xe(i){return new K(i)}var Re=!1,Ae=!1,ne=[];function le(){Ae=!0;for(let i of ne)i();ne.length=0}function ce(i,e={}){var t,n;return Ae||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(le(),Promise.resolve()):Re?new Promise(r=>ne.push(r)):(Re=!0,new Promise((r,s)=>{if(ne.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let l=()=>{var g,u;(u=(g=window.google)==null?void 0:g.maps)!=null&&u.places?le():setTimeout(l,100)};l();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=()=>le(),d.onerror=()=>s(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var j=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 l,g,u;o(d===((u=(g=(l=window.google)==null?void 0:l.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,l,g;s(a===((g=(l=(d=window.google)==null?void 0:d.maps)==null?void 0:l.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="",l="",g="";for(let c of e.address_components??[]){let m=c.types;m.includes("subpremise")&&(t.subpremise=c.long_name),m.includes("street_number")&&(t.streetNumber=c.long_name),m.includes("premise")&&(n=c.long_name),m.includes("route")&&(t.route=c.long_name),m.includes("neighborhood")&&(r=c.long_name),m.includes("sublocality_level_5")&&(s=c.long_name),m.includes("sublocality_level_4")&&(o=c.long_name),m.includes("sublocality_level_3")&&(a=c.long_name),m.includes("sublocality_level_2")&&(d=c.long_name),m.includes("sublocality_level_1")&&(l=c.long_name),m.includes("locality")&&(t.locality=c.long_name),m.includes("postal_town")&&(g=c.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=c.short_name,t.administrativeAreaLevel2Long=c.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=c.short_name,t.administrativeAreaLevel1Long=c.long_name),m.includes("country")&&(t.country=c.short_name),m.includes("postal_code")&&(t.postalCode=c.long_name)}t.locality||(t.locality=g||d||l||""),!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 c=`${a}-${o}-${n}`;d&&(c=`${c} ${d}`),t.fullStreetAddress=c}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 Te="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",G=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],H=new Map,re=new Map,pe=new Map,me=new Map;async function Xe(i){let e=H.get(i);if(e)return e;let t=pe.get(i);return t||(t=(async()=>{let n=`${Te}/${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 H.set(i,s),pe.delete(i),s})(),pe.set(i,t),t)}async function et(i){let e=re.get(i);if(e)return e;let t=me.get(i);return t||(t=(async()=>{let n=`${Te}/${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 re.set(i,s),me.delete(i),s})(),me.set(i,t),t)}function tt(i){return H.get(i)||H.get("en")||{}}function nt(i){return re.get(i)||re.get("en")||{}}async function B(i="en"){await Promise.all([Xe(i),et(i)])}var $=(i="en")=>{let e=tt(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))},V=(i,e="en")=>{let n=nt(e)[i];return n?n.map(([r,s])=>({code:r,name:s,countryCode:i})).sort((r,s)=>r.name.localeCompare(s.name)):[]};function z(i){return H.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 V(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 z(e)}static getAvailableLanguages(){return G}};var rt={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"},st={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"},it=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),A=class i{static getSymbol(e){return rt[e]??e}static getName(e){return st[e]??e}static getDecimalPlaces(e){return it.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function ge(i,e="USD",t="en-US"){let n=A.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`${A.getSymbol(e)}${r.toFixed(n)}`}}return Ue(ot);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
8
8
  //# sourceMappingURL=tagada-headless.min.js.map