@tagadapay/headless-sdk 1.19.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +193 -0
- package/dist/core/helpers/cryptoOnchain.d.ts +83 -0
- package/dist/core/helpers/cryptoOnchain.d.ts.map +1 -0
- package/dist/core/helpers/cryptoOnchain.js +247 -0
- package/dist/core/helpers/cryptoOnchain.js.map +1 -0
- package/dist/core/helpers/oceanpayment.d.ts +33 -0
- package/dist/core/helpers/oceanpayment.d.ts.map +1 -0
- package/dist/core/helpers/oceanpayment.js +111 -0
- package/dist/core/helpers/oceanpayment.js.map +1 -0
- package/dist/core/http.d.ts.map +1 -1
- package/dist/core/http.js +3 -0
- package/dist/core/http.js.map +1 -1
- package/dist/core/index.d.ts +4 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/modules/payment.d.ts +66 -1
- package/dist/core/modules/payment.d.ts.map +1 -1
- package/dist/core/modules/payment.js +297 -2
- package/dist/core/modules/payment.js.map +1 -1
- package/dist/core/modules/portal/types.d.ts +10 -1
- package/dist/core/modules/portal/types.d.ts.map +1 -1
- package/dist/core/modules/rx.d.ts +43 -0
- package/dist/core/modules/rx.d.ts.map +1 -1
- package/dist/core/modules/rx.js +13 -0
- package/dist/core/modules/rx.js.map +1 -1
- package/dist/core/types.d.ts +159 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/pixels/pixelMapping.d.ts.map +1 -1
- package/dist/pixels/pixelMapping.js +9 -1
- package/dist/pixels/pixelMapping.js.map +1 -1
- package/dist/react/hooks/useCryptoOnchainPayment.d.ts +40 -0
- package/dist/react/hooks/useCryptoOnchainPayment.d.ts.map +1 -0
- package/dist/react/hooks/useCryptoOnchainPayment.js +77 -0
- package/dist/react/hooks/useCryptoOnchainPayment.js.map +1 -0
- package/dist/react/hooks/usePayment.d.ts.map +1 -1
- package/dist/react/hooks/usePayment.js +3 -0
- package/dist/react/hooks/usePayment.js.map +1 -1
- package/dist/react/index.d.ts +4 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +2 -0
- package/dist/react/index.js.map +1 -1
- package/dist/tagada-headless-commerce.min.js +1 -1
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +4 -4
- package/dist/tagada-headless.js +626 -9
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +4 -4
- package/dist/tagada-pixels.min.js +2 -2
- package/dist/tagada-pixels.min.js.map +3 -3
- package/package.json +3 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.20.1
|
|
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 ot=Object.create;var re=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ge=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var lt=(s,e)=>{for(var t in e)re(s,t,{get:e[t],enumerable:!0})},Ee=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dt(e))!ut.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return s};var he=(s,e,t)=>(t=s!=null?ot(ct(s)):{},Ee(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s)),pt=s=>Ee(re({},"__esModule",{value:!0}),s);var Kt={};lt(Kt,{AVAILABLE_LANGUAGES:()=>Z,CRYPTO_ONCHAIN_FINAL_PHASES:()=>de,CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>Ce,CRYPTO_ONCHAIN_STATUS_POLL_MS:()=>je,CatalogModule:()=>K,CheckoutModule:()=>O,CryptoOnchainCheckout:()=>F,CurrencyUtils:()=>N,CustomerModule:()=>_,CustomerPortalModule:()=>E,ExperimentsModule:()=>B,FunnelModule:()=>j,GoogleAutocompleteCore:()=>Q,HeadlessClient:()=>Y,HttpClient:()=>A,ISODataCore:()=>ne,OffersModule:()=>T,PaymentModule:()=>$,RxModule:()=>G,TagadaAuthError:()=>L,TagadaError:()=>P,TagadaNetworkError:()=>R,TagadaNotFoundError:()=>v,TagadaPaymentError:()=>se,TagadaRateLimitError:()=>D,TagadaValidationError:()=>M,TrackModule:()=>U,createHeadlessClient:()=>et,cryptoOnchainPhase:()=>ke,cryptoOnchainSecondsLeft:()=>ce,defaultCryptoOnchainSelection:()=>Se,ensureGeoDataLoaded:()=>X,formatCryptoOnchainCountdown:()=>Be,formatMoney:()=>Te,getCountries:()=>V,getStatesForCountry:()=>ee,isCryptoOnchainMethod:()=>Ge,isLanguageLoaded:()=>te,isQuestionActive:()=>be,loadGoogleMapsScript:()=>Re,parseTokensFromUrl:()=>Le,selectCryptoOnchainNetwork:()=>we,toIntakeAnswers:()=>Xe});var P=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},L=class extends P{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},M=class extends P{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},v=class extends P{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},D=class extends P{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},se=class extends P{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}},R=class extends P{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var fe="headless",z="1.20.1";var Ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},A=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??Ne[e]??Ne.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:i={},params:o,token:a,signal:d}=t,u=`${this.baseUrl}${e}`;if(o){let f=new URLSearchParams;for(let[C,w]of Object.entries(o))w!==void 0&&f.set(C,String(w));let h=f.toString();h&&(u+=`?${h}`)}let g={"Content-Type":"application/json","X-Tagada-SDK":`headless-sdk/${z}`,...i},c=a??this.apiKey??((m=this.getToken)==null?void 0:m.call(this));c&&(g["x-cms-token"]=c);let p=new AbortController,l=setTimeout(()=>p.abort(),this.timeout);try{let f=await fetch(u,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(l),f.ok){let h=await f.text();return h?JSON.parse(h):{}}throw await this.handleErrorResponse(f,e),new P("Unexpected error","unknown",f.status)}catch(f){throw clearTimeout(l),f instanceof P?f:f instanceof DOMException&&f.name==="AbortError"?new R(`Request to ${e} timed out after ${this.timeout}ms.`):new R(f instanceof Error?f.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=mt(n.data),i=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 L(i);case 404:throw new v(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new M(i,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new D(a)}default:throw new P(i,"api_error",e.status,n)}}};function mt(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var O=class s{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 i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(d=this.onSession)==null||d.call(this,o)}catch{}return o}async createSession(e){var d,u,g;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,...c.sellingPlanId!==void 0?{sellingPlanId:c.sellingPlanId}:{},...c.trialDays!==void 0?{trialDays:c.trialDays}:{},...c.trialPrice!==void 0?{trialPrice:c.trialPrice}:{},quantity:c.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),(u=e.customerTags)!=null&&u.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 i=await this.http.post("/api/v1/checkout/session/init",n),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,i=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),d=`${o}${t}?${a.toString()}`;return{...i,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 i=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:i}}parseTokensFromUrl(e){return s.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),i=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:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=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:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return gt({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]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=i.map(c=>{let p=c.price,l=c.variant??(p==null?void 0:p.variant)??{},m=c.product??l.product??{},f=(p==null?void 0:p.currencyOptions)??{},h=(a?f[a]:void 0)??f[Object.keys(f)[0]],C=(h==null?void 0:h.amount)??0;return{id:c.id,variantId:c.variantId,priceId:c.priceId,productName:m.name??"",variantName:l.name??"",quantity:c.quantity??1,unitAmount:C,totalAmount:C*(c.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),u=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??u.reduce((c,p)=>c+(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}},Le=O.parseTokensFromUrl;function gt(s){let e={};for(let[t,n]of Object.entries(s))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function ie(s){var t,n;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(n=s.addressLines)==null?void 0:n[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Me(e)?e:void 0}function oe(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Me(n)?n:void 0}function Me(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var De="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-pixels.min.js";function He(s,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function ht(){if(typeof window>"u")return null;if(De){let s=window;return s.TagadaPixels?s.TagadaPixels:(await He(De,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ue="__tgd_track",ft="__tgd_aid",yt="__tgd_sid",Fe=50,Pt=2e3,qe=1e3,Ct=64;function ae(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function $e(s){if(!s)return;let e={};for(let[t,n]of Object.entries(s))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var St={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function ye(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function wt(s){let e={};for(let t of s){let{provider:n,id:r,idKey:i,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[i]:r,events:t.events??{}})}return e}var U=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(Ue)??"").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(Ue,`${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}`,i=Date.now(),o=this.lastStep.get(r);o!==void 0&&i-o<qe||(this.remember(r,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,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=St[e],i=`${r??e}_${ye()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:$e(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...$e(t)??{},step_id:n,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=qe&&this.lastStep.delete(n);for(;this.lastStep.size>=Ct;){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 i;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(i=n.items)==null?void 0:i.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:fe,version:z},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(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await He(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.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 ht();if(n===null)return null;let r=n.createPixelEngine({pixels:wt(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.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>=Fe){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),Pt))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=ye();return n.setItem(t,i),i}catch{return ye()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Fe),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:fe,version:z},anonymousId:this.identifier("local",ft),sessionId:this.identifier("session",yt),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 Ce="crypto_onchain",je=5e3,de=["paid","underpaid","failed","expired"];function Ge(s){return s?s.trim().toLowerCase().replace(/-/g,"_").split(":")[0]===Ce:!1}function Se(s){let e=s.filter(r=>r.assets.length>0),t=e.find(r=>!r.testnet)??e[0];if(!t)return null;let n=t.assets.find(r=>r.stable)??t.assets[0];return{chainId:t.chainId,asset:n.symbol}}function we(s,e,t){var o,a;let n=((o=s.find(d=>d.chainId===e))==null?void 0:o.assets)??[],r=n.find(d=>d.symbol===t),i=n.find(d=>d.stable)??n[0];return{chainId:e,asset:((a=r??i)==null?void 0:a.symbol)??t}}function ke(s){if(!s)return"waiting";if(s.paid)return"paid";switch(s.status){case"detected":case"overpaid":return"confirming";case"underpaid":return"underpaid";case"failed":return"failed";case"expired":return"expired";default:return s.expired?"expired":"waiting"}}function ce(s,e){if(!s)return 0;let t=Date.parse(s);return Number.isNaN(t)?0:Math.max(0,Math.floor((t-e)/1e3))}function Be(s){let e=Math.max(0,Math.floor(s)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=String(e%60).padStart(2,"0");return t>0?`${t}:${String(n).padStart(2,"0")}:${r}`:`${n}:${r}`}var Pe="Crypto payments are not available right now. Choose another payment method.",F=class{constructor(e,t){this.api=e;this.options=t;this.state={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null};this.listeners=new Set;this.pollTimer=null;this.stopped=!1;this.paidNotified=!1;this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this)}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPhase(e=Date.now()){let{payment:t,paymentStatus:n}=this.state,r=ke(n??(t?{status:t.status,paid:!1,expired:!1}:null));return t!==null&&r==="waiting"&&ce(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return ce(((t=this.state.payment)==null?void 0:t.expiresAt)??null,e)}async loadOptions(){this.setState({options:"loading",error:null});try{let e=await this.api.getCryptoOnchainOptions(this.options.checkoutSessionId);if(!e.ok)return this.setState({options:"unavailable",networks:[],selection:null,error:e.message||Pe}),this.state;let t=this.state.selection??Se(e.networks);this.setState(t?{options:"ready",networks:e.networks,selection:t}:{options:"unavailable",networks:e.networks,selection:null,error:Pe})}catch(e){this.setState({options:"unavailable",error:Ke(e)})}return this.state}select(e){let t=this.state.selection;if(e.chainId!==void 0&&e.chainId!==(t==null?void 0:t.chainId)){this.setState({selection:we(this.state.networks,e.chainId,e.asset??(t==null?void 0:t.asset)??"")});return}e.asset!==void 0&&t&&this.setState({selection:{...t,asset:e.asset}})}async pay(e){let t=e??this.state.selection;if(!t)return{ok:!1,code:"ASSET_NOT_AVAILABLE",message:"Choose a network and a coin"};if(this.state.isCreating)return{ok:!1,code:"CHECKOUT_FAILED",message:"A payment is already being created"};this.setState({isCreating:!0,error:null,selection:t});try{let n=await this.api.createCryptoOnchainPayment({checkoutSessionId:this.options.checkoutSessionId,chainId:t.chainId,asset:t.asset});return n.ok?(this.stopped=!1,this.setState({isCreating:!1,payment:n.payment,paymentStatus:null}),this.schedulePoll(),n):(this.setState({isCreating:!1,error:n.message}),n)}catch(n){let r=Ke(n);return this.setState({isCreating:!1,error:r}),{ok:!1,code:"CHECKOUT_FAILED",message:r}}}async refreshStatus(){var t,n,r;let e=this.state.payment;if(!e)return null;try{let i=await this.api.getCryptoOnchainStatus({checkoutSessionId:this.options.checkoutSessionId,cryptoOnchainPaymentId:e.cryptoOnchainPaymentId});if(!i.ok||((t=this.state.payment)==null?void 0:t.cryptoOnchainPaymentId)!==e.cryptoOnchainPaymentId)return null;let o={status:i.status,paymentId:i.paymentId,orderId:i.orderId,confirmations:i.confirmations,requiredConfirmations:i.requiredConfirmations,txHash:i.txHash,explorerTxUrl:i.explorerTxUrl,paid:i.paid,expired:i.expired,redirectUrl:i.redirectUrl};return this.setState({paymentStatus:o}),o.paid&&!this.paidNotified&&(this.paidNotified=!0,(r=(n=this.options).onPaid)==null||r.call(n,o)),o}catch{return null}}resume(){!this.state.payment||de.includes(this.getPhase())||(this.stopped=!1,this.schedulePoll())}stop(){this.stopped=!0,this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=null}schedulePoll(){this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.refreshStatus(),!this.stopped&&!de.includes(this.getPhase())&&this.schedulePoll()},this.options.pollIntervalMs??5e3)}setState(e){var t,n;this.state={...this.state,...e},(n=(t=this.options).onChange)==null||n.call(t,this.state),this.listeners.forEach(r=>r(this.state))}};function Ke(s){return s instanceof Error&&s.message?s.message:Pe}var kt="https://secure.oceanpayment.com/pages/js/oceanpayment.js",Ie="oceanpayment-element";var vt={fi:"en"};function Ve(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?vt[e]??e:"en"}var It=3e4,J=null;function ze(){let s=window;return s.Oceanpayment?Promise.resolve(s.Oceanpayment):J||(J=new Promise((e,t)=>{let n=document.createElement("script"),r=o=>{clearTimeout(i),n.remove(),J=null,t(new Error(o))},i=setTimeout(()=>r("The Ocean Payment card form took too long to load"),It);n.addEventListener("load",()=>{if(!s.Oceanpayment)return r("Ocean Payment script loaded without window.Oceanpayment");clearTimeout(i),e(s.Oceanpayment)}),n.addEventListener("error",()=>r("Failed to load the Ocean Payment card form")),n.src=kt,document.head.appendChild(n)}),J)}var ve="tgd:headless:oceanpayment:pending",bt=30*60*1e3;function Je(s){try{sessionStorage.setItem(ve,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function xt(){try{let s=sessionStorage.getItem(ve);if(!s)return;sessionStorage.removeItem(ve);let{paymentId:e,at:t}=JSON.parse(s);return!e||!t||Date.now()-t>bt?void 0:e}catch{return}}function Ye(){if(typeof window>"u")return;let s=xt();if(s)try{let e=new URL(window.location.href);if(e.searchParams.get("paymentId"))return;e.searchParams.set("paymentId",s),e.searchParams.set("paymentAction","requireAction"),e.searchParams.set("paymentActionStatus","completed"),window.history.replaceState(window.history.state,"",e.toString())}catch{}}var Qe=new Set(["failed","declined","rejected","error"]),q=null,At=()=>!!q&&(!q.attached||q.element.isConnected),We=Symbol("ocean-timed-out"),Ze=Symbol("ocean-unmounted"),Ot=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Tt(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,n=s.settings??{},r=n.processors,i=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Ot.has(t),integrationId:e?void 0:s.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}function _t(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let s=()=>window.Stripe,e=s();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 i=s();i?t(i):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}var $=class{constructor(e,t,n,r,i,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=i;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 i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof v))throw i}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(Tt):(t==null?void 0:t.methods)??[],r={};for(let i of n){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;r[o]=i}return r}async getExpressMethods(e,t){var i,o,a,d,u,g,c,p,l,m;let n=await this.getPaymentSetup(e,t),r={};for(let[f,h]of Object.entries(n)){if(!h.enabled)continue;if(f.startsWith("express_checkout:")&&h.methods){let b={available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if((i=h.methods.apple_pay)!=null&&i.enabled){let y=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...b,type:"apple_pay",available:!!y}}(d=h.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...b,type:"google_pay"}),(g=h.methods.link)!=null&&g.enabled&&(r.link={...b,type:"link"}),(c=h.methods.klarna_express)!=null&&c.enabled&&(r.klarna={...b,type:"klarna_express"});continue}if(!h.express)continue;let C=h.method,w={type:C,available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if(C==="apple_pay"||h.type==="apple_pay"){let b=typeof window<"u"&&"ApplePaySession"in window&&((l=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:l.call(p));r.applePay={...w,available:!!b}}else C==="google_pay"||h.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((m=this.onSignal)==null||m.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=w):C==="paypal"?r.paypal=w:C==="klarna"||C==="klarna_express"?r.klarna=w:C==="link"&&(r.link=w)}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 i=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(i,n.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress: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 i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:n,billingAddress:r})}async processApplePay(e){var a,d,u,g,c,p,l,m,f;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:ie(e.shippingContact),billingAddress:ie(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((c=e.shippingContact)==null?void 0:c.givenName)??((p=e.billingContact)==null?void 0:p.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((m=e.billingContact)==null?void 0:m.familyName)});let t=e.merchantRegistrationId??((f=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:f.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let i=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(i,"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=i=>{var o;for(let a of Object.values(i??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!d||typeof d!="object")continue;let u=d[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.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,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:oe(e.shippingAddress),billingAddress:oe(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)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async getCryptoOnchainOptions(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e)}/crypto-onchain/options`)}async createCryptoOnchainPayment(e){return this.http.post(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/session`,{chainId:e.chainId,asset:e.asset})}async getCryptoOnchainStatus(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/status`,{params:{cryptoOnchainPaymentId:e.cryptoOnchainPaymentId}})}createCryptoOnchainCheckout(e){return new F(this,e)}async getOceanPaymentConfig(e){let t=await this.http.post(`/api/v1/checkout-sessions/${e}/oceanpayment-embedded-config`,{});return{embedded:!!(t!=null&&t.embedded),sandboxed:!!(t!=null&&t.sandboxed)}}async mountOceanPayment(e){if(typeof window>"u")throw new Error("Ocean Payment needs a browser");let{checkoutSessionId:t,signal:n}=e,r=()=>Object.assign(new Error("Ocean Payment mount aborted"),{name:"AbortError"});if(n!=null&&n.aborted)throw r();let i=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!i&&e.mode!=="redirect")throw new Error(`Ocean Payment container not found: ${String(e.container)}`);if(At()||document.getElementById(Ie))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=Ie;let d={element:a,attached:!1};q=d;let u=()=>{q===d&&(q=null)},g=!0,c=null,p=y=>{let k=c;c=null,k==null||k(y)},l=()=>{g&&(g=!1,o.oceanpaymentCallBack===p&&delete o.oceanpaymentCallBack,a.remove(),u(),p(Ze))};n==null||n.addEventListener("abort",l,{once:!0});let m,f;try{if(m=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||m.embedded&&(f=await ze(),n!=null&&n.aborted))throw r()}catch(y){throw l(),y}let h=!1;if(!f)return u(),{mode:"redirect",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let y=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(y!=null&&y.url)||!y.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:y.url,method:"GET",paymentId:y.paymentId}}catch(y){return{status:"failed",error:y instanceof Error?y.message:String(y)}}finally{h=!1}},unmount:l};let C=f;i.appendChild(a),d.attached=!0,o.oceanpaymentCallBack=p;let w=window.location.href;return C.init(m.sandboxed,"",Ve(e.locale),{showCardName:!1}),{mode:"embedded",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment card form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let y=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:w});if(!(y!=null&&y.paymentId)||!y.params)return{status:"failed",error:"Failed to start the payment"};let k=y.paymentId,x=await new Promise(_e=>{let st=setTimeout(()=>{c=null,_e(We)},12e4);c=it=>{clearTimeout(st),_e(it)},C.checkout(y.params)});if(x===We||x===Ze)return this.pollUntilDone(k);if(x&&typeof x=="object"&&"msg"in x)return{status:"failed",error:String(x.msg||"Please check your card details.")};let S=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:k,response:String(x)});return(S==null?void 0:S.status)==="requires_action"&&S.payUrl?(Je(k),{status:"requires_redirect",redirectUrl:S.payUrl,method:"GET",paymentId:k}):(S==null?void 0:S.status)==="succeeded"||(S==null?void 0:S.status)==="pending"?this.pollUntilDone(k):{status:"failed",error:(S==null?void 0:S.message)||"Payment declined"}}catch(y){return{status:"failed",error:y instanceof Error?y.message:String(y)}}finally{h=!1}},unmount:l}}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,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((i=e.order)==null?void 0:i.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;e!=null&&e.url||Ye();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"),i=n.searchParams.get("paymentActionStatus"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>d.delete(g));let u=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}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,i=Date.now();for(;Date.now()-i<r;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||Qe.has(o.status))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 i,o;let n=(i=t.metadata)==null?void 0:i.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 i,o;let n=(o=(i=e.requireActionData)==null?void 0:i.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 i=await _t(),{radarSession:o,error:a}=await i(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(i){return{status:"failed",error:i instanceof Error?i.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,i=Date.now(),o=0;for(;Date.now()-i<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(u=>setTimeout(u,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(Qe.has(d.status))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(u=>setTimeout(u,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:ae(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 I=typeof document>"u"?null:document.currentScript,Et=I!=null&&I.src?new URL("tagada-headless-commerce.min.js",I.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-headless-commerce.min.js",ue;function H(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(ue||(ue=new Promise((s,e)=>{let t=document.createElement("script");t.src=Et,t.async=!0,I!=null&&I.nonce&&(t.nonce=I.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(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(s=>{throw ue=void 0,s})),ue)}var T=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=H().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])T.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var _=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=H().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])_.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var E=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=H().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s 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"])E.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var K=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var r,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var j=class{constructor(e,t,n,r,i){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=i}async navigate(e){var a,d;let t=this.checkout.getCurrentSession();if(!t)throw new P("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 P("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 i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(d=this.onFunnelSession)==null||d.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:i}}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 i=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)??Nt(),userAgent:Lt(),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=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var c,p,l,m;let{funnelSessionId:t,stepId:n,session:r,input:i,currentUrl:o}=e,a=r.items.map(f=>({variantId:f.variantId,priceId:f.priceId,quantity:f.quantity})),d=i.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),u={email:((c=i.customer)==null?void 0:c.email)??((p=r.customer)==null?void 0:p.email),currency:((l=i.customer)==null?void 0:l.currency)??r.currency,locale:(m=i.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:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function Nt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Lt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var le=(s,e)=>e!==null&&String(s).trim().toLowerCase()===e.trim().toLowerCase();function be(s,e,t={}){if(s.visible===!1||s.type==="file")return!1;let n=s.rules??[];return n.length===0?!0:n.some(r=>{let i=o=>{if(o.basedOn==="state")return le(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return le(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=>le(d,o.answer)):le(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(i):r.requirements.some(i)})}function Xe(s,e,t={}){let n=[];for(let r of s){if(r.visible===!1){r.defaultValue&&n.push({questionId:r.title,question:r.title,value:r.defaultValue,type:"string"});continue}if(!be(r,e,t))continue;let i=e[r.externalQuestionId];i===void 0||typeof i=="string"&&i.trim()===""||n.push({questionId:r.title,question:r.title,value:i,type:r.type==="number"?"number":r.type==="boolean"?"boolean":"string",...r.options.length>0?{displayedOptions:r.options.map(o=>o.label)}:{}})}return n}var G=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 B=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,i;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.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,i;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)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.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 Y=class{constructor(e){let t=e.environment??"production",n=A.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new A({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new U(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new B(()=>this.track.core(),this.config.bootstrap);let r=i=>{this._sessionToken=i};this.checkout=new O(this.http,this.config.storeId,r,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:ae(i.items)})),this.payment=new $(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new T(this.http,this.config.storeId,this.payment),this.customer=new _(this.http,this.config.storeId),this.portal=new E(this.http,this.config.storeId,r),this.catalog=new K(this.http,this.config.storeId),this.funnel=new j(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new G(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function et(s){return new Y(s)}var tt=!1,nt=!1,pe=[];function xe(){nt=!0;for(let s of pe)s();pe.length=0}function Re(s,e={}){var t,n;return nt||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(xe(),Promise.resolve()):tt?new Promise(r=>pe.push(r)):(tt=!0,new Promise((r,i)=>{if(pe.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,c;(c=(g=window.google)==null?void 0:g.maps)!=null&&c.places?xe():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${a}`,d.async=!0,d.defer=!0,d.onload=()=>xe(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var Q=class s{static async searchPlaces(e,t={}){var r,i;if(!((i=(r=window.google)==null?void 0:r.maps)!=null&&i.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 u,g,c;o(d===((c=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:c.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(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var d,u,g;i(a===((g=(u=(d=window.google)==null?void 0:d.maps)==null?void 0:u.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="",i="",o="",a="",d="",u="",g="";for(let l of e.address_components??[]){let m=l.types;m.includes("subpremise")&&(t.subpremise=l.long_name),m.includes("street_number")&&(t.streetNumber=l.long_name),m.includes("premise")&&(n=l.long_name),m.includes("route")&&(t.route=l.long_name),m.includes("neighborhood")&&(r=l.long_name),m.includes("sublocality_level_5")&&(i=l.long_name),m.includes("sublocality_level_4")&&(o=l.long_name),m.includes("sublocality_level_3")&&(a=l.long_name),m.includes("sublocality_level_2")&&(d=l.long_name),m.includes("sublocality_level_1")&&(u=l.long_name),m.includes("locality")&&(t.locality=l.long_name),m.includes("postal_town")&&(g=l.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),m.includes("country")&&(t.country=l.short_name),m.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=g||d||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let c=t.streetNumber||n,p=t.route||i||o||a||r;if(t.subpremise&&c&&p)t.fullStreetAddress=`${t.subpremise}/${c} ${p}`;else if(c&&p)if(n&&o&&a){let l=`${a}-${o}-${n}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${c} ${p}`;else p?t.fullStreetAddress=p:c&&(t.fullStreetAddress=c);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var rt="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",Z=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],W=new Map,me=new Map,Ae=new Map,Oe=new Map;async function Mt(s){let e=W.get(s);if(e)return e;let t=Ae.get(s);return t||(t=(async()=>{let n=`${rt}/${s}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return W.set(s,i),Ae.delete(s),i})(),Ae.set(s,t),t)}async function Dt(s){let e=me.get(s);if(e)return e;let t=Oe.get(s);return t||(t=(async()=>{let n=`${rt}/${s}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return me.set(s,i),Oe.delete(s),i})(),Oe.set(s,t),t)}function Ut(s){return W.get(s)||W.get("en")||{}}function Ft(s){return me.get(s)||me.get("en")||{}}async function X(s="en"){await Promise.all([Mt(s),Dt(s)])}var V=(s="en")=>{let e=Ut(s);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))},ee=(s,e="en")=>{let n=Ft(e)[s];return n?n.map(([r,i])=>({code:r,name:i,countryCode:s})).sort((r,i)=>r.name.localeCompare(i.name)):[]};function te(s){return W.has(s)}var ne=class s{static ensureLoaded(e="en"){return X(e)}static getCountries(e="en"){let t=V(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 V(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return ee(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return s.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let i=s.getRegions(n,r);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return te(e)}static getAvailableLanguages(){return Z}};var qt={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"},$t={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"},Ht=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),N=class s{static getSymbol(e){return qt[e]??e}static getName(e){return $t[e]??e}static getDecimalPlaces(e){return Ht.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function Te(s,e="USD",t="en-US"){let n=N.getDecimalPlaces(e),r=s/(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`${N.getSymbol(e)}${r.toFixed(n)}`}}return pt(Kt);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|