"use strict";(()=>{var oe=Object.create;var T=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ae=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var le=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var ce=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of se(t))!de.call(e,o)&&o!==r&&T(e,o,{get:()=>t[o],enumerable:!(i=ne(t,o))||i.enumerable});return e};var he=(e,t,r)=>(r=e!=null?oe(ae(e)):{},ce(t||!e||!e.__esModule?T(r,"default",{value:e,enumerable:!0}):r,e));var Y=le((pt,J)=>{"use strict";var L=Object.defineProperty,ge=Object.getOwnPropertyDescriptor,me=Object.getOwnPropertyNames,we=Object.prototype.hasOwnProperty,fe=(e,t)=>{for(var r in t)L(e,r,{get:t[r],enumerable:!0})},ve=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of me(t))!we.call(e,o)&&o!==r&&L(e,o,{get:()=>t[o],enumerable:!(i=ge(t,o))||i.enumerable});return e},ye=e=>ve(L({},"__esModule",{value:!0}),e),H={};fe(H,{createContextualWidget:()=>at});J.exports=ye(H);var We=e=>!!e.getInstance,Ie=e=>!!e.getDeviceId,N=e=>{let t=null,r=null;if(!e.amplitude)return{userId:t,deviceId:r};if(We(e.amplitude)){let i=e.amplitude?.getInstance();t=i?.options?.userId??null,r=i?.options?.deviceId??null}return Ie(e.amplitude)&&(t=e.amplitude?.getUserId?.()??null,r=e.amplitude?.getDeviceId?.()??null),{userId:t,deviceId:r}},Ee=500,Ue=5,U=null,Ae=(e,t)=>{let{delay:r=Ee,times:i=Ue}=t||{},o=0;return n=>{n.cohortUserId||(U&&e.removeEventListener("load",U),U=()=>{let a=setInterval(()=>{o+=1;let{userId:d}=N(e);if(d){n.identifyUser({cohortUserId:d}),clearInterval(a);return}o>=i&&clearInterval(a)},r)},e.addEventListener("load",U))}},Re={apiKey:"",snippetCdnUrl:"https://snippet.maze.co",apiUrl:"https://prompts.maze.co/api",testingPagesUrl:"https://t.maze.co"},Le=480,be=e=>({...Re,...e.mazeContextualSettings||{}}),K=class{constructor(e){this.cacheClearTimeouts={},this.cachedItems=new Set,this.storage=e}getValue(e){let t=this.storage.getItem(e);if(!t)return null;let r=JSON.parse(t);return this.isValueExpired(r)?(this.removeValue(e),null):r.value}setValue(e,t,r=0){let i={value:t,expiresIn:r>0?Date.now()+r*60*1e3:0};this.storage.setItem(e,JSON.stringify(i)),this.cachedItems.add(e),this.cacheClearTimeouts[e]&&clearTimeout(this.cacheClearTimeouts[e]),r>0&&(this.cacheClearTimeouts[e]=setTimeout(()=>{this.removeValue(e)},r*60*1e3))}removeValue(e){this.storage.removeItem(e),this.cachedItems.delete(e),this.cacheClearTimeouts[e]&&(clearTimeout(this.cacheClearTimeouts[e]),delete this.cacheClearTimeouts[e])}clearAll(){this.cachedItems.forEach(e=>{this.removeValue(e)})}isValueExpired(e){return e.expiresIn>0&&e.expiresIn0&&this.supportsExipresIn&&(this.cacheClearTimeouts[e]=setTimeout(()=>{this.removeValue(e)},r*60*1e3))}removeValue(e){delete this.storage[e],this.cacheClearTimeouts[e]&&(clearTimeout(this.cacheClearTimeouts[e]),delete this.cacheClearTimeouts[e])}clearAll(){Object.keys(this.storage).forEach(e=>{this.removeValue(e)})}},Te="__contextual-widget__",xe=({type:e,action:t,payload:r,channel:i})=>({type:e,action:t,payload:r,channel:i}),P=e=>`${Te}${e}`,Ce=(e,t={})=>{let{id:r="PROMPT",allowedOrigins:i}=t,o=[];return{send:n=>{let a=xe({channel:P(r),...n});e.postMessage(a,"*")},listen:n=>{let a=c=>{if(i&&!i.includes(c.origin))return;let{data:l}=c,{channel:g,...m}=l;g===P(r)&&n(m)};e.addEventListener("message",a);let d=()=>{e.removeEventListener("message",a)};o.push(d)},close:()=>{o.forEach(n=>{n()}),o=[]}}},B=class extends Error{constructor(e){super(e),this.name="ScriptLoadError"}},Se=(e,t)=>{let r=e.location.href;return i=>{let o=t.body||t,{location:n}=e;function a(){n.href!==r&&(r=n.href,i(n.href))}let d=new MutationObserver(a);o&&d.observe(o,{subtree:!0,childList:!0})}},k=e=>(t,r={})=>{let i=e.createElement("script");return i.src=t,i.async=r.async||!1,i.defer=r.defer||!1,i.id=r.id||"",r.nonce&&i.setAttribute("nonce",r.nonce),e.getElementsByTagName("head")[0].appendChild(i),i},Pe="https://snippet.maze.co",Fe="maze-scaffold-helper-script",De=async(e,t,r={})=>new Promise((i,o)=>{let{snippetCdnUrl:n=Pe,nonce:a}=r,d=Fe;if(e.getElementById(d)){i(e.getElementById(d));return}let c=`${n}/contextualScaffoldHelpers.js`,l=k(e)(c,{id:d,async:!0,nonce:a});l.addEventListener("load",()=>{i(l)}),l.addEventListener("error",()=>{o(new B(`Error loading script ${c}`))})}),ze="https://snippet.maze.co",Me="maze-widget-app-script",_e=(e,t,r={})=>{let{snippetCdnUrl:i=ze,nonce:o}=r,n=Me;if(e.getElementById(n))return e.getElementById(n);let a=`${i}/contextualWidgetAppScaffold.js`;return k(e)(a,{id:n,async:!0,nonce:o})},F={0:void 0,1:"color: cyan",3:void 0,5:"color: yellow",9:"color: red"};function Ve(e){try{if(!e?.localStorage)return;let t=e.localStorage.getItem("maze-log-level");return t?Number.parseInt(t,10):void 0}catch{return}}var q=class R{static initializeLoggerMode(t){t&&(R._window=t,t.MAZE_LOG_LEVEL=Ve(t)??9)}getCurrentLogLevel(){return R._window?.MAZE_LOG_LEVEL??9}verbose(t,r){this.logEvent(t,1,r)}info(t,r){this.logEvent(t,3,r)}warning(t,r){this.logEvent(t,5,r)}error(t,r){this.logEvent(t,9,r)}logEvent(t,r=3,i){let o=this.getCurrentLogLevel();r>=o&&(i===void 0?console.info(`%c maze-snippet: ${t}`,F[r]):console.info(`%c maze-snippet: ${t}`,F[r],i))}},s=new q,G=class extends Error{constructor(e,t,r){super(e),this.statusCode=t,this.correlationId=r,this.name="WidgetLoadError"}};function Oe(e,t){return Math.random()*(t-e)+e}function $e(){return`${Date.now()}-${Oe(0,1e4)}`}function He({apiUrl:e,apiKey:t}){return async function(r,i,o){let n=await fetch(`${e}/${r}`,{method:"POST",headers:{"Content-Type":"text/plain",Accept:"application/json"},body:JSON.stringify({...i,apiKey:t,snippetSrc:"contextual-widget",correlationId:o})});if(n.ok)return n;let a="Error fetching contextual prompts.";try{a=(await n.json()).message||a}catch{}throw new G(a,n.status,o)}}var j=({apiUrl:e,apiKey:t})=>{let r=He({apiUrl:e,apiKey:t}),i=typeof window<"u"?window.navigator?.userAgent:"unknown",o=$e();return{getWidgetsForVisitor:async({cohortProvider:n,cohortUserId:a})=>{try{return await(await r("widgets",{cohortProvider:n,cohortUserId:a},o)).json()}catch(d){return s.error("Error fetching contextual prompts.",{error:d}),[]}},logEvent:async({source:n,level:a,message:d,data:c})=>{try{await r("event",{source:n,level:a,message:d,data:{...c,userAgent:i,pathname:window?.location?.pathname||""}},o)}catch(l){s.error("Error logging events to the API.",{error:l})}}}},Ne=typeof window<"u"&&window.localStorage?new K(window.localStorage):new I,D=new I,z=!1,M=e=>{if(z)return D.getValue(e)||[];try{return Ne.getValue(e)||[]}catch{return z=!0,s.warning("[getWidgetIdsFromKey] Failed to get widget key from cache. Using fallback."),D.getValue(e)||[]}},Ke=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("notrack")==="true",Be=()=>{let e=M("maze-contextual-widget-dismissed"),t=M("maze-contextual-widget-started");return[...e,...t]},ke={promptHostElement:{self:{default:2147483647},children:{contextualWidgetBranding:{self:{default:10}}}},mediaHostElement:{self:{hidden:0,shown:2147483647},children:{imageZoomControlButtons:{self:{default:10}}}}},qe=(e,t)=>{let r="maze-contextual-widget-fonts";if(t.contentWindow?.document?.querySelector(`link#${r}`))return;let i=e.createElement("link");i.href="https://assets-cdn.maze.co/fonts/roobert-pro.css",i.rel="stylesheet",i.type="text/css",i.id=r,t?.contentWindow?.document?.head.appendChild(i)},A=e=>`${e}px`;function Ge(e,{id:t}){return e.querySelector(`#${t}`)}function je(e,{id:t,tag:r}){let i=Ge(e,{id:t});if(i)return i;let o=e.createElement(r);return o.id=t,e.body.appendChild(o),o}var Z=({id:e,_document:t=document})=>t.querySelector(`#${e}`),Ze=(e,t,{id:r,className:i})=>{let o=Z({_document:t.contentWindow?.document,id:r});return o||(o=e.createElement("div"),o.id=r),o.classList.contains(i)||o.classList.add(i),o.style.cssText=` width: 100%; height: 100%; position:relative; `,o},Je=(e,t)=>({id:r})=>{let i=`${r}-host`,o=`${r}-container`,n=je(t,{id:i,tag:"iframe"}),a=Ze(t,n,{id:o,className:o});return n.contentWindow?.document?.body?.appendChild(a),n.addEventListener("load",()=>{Z({_document:n.contentWindow?.document,id:o})||n.contentWindow?.document?.body?.appendChild(a)}),{host:n,container:a}},Ye="maze-contextual-widget",_=16,V={compact:{height:A(430),width:A(420+_)},expanded:{height:A(680),width:A(420+_)}},Qe=` height: ${V.compact.height}; width: ${V.compact.width}; max-width: 100%; position: fixed; border: none; overflow: hidden; z-index: ${ke.promptHostElement.self.default}; color-scheme: normal; `,O={BOTTOM_LEFT:{left:"0",bottom:"0",transform:"initial",right:"initial",top:"initial"},BOTTOM_RIGHT:{right:"0",bottom:"0",transform:"initial",left:"initial",top:"initial"},MIDDLE_LEFT:{left:"0",top:"50%",transform:"translateY(-50%)",right:" initial",bottom:"initial"},MIDDLE_RIGHT:{right:"0",top:"50%",transform:"translateY(-50%)",left:"initial",bottom:"initial"},CENTERED:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",right:"initial",bottom:"initial"}},Xe={left:"0",right:"0",bottom:"0",top:"initial",transform:"initial"},$=e=>Object.entries(e).reduce((t,[r,i])=>`${t}${r}:${i}; `,""),et=e=>{if(e.hostMaxWidth(e.style.cssText=Qe+et({position:t,hostMaxWidth:r}),e),rt=(e,t)=>({position:r})=>{let{host:i,container:o}=Je(window,document)({id:Ye});return tt(i,{position:r,hostMaxWidth:window.outerWidth}),qe(t,i),{host:i,container:o}};function it(e,t,r){return function(i){let{container:o,host:n}=rt(e,t)({position:i?.styles.position||"BOTTOM_RIGHT"});if(!o)throw new Error("Cannot mount app");return r?r({host:n,container:o},i):(console.warn("mountApp is not defined"),null)}}var ot=class{constructor(e,t){this.config=e,this.cacheManager=t,this.unmountWidgetApp=null,this.widgetApp=null,this.shownPromptIds=new Set,this.identifyUser=r=>r.cohortUserId?(this.cohortUserId=r.cohortUserId,this.cohortProvider="AMPLITUDE",this.hasIdentifiedUser()&&(this.clearWidgetsForDomain(),this.config.onUserIdentified?.({cohortUserId:this.cohortUserId})),!0):!1,this.registerWidgetApp=r=>{this.widgetApp=r},this.deregisterWidgetApp=()=>{this.unMountApp(),this.widgetApp=null},this.renderWidget=async(r,i,{forceRequest:o}={})=>{let n={step:"start",hasUnmountWidgetAppCallback:!!this.unmountWidgetApp};try{s.verbose("[renderWidget] START",{url:this.url,forceRequest:o});let{shouldRender:a,widgetsForRoute:d,widgetsForDomain:c}=await this.shouldRenderWidget({forceRequest:o,errorLogInfo:n});if(n.step="fetchedWidgets",n.hasWidgetsForDomain=!!c.length,n.hasWidgetsForRoute=!!d.length,n.widgetsForDomain=c.map(m=>m.uuid),n.widgetsForRoute=d.map(m=>m.uuid),n.shouldRender=a,s.verbose("[renderWidget] shouldRenderWidget",{shouldRender:a,widgetsForRoute:d,widgetsForDomain:c,widgetApp:this.widgetApp}),this.widgetApp||(n.step="registeringWidgetApp",await this.config.onShouldRegisterWidgetApp?.({widgets:c,filteredWidgets:d})),n.step="registeredWidgetApp",n.registeredWidgetApp=!!this.widgetApp,!a){this.unMountApp();return}let[l]=d;if(this.unMountApp(),!this.widgetApp)return;let g=await this.executeGetVariablesFromRouteLazy({url:this.url,paths:l.paths});if(n.routeVariables=g,n.step="renderingWidget",!this.widgetApp)return;this.unmountWidgetApp=it(r,i,this.widgetApp)({...l,testingPagesUrl:this.config.testingPagesUrl,cohortUserId:this.cohortUserId,cohortProvider:this.cohortProvider,routeVariables:g,apiKey:this.config.apiKey,apiUrl:this.config.apiUrl}),this.unmountWidgetApp&&!Ke()&&!this.shownPromptIds.has(l.uuid)&&(this.shownPromptIds.add(l.uuid),this.config.communicate.send({type:"promptShown",payload:{promptId:l.uuid,mazeId:l.mazeId[0]??""}}))}catch(a){let d=a,c={};throw d instanceof G&&(c={statusCode:d.statusCode,correlationId:d.correlationId}),s.error("[renderWidget] error",{error:d}),this.mazeApi.logEvent({source:"contextualScaffold",level:n.shouldRender?"error":"warn",message:"Error while rendering widget",data:{message:d.message,stack:d.stack,errorName:d.name,...c,errorLogInfo:n}}),d}},this.setUrl=r=>{this.url=r},this.hasIdentifiedUser=()=>!!this.cohortUserId,this.clearWidgetsForDomain=()=>{this.widgetsForDomain=null},this.getWidgetsForDomain=async()=>(s.verbose("[getWidgetsForDomain] START",{currentWidgetsForDomain:this.widgetsForDomain}),this.widgetsForDomain?(s.verbose("[getWidgetsForDomain] returned widgets from cache"),this.widgetsForDomain):(this.widgetsForDomain=await this.mazeApi.getWidgetsForVisitor({cohortProvider:this.cohortProvider,cohortUserId:this.cohortUserId}),s.verbose("[getWidgetsForDomain] API result",{widgetsForDomain:this.widgetsForDomain}),this.widgetsForDomain)),this.getWidgetsToRender=async({forceRequest:r}={})=>{r&&this.clearWidgetsForDomain();let i=await this.getWidgetsForDomain(),o=Be();return i?.filter(n=>!o.includes(n.uuid))??[]},this.filterWidgetsForRoute=async r=>{let i=r.map(async o=>{let{paths:n=[]}=o;return n.length===0||await this.executePathMatchesPatternLazy({url:this.url,paths:n})?o:null});return(await Promise.all(i)).filter(Boolean)},this.shouldRenderWidget=async({forceRequest:r,errorLogInfo:i}={})=>{let o=await this.getWidgetsToRender({forceRequest:r});if(i&&(i.step="getWidgetsToRender"),s.verbose("[shouldRenderWidget] filteredWidgetsForDomain",{filteredWidgetsForDomain:o,forceRequest:r}),!o.length)return{shouldRender:!1,widgetsForRoute:o,widgetsForDomain:o};let n=await this.filterWidgetsForRoute(o);return i&&(i.step="filterWidgetsForRoute"),{shouldRender:!!n.length,widgetsForRoute:n,widgetsForDomain:o}},this.unMountApp=()=>{this.unmountWidgetApp&&(this.unmountWidgetApp(),this.unmountWidgetApp=null)},this.initHelpers=async()=>{this.helpersLoadPromise&&await this.helpersLoadPromise,!this.helpers&&(this.helpersLoadPromise=this.config.onLoadWidgetHelper?.(),this.helpers=await this.helpersLoadPromise,s.verbose("[initHelpers] helpers",{helpers:this.helpers}))},this.cohortUserId=e.cohortUserId,this.cohortProvider=e.cohortProvider,this.url=e.url,this.mazeApi=j({apiUrl:e.apiUrl,apiKey:e.apiKey})}get widgetsForDomain(){return this.cacheManager.getValue("maze:widgets")}set widgetsForDomain(e){try{this.cacheManager.setValue("maze:widgets",e,15),s.verbose("[set widgetsForDomain] cached widgets",{value:e})}catch(t){this.cacheManager=new I,this.cacheManager.setValue("maze:widgets",e),s.error("[set widgetsForDomain] error while saving to cache (using fallback)",{error:t,value:e}),this.mazeApi.logEvent({source:"contextualScaffold",level:"warn",message:"Failed to save widgets to session storage. Using fallback.",data:{message:t.message,value:e}})}}async executeGetVariablesFromRouteLazy({url:e,paths:t}){return this.helpers||await this.initHelpers(),this.helpers?.getVariablesFromRoute?this.helpers.getVariablesFromRoute({url:e,paths:t}):(s.error("[executeGetVariablesFromRouteLazy] helpers not initialized"),{})}async executePathMatchesPatternLazy({url:e,paths:t}){return this.helpers||await this.initHelpers(),this.helpers?.pathMatchesPattern?this.helpers.pathMatchesPattern({url:e,paths:t}):(s.error("[executePathMatchesPatternLazy] helpers not initialized"),!1)}},nt=(e,t)=>{let r={...be(e),...t||{}},{userId:i}=N(e);return!r.cohortUserId&&i&&(r.cohortUserId=i,r.cohortProvider="AMPLITUDE"),r},st=(e,t)=>t.debug?new I:typeof e<"u"&&e.sessionStorage?new K(e.sessionStorage):new I;function at(e,t){let r=Ce(e);q.initializeLoggerMode(e);let i=window.location.href;return s.verbose("[createContextualWidget] START"),function(o){let n=nt(e,o),a=st(e,n),d=Ae(e),c=j({apiUrl:n.apiUrl,apiKey:n.apiKey}),l=!1,g=h=>{u.setUrl(h),u.renderWidget(e,t).catch(p=>{s.error("[handleRouteChange] renderWidget",{error:p})})},m=({widgets:h,filteredWidgets:p})=>new Promise((f,v)=>{if(s.verbose("[onShouldRegisterWidgetApp] START",{attachedRouteChangeListener:l,widgetsForDomain:h,widgetsForPath:p}),h?.length&&!l){l=!0;let ie=Se(e,t);e.addEventListener("hashchange",W=>{s.verbose("[onShouldRegisterWidgetApp] hashChange event",{url:W.newURL}),g(W.newURL)}),ie(W=>{s.verbose("[onShouldRegisterWidgetApp] onRouteChange",{url:W}),g(W)})}if(!p||p.length===0){f(!1);return}s.verbose("[onShouldRegisterWidgetApp] loadWidgetAppScript",{snippetCdnUrl:n.snippetCdnUrl});let b=_e(t,e,{snippetCdnUrl:n.snippetCdnUrl,nonce:n.nonce});b.onload=()=>{s.verbose("[onShouldRegisterWidgetApp] loadWidgetAppScript onLoad event"),f(!0)},b.onerror=()=>{v(new B("Error loading widget app script"))}}),te=async()=>(s.verbose("[onLoadWidgetHelper] load helper script",{snippetCdnUrl:n.snippetCdnUrl}),await De(t,e,{snippetCdnUrl:n.snippetCdnUrl,nonce:n.nonce}),e.mazeHelpers);r.listen(({type:h,payload:p})=>{if(h==="registerWidgetApp"){s.verbose("[onWidgetEvent] registerWidgetApp",{type:h}),u.renderWidget(e,t).catch(f=>{s.error("[onWidgetEvent] renderWidget",{type:h,error:f})});return}h==="deregisterWidgetApp"&&(s.verbose("[onWidgetEvent] deregisterWidgetApp",{type:h}),u.deregisterWidgetApp()),h==="widgetAppError"&&(s.error("[widgetAppError]",{...p}),c.logEvent({source:"widgetApp",level:"error",message:"Error in widget React app",data:p}))});let re=async()=>{await u.renderWidget(e,t)},u=new ot({...n,communicate:r,onShouldRegisterWidgetApp:m,onLoadWidgetHelper:te,onUserIdentified:re,url:i},a);d(u);let w=!1,y=0,E=setInterval(()=>{if(y+=1,w){s.verbose("[detection] widget already loaded",{siteLoaded:w,activationAttempt:y}),clearInterval(E);return}if(y>10){s.warning("[detection] max activation attempt triggered",{activationAttempt:y,siteLoaded:w}),clearInterval(E);return}(t.readyState==="complete"||t.readyState==="interactive")&&(s.verbose("[detection] readyState triggered",{siteLoaded:w,activationAttempt:y}),clearInterval(E),w=!0,u.renderWidget(e,t))},1e3);return e.addEventListener("load",async()=>{s.verbose("[window] onLoad",{siteLoaded:w}),clearInterval(E),w=!0,await u.renderWidget(e,t)}),{...u,render:({forceRequest:h=!1,forRoute:p}={})=>{if(s.verbose("[render] START",{forceRequest:h,forRoute:p}),p){let f=new URL(e.location.href).origin;try{let v=new URL(f+p);s.verbose("[render] set new URL",{newUrl:v}),u.setUrl(v.href)}catch(v){s.error("[render] Invalid URL",{baseUrl:f,forRoute:p,error:v});return}}u.renderWidget(e,t,{forceRequest:h})}}}}});var pe=(e,t)=>e&&t?`${e}/static/${t}`:"",ue="53f5fd4a4a55cddd8f13e5de30b02bb8d05bbfe8",x=pe("https://snippet.maze.co",ue);var C="https://prompts.maze.co/api",S="https://t.maze.co";var Q=he(Y()),X=(e,t,r)=>{let i=e?.mazeUniversalSnippetApiKey||"",o={...e?.mazePromptsSettings||{apiKey:i}};return(n={})=>{!o.apiKey&&i&&(o.apiKey=i),e.mazePrompts=(0,Q.createContextualWidget)(e,t)({...o,...r&&{nonce:r},...n})}};var ee=document.currentScript,dt=ee?.nonce||ee?.getAttribute("nonce")||void 0,lt={apiUrl:C,testingPagesUrl:S,snippetCdnUrl:x};X(window,document,dt)(lt);})();