var aliaLauncher=function(exports){"use strict";var K=Object.defineProperty;var W=(e,t,r)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var S=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);function assertNever(e,t){throw new Error(`Unhandled discriminated union member: ${JSON.stringify(e)}`)}const JWT_HEADER="x-alia-jwt",SHOP_HEADER="x-alia-shop",SHOPIFY_CUSTOMER_ID_HEADER="x-alia-shopify-customer-id",PREVIEW_KEY_HEADER="x-alia-preview-key",ALL_EU_COUNTRIES=["AT","BE","BG","HR","CH","CY","CZ","DK","EE","FI","FR","DE","GB","GR","HU","IE","IS","IT","LI","LV","LT","LU","MT","NO","NL","PL","PT","RO","SK","SI","ES","SE"],ALL_EU_COUNTRIES_LABEL="_allEUCountries";function isAllEUCountries(e){return e===ALL_EU_COUNTRIES_LABEL}function getAllCountryCodes(e){return e.flatMap(t=>isAllEUCountries(t)?ALL_EU_COUNTRIES:[t])}function glob(e,t){return new RegExp("^"+e.replace(/([.?+^$[\]\\(){}|/-])/g,"\\$1").replace(/\*/g,".*")+"$").test(t)}const getStorage=e=>e==="local"?localStorage:sessionStorage;function getFromStorage(e,t){try{const n=getStorage(e).getItem(t);return n?JSON.parse(n):null}catch(r){return console.error(`Error getting ${t} from ${e}Storage:`,r),null}}function setInStorage(e,t,r){try{getStorage(e).setItem(t,JSON.stringify(r))}catch(n){console.error(`Error setting ${t} in ${e}Storage:`,n)}}function unknownErrToStr(e){return typeof e=="string"?e:e instanceof Error?e.message:typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"?e.error:"An unknown error occurred"}async function wait(e){return new Promise(t=>setTimeout(t,e))}async function timeout(e,t){return Promise.race([wait(e),t()])}function createSDKMessages(e){const t=i(e)?e:[],r=new Map;function n(...u){var d;t.push(...u);for(const I of u)(d=r.get(I.type))==null||d.forEach(m=>m(I))}function s({type:u,callback:d,retroactive:I=!1}){const m=d,h=r.get(u)??[];return h.push(m),r.set(u,h),I&&t.filter(c=>c.type===u).forEach(m),()=>{r.set(u,h.filter(P=>P!==d))}}function a(u){n({type:"open",triggerID:u})}function o(){n({type:"close"})}return{push:n,listen:s,open:a,close:o};function g(u){return typeof u=="object"&&u!==null&&"type"in u&&typeof u.type=="string"}function i(u){return Array.isArray(u)&&u.every(g)}}const getDocument=()=>document;function getWindowProperty(e){return window[e]}function setWindowProperty(e,t){window[e]=t}async function loadScript(e){return new Promise((t,r)=>{const n=getDocument().createElement("script");n.src=e,n.async=!0,n.onload=()=>t(n),n.onerror=()=>r(new Error("Failed to load Alia script")),getDocument().head.appendChild(n)})}class Logger{constructor(){S(this,"debugExtensionEnabled",!1);S(this,"appName","launcher");window.postMessage({type:"alia:loaded"},"*"),window.addEventListener("message",t=>{t.data&&t.data.type==="alia:debug_extension_enabled"&&(this.debugExtensionEnabled=!0)})}log(...t){console.log(`[Alia ${this.appName}]`,...t)}debug(...t){this.debugExtensionEnabled&&console.log(`%c[Alia ${this.appName} debug]`,"color: cyan",...t)}error(...t){console.error(`[Alia ${this.appName}]`,...t)}}const logger=new Logger;function attempt(e){try{e()}catch(t){logger.error(t)}}function interceptNavigation({onLinkClick:e,onHistoryChange:t}){getDocument().addEventListener("click",s=>{if(s.target instanceof HTMLElement){const a=s.target.closest("a");a&&(e==null||e(a))}});const r=history.pushState;history.pushState=function(s,a,o){let g;try{g=t==null?void 0:t(o)}catch(i){logger.error("Error intercepting navigation",i)}return r.call(this,s,a,g??o)};const n=history.replaceState;history.replaceState=function(s,a,o){let g;try{g=t==null?void 0:t(o)}catch(i){logger.error("Error intercepting navigation",i)}return n.call(this,s,a,g??o)}}const ALIA_JWT_KEY="alia-jwt";async function launcherFetch({method:e,path:t,args:r,headers:n,keepAlive:s}){var m;const a="body"in r,o=getJWT(),{key:g}=getPreview(),i=(m=shopifyExtensionInfo())==null?void 0:m.customerID,u=await fetch(I(t,"params"in r&&r.params,"query"in r&&r.query),{method:e,keepalive:s,headers:{...a?{"Content-Type":"application/json"}:{},[SHOP_HEADER]:SHOP(),...o?{[JWT_HEADER]:o}:{},...g?{[PREVIEW_KEY_HEADER]:g}:{},...i?{[SHOPIFY_CUSTOMER_ID_HEADER]:i}:{},...n},...a?{body:JSON.stringify("body"in r?r.body:void 0)}:{}});if(u.status===204)return;const d=await u.json();if(u.ok)return d;throw typeof d!="object"||d==null?new Error("An unknown error occurred"):"error"in d&&typeof d.error=="string"?new Error(d.error):new Error("An unknown error occurred");function I(h,P,c){const p=new URL("https://backend.alia-cloudflare.com");for(const[l,w]of Object.entries(P))h=h.replace(`:${l}`,String(w));p.pathname=`/launcher${h}`;for(const[l,w]of Object.entries(c))w!=null&&p.searchParams.set(l,String(w));return p.toString()}}const memStorage=(()=>{const e={};return{setItem:(t,r)=>{e[t]=r},getItem:t=>e[t]}})();function jwtStorages(){const e=[sessionStorage,memStorage];return getPreview().key||e.unshift(localStorage),e}function saveJWT(e){for(const t of jwtStorages())try{t.setItem(ALIA_JWT_KEY,e)}catch{}}function getJWT(){for(const e of jwtStorages())try{const t=e.getItem(ALIA_JWT_KEY);if(t)return t}catch{}return null}function getPreview(){const e="alia_preview_key",t=new URLSearchParams(window.location.search),r=t.get("alia_preview_key");r&&sessionStorage.setItem(e,r);const n=t.get("flow_id"),s=n?parseInt(n):void 0;return{key:sessionStorage.getItem(e),flowID:Number.isNaN(s)?void 0:s}}function getStorageType(){return getPreview().key?"session":"local"}const URL_STORAGE_PARAM="alia_user";function extractJWTFromURL(){attempt(()=>{const t=new URL(window.location.href).searchParams.get(URL_STORAGE_PARAM);if(t){const r=atob(t);saveJWT(r)}return null})}function appendJWTOnDomainChange(e,t){attempt(()=>{const r=[(t==null?void 0:t.primaryDomain)??"",...(t==null?void 0:t.otherDomains)??[]].filter(a=>!!a);if(r.length<=1)return;const n=r.map(a=>new URL(a)).filter(a=>a.hostname!==window.location.hostname),s=a=>(a.searchParams.set(URL_STORAGE_PARAM,btoa(e)),a);interceptNavigation({onLinkClick:a=>{n.some(o=>o.hostname===a.hostname)&&(a.href=s(new URL(a.href)).toString())},onHistoryChange:a=>{if(a)return s(new URL(a)).toString()}})})}function logError(e){return launcherFetch({method:"POST",path:"/errors",args:{body:e}})}async function upsertManyUserFlows(e){return await launcherFetch({method:"POST",path:"/user-flows",args:{body:e}})}async function upsertForPreviewUserFlow(e){return await launcherFetch({method:"POST",path:"/user-flows/preview",args:{body:e}})}async function updateUser(e){return await launcherFetch({method:"POST",path:"/users",args:{query:e}})}async function createUserAction(e){return await launcherFetch({method:"POST",path:"/user-actions",args:{body:e}})}const STORAGE_KEY="alia-user-actions";function getInitialUserActions(e){const t=[...e],r=getFromStorage(getStorageType(),STORAGE_KEY)??[];for(const n of r)n.id&&t.some(s=>s.id===n.id)||t.push(n);return t}class UserActionsStore{constructor(t){S(this,"mediator");this.mediator=t}setActions(t){const r=this.mediator.update(n=>({...n,actions:t(n.actions)}));setInStorage(getStorageType(),STORAGE_KEY,r.actions)}addActions(...t){this.setActions(r=>[...r,...t])}updateByCreatedAt(t,r){this.setActions(n=>n.map(s=>s.createdAt===t&&s.type===r.type?r:s))}async createAction(t){try{const r=new Date().toISOString();this.addActions({...t,type:t.data.type,createdAt:r});const n=await createUserAction(t);this.updateByCreatedAt(r,n)}catch(r){logError({message:`Failed to create ${t.data.type} user action`,data:{action:t,error:unknownErrToStr(r)}})}}}class Mediator{constructor(t){S(this,"state");S(this,"subscriptions",[]);S(this,"userActionsStore");this.state=t,this.userActionsStore=new UserActionsStore(this)}update(t){return this.state={...this.state,...t(this.state)},this.subscriptions.forEach(r=>r(this.state)),this.state}subscribe(t){return this.subscriptions.push(t),()=>{this.subscriptions=this.subscriptions.filter(r=>r!==t)}}}class SessionTracker{constructor(t,r){S(this,"isNewSession");S(this,"flowID",null);S(this,"onEngaged",null);this.flowID=t??null,this.onEngaged=r??null,this.setupEngagedListeners(),getFromStorage("session",this.getStorageKey())?this.isNewSession=!1:(this.isNewSession=!0,this.setValue({start:Date.now(),isEngaged:!1}))}getStorageKey(){return`alia-session${this.flowID?`-${this.flowID}`:""}`}getValue(){return getFromStorage("session",this.getStorageKey())}setValue(t){setInStorage("session",this.getStorageKey(),t)}setupEngagedListeners(){interceptNavigation({onLinkClick:t=>{t.href&&t.hostname===window.location.hostname&&this.handleEngagedSession()},onHistoryChange:()=>{this.handleEngagedSession()}})}handleNewSession(){this.isNewSession}handleEngagedSession(){var r;const t=this.getValue();t.isEngaged||(this.setValue({...t,isEngaged:!0}),(r=this.onEngaged)==null||r.call(this))}}async function registerForFlow(e){await launcherFetch({method:"POST",path:"/events/flow",args:e,keepAlive:!0})}class SessionEventRecorder{constructor(t){S(this,"tracker");S(this,"flowID",null);this.flowID=t??null,this.tracker=new SessionTracker(t,()=>{registerForFlow({query:{metric:"ENGAGED_SESSION"},body:{flowID:this.flowID}})})}handleNewSession(){this.tracker.isNewSession&®isterForFlow({query:{metric:"SESSION"},body:{flowID:this.flowID}})}}function safeEval(code){try{return eval(code)}catch(e){return logger.error("Error evaluating code",{code,error:unknownErrToStr(e)}),null}}async function evaluateKlaviyoIdentifiedCond(e){const t=await klaviyoIsIdentified();return t===void 0?"skip":e.type==="klaviyo.identified"?t:!t}async function klaviyoIsIdentified(){try{const{klaviyo:e}=await klaviyoObject(),t=await timeout(1e3,async()=>await(e==null?void 0:e.isIdentified()));return t===void 0?void 0:t===!0}catch{return}}async function evaluateKlaviyoListCond(e,{integrationUsers:t}){if(!e.listID)return!0;const r=e.listID;if(a()===!0||await getKDPResult(r)===!0)return e.type==="klaviyo.inList";return e.type!=="klaviyo.inList";function a(){var o,g;for(const i of t){if(i.data.type==="KLAVIYO")return((o=i.data.subscribedLists)==null?void 0:o.includes(r))??!1;if(i.data.type==="KLAVIYO_OAUTH")return((g=i.data.subscribedLists)==null?void 0:g.includes(r))??!1}return!1}}async function evaluateKlaviyoSegmentCond(e){if(!e.segmentID)return!0;const t=e.segmentID;return await getKDPResult(t)===!0?e.type==="klaviyo.inSegment":e.type!=="klaviyo.inSegment"}const kdpResults=new Map;async function getKDPResult(e){try{if(kdpResults.has(e))return kdpResults.get(e);const{klaviyo:t}=await klaviyoObject();if(!(t!=null&&t.getGroupMembership))return;const r=await timeout(1e3,async()=>await(t==null?void 0:t.getGroupMembership([e])));if(!Array.isArray(r))return;const n=r.includes(e);return kdpResults.set(e,n),n}catch{return}}async function klaviyoObject(){try{if(!Array.from(getDocument().scripts).find(n=>n.src.includes("klaviyo.js")))return{klaviyo:void 0};const t=()=>getWindowProperty("klaviyo");return t()?{klaviyo:t()}:await timeout(1e3,async()=>await new Promise(n=>{const s=setInterval(()=>{t()&&(n({klaviyo:t()}),clearInterval(s))},100)}))??{klaviyo:void 0}}catch{return{klaviyo:void 0}}}async function evaluateTargetingRuleCond(e,t){var s,a,o,g;if(t.evaluated.includes(e.resource.id))return"skip";const r=e.resource.type==="targetingRule"?(a=(s=t.targetingRules)==null?void 0:s.rules.find(i=>i.id===e.resource.id))==null?void 0:a.config:(g=(o=t.segments.find(i=>i.id===e.resource.id))==null?void 0:o.targeting)==null?void 0:g.rule;if(!r)return"skip";const n=await evaluateTargetingRule(r,{...t,evaluated:[...t.evaluated,e.resource.id]});return n!=="skip"?e.type==="inTargetingRule"?n:!n:e.resource.type==="segment"&&e.type==="notInTargetingRule"?!1:"skip"}async function evaluateCustomCodeCond(e,t){return await Promise.race([safeEval(`(async ({ campaignID, profile: { user, actions } }) => { ${e.code} })(${JSON.stringify({campaignID:t.segmentID,profile:t})})`),wait(1e3)])===!0}const checkCookieMap={klaviyo:async()=>await klaviyoIsIdentified(),smsbump:async()=>{var e,t;return(t=(e=getWindowProperty("smsbump"))==null?void 0:e.isIdentified)==null?void 0:t.call(e)},unveild:async()=>{var e,t;return(t=(e=getWindowProperty("unveild"))==null?void 0:e.checkIfUserIdentified)==null?void 0:t.call(e)},upstack:async()=>{var e,t;return await((t=(e=getWindowProperty("_upsShopifyClient"))==null?void 0:e.isKnown)==null?void 0:t.call(e))}};async function evaluateCookieIdentificationCond(e,t){const n=(await Promise.all(Object.keys(checkCookieMap).filter(s=>!e.exclude.includes(s)).map(async s=>{try{const a=await checkCookieMap[s](t);return a===!0?!0:a===!1?!1:"skip"}catch{return"skip"}}))).some(s=>s===!0);return e.type==="cookie.identified"?n:!n}function evaluateNumFilter(e,t){switch(e.operator){case"eq":return t===e.value;case"neq":return t!==e.value;case"gt":return t>e.value;case"gte":return t>=e.value;case"lt":return tr;case"lt":return nnew URL(i)):[new URL(window.location.href)],o=(e.matchType==="exact"?e.values:e.matchType==="contains"?e.values.map(i=>`*${i}*`):assertNever(e.matchType)).some(i=>s.some(u=>g(e.pageType,u,i)));return e.type==="hasVisitedPage"||e.type==="isOnPage"?o:!o;function g(i,u,d){const I=i==="url"?u.toString():i==="path"?u.pathname+u.search:assertNever(i);return glob(m(d),m(I));function m(h){return h.replace(/\/$/,"")}}}function evaluateNumPagesViewedCond(e,{user:t}){var n;const r=(n=t.profile.history)==null?void 0:n.at(-1);return r?evaluateNumFilter(e.value,r.length):!1}function evaluateNumSessionsCond(e,{user:t}){var r;return evaluateNumFilter(e.value,((r=t.profile.history)==null?void 0:r.length)??0)}async function getCustomerPrivacy(){const e=getWindowProperty("Shopify");if(!e)return{};const t=new Promise(r=>{e==null||e.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],r)});return await Promise.race([t,wait(1e3)]),e.customerPrivacy?{marketingAllowed:e.customerPrivacy.marketingAllowed(),saleOfDataAllowed:e.customerPrivacy.saleOfDataAllowed(),analyticsProcessingAllowed:e.customerPrivacy.analyticsProcessingAllowed(),preferencesProcessingAllowed:e.customerPrivacy.preferencesProcessingAllowed()}:{}}function evaluateShopifyNumOrdersCond(e,t){return evaluateNumFilter(e.value,t.user.shopifyNumOrders??0)}function evaluateShopifyCountriesCond(e,t){const r=t.user.country;if(r===null)return!0;const n=getAllCountryCodes(e.countries).includes(r);return e.type==="shopify.inCountries"?n:!n}function evaluateMarketsCond(e,t){const r=t.user.market;return r===null?!0:e.type==="shopify.inMarkets"?e.markets.includes(r):!e.markets.includes(r)}function evaluateLocalesCond(e,t){const r=t.user.language;return r===null?!0:e.type==="shopify.inLocales"?e.locales.includes(r):!e.locales.includes(r)}async function evaluateCustomerPrivacyCond(e){const{marketingAllowed:t,saleOfDataAllowed:r,analyticsProcessingAllowed:n,preferencesProcessingAllowed:s}=await getCustomerPrivacy();return e.consentTypes.some(o=>{switch(o){case"marketing":return t;case"saleOfData":return r;case"analyticsProcessing":return n;case"preferencesProcessing":return s}})}function evaluateUtmSourceCond(e,t){const r=getLatestParamValue("utm_source",t.user),n=e.values.includes(r);return e.type==="traffic.utmSourceIsIn"?n:!n}function evaluateUtmMediumCond(e,t){const r=getLatestParamValue("utm_medium",t.user),n=e.values.includes(r);return e.type==="traffic.utmMediumIsIn"?n:!n}function getLatestParamValue(e,{profile:t}){const r=t.history.flat();for(const n of r.reverse()){const a=new URL(n).searchParams.get(e);if(a)return a}return null}function evaluateUserCreatedAtCond(e,t){return evaluateRelativeDateFilter(e.value,new Date(t.user.createdAt))}function evaluateUserDeviceCond(e,t){const r=t.user.isMobile;return r===null?!0:e.device==="mobile"?r:!r}function evaluateUserCountriesCond(e,t){const r=t.user.ipCountry;if(r===null)return"skip";const n=getAllCountryCodes(e.countries).includes(r);return e.type==="user.inCountries"?n:!n}function evaluateUserRegionsCond(e,t){const r=t.user.ipRegion;return r===null?"skip":e.type==="user.inRegions"?e.regions.includes(r):!e.regions.includes(r)}function evaluateUserActionCond(e,t){const r=t.actions.some(n=>n.data.type!==e.action.type?!1:e.filters?evaluateUserActionFilters(n,e.filters):!0);return e.type==="user.hasDoneAction"?!!r:!r}function evaluateUserActionFilters(e,t){return t.every(s=>{switch(s.type){case"userAction.date":return r(s);case"userAction.inSegments":case"userAction.notInSegments":return n(s)}});function r(s){return evaluateRelativeDateFilter(s.value,new Date(e.createdAt))}function n(s){const a=s.segmentIDs.some(o=>e.segmentID===o);return s.type==="userAction.inSegments"?a:!a}}async function evaluateCond(e,t){switch(e.type){case"inTargetingRule":case"notInTargetingRule":return evaluateTargetingRuleCond(e,t);case"customCode":return await evaluateCustomCodeCond(e,t);case"klaviyo.identified":case"klaviyo.notIdentified":return await evaluateKlaviyoIdentifiedCond(e);case"klaviyo.inList":case"klaviyo.notInList":return await evaluateKlaviyoListCond(e,t);case"klaviyo.inSegment":case"klaviyo.notInSegment":return await evaluateKlaviyoSegmentCond(e);case"isOnPage":case"isNotOnPage":case"hasVisitedPage":case"hasNotVisitedPage":return evaluatePagesCond(e,t);case"pages.numPagesViewed":return evaluateNumPagesViewedCond(e,t);case"pages.numSessions":return evaluateNumSessionsCond(e,t);case"shopify.numOrders":return evaluateShopifyNumOrdersCond(e,t);case"shopify.inMarkets":case"shopify.notInMarkets":return evaluateMarketsCond(e,t);case"shopify.inLocales":case"shopify.notInLocales":return evaluateLocalesCond(e,t);case"shopify.inCountries":case"shopify.notInCountries":return evaluateShopifyCountriesCond(e,t);case"shopify.customerPrivacyAllowed":return evaluateCustomerPrivacyCond(e);case"user.createdAt":return evaluateUserCreatedAtCond(e,t);case"user.device":return evaluateUserDeviceCond(e,t);case"user.inCountries":case"user.notInCountries":return evaluateUserCountriesCond(e,t);case"user.inRegions":case"user.notInRegions":return evaluateUserRegionsCond(e,t);case"user.hasDoneAction":case"user.hasNotDoneAction":return evaluateUserActionCond(e,t);case"traffic.utmSourceIsIn":case"traffic.utmSourceIsNotIn":return evaluateUtmSourceCond(e,t);case"traffic.utmMediumIsIn":case"traffic.utmMediumIsNotIn":return evaluateUtmMediumCond(e,t);case"cookie.identified":case"cookie.notIdentified":return evaluateCookieIdentificationCond(e,t)}}async function evaluateTargetingRule(e,t){switch(e.type){case"and":return evaluateAndRule(e,t);case"or":return evaluateOrRule(e,t)}}async function evaluateAndRule(e,t){const r=await Promise.all(e.conds.map(n=>evaluateCond(n,t)));return r.some(n=>n===!1)?!1:r.some(n=>n==="skip")?"skip":!0}async function evaluateOrRule(e,t){const r=await Promise.all(e.conds.map(n=>evaluateCond(n,t)));return r.some(n=>n===!0)?!0:r.some(n=>n==="skip")?"skip":!1}async function evaluateTargeting({user:e,actions:t,targetingRules:r,segments:n,integrationUsers:s}){return(await Promise.all(n.map(async o=>{try{return await evaluateTargetingRule(o.targeting.rule,{user:e,actions:t,integrationUsers:s,evaluated:[],targetingRules:r,segments:n,segmentID:o.id})===!1?void 0:o.id}catch(g){logger.error(g),logError({message:"Error evaluating targeting rule",data:{error:unknownErrToStr(g)}});return}}))).filter(o=>o!==void 0)}const SHOP=()=>"raddish-kids.myshopify.com".substring(0);logger.log(SHOP());const BACKEND_URL="https://backend.alia-cloudflare.com",RELEASE_TAG="v3.0.63",MAX_TRIES=5,LOAD_SEGMENTS_INTERVAL=1e3,shopifyExtensionInfo=()=>getWindowProperty("ALIA_SHOPIFY_EXTENSION_INFO");getDocument().readyState!=="loading"?tryInit():getDocument().addEventListener("DOMContentLoaded",()=>{tryInit()},{once:!0});async function tryInit(e=MAX_TRIES){const t="ALIA_HAS_INITIALIZED";if(getWindowProperty(t)){logger.log("Alia already initialized");return}if(setWindowProperty(t,!0),r()){logger.log("Disabled for bot",navigator.userAgent);return}try{await init()}catch(n){if(e<=0){logger.error(`Failed after ${MAX_TRIES} tries`),logError({message:"Init failed",data:{error:unknownErrToStr(n)}});return}else logger.error("Init failed, trying again...",n),await wait(2e3),tryInit(e-1)}function r(){const n=navigator.userAgent;return["Googlebot","bingbot","facebookexternalhit","Storebot-Google","AmazonProductDiscovery","Petalbot","Pinterestbot","Applebot","Twitterbot","meta-externalads","AdsBot-Google"].some(s=>n.includes(s))}}async function init(){var I,m,h,P;const e=await g();extractJWTFromURL();const t=new SessionEventRecorder,{jwt:r,disabledReason:n,...s}=await updateUser({path:window.location.pathname+location.search,url:window.location.href,is_mobile:window.innerWidth<1024,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,ip_address:e,user_agent:navigator.userAgent,country:(I=shopifyExtensionInfo())==null?void 0:I.country,market:(m=shopifyExtensionInfo())==null?void 0:m.market,language:(h=shopifyExtensionInfo())==null?void 0:h.language,release_tag:RELEASE_TAG,new_session:t.tracker.isNewSession});if(saveJWT(r),appendJWTOnDomainChange(r,(P=s.merchant)==null?void 0:P.settings),n){logger.debug("Disabled",n);return}t.handleNewSession(),s.merchant.settings.internal.checkTargeting?o():a();async function a(){const{flowID:c,key:p}=getPreview(),l=c?[]:await evaluateTargeting(s);if(c)logger.debug("Previewing popup",c);else if(!l.length){logger.debug("No matching campaigns");return}const[w]=await Promise.all([(async()=>c?[await upsertForPreviewUserFlow({previewKey:p??"",flowID:c})]:upsertManyUserFlows({segmentIDs:l}))(),i()]);if(!w.length){logger.debug("No matching campaigns");return}w.forEach(({userFlow:y})=>{y&&logger.debug(`Matched campaign ${y.segmentID} (${y.segmentTitle}), serving flow ${y.flowID} (${y.flowTitle})`),new SessionEventRecorder(y==null?void 0:y.flowID).handleNewSession()}),setWindowProperty("alia",O());function O(){const y=getWindowProperty("alia"),D=createSDKMessages(y??[]),T=new Mediator({actions:getInitialUserActions(s.actions),modalFlowID:u(w),user:s.user}),L=w.map(k=>{const _=getDocument().createElement("div");return _.style.position="fixed",getDocument().body.appendChild(_),window.mountAliaCustomerApp({shop:SHOP(),jwt:r,useShadowDOM:k.settings.useShadowDOM,initialData:k,targetingArgs:s,target:_,messages:D,mediator:T})});return d(),{unmount:()=>L.forEach(k=>k()),push:D.push,messages:D,open:D.open,close:D.close,mediator:T}}}function o(){let c=!1,p,l,w;const O=[],y=[],D=[],T=[];L();async function L(){await k(),!getPreview().flowID&&setTimeout(L,LOAD_SEGMENTS_INTERVAL)}async function k(){var N;const{flowID:A}=getPreview(),C=new Set;A||((await evaluateTargeting({...s,segments:s.segments.filter(E=>!y.includes(E.id))})).forEach(E=>C.add(E)),O.forEach(E=>C.add(E)));const R=Array.from(C).filter(v=>!y.includes(v));if(c||(A?logger.debug("Previewing popup",A):R.length||logger.debug("No matching campaigns")),!R.length&&!A)return;y.push(...R);const[f]=await Promise.all([A?_():F(R),c?void 0:i()]);c||(p=getWindowProperty("alia"),l=createSDKMessages(p??[]),l.listen({type:"open",callback:({ignoreTargeting:v,campaignID:E})=>{const b=Number(E);v===!0&&!isNaN(b)&&s.segments.some(M=>M.id===b)&&O.push(b)},retroactive:!0}),w=new Mediator({actions:getInitialUserActions(s.actions),modalFlowID:u(f),user:s.user}));for(const v of f){if(!((N=v.userFlow)!=null&&N.flowID)||D.includes(v.userFlow.flowID))continue;D.push(v.userFlow.flowID);const E=getDocument().createElement("div");E.style.position="fixed",getDocument().body.appendChild(E),T.push(window.mountAliaCustomerApp({shop:SHOP(),jwt:r,useShadowDOM:v.settings.useShadowDOM,initialData:v,targetingArgs:s,target:E,messages:l,mediator:w}))}c||(c=!0,d(),setWindowProperty("alia",{unmount:()=>T.forEach(v=>v()),push:l.push,messages:l,open:l.open,close:l.close,mediator:w}))}async function _(){const{flowID:A,key:C}=getPreview();return A?[await upsertForPreviewUserFlow({previewKey:C??"",flowID:A})]:[]}const U=new Set;async function F(A){const R=(await upsertManyUserFlows({segmentIDs:A})).filter(({userFlow:f})=>!(f!=null&&f.flowID)||!U.has(f.flowID));return R.forEach(({userFlow:f})=>{f!=null&&f.flowID&&U.add(f.flowID),f&&logger.debug(`Matched campaign ${f.segmentID} (${f.segmentTitle}), serving flow ${f.flowID} (${f.flowTitle})`),new SessionEventRecorder(f==null?void 0:f.flowID).handleNewSession()}),R}}async function g(){try{const c=await fetch("https://api.ipify.org");return c.status!==200?void 0:await c.text()}catch{return}}async function i(){await loadScript(BACKEND_URL+`/public/app.js?tag=${encodeURIComponent(RELEASE_TAG)}`)}function u(c){for(const p of c.map(l=>l.userFlow)){const l=p==null?void 0:p.state.steps.at(-1);if((l==null?void 0:l.step)==="popup"&&!(l!=null&&l.floatingButton))return p==null?void 0:p.flowID}}function d(){try{const c=getWindowProperty("onAliaReady"),p=l=>{typeof l=="function"&&l()};Array.isArray(c)?c.forEach(p):p(c),setWindowProperty("onAliaReady",void 0),setTimeout(d,1e3)}catch(c){console.error("Error calling executeOnReady",c)}}}return exports.SHOP=SHOP,exports.shopifyExtensionInfo=shopifyExtensionInfo,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports}({});