wineater-bot 3.1.6 → 3.1.8
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/dist/wineater-chatbot.mjs +1138 -1138
- package/dist/wineater-chatbot.umd.js +82 -82
- package/package.json +1 -1
- package/src/js/widget-styles.js +46 -46
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(st){typeof define=="function"&&define.amd?define(st):st()})(function(){"use strict";var bs,ys,vs,ws,Ss,xs;const st=`
|
|
2
2
|
:root {
|
|
3
3
|
--wineater-corp-color: #0044FF;
|
|
4
4
|
--wineater-color: #7B2BEB;
|
|
@@ -644,27 +644,27 @@ visibility: visible;
|
|
|
644
644
|
height: 80px;
|
|
645
645
|
}
|
|
646
646
|
}
|
|
647
|
-
`,Gn=document.createElement("style");Gn.textContent=it,document.head.appendChild(Gn);function Ni(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function rt(t,e,n){console.log(t,n);let s="";if(n){const i=new Date;i.setTime(i.getTime()+n*24*60*60*1e3),s="; expires="+i.toUTCString()}document.cookie=t+"="+(e||"")+s+"; path=/; secure; samesite=strict"}function se(t){const e=t+"=",n=document.cookie.split(";");for(let s=0;s<n.length;s++){let i=n[s];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null}function Oi(t){document.cookie=t+"=; Max-Age=-99999999;"}function Ri(){const t="uniqueUserID";let e=se(t);return e||(e=Ni(),rt(t,e,365)),e}function Ke(t,e){fetch("https://wineater-backend.vercel.app/proxy/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:t,properties:e})}).then(i=>{i.ok||console.error("Mixpanel tracking failed",i)}).catch(i=>{console.error("Mixpanel tracking error",i)})}function Ai(){Ke("Chatbot Opened",{distinct_id:se("uniqueUserID"),client:se("chatbotToken")})}function Vn(){Ke("Chatbot Closed",{distinct_id:se("uniqueUserID"),client:se("chatbotToken")})}function Di(t){Ke("Message Sent",{distinct_id:se("uniqueUserID"),message_content:t,client:se("chatbotToken")})}function Li(t){Ke("Products Got",{distinct_id:se("uniqueUserID"),products:t,client:se("chatbotToken")})}function Fi(t){Ke("Product Clicked",{distinct_id:se("uniqueUserID"),product_id:t,client:se("chatbotToken")})}var Fe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Kn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Lt={exports:{}};(function(t,e){(function(n,s){s(e)})(Fe,function(n){var s={getItemSync:function(b){try{return localStorage.getItem(b)||null}catch{return null}},getItem:function(b,f){var h=this;return new Promise(function(m,g){try{var w=h.getItemSync(b);f==null||f(null,w),m(w)}catch(x){f&&f(x,null),g(x)}})},setItem:function(b,f,h){return new Promise(function(m,g){try{localStorage.setItem(b,f),h&&h(null,f),m(f)}catch(w){h&&h(w,null),g(w)}})}},i=function(){return i=Object.assign||function(b){for(var f,h=1,m=arguments.length;h<m;h++)for(var g in f=arguments[h])Object.prototype.hasOwnProperty.call(f,g)&&(b[g]=f[g]);return b},i.apply(this,arguments)};function r(b,f,h,m){return new(h||(h=Promise))(function(g,w){function x($){try{M(m.next($))}catch(_){w(_)}}function R($){try{M(m.throw($))}catch(_){w(_)}}function M($){var _;$.done?g($.value):(_=$.value,_ instanceof h?_:new h(function(W){W(_)})).then(x,R)}M((m=m.apply(b,f||[])).next())})}function o(b,f){var h,m,g,w,x={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return w={next:R(0),throw:R(1),return:R(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function R(M){return function($){return function(_){if(h)throw new TypeError("Generator is already executing.");for(;x;)try{if(h=1,m&&(g=2&_[0]?m.return:_[0]?m.throw||((g=m.return)&&g.call(m),0):m.next)&&!(g=g.call(m,_[1])).done)return g;switch(m=0,g&&(_=[2&_[0],g.value]),_[0]){case 0:case 1:g=_;break;case 4:return x.label++,{value:_[1],done:!1};case 5:x.label++,m=_[1],_=[0];continue;case 7:_=x.ops.pop(),x.trys.pop();continue;default:if(g=x.trys,!((g=g.length>0&&g[g.length-1])||_[0]!==6&&_[0]!==2)){x=0;continue}if(_[0]===3&&(!g||_[1]>g[0]&&_[1]<g[3])){x.label=_[1];break}if(_[0]===6&&x.label<g[1]){x.label=g[1],g=_;break}if(g&&x.label<g[2]){x.label=g[2],x.ops.push(_);break}g[2]&&x.ops.pop(),x.trys.pop();continue}_=f.call(b,x)}catch(W){_=[6,W],m=0}finally{h=g=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}([M,$])}}}function l(b,f,h){if(h||arguments.length===2)for(var m,g=0,w=f.length;g<w;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return b.concat(m||Array.prototype.slice.call(f))}var a=function b(f,h){if(f===h)return!0;if(f&&h&&typeof f=="object"&&typeof h=="object"){if(f.constructor!==h.constructor)return!1;var m,g,w;if(Array.isArray(f)){if((m=f.length)!=h.length)return!1;for(g=m;g--!=0;)if(!b(f[g],h[g]))return!1;return!0}if(f.constructor===RegExp)return f.source===h.source&&f.flags===h.flags;if(f.valueOf!==Object.prototype.valueOf)return f.valueOf()===h.valueOf();if(f.toString!==Object.prototype.toString)return f.toString()===h.toString();if((m=(w=Object.keys(f)).length)!==Object.keys(h).length)return!1;for(g=m;g--!=0;)if(!Object.prototype.hasOwnProperty.call(h,w[g]))return!1;for(g=m;g--!=0;){var x=w[g];if(!b(f[x],h[x]))return!1}return!0}return f!=f&&h!=h};function d(b,f){var h=Object.keys(f||{}).filter(function(m){var g=b==null?void 0:b[m],w=f==null?void 0:f[m];return!a(g,w)});return Object.keys(b||{}).filter(function(m){Object.keys(f||{}).includes(m)||h.push(m)}),Object.keys(h).length?h:null}var c,u;function p(b,f,h){var m="shortString",g=!0;typeof h=="number"&&(m="javaDouble",g=!1),b[m]=b[m]||{},b[m][f]=g?h+"":h}function y(b){return!!b&&typeof b=="object"&&b.value!==void 0}function S(b){return Object.fromEntries(Object.entries(b).map(function(f){var h=f[0],m=f[1];return[h,y(m)?m:{value:m}]}))}function v(b){return i(i({},b),{identity:b.identity?i(i({},b.identity),{traits:S(b.identity.traits||{})}):void 0})}(function(b){b.NONE="NONE",b.DEFAULT_FLAGS="DEFAULT_FLAGS",b.CACHE="CACHE",b.SERVER="SERVER"})(c||(c={}));var T,A=null,B="BULLET_TRAIN_DB",D="BULLET_TRAIN_EVENT",k="https://edge.api.flagsmith.com/api/v1/",N="flagsmith_value_",O="flagsmith_enabled_",L="flagsmith_trait_",I=function(){function b(f){var h=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var m=h,g=m.api,w=m.evaluationContext;h.log("Get Flags"),h.isLoading=!0,h.loadingState.isFetching||h.setLoadingState(i(i({},h.loadingState),{isFetching:!0}));var x="".concat(h.getContext().identity),R=function(M){var $,_,W,ee;if(M&&x==="".concat(h.getContext().identity)){var ae=M.flags,te=M.traits,ne=M.identifier;h.isLoading=!1;var he={},ue={};te=te||[],(ae=ae||[]).forEach(function(X){he[X.feature.name.toLowerCase().replace(/ /g,"_")]={id:X.feature.id,enabled:X.enabled,value:X.feature_state_value}}),te.forEach(function(X){ue[X.trait_key.toLowerCase().replace(/ /g,"_")]={transient:X.transient,value:X.trait_value}}),h.oldFlags=i({},h.flags);var we=d(h.oldFlags,he),Ze=d(($=h.evaluationContext.identity)===null||$===void 0?void 0:$.traits,ue);if((ne||Object.keys(ue).length)&&(h.evaluationContext.identity={traits:ue},ne&&(h.evaluationContext.identity.identifier=ne)),h.flags=he,h.updateStorage(),h._onChange(h.oldFlags,{isFromServer:!0,flagsChanged:we,traitsChanged:Ze},h._loadedState(null,c.SERVER)),h.datadogRum)try{if(h.datadogRum.trackTraits){var et={};Object.keys(((_=h.evaluationContext.identity)===null||_===void 0?void 0:_.traits)||{}).map(function(X){et[L+X]=h.getTrait(X)});var We=i(i(i({},h.datadogRum.client.getUser()),{id:h.datadogRum.client.getUser().id||((W=h.evaluationContext.identity)===null||W===void 0?void 0:W.identifier)}),et);h.log("Setting Datadog user",We),h.datadogRum.client.setUser(We)}}catch(X){console.error(X)}if(h.dtrum)try{var re={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(h.flags).map(function(X){p(re,N+X,h.getValue(X,{skipAnalytics:!0})),p(re,O+X,h.hasFeature(X,{skipAnalytics:!0}))}),Object.keys(((ee=h.evaluationContext.identity)===null||ee===void 0?void 0:ee.traits)||{}).map(function(X){p(re,L+X,h.getTrait(X))}),h.log("Sending javaLongOrObject traits to dynatrace",re.javaLongOrObject),h.log("Sending date traits to dynatrace",re.date),h.log("Sending shortString traits to dynatrace",re.shortString),h.log("Sending javaDouble to dynatrace",re.javaDouble),h.dtrum.sendSessionProperties(re.javaLongOrObject,re.date,re.shortString,re.javaDouble)}catch(X){console.error(X)}}};return w.identity?Promise.all([w.identity.traits&&Object.keys(w.identity.traits).length||!w.identity.identifier?h.getJSON(g+"identities/","POST",JSON.stringify({identifier:w.identity.identifier,transient:w.identity.transient,traits:Object.entries(w.identity.traits).map(function(M){var $=M[0],_=M[1];return{trait_key:$,trait_value:_==null?void 0:_.value,transient:_==null?void 0:_.transient}}).filter(function(M){return M.trait_value!==void 0||(h.log("Warning - attempted to set an undefined trait value for key",M.trait_key),!1)})})):h.getJSON(g+"identities/?identifier="+encodeURIComponent(w.identity.identifier)+(w.identity.transient?"&transient=true":""))]).then(function(M){return h.evaluationContext.identity=i(i({},h.evaluationContext.identity),{traits:{}}),R(M==null?void 0:M[0])}).catch(function(M){var $=M.message,_=new Error($);return Promise.reject(_)}):h.getJSON(g+"flags/").then(function(M){return R({flags:M,traits:void 0})})},this.analyticsFlags=function(){var m=h.api;if(h.evaluationEvent&&h.evaluationContext.environment&&h.evaluationEvent[h.evaluationContext.environment.apiKey])return h.evaluationEvent&&Object.getOwnPropertyNames(h.evaluationEvent).length!==0&&Object.getOwnPropertyNames(h.evaluationEvent[h.evaluationContext.environment.apiKey]).length!==0?h.getJSON(m+"analytics/flags/","POST",JSON.stringify(h.evaluationEvent[h.evaluationContext.environment.apiKey])).then(function(g){if(h.evaluationContext.environment){var w=h.getState();h.evaluationEvent||(h.evaluationEvent={}),h.evaluationEvent[h.evaluationContext.environment.apiKey]={},h.setState(i(i({},w),{evaluationEvent:h.evaluationEvent})),h.updateEventStorage()}}).catch(function(g){h.log("Exception fetching evaluationEvent",g)}):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:c.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.ts=null,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1},this.getValue=function(m,g,w){var x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=null;if(x&&(R=x.value),g!=null&&g.skipAnalytics||w||h.evaluateFlag(m,"VALUE"),R===null&&(g==null?void 0:g.fallback)!==void 0)return g.fallback;if(g!=null&&g.json)try{return R===null?(h.log("Tried to parse null flag as JSON: "+m),null):JSON.parse(R)}catch{return g.fallback}return R},this.getTrait=function(m){var g,w;return((g=h.evaluationContext.identity)===null||g===void 0?void 0:g.traits)&&((w=h.evaluationContext.identity.traits[m.toLowerCase().replace(/ /g,"_")])===null||w===void 0?void 0:w.value)},this.getAllTraits=function(){var m;return Object.fromEntries(Object.entries(((m=h.evaluationContext.identity)===null||m===void 0?void 0:m.traits)||{}).map(function(g){var w=g[0],x=g[1];return[w,x==null?void 0:x.value]}))},this.setContext=function(m){var g=v(m);return h.evaluationContext=i(i({},g),{environment:g.environment||h.evaluationContext.environment}),h.initialised?h.getFlags():Promise.resolve()},this.getContext=function(){return h.evaluationContext},this.updateContext=function(m){return h.setContext(i(i({},h.getContext()),m))},this.setTrait=function(m,g){var w;if(h.api)return h.setContext(i(i({},h.evaluationContext),{identity:i(i({},h.evaluationContext.identity),{traits:i(i({},(w=h.evaluationContext.identity)===null||w===void 0?void 0:w.traits),S(Object.fromEntries([[m,g]])))})}))},this.setTraits=function(m){var g;if(h.api)return h.setContext(i(i({},h.evaluationContext),{identity:i(i({},h.evaluationContext.identity),{traits:i(i({},(g=h.evaluationContext.identity)===null||g===void 0?void 0:g.traits),Object.fromEntries(Object.entries(m).map(function(w){var x=w[0],R=w[1];return[x,y(R)?R:{value:R}]})))})}));console.error("Attempted to setTraits a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(m,g){var w=typeof g=="object",x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=!1;return!x&&w&&g.fallback!==void 0?R=g==null?void 0:g.fallback:x&&x.enabled&&(R=!0),(w&&!g.skipAnalytics||!g)&&h.evaluateFlag(m,"ENABLED"),R},this.getJSON=function(m,g,w){var x,R=h;R.evaluationContext;var M=R.headers,$={method:g||"GET",body:w,cache:"no-cache",headers:{}};h.evaluationContext.environment&&($.headers["X-Environment-Key"]=h.evaluationContext.environment.apiKey),g&&g!=="GET"&&($.headers["Content-Type"]="application/json; charset=utf-8"),M&&Object.assign($.headers,M),u||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var _="".concat((x=h.evaluationContext.identity)===null||x===void 0?void 0:x.identifier);return u(m,$).then(function(W){var ee,ae,te="".concat((ee=h.evaluationContext.identity)===null||ee===void 0?void 0:ee.identifier);if(_===te){var ne=(ae=W.headers)===null||ae===void 0?void 0:ae.get("x-flagsmith-document-updated-at");if(ne)try{var he=parseFloat(ne);if(isNaN(he))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");h.timestamp=he}catch(ue){h.log(ue,"Failed to parse x-flagsmith-document-updated-at",ne)}return h.log("Fetch response: "+W.status+" "+(g||"GET")+0+m),W.text().then(function(ue){var we=ue;try{we=JSON.parse(ue)}catch{}return!we&&W.status&&(we="API Response: ".concat(W.status)),W.status&&W.status>=200&&W.status<300?we:Promise.reject(new Error(we))})}h.log("Received response with identity mismatch, ignoring response. Requested: ".concat(_,", Current: ").concat(te))})},this.evaluateFlag=function(m,g){if(h.datadogRum&&(h.datadogRum.client.addFeatureFlagEvaluation?g==="VALUE"?h.datadogRum.client.addFeatureFlagEvaluation(N+m,h.getValue(m,{},!0)):h.datadogRum.client.addFeatureFlagEvaluation(O+m,h.hasFeature(m,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),h.enableAnalytics){if(!h.evaluationEvent||!h.evaluationContext.environment)return;h.evaluationEvent[h.evaluationContext.environment.apiKey]||(h.evaluationEvent[h.evaluationContext.environment.apiKey]={}),h.evaluationEvent[h.evaluationContext.environment.apiKey][m]===void 0&&(h.evaluationEvent[h.evaluationContext.environment.apiKey][m]=0),h.evaluationEvent[h.evaluationContext.environment.apiKey][m]+=1}h.updateEventStorage()},this._onChange=function(m,g,w){var x,R;h.setLoadingState(w),(x=h.onChange)===null||x===void 0||x.call(h,m,g,h.loadingState),(R=h._trigger)===null||R===void 0||R.call(h)},u=f.fetch?f.fetch:typeof fetch<"u"?fetch:Fe==null?void 0:Fe.fetch,this.canUseStorage=typeof window<"u"||!!f.browserlessStorage,this.log("Constructing flagsmith instance "+f),f.eventSource&&(T=f.eventSource),f.AsyncStorage&&(A=f.AsyncStorage)}return b.prototype.init=function(f){var h,m,g;return r(this,void 0,void 0,function(){var w,x,R,M,$,_,W,ee,ae,te,ne,he,ue,we,Ze,et,We,re,X,En,tt,ki,nt,In,Ti,Ei,Cn,Ii,_n,st,Ge,Ci,oe=this;return o(this,function(ge){switch(ge.label){case 0:w=v(f.evaluationContext||this.evaluationContext),ge.label=1;case 1:if(ge.trys.push([1,13,,14]),x=f.environmentID,R=f.api,M=R===void 0?k:R,$=f.headers,_=f.onChange,W=f.cacheFlags,ee=f.datadogRum,ae=f.onError,te=f.defaultFlags,ne=f.fetch,he=f.preventFetch,ue=f.enableLogs,we=f.enableDynatrace,Ze=f.enableAnalytics,et=f.realtime,We=f.eventSourceUrl,re=We===void 0?"https://realtime.flagsmith.com/":We,X=f.AsyncStorage,En=f.identity,tt=f.traits,ki=f.state,nt=f.cacheOptions,In=f.angularHttpClient,Ti=f._trigger,Ei=f._triggerLoadingState,w.environment=x?{apiKey:x}:w.environment,!w.environment||!w.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(w.identity=En||tt?{identifier:En,traits:tt?Object.fromEntries(Object.entries(tt).map(function(fe){return[fe[0],{value:fe[1]}]})):{}}:w.identity,this.evaluationContext=w,this.api=M,this.headers=$,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=_,Cn="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=Ti||this._trigger,this._triggerLoadingState=Ei||this._triggerLoadingState,this.onError=function(fe){oe.setLoadingState(i(i({},oe.loadingState),{isFetching:!1,isLoading:!1,error:fe})),ae==null||ae(fe)},this.enableLogs=ue||!1,this.cacheOptions=nt?{skipAPI:!!nt.skipAPI,ttl:nt.ttl||0,loadStale:!!nt.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),ne&&(u=ne),this.enableAnalytics=Ze||!1,this.flags=Object.assign({},te)||{},this.datadogRum=ee||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?new Date().valueOf():null,this.cacheFlags=A!==void 0&&!!W,X&&(A=X),et&&typeof window<"u"&&this.setupRealtime(re,w.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=i(i({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(ki),this.log("Initialising with properties",f,this),we&&(typeof dtrum>"u"?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),In&&(u=function(fe){return function(Se,xe){var Ne=xe.headers,Y=xe.method,Ve=xe.body;return new Promise(function(Le){switch(Y){case"GET":return fe.get(Se,{headers:Ne}).subscribe(function(Te){Le({ok:!0,text:function(){return Promise.resolve(Te)}})});case"POST":case"PUT":return fe.post(Se,Ve,{headers:Ne}).subscribe(function(Te){Le({ok:!0,text:function(){return Promise.resolve(Te)}})})}})}}(In)),A&&this.canUseStorage&&A.getItem(D).then(function(fe){try{oe.evaluationEvent=JSON.parse(fe)||{}}catch{oe.evaluationEvent={}}oe.analyticsInterval=setInterval(oe.analyticsFlags,oe.ticks)}),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),A&&this.canUseStorage&&A.getItem(D,function(fe,Se){if(Se&&oe.evaluationContext.environment){var xe=JSON.parse(Se);if(xe[oe.evaluationContext.environment.apiKey]){var Ne=oe.getState();oe.log("Retrieved events from cache",Se),oe.setState(i(i({},Ne),{evaluationEvent:xe[oe.evaluationContext.environment.apiKey]}))}}})),!W)return[3,9];if(!A||!this.canUseStorage)return[3,8];Ii=function(fe,Se){return r(oe,void 0,void 0,function(){var xe,Ne,Y,Ve,Le,Te,Nn,_i,On,Rn,An,Dn,Ln,Fn,Mn,Pn,Bn,jn,zn,Un,Hn,$n,qn,Wn;return o(this,function(Oe){switch(Oe.label){case 0:if(!Se)return[3,7];xe=null,Ne=null,Oe.label=1;case 1:return Oe.trys.push([1,5,,6]),Y=JSON.parse(Se),Ve=!1,Le=!1,Y&&Y.api===this.api&&((Rn=(On=Y.evaluationContext)===null||On===void 0?void 0:On.environment)===null||Rn===void 0?void 0:Rn.apiKey)===((An=this.evaluationContext.environment)===null||An===void 0?void 0:An.apiKey)&&(Te=!0,this.evaluationContext.identity&&((Ln=(Dn=Y.evaluationContext)===null||Dn===void 0?void 0:Dn.identity)===null||Ln===void 0?void 0:Ln.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+((Mn=(Fn=Y.evaluationContext)===null||Fn===void 0?void 0:Fn.identity)===null||Mn===void 0?void 0:Mn.identifier)+" to "+this.evaluationContext.identity.identifier),Te=!1),this.cacheOptions.ttl&&(!Y.ts||new Date().valueOf()-Y.ts>this.cacheOptions.ttl)&&(Y.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+Y.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-Y.ts)+"ms"),Te=!1):Y.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+Y.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-Y.ts)+"ms"),Le=!0,Te=!0)),Te&&(Ve=!0,Ne=d((Pn=this.evaluationContext.identity)===null||Pn===void 0?void 0:Pn.traits,(jn=(Bn=Y.evaluationContext)===null||Bn===void 0?void 0:Bn.identity)===null||jn===void 0?void 0:jn.traits),xe=d(this.flags,Y.flags),this.setState(i(i({},Y),{evaluationContext:v(i(i({},Y.evaluationContext),{identity:!((zn=Y.evaluationContext)===null||zn===void 0)&&zn.identity?i(i({},(Un=Y.evaluationContext)===null||Un===void 0?void 0:Un.identity),{traits:i(i({},(($n=(Hn=Y.evaluationContext)===null||Hn===void 0?void 0:Hn.identity)===null||$n===void 0?void 0:$n.traits)||{}),tt||{})}):void 0}))})),this.log("Retrieved flags from cache",Y))),Ve?(Nn=!he&&(!this.cacheOptions.skipAPI||Le),this._onChange(null,{isFromServer:!1,flagsChanged:xe,traitsChanged:Ne},this._loadedState(null,c.CACHE,Nn)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&Ve&&!Le&&this.log("Skipping API, using cache"),Nn&&this.getFlags(),[3,4]):[3,2];case 2:return he?[3,4]:[4,this.getFlags()];case 3:Oe.sent(),Oe.label=4;case 4:return[3,6];case 5:return _i=Oe.sent(),this.log("Exception fetching cached logs",_i),[3,6];case 6:return[3,10];case 7:return he?[3,9]:[4,this.getFlags()];case 8:return Oe.sent(),[3,10];case 9:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(qn=this.evaluationContext.identity)===null||qn===void 0?void 0:qn.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(Cn);this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(Wn=this.evaluationContext.identity)===null||Wn===void 0?void 0:Wn.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}Oe.label=10;case 10:return[2]}})})},ge.label=2;case 2:return ge.trys.push([2,7,,8]),A.getItemSync?(_n=A.getItemSync(B),[3,5]):[3,3];case 3:return[4,A.getItem(B)];case 4:_n=ge.sent(),ge.label=5;case 5:return[4,Ii(null,_n)];case 6:case 7:return ge.sent(),[3,8];case 8:return[3,12];case 9:return he?[3,11]:[4,this.getFlags()];case 10:return ge.sent(),[3,12];case 11:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:d({},te),traitsChanged:d({},(h=w.identity)===null||h===void 0?void 0:h.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(st=null,Object.keys(this.flags).length===0&&(st=Cn),this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(m=w.identity)===null||m===void 0?void 0:m.traits)},this._loadedState(st,c.DEFAULT_FLAGS)),st))throw new Error(st);ge.label=12;case 12:return[3,14];case 13:throw Ge=ge.sent(),this.log("Error during initialisation ",Ge),Ci=Ge instanceof Error?Ge:new Error("".concat(Ge)),(g=this.onError)===null||g===void 0||g.call(this,Ci),Ge;case 14:return[2]}})})},b.prototype._loadedState=function(f,h,m){return f===void 0&&(f=null),m===void 0&&(m=!1),{error:f,isFetching:m,isLoading:!1,source:h}},b.prototype.getAllFlags=function(){return this.flags},b.prototype.identify=function(f,h,m){return this.evaluationContext.identity={identifier:f,transient:m,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==f?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=f,this.log("Identify: "+this.evaluationContext.identity.identifier),h&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(h).map(function(g){var w=g[0],x=g[1];return[w,y(x)?x:{value:x}]}))),this.initialised?this.getFlags():Promise.resolve()},b.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,evaluationEvent:this.evaluationEvent}},b.prototype.setState=function(f){f&&(this.initialised=!0,this.api=f.api||this.api||k,this.flags=f.flags||this.flags,this.evaluationContext=f.evaluationContext||this.evaluationContext,this.evaluationEvent=f.evaluationEvent||this.evaluationEvent,this.log("setState called",this))},b.prototype.logout=function(){return this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},b.prototype.startListening=function(f){f===void 0&&(f=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,f)},b.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},b.prototype.log=function(){for(var f=[],h=0;h<arguments.length;h++)f[h]=arguments[h];this.enableLogs&&console.log.apply(this,l(["FLAGSMITH:",new Date().valueOf()-(this.timer||0),"ms"],f,!0))},b.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=new Date().valueOf();var f=JSON.stringify(this.getState());this.log("Setting storage",f),A.setItem(B,f)}},b.prototype.updateEventStorage=function(){if(this.enableAnalytics){var f=JSON.stringify(this.getState().evaluationEvent);A.setItem(D,f)}},b.prototype.setLoadingState=function(f){var h;a(f,this.loadingState)||(this.loadingState=i({},f),this.log("Loading state changed",f),(h=this._triggerLoadingState)===null||h===void 0||h.call(this))},b.prototype.setupRealtime=function(f,h){var m=this,g=f+"sse/environments/"+h+"/stream";T?this.eventSource||(this.log("Creating event source with url "+g),this.eventSource=new T(g),this.eventSource.addEventListener("environment_updated",function(w){var x;try{x=JSON.parse(w.data).updated_at}catch(R){m.log("Could not parse sse event",R)}x?!m.timestamp||x>m.timestamp?m.isLoading?m.log("updated_at is new, but flags are loading",w.data,m.timestamp):(m.log("updated_at is new, fetching flags",w.data,m.timestamp),m.getFlags()):m.log("updated_at is outdated, skipping get flags",w.data,m.timestamp):m.log("No updated_at received, fetching flags",w)})):this.log("Error, EventSource is undefined")},b}();function E(b){var f=b.fetch,h=b.AsyncStorage,m=b.eventSource;return new I({fetch:f,AsyncStorage:h,eventSource:m})}var P,V=(P=function(b,f){return P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,m){h.__proto__=m}||function(h,m){for(var g in m)Object.prototype.hasOwnProperty.call(m,g)&&(h[g]=m[g])},P(b,f)},function(b,f){if(typeof f!="function"&&f!==null)throw new TypeError("Class extends value "+String(f)+" is not a constructor or null");function h(){this.constructor=b}P(b,f),b.prototype=f===null?Object.create(f):(h.prototype=f.prototype,new h)}),j=function(b){var f=typeof Symbol=="function"&&Symbol.iterator,h=f&&b[f],m=0;if(h)return h.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&m>=b.length&&(b=void 0),{value:b&&b[m++],done:!b}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},q=function(b,f){var h=typeof Symbol=="function"&&b[Symbol.iterator];if(!h)return b;var m,g,w=h.call(b),x=[];try{for(;(f===void 0||f-- >0)&&!(m=w.next()).done;)x.push(m.value)}catch(R){g={error:R}}finally{try{m&&!m.done&&(h=w.return)&&h.call(w)}finally{if(g)throw g.error}}return x},C=function(b,f,h){if(h||arguments.length===2)for(var m,g=0,w=f.length;g<w;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return b.concat(m||Array.prototype.slice.call(f))},F=function(b){function f(){return b.call(this,`EventSource not available.
|
|
648
|
-
Consider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.`)||this}return V(f,b),f}(Error),G=function(){function b(f,h){var m=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=h!=null?Object.assign({},h):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=f.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,this._configuration!=null&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),this.eventSourceClass==null||typeof this.eventSourceClass!="function")throw new F;this._onevent_wrapped=function(g){m._onevent(g)},this._start()}return b.prototype.dispatchEvent=function(f){throw new Error("Method not implemented.")},b.prototype._start=function(){var f,h,m=this,g=this.url;this._lastEventId&&(g.indexOf("?")===-1?g+="?":g+="&",g+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(g,this._configuration),this._eventSource.onopen=function(M){m._onopen(M)},this._eventSource.onerror=function(M){m._onerror(M)},this._eventSource.onmessage=function(M){m.onmessage(M)};try{for(var w=j(Object.keys(this._listeners)),x=w.next();!x.done;x=w.next()){var R=x.value;this._eventSource.addEventListener(R,this._onevent_wrapped)}}catch(M){f={error:M}}finally{try{x&&!x.done&&(h=w.return)&&h.call(w)}finally{if(f)throw f.error}}},b.prototype._onopen=function(f){this.readyState===0&&(this.readyState=1,this.onopen(f))},b.prototype._onerror=function(f){var h=this;if(this.readyState===1&&(this.readyState=0,this.onerror(f)),this._eventSource){this._eventSource.close(),this._eventSource=null;var m=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout(function(){return h._start()},m)}},b.prototype._onevent=function(f){var h,m;f&&f.lastEventId&&(this._lastEventId=f.lastEventId);var g=this._listeners[f.type];if(g!=null)try{for(var w=j(C([],q(g),!1)),x=w.next();!x.done;x=w.next())x.value.call(this,f)}catch(R){h={error:R}}finally{try{x&&!x.done&&(m=w.return)&&m.call(w)}finally{if(h)throw h.error}}f.type==="message"&&this.onmessage(f)},b.prototype.onopen=function(f){},b.prototype.onerror=function(f){},b.prototype.onmessage=function(f){},b.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},b.prototype.addEventListener=function(f,h,m){this._listeners[f]==null&&(this._listeners[f]=[],this._eventSource!=null&&this._eventSource.addEventListener(f,this._onevent_wrapped));var g=this._listeners[f];g.includes(h)||(this._listeners[f]=C(C([],q(g),!1),[h],!1))},b.prototype.removeEventListener=function(f,h,m){var g=this._listeners[f];this._listeners[f]=g.filter(function(w){return w!==h})},b}();globalThis.FlagsmithEventSource=typeof EventSource<"u"?EventSource:null;var K=function(b,f){return f=f||{},new Promise(function(h,m){var g=new XMLHttpRequest,w=[],x=[],R={},M=function(){return{ok:(g.status/100|0)==2,statusText:g.statusText,status:g.status,url:g.responseURL,text:function(){return Promise.resolve(g.responseText)},json:function(){return Promise.resolve(g.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([g.response]))},clone:M,headers:{keys:function(){return w},entries:function(){return x},get:function(_){return R[_.toLowerCase()]},has:function(_){return _.toLowerCase()in R}}}};for(var $ in g.open(f.method||"get",b,!0),g.onload=function(){g.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(_,W,ee){w.push(W=W.toLowerCase()),x.push([W,ee]),R[W]=R[W]?R[W]+","+ee:ee}),h(M())},g.onerror=m,g.withCredentials=f.credentials=="include",f.headers)g.setRequestHeader($,f.headers[$]);g.send(f.body||null)})},U=E({AsyncStorage:s,fetch:K,eventSource:G});typeof window<"u"&&(window.flagsmith=U),n.createFlagsmithInstance=function(){return E({AsyncStorage:s,fetch:K,eventSource:G})},n.default=U,Object.defineProperty(n,"__esModule",{value:!0})})})(Lt,Lt.exports);var Mi=Lt.exports;const Xn=Kn(Mi);var Jn={},Pi=function(t,e,n,s,i){var r=new Worker(Jn[e]||(Jn[e]=URL.createObjectURL(new Blob([t+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return r.onmessage=function(o){var l=o.data,a=l.$e$;if(a){var d=new Error(a[0]);d.code=a[1],d.stack=a[2],i(d,null)}else i(null,l)},r.postMessage(n,s),r},ce=Uint8Array,ie=Uint16Array,ot=Int32Array,at=new ce([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ct=new ce([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ft=new ce([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yn=function(t,e){for(var n=new ie(31),s=0;s<31;++s)n[s]=e+=1<<t[s-1];for(var i=new ot(n[30]),s=1;s<30;++s)for(var r=n[s];r<n[s+1];++r)i[r]=r-n[s]<<5|s;return{b:n,r:i}},Qn=Yn(at,2),Bi=Qn.b,lt=Qn.r;Bi[28]=258,lt[258]=28;for(var ji=Yn(ct,0),Mt=ji.r,dt=new ie(32768),J=0;J<32768;++J){var Ee=(J&43690)>>1|(J&21845)<<1;Ee=(Ee&52428)>>2|(Ee&13107)<<2,Ee=(Ee&61680)>>4|(Ee&3855)<<4,dt[J]=((Ee&65280)>>8|(Ee&255)<<8)>>1}for(var Me=function(t,e,n){for(var s=t.length,i=0,r=new ie(e);i<s;++i)t[i]&&++r[t[i]-1];var o=new ie(e);for(i=1;i<e;++i)o[i]=o[i-1]+r[i-1]<<1;var l;if(n){l=new ie(1<<e);var a=15-e;for(i=0;i<s;++i)if(t[i])for(var d=i<<4|t[i],c=e-t[i],u=o[t[i]-1]++<<c,p=u|(1<<c)-1;u<=p;++u)l[dt[u]>>a]=d}else for(l=new ie(s),i=0;i<s;++i)t[i]&&(l[i]=dt[o[t[i]-1]++]>>15-t[i]);return l},Ie=new ce(288),J=0;J<144;++J)Ie[J]=8;for(var J=144;J<256;++J)Ie[J]=9;for(var J=256;J<280;++J)Ie[J]=7;for(var J=280;J<288;++J)Ie[J]=8;for(var Xe=new ce(32),J=0;J<32;++J)Xe[J]=5;var Zn=Me(Ie,9,0),es=Me(Xe,5,0),Pt=function(t){return(t+7)/8|0},ts=function(t,e,n){return(e==null||e<0)&&(e=0),(n==null||n>t.length)&&(n=t.length),new ce(t.subarray(e,n))},zi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ns=function(t,e,n){var s=new Error(e||zi[t]);if(s.code=t,Error.captureStackTrace&&Error.captureStackTrace(s,ns),!n)throw s;return s},me=function(t,e,n){n<<=e&7;var s=e/8|0;t[s]|=n,t[s+1]|=n>>8},Pe=function(t,e,n){n<<=e&7;var s=e/8|0;t[s]|=n,t[s+1]|=n>>8,t[s+2]|=n>>16},ht=function(t,e){for(var n=[],s=0;s<t.length;++s)t[s]&&n.push({s,f:t[s]});var i=n.length,r=n.slice();if(!i)return{t:Ut,l:0};if(i==1){var o=new ce(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(N,O){return N.f-O.f}),n.push({s:-1,f:25001});var l=n[0],a=n[1],d=0,c=1,u=2;for(n[0]={s:-1,f:l.f+a.f,l,r:a};c!=i-1;)l=n[n[d].f<n[u].f?d++:u++],a=n[d!=c&&n[d].f<n[u].f?d++:u++],n[c++]={s:-1,f:l.f+a.f,l,r:a};for(var p=r[0].s,s=1;s<i;++s)r[s].s>p&&(p=r[s].s);var y=new ie(p+1),S=ut(n[c-1],y,0);if(S>e){var s=0,v=0,T=S-e,A=1<<T;for(r.sort(function(O,L){return y[L.s]-y[O.s]||O.f-L.f});s<i;++s){var B=r[s].s;if(y[B]>e)v+=A-(1<<S-y[B]),y[B]=e;else break}for(v>>=T;v>0;){var D=r[s].s;y[D]<e?v-=1<<e-y[D]++-1:++s}for(;s>=0&&v;--s){var k=r[s].s;y[k]==e&&(--y[k],++v)}S=e}return{t:new ce(y),l:S}},ut=function(t,e,n){return t.s==-1?Math.max(ut(t.l,e,n+1),ut(t.r,e,n+1)):e[t.s]=n},Bt=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new ie(++e),s=0,i=t[0],r=1,o=function(a){n[s++]=a},l=1;l<=e;++l)if(t[l]==i&&l!=e)++r;else{if(!i&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(i),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(i);r=1,i=t[l]}return{c:n.subarray(0,s),n:e}},Be=function(t,e){for(var n=0,s=0;s<e.length;++s)n+=t[s]*e[s];return n},jt=function(t,e,n){var s=n.length,i=Pt(e+2);t[i]=s&255,t[i+1]=s>>8,t[i+2]=t[i]^255,t[i+3]=t[i+1]^255;for(var r=0;r<s;++r)t[i+r+4]=n[r];return(i+4+s)*8},zt=function(t,e,n,s,i,r,o,l,a,d,c){me(e,c++,n),++i[256];for(var u=ht(i,15),p=u.t,y=u.l,S=ht(r,15),v=S.t,T=S.l,A=Bt(p),B=A.c,D=A.n,k=Bt(v),N=k.c,O=k.n,L=new ie(19),I=0;I<B.length;++I)++L[B[I]&31];for(var I=0;I<N.length;++I)++L[N[I]&31];for(var E=ht(L,7),P=E.t,V=E.l,j=19;j>4&&!P[Ft[j-1]];--j);var q=d+5<<3,C=Be(i,Ie)+Be(r,Xe)+o,F=Be(i,p)+Be(r,v)+o+14+3*j+Be(L,P)+2*L[16]+3*L[17]+7*L[18];if(a>=0&&q<=C&&q<=F)return jt(e,c,t.subarray(a,a+d));var G,K,U,b;if(me(e,c,1+(F<C)),c+=2,F<C){G=Me(p,y,0),K=p,U=Me(v,T,0),b=v;var f=Me(P,V,0);me(e,c,D-257),me(e,c+5,O-1),me(e,c+10,j-4),c+=14;for(var I=0;I<j;++I)me(e,c+3*I,P[Ft[I]]);c+=3*j;for(var h=[B,N],m=0;m<2;++m)for(var g=h[m],I=0;I<g.length;++I){var w=g[I]&31;me(e,c,f[w]),c+=P[w],w>15&&(me(e,c,g[I]>>5&127),c+=g[I]>>12)}}else G=Zn,K=Ie,U=es,b=Xe;for(var I=0;I<l;++I){var x=s[I];if(x>255){var w=x>>18&31;Pe(e,c,G[w+257]),c+=K[w+257],w>7&&(me(e,c,x>>23&31),c+=at[w]);var R=x&31;Pe(e,c,U[R]),c+=b[R],R>3&&(Pe(e,c,x>>5&8191),c+=ct[R])}else Pe(e,c,G[x]),c+=K[x]}return Pe(e,c,G[256]),c+K[256]},ss=new ot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ut=new ce(0),is=function(t,e,n,s,i,r){var o=r.z||t.length,l=new ce(s+o+5*(1+Math.ceil(o/7e3))+i),a=l.subarray(s,l.length-i),d=r.l,c=(r.r||0)&7;if(e){c&&(a[0]=r.r>>3);for(var u=ss[e-1],p=u>>13,y=u&8191,S=(1<<n)-1,v=r.p||new ie(32768),T=r.h||new ie(S+1),A=Math.ceil(n/3),B=2*A,D=function(ne){return(t[ne]^t[ne+1]<<A^t[ne+2]<<B)&S},k=new ot(25e3),N=new ie(288),O=new ie(32),L=0,I=0,E=r.i||0,P=0,V=r.w||0,j=0;E+2<o;++E){var q=D(E),C=E&32767,F=T[q];if(v[C]=F,T[q]=C,V<=E){var G=o-E;if((L>7e3||P>24576)&&(G>423||!d)){c=zt(t,a,0,k,N,O,I,P,j,E-j,c),P=L=I=0,j=E;for(var K=0;K<286;++K)N[K]=0;for(var K=0;K<30;++K)O[K]=0}var U=2,b=0,f=y,h=C-F&32767;if(G>2&&q==D(E-h))for(var m=Math.min(p,G)-1,g=Math.min(32767,E),w=Math.min(258,G);h<=g&&--f&&C!=F;){if(t[E+U]==t[E+U-h]){for(var x=0;x<w&&t[E+x]==t[E+x-h];++x);if(x>U){if(U=x,b=h,x>m)break;for(var R=Math.min(h,x-2),M=0,K=0;K<R;++K){var $=E-h+K&32767,_=v[$],W=$-_&32767;W>M&&(M=W,F=$)}}}C=F,F=v[C],h+=C-F&32767}if(b){k[P++]=268435456|lt[U]<<18|Mt[b];var ee=lt[U]&31,ae=Mt[b]&31;I+=at[ee]+ct[ae],++N[257+ee],++O[ae],V=E+U,++L}else k[P++]=t[E],++N[t[E]]}}for(E=Math.max(E,V);E<o;++E)k[P++]=t[E],++N[t[E]];c=zt(t,a,d,k,N,O,I,P,j,E-j,c),d||(r.r=c&7|a[c/8|0]<<3,c-=7,r.h=T,r.p=v,r.i=E,r.w=V)}else{for(var E=r.w||0;E<o+d;E+=65535){var te=E+65535;te>=o&&(a[c/8|0]=d,te=o),c=jt(a,c+1,t.subarray(E,te))}r.i=o}return ts(l,0,s+Pt(c)+i)},rs=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,s=9;--s;)n=(n&1&&-306674912)^n>>>1;t[e]=n}return t}(),os=function(){var t=-1;return{p:function(e){for(var n=t,s=0;s<e.length;++s)n=rs[n&255^e[s]]^n>>>8;t=n},d:function(){return~t}}},Ht=function(t,e,n,s,i){if(!i&&(i={l:1},e.dictionary)){var r=e.dictionary.subarray(-32768),o=new ce(r.length+t.length);o.set(r),o.set(t,r.length),t=o,i.w=r.length}return is(t,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(t.length)))*1.5):20:12+e.mem,n,s,i)},Ui=function(t,e){var n={};for(var s in t)n[s]=t[s];for(var s in e)n[s]=e[s];return n},as=function(t,e,n){for(var s=t(),i=t.toString(),r=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),o=0;o<s.length;++o){var l=s[o],a=r[o];if(typeof l=="function"){e+=";"+a+"=";var d=l.toString();if(l.prototype)if(d.indexOf("[native code]")!=-1){var c=d.indexOf(" ",8)+1;e+=d.slice(c,d.indexOf("(",c))}else{e+=d;for(var u in l.prototype)e+=";"+a+".prototype."+u+"="+l.prototype[u].toString()}else e+=d}else n[a]=l}return e},ft=[],Hi=function(t){var e=[];for(var n in t)t[n].buffer&&e.push((t[n]=new t[n].constructor(t[n])).buffer);return e},$i=function(t,e,n,s){if(!ft[n]){for(var i="",r={},o=t.length-1,l=0;l<o;++l)i=as(t[l],i,r);ft[n]={c:as(t[o],i,r),e:r}}var a=Ui({},ft[n].e);return Pi(ft[n].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",n,a,Hi(a),s)},qi=function(){return[ce,ie,ot,at,ct,Ft,lt,Mt,Zn,Ie,es,Xe,dt,ss,Ut,Me,me,Pe,ht,ut,Bt,Be,jt,zt,Pt,ts,is,Ht,Vi,cs]},Wi=function(){return[ls,ds,pt,os,rs]},cs=function(t){return postMessage(t,[t.buffer])},Gi=function(t,e,n,s,i,r){var o=$i(n,s,i,function(l,a){o.terminate(),r(l,a)});return o.postMessage([t,e],e.consume?[t.buffer]:[]),function(){o.terminate()}},pt=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8},ls=function(t,e){var n=e.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=e.level<2?4:e.level==9?2:0,t[9]=3,e.mtime!=0&&pt(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),n){t[3]=8;for(var s=0;s<=n.length;++s)t[s+10]=n.charCodeAt(s)}},ds=function(t){return 10+(t.filename?t.filename.length+1:0)};function Vi(t,e){return Ht(t,e||{},0,0)}function Ki(t,e,n){return n||(n=e,e={}),typeof n!="function"&&ns(7),Gi(t,e,[qi,Wi,function(){return[hs]}],function(s){return cs(hs(s.data[0],s.data[1]))},2,n)}function hs(t,e){e||(e={});var n=os(),s=t.length;n.p(t);var i=Ht(t,e,ds(e),8),r=i.length;return ls(i,e),pt(i,r-8,n.d()),pt(i,r-4,s),i}var Xi=typeof TextDecoder<"u"&&new TextDecoder,Ji=0;try{Xi.decode(Ut,{stream:!0}),Ji=1}catch{}class us{constructor(){this.idx=1,this.backDict={}}getKey(e){let n=!1;return this.backDict[e]||(n=!0,this.backDict[e]=this.idx++),[this.backDict[e],n]}}class Yi{constructor(e,n){this.app=e,this.isDictDisabled=n,this.dict=new us}sendSetAttribute(e,n,s){if(this.isDictDisabled){const i=[12,e,n,s];return this.app.send(i)}else{const i=[51,e,this.applyDict(n),this.applyDict(s)];return this.app.send(i)}}applyDict(e){const[n,s]=this.dict.getKey(e);return s&&this.app.send([50,n,e]),n}clear(){this.dict=new us}}class Qi{constructor(e,n){this.app=e,this.startParams=n,this.conditions=[],this.hasStarted=!1,this.createConditionFromFilter=s=>{if(s.value.length){const i=Zi(s);if(i.type)return i}},this.durationInt=null}setConditions(e){this.conditions=e}async fetchConditions(e,n){try{const s=await fetch(`${this.app.options.ingestPoint}/v1/web/conditions/${e}`,{method:"GET",headers:{Authorization:`Bearer ${n}`}}),{conditions:i}=await s.json(),r=[];i.forEach(o=>{o.filters.forEach(a=>{let d;a.type==="fetch"?(d={type:"network_request",subConditions:[],name:o.name},a.filters.forEach(c=>{const u=this.createConditionFromFilter(c);u&&d.subConditions.push(u)})):d=this.createConditionFromFilter(a),d&&(d.type==="session_duration"&&this.processDuration(d.value[0],o.name),r.push({...d,name:o.name}))})}),this.conditions=r}catch{this.app.debug.error("Critical: cannot fetch start conditions")}}trigger(e){if(!this.hasStarted)try{this.hasStarted=!0,this.app.start(this.startParams,void 0,e)}catch(n){this.app.debug.error(n)}}processMessage(e){if(!this.hasStarted)switch(e[0]){case 78:this.jsExceptionEvent(e);break;case 27:this.customEvent(e);break;case 68:this.clickEvent(e);break;case 122:this.pageLocationEvent(e);break;case 83:this.networkRequest(e);break}}processFlags(e){const n=this.conditions.filter(s=>s.type==="feature_flag");n.length&&n.forEach(s=>{const i=je[s.operator];i&&e.find(r=>i(r.key,s.value))&&this.trigger(s.name)})}processDuration(e,n){this.durationInt=setInterval(()=>{performance.now()>e&&this.trigger(n)},1e3),this.app.attachStopCallback(()=>{this.durationInt&&clearInterval(this.durationInt)})}networkRequest(e){const n=this.conditions.filter(s=>s.type==="network_request");n.length&&n.forEach(s=>{const i=s.subConditions.filter(r=>r.operator!=="isAny");i.length?i.every(o=>{let l;switch(o.key){case"url":l=e[3];break;case"status":l=e[6];break;case"method":l=e[2];break;case"duration":l=e[8];break}const a=je[o.operator];if(a&&a(l,o.value))return!0})&&this.trigger(s.name):i.length===0&&s.subConditions.length&&this.trigger(s.name)})}customEvent(e){const n=this.conditions.filter(s=>s.type==="custom_event");n.length&&n.forEach(s=>{const i=je[s.operator];i&&(i(e[1],s.value)||i(e[2],s.value))&&this.trigger(s.name)})}clickEvent(e){const n=this.conditions.filter(s=>s.type==="click");n.length&&n.forEach(s=>{const i=je[s.operator];i&&(i(e[3],s.value)||i(e[4],s.value))&&this.trigger(s.name)})}pageLocationEvent(e){const n=this.conditions.filter(s=>s.type==="visited_url");n&&n.forEach(s=>{const i=je[s.operator];i&&i(e[1],s.value)&&this.trigger(s.name)})}jsExceptionEvent(e){const n=[e[1],e[2],e[3]],s=this.conditions.filter(i=>i.type==="exception");s&&s.forEach(i=>{const r=je[i.operator];r&&n.some(o=>r(o,i.value))&&this.trigger(i.name)})}}const je={is:(t,e)=>e.some(n=>t.includes(n)),isAny:()=>!0,isNot:(t,e)=>!e.some(n=>t.includes(n)),contains:(t,e)=>e.some(n=>t.includes(n)),notContains:(t,e)=>!e.some(n=>t.includes(n)),startsWith:(t,e)=>e.some(n=>t.startsWith(n)),endsWith:(t,e)=>e.some(n=>t.endsWith(n)),greaterThan:(t,e)=>t>e,greaterOrEqual:(t,e)=>t>=e,lessOrEqual:(t,e)=>t<=e,lessThan:(t,e)=>t<e},Zi=t=>{const e={on:"is",notOn:"isNot",">":"greaterThan","<":"lessThan","=":"is","<=":"lessOrEqual",">=":"greaterOrEqual"},n=i=>{if(Object.keys(e).includes(i))return e[i]};let s={type:"",operator:"",value:t.value,key:""};switch(t.type){case"click":s={type:"click",operator:n(t.operator),value:t.value,key:""};break;case"location":s={type:"visited_url",operator:t.operator,value:t.value,key:""};break;case"custom":s={type:"custom_event",operator:t.operator,value:t.value,key:""};break;case"metadata":s={type:t.source==="featureFlag"?"feature_flag":t.type,operator:t.operator,value:t.value,key:""};break;case"error":s={type:"exception",operator:t.operator,value:t.value,key:""};break;case"duration":s={type:"session_duration",value:t.value[0],key:""};break;case"fetchUrl":s={type:"network_request",key:"url",operator:t.operator,value:t.value};break;case"fetchStatusCode":s={type:"network_request",key:"status",operator:n(t.operator),value:t.value};break;case"fetchMethod":s={type:"network_request",key:"method",operator:n(t.operator),value:t.value};break;case"fetchDuration":s={type:"network_request",key:"duration",operator:n(t.operator),value:t.value};break}return s};class er{constructor(e){this.app=e,this.flags=[],this.storageKey="__openreplay_flags";const n=this.app.sessionStorage.getItem(this.storageKey);if(n){const s=n.split(";").filter(Boolean);this.flags=s.map(i=>JSON.parse(i))}}getFeatureFlag(e){return this.flags.find(n=>n.key===e)}isFlagEnabled(e){return this.flags.findIndex(n=>n.key===e)!==-1}onFlagsLoad(e){this.onFlagsCb=e}async reloadFlags(e){const n=this.app.sessionStorage.getItem(this.storageKey),s={};n&&n.split(";").filter(Boolean).forEach(c=>{const u=JSON.parse(c);s[u.key]={key:u.key,value:u.value}});const i=this.app.session.getInfo(),r=this.app.session.userInfo,o={projectID:i.projectID,userID:i.userID,metadata:i.metadata,referrer:document.referrer,os:r.userOS,device:r.userDevice,country:r.userCountry,state:r.userState,city:r.userCity,browser:r.userBrowser,persistFlags:s},l=e??this.app.session.getSessionToken(),a=await fetch(this.app.options.ingestPoint+"/v1/web/feature-flags",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(o)});if(a.status===200){const d=await a.json();return this.handleFlags(d.flags)}}handleFlags(e){var r;const n=[];e.forEach(o=>{o.is_persist&&n.push(o)});let s="";return this.diffPersist(n).forEach(o=>{s+=`${JSON.stringify(o)};`}),this.app.sessionStorage.setItem(this.storageKey,s),this.flags=e,(r=this.onFlagsCb)==null?void 0:r.call(this,e)}clearPersistFlags(){this.app.sessionStorage.removeItem(this.storageKey)}diffPersist(e){const n=this.app.sessionStorage.getItem(this.storageKey);if(!n)return e;const i=n.split(";").filter(Boolean).map(r=>JSON.parse(r));return e.filter(r=>i.findIndex(o=>o.key===r.key)===-1)}}const fs={htmlmasked:"hidden",masked:"obscured"},be=!(typeof window>"u"),tr=be&&navigator.userAgent.match(/firefox|fxios/i),nr=1e5;let $t=be?Date.now()-performance.now():0;function qt(){$t=Date.now()-performance.now()}function ze(){return $t}const pe=be&&performance.now?()=>Math.round(performance.now()+$t):()=>Date.now(),Wt="repeat"in String.prototype?t=>"*".repeat(t.length):t=>t.replace(/./g,"*");function ps(t){return t.trim().replace(/\s+/g," ")}function gs(t){return t.startsWith("https://")||t.startsWith("http://")}const gt="https://docs.openreplay.com",ms={};function Ce(t,e,n="/"){ms[t]||(console.warn(`OpenReplay: ${t} is deprecated. ${e?`Please, use ${e} instead.`:""} Visit ${gt}${n} for more information.`),ms[t]=!0)}function Gt(t){let e=t.getAttribute("data-openreplay-label");return e!==null||(e=t.getAttribute("data-asayer-label"),e!==null&&Ce('"data-asayer-label" attribute','"data-openreplay-label" attribute',"/")),e}function Re(t,e){const n=`data-openreplay-${e}`;return t.hasAttribute(n)?(fs[e]&&Ce(`"${n}" attribute`,`"${fs[e]}" attribute`,"/installation/sanitize-data"),!0):!1}function sr(t){try{return!!t.contentDocument}catch{return!1}}function bs(t){return t.toString(16).padStart(2,"0")}function ir(t){const e=new Uint8Array((t||40)/2),n=window.crypto||window.msCrypto;return n?(n.getRandomValues(e),Array.from(e,bs).join("")):Array.from({length:t||40},()=>bs(Math.floor(Math.random()*16))).join("")}function rr(){try{return window.self&&window.top&&window.self!==window.top}catch{return!0}}function Vt(t){return window.Zone&&"__symbol__"in window.Zone?window.Zone.__symbol__(t):t}function ys(t){const e=Vt("MutationObserver");return new window[e](t)}function vs(t,e,n,s){const i=Vt("addEventListener");try{t[i](e,n,s)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}function ws(t,e,n,s){const i=Vt("removeEventListener");try{t[i](e,n,s)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}class or{constructor(){this.taskQueue=[],this.isRunning=!1}addTask(e){this.taskQueue.push(e),this.runTasks()}runTasks(){if(this.isRunning||this.taskQueue.length===0)return;this.isRunning=!0;const e=()=>{if(this.taskQueue.length===0){this.isRunning=!1;return}const n=this.taskQueue.shift();Promise.resolve(n()).then(()=>{requestAnimationFrame(()=>e())})};e()}}const ar=new or;function cr(t){ar.addTask(t)}function Ss(t,e){const n={...t};for(const s in e)if(e.hasOwnProperty(s)){const i=e[s],r=t[s];typeof i=="object"&&!Array.isArray(i)&&i!==null?n[s]=Ss(r||{},i):n[s]=i}return n}function Ae(t){return[0,t]}function lr(t,e){return[5,t,e]}function dr(t,e){return[6,t,e]}function hr(){return[7]}function ur(t,e,n,s,i){return[8,t,e,n,s,i]}function fr(t,e,n){return[9,t,e,n]}function pr(t,e,n){return[10,t,e,n]}function gr(t){return[11,t]}function xs(t,e){return[13,t,e]}function mr(t,e){return[14,t,e]}function br(t,e,n){return[16,t,e,n]}function yr(t,e,n){return[18,t,e,n]}function vr(t,e){return[19,t,e]}function wr(t,e){return[20,t,e]}function Sr(t,e){return[22,t,e]}function xr(t,e,n,s,i,r,o,l,a){return[23,t,e,n,s,i,r,o,l,a]}function kr(t,e,n){return[24,t,e,n]}function Tr(t,e){return[27,t,e]}function Er(t){return[28,t]}function Ir(t){return[29,t]}function ks(t,e){return[30,t,e]}function Cr(t,e,n,s){return[49,t,e,n,s]}function _r(t,e){return[54,t,e]}function Nr(t){return[55,t]}function Ts(t,e,n,s){return[57,t,e,n,s]}function Es(t){return[58,t]}function Kt(t,e,n,s){return[60,t,e,n,s]}function Or(t,e,n){return[61,t,e,n]}function Rr(t,e){return[63,t,e]}function Ar(t,e){return[64,t,e]}function Dr(t,e,n,s,i,r){return[68,t,e,n,s,i,r]}function Xt(t,e){return[70,t,e]}function Is(t,e,n){return[71,t,e,n]}function Jt(t,e,n,s){return[73,t,e,n,s]}function Cs(t,e){return[75,t,e]}function _s(t,e){return[76,t,e]}function Lr(t,e){return[77,t,e]}function Yt(t,e,n,s){return[78,t,e,n,s]}function mt(t,e,n,s,i,r,o,l,a){return[83,t,e,n,s,i,r,o,l,a]}function Fr(t,e,n,s,i,r){return[84,t,e,n,s,i,r]}function Mr(t,e,n,s,i,r){return[112,t,e,n,s,i,r]}function Ns(t,e,n){return[113,t,e,n]}function Pr(t){return[114,t]}function Br(t){return[115,t]}function Os(t,e,n,s,i,r,o,l,a,d){return[116,t,e,n,s,i,r,o,l,a,d]}function bt(t){return[117,t]}function De(t){return[118,t]}function jr(t,e){return[119,t,e]}function zr(t){return[120,t]}function Ur(t,e,n,s){return[122,t,e,n,s]}const Qt=be&&"performance"in window&&"memory"in performance?performance:{memory:{}},Zt=be?(navigator.deviceMemory||0)*1024:0,en=Qt.memory.jsHeapSizeLimit||0;function Hr(t,e){if(!Object.assign({capturePerformance:!0},e).capturePerformance)return;let s,i;const r=()=>{s===void 0||s===-1||(s++,requestAnimationFrame(r))};t.ticker.attach(()=>{i===void 0||i===-1||i++},0,!1);const o=()=>{s===void 0||i===void 0||(t.send(Cr(s,i,Qt.memory.totalJSHeapSize||0,Qt.memory.usedJSHeapSize||0)),i=s=document.hidden?-1:0)};t.attachStartCallback(()=>{i=s=-1,o(),r()}),t.attachStopCallback(()=>{i=s=void 0}),t.ticker.attach(o,40,!1),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",o,!1,!1)}const Rs="__or__watched_tags__";class $r{constructor(e,n,s){this.sessionStorage=e,this.errLog=n,this.onTag=s,this.intervals={},this.tags=[];const i=JSON.parse(e.getItem(Rs)??"[]");this.setTags(i),this.observer=new IntersectionObserver(r=>{r.forEach(o=>{if(o.isIntersecting&&o.target){const l=o.target.__or_watcher_tagname;l&&this.onTagRendered(l),this.observer.unobserve(o.target)}})})}async fetchTags(e,n){return fetch(`${e}/v1/web/tags`,{method:"GET",headers:{Authorization:`Bearer ${n}`}}).then(s=>s.json()).then(({tags:s})=>{if(s&&s.length){this.setTags(s);const i=JSON.stringify(s);this.sessionStorage.setItem(Rs,i||"")}}).catch(s=>this.errLog(s))}setTags(e){this.tags=e,this.intervals={},e.forEach(n=>{this.intervals[n.id]=setInterval(()=>{const s=document.querySelectorAll(n.selector);if(s.length>0){const i=s[0];i.__or_watcher_tagname=n.id,this.observer.observe(i)}},500)})}onTagRendered(e){this.intervals[e]&&clearInterval(this.intervals[e]),this.onTag(e)}clear(){this.tags.forEach(e=>{clearInterval(this.intervals[e.id])}),this.tags=[],this.intervals={},this.observer.disconnect()}}const qr={position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0, 0, 0, 0.40)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:999999,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"'},Wr={display:"flex",flexDirection:"column",gap:"2rem",alignItems:"center",padding:"1.5rem",borderRadius:"2px",border:"1px solid #D9D9D9",background:"#FFF",width:"22rem"},yt={display:"flex","flex-direction":"column",gap:"unset","align-items":"center",padding:"unset",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',"border-radius":"2px",border:"1px solid #D9D9D9",background:"rgba(255, 255, 255, 0.75)",width:"22rem"},Gr={fontFamily:"Verdana, sans-serif",fontSize:"1.25rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.75rem",color:"rgba(0, 0, 0, 0.85)"},Vr={borderTop:"1px solid rgba(0, 0, 0, 0.06)",borderBottom:"1px solid rgba(0, 0, 0, 0.06)",padding:"1.25rem 0rem",color:"rgba(0, 0, 0, 0.85)",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"400",lineHeight:"auto",whiteSpace:"pre-wrap"},Kr={display:"flex",padding:"0.4rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.625rem",borderRadius:"0.25rem",border:"1px solid #394EFF",background:"#394EFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",color:"#FFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"1rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.5rem",cursor:"pointer"},As={fontFamily:"Verdana, sans-serif",fontSize:"13px",fontWeight:"500",lineHeight:"auto",display:"flex",justifyContent:"space-between",width:"100%",cursor:"pointer"},Ue={display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"0.625rem",fontSize:"13px",lineHeight:"auto"},Xr={padding:"0.5rem",gap:"0.5rem",fontFamily:"Verdana, sans-serif",fontSize:"16px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto",color:"white",display:"flex",alignItems:"center",width:"100%",borderRadius:"2px",background:"rgba(0, 0, 0, 0.75)",boxSizing:"border-box"},He={boxSizing:"border-box",display:"block",width:"100%",borderBottom:"1px solid #D9D9D9",background:"#FFF",padding:"0.65rem",alignSelf:"stretch",color:"#000",fontFamily:"Verdana, sans-serif",fontStyle:"normal",fontWeight:"400"},Jr={...He,display:"flex",flexDirection:"column",alignItems:"center",gap:"0.625rem"},Ds={fontSize:"1.25rem",fontWeight:"500",cursor:"pointer",color:"#394EFF"},Ls={display:"flex",padding:"0.4rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.625rem",borderRadius:"0.25rem",border:"1px solid #394EFF",background:"#394EFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",color:"#FFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"1rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.5rem",width:"100%",boxSizing:"border-box",cursor:"pointer"},Fs={marginTop:"1rem",marginBottom:"1rem",cursor:"pointer",display:"block",fontWeight:"500",fontSize:"13px!important",lineHeight:"auto"},Yr={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",padding:"0.5rem",width:"100%",boxSizing:"border-box"},Ms={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #394EFF",fontSize:"13px",height:"24px",width:"24px"},Qr={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #D2DFFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",background:"#D2DFFF",fontSize:"13px",height:"24px",width:"24px"},Ps={borderRadius:"0.375rem",border:"1px solid rgba(0, 0, 0, 0.06)",background:"#F5F7FF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",display:"flex",flexDirection:"column",padding:"0.625rem 0.9375rem",gap:"0.5rem",alignSelf:"stretch"},Bs={fontWeight:"bold"},Zr={fontSize:"13px",lineHeight:"auto"},js={marginRight:"0.5rem",cursor:"pointer",color:"#394EFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto"},eo={...js,display:"flex",padding:"0.25rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.5rem",borderRadius:"0.25rem",border:"1px solid #394EFF"},to={display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",boxSizing:"border-box"},no={border:"4px solid rgba(255, 255, 255, 0.4)",width:"16px",height:"16px",borderRadius:"50%",borderLeftColor:"#fff",animation:"spin 0.5s linear infinite"},zs={Standard:{width:1280,height:720},High:{width:1920,height:1080}};class so{constructor(e){this.app=e,this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this.recStartTs=null}async startRecording(e,n,s,i){this.recStartTs=this.app.timestamp();const r=n;try{this.stream=await navigator.mediaDevices.getUserMedia({video:i?{...r,frameRate:{ideal:e}}:!1,audio:s}),this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/webm;codecs=vp9"}),this.recordedChunks=[],this.mediaRecorder.ondataavailable=o=>{o.data.size>0&&this.recordedChunks.push(o.data)},this.mediaRecorder.start()}catch(o){console.error(o)}}async stopRecording(){return new Promise(e=>{this.mediaRecorder&&(this.mediaRecorder.onstop=()=>{const n=new Blob(this.recordedChunks,{type:"video/webm"});e(n)},this.mediaRecorder.stop())})}async sendToAPI(){const e=await this.stopRecording();return fetch(`${this.app.options.ingestPoint}/v1/web/uxt/upload-url`,{headers:{Authorization:`Bearer ${this.app.session.getSessionToken()}`}}).then(n=>{if(n.ok)return n.json();throw new Error("Failed to get upload url")}).then(({url:n})=>fetch(n,{method:"PUT",headers:{"Content-Type":"video/webm"},body:e})).catch(console.error).finally(()=>{this.discard()})}async saveToFile(e="recorded-video.webm"){const n=await this.stopRecording(),s=URL.createObjectURL(n),i=document.createElement("a");i.style.display="none",i.href=s,i.download=e,document.body.appendChild(i),i.click(),window.URL.revokeObjectURL(s),document.body.removeChild(i)}discard(){var e,n;(e=this.mediaRecorder)==null||e.stop(),(n=this.stream)==null||n.getTracks().forEach(s=>s.stop())}}function io(t,e){e.onmousedown=function(n){const s=t.getBoundingClientRect(),i=n.clientX-s.left,r=n.clientY-s.top;t.style.position="fixed",t.style.zIndex=99999999999999,o(n.pageX,n.pageY);function o(d,c){let u=d-i,p=c-r;u<=5&&(u=5),p<=5&&(p=5),u>=window.innerWidth-s.width&&(u=window.innerWidth-s.width),p>=window.innerHeight-s.height&&(p=window.innerHeight-s.height),t.style.left=`${u}px`,t.style.top=`${p}px`}function l(d){o(d.pageX,d.pageY)}document.addEventListener("mousemove",l);const a=()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",a)};document.addEventListener("mouseup",a)},e.ondragstart=function(){return!1}}function ro(){const t=document.createElement("div");t.className="grid";for(let e=0;e<16;e++){const n=document.createElement("div");Object.assign(n.style,{width:"2px",height:"2px",borderRadius:"10px",background:"white"}),n.className="cell",t.appendChild(n)}return Object.assign(t.style,{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gridTemplateRows:"repeat(4, 1fr)",gap:"2px",cursor:"grab"}),t}function oo(){const t=document.createElement("div");Object.assign(t.style,{width:"0",height:"0",borderLeft:"7px solid transparent",borderRight:"7px solid transparent",borderBottom:"7px solid white"});const e=document.createElement("div");return e.appendChild(t),Object.assign(e.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",cursor:"pointer",marginLeft:"auto",transform:"rotate(180deg)"}),e}function ao(){const t=document.createElement("style");t.type="text/css",t.innerText=`@keyframes spin {
|
|
647
|
+
`,Gn=document.createElement("style");Gn.textContent=st,document.head.appendChild(Gn);function Ns(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function rt(t,e,n){console.log(t,n);let i="";if(n){const s=new Date;s.setTime(s.getTime()+n*24*60*60*1e3),i="; expires="+s.toUTCString()}document.cookie=t+"="+(e||"")+i+"; path=/; secure; samesite=strict"}function ie(t){const e=t+"=",n=document.cookie.split(";");for(let i=0;i<n.length;i++){let s=n[i];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return s.substring(e.length,s.length)}return null}function Os(t){document.cookie=t+"=; Max-Age=-99999999;"}function Rs(){const t="uniqueUserID";let e=ie(t);return e||(e=Ns(),rt(t,e,365)),e}function Ke(t,e){fetch("https://wineater-backend.vercel.app/proxy/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:t,properties:e})}).then(s=>{s.ok||console.error("Mixpanel tracking failed",s)}).catch(s=>{console.error("Mixpanel tracking error",s)})}function As(){Ke("Chatbot Opened",{distinct_id:ie("uniqueUserID"),client:ie("chatbotToken")})}function Vn(){Ke("Chatbot Closed",{distinct_id:ie("uniqueUserID"),client:ie("chatbotToken")})}function Ds(t){Ke("Message Sent",{distinct_id:ie("uniqueUserID"),message_content:t,client:ie("chatbotToken")})}function Ls(t){Ke("Products Got",{distinct_id:ie("uniqueUserID"),products:t,client:ie("chatbotToken")})}function Fs(t){Ke("Product Clicked",{distinct_id:ie("uniqueUserID"),product_id:t,client:ie("chatbotToken")})}var Fe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Kn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Lt={exports:{}};(function(t,e){(function(n,i){i(e)})(Fe,function(n){var i={getItemSync:function(b){try{return localStorage.getItem(b)||null}catch{return null}},getItem:function(b,f){var h=this;return new Promise(function(m,g){try{var w=h.getItemSync(b);f==null||f(null,w),m(w)}catch(x){f&&f(x,null),g(x)}})},setItem:function(b,f,h){return new Promise(function(m,g){try{localStorage.setItem(b,f),h&&h(null,f),m(f)}catch(w){h&&h(w,null),g(w)}})}},s=function(){return s=Object.assign||function(b){for(var f,h=1,m=arguments.length;h<m;h++)for(var g in f=arguments[h])Object.prototype.hasOwnProperty.call(f,g)&&(b[g]=f[g]);return b},s.apply(this,arguments)};function r(b,f,h,m){return new(h||(h=Promise))(function(g,w){function x($){try{M(m.next($))}catch(_){w(_)}}function R($){try{M(m.throw($))}catch(_){w(_)}}function M($){var _;$.done?g($.value):(_=$.value,_ instanceof h?_:new h(function(W){W(_)})).then(x,R)}M((m=m.apply(b,f||[])).next())})}function o(b,f){var h,m,g,w,x={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return w={next:R(0),throw:R(1),return:R(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function R(M){return function($){return function(_){if(h)throw new TypeError("Generator is already executing.");for(;x;)try{if(h=1,m&&(g=2&_[0]?m.return:_[0]?m.throw||((g=m.return)&&g.call(m),0):m.next)&&!(g=g.call(m,_[1])).done)return g;switch(m=0,g&&(_=[2&_[0],g.value]),_[0]){case 0:case 1:g=_;break;case 4:return x.label++,{value:_[1],done:!1};case 5:x.label++,m=_[1],_=[0];continue;case 7:_=x.ops.pop(),x.trys.pop();continue;default:if(g=x.trys,!((g=g.length>0&&g[g.length-1])||_[0]!==6&&_[0]!==2)){x=0;continue}if(_[0]===3&&(!g||_[1]>g[0]&&_[1]<g[3])){x.label=_[1];break}if(_[0]===6&&x.label<g[1]){x.label=g[1],g=_;break}if(g&&x.label<g[2]){x.label=g[2],x.ops.push(_);break}g[2]&&x.ops.pop(),x.trys.pop();continue}_=f.call(b,x)}catch(W){_=[6,W],m=0}finally{h=g=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}([M,$])}}}function l(b,f,h){if(h||arguments.length===2)for(var m,g=0,w=f.length;g<w;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return b.concat(m||Array.prototype.slice.call(f))}var a=function b(f,h){if(f===h)return!0;if(f&&h&&typeof f=="object"&&typeof h=="object"){if(f.constructor!==h.constructor)return!1;var m,g,w;if(Array.isArray(f)){if((m=f.length)!=h.length)return!1;for(g=m;g--!=0;)if(!b(f[g],h[g]))return!1;return!0}if(f.constructor===RegExp)return f.source===h.source&&f.flags===h.flags;if(f.valueOf!==Object.prototype.valueOf)return f.valueOf()===h.valueOf();if(f.toString!==Object.prototype.toString)return f.toString()===h.toString();if((m=(w=Object.keys(f)).length)!==Object.keys(h).length)return!1;for(g=m;g--!=0;)if(!Object.prototype.hasOwnProperty.call(h,w[g]))return!1;for(g=m;g--!=0;){var x=w[g];if(!b(f[x],h[x]))return!1}return!0}return f!=f&&h!=h};function d(b,f){var h=Object.keys(f||{}).filter(function(m){var g=b==null?void 0:b[m],w=f==null?void 0:f[m];return!a(g,w)});return Object.keys(b||{}).filter(function(m){Object.keys(f||{}).includes(m)||h.push(m)}),Object.keys(h).length?h:null}var c,u;function p(b,f,h){var m="shortString",g=!0;typeof h=="number"&&(m="javaDouble",g=!1),b[m]=b[m]||{},b[m][f]=g?h+"":h}function y(b){return!!b&&typeof b=="object"&&b.value!==void 0}function S(b){return Object.fromEntries(Object.entries(b).map(function(f){var h=f[0],m=f[1];return[h,y(m)?m:{value:m}]}))}function v(b){return s(s({},b),{identity:b.identity?s(s({},b.identity),{traits:S(b.identity.traits||{})}):void 0})}(function(b){b.NONE="NONE",b.DEFAULT_FLAGS="DEFAULT_FLAGS",b.CACHE="CACHE",b.SERVER="SERVER"})(c||(c={}));var T,A=null,B="BULLET_TRAIN_DB",D="BULLET_TRAIN_EVENT",k="https://edge.api.flagsmith.com/api/v1/",N="flagsmith_value_",O="flagsmith_enabled_",L="flagsmith_trait_",I=function(){function b(f){var h=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var m=h,g=m.api,w=m.evaluationContext;h.log("Get Flags"),h.isLoading=!0,h.loadingState.isFetching||h.setLoadingState(s(s({},h.loadingState),{isFetching:!0}));var x="".concat(h.getContext().identity),R=function(M){var $,_,W,ee;if(M&&x==="".concat(h.getContext().identity)){var ae=M.flags,te=M.traits,ne=M.identifier;h.isLoading=!1;var he={},ue={};te=te||[],(ae=ae||[]).forEach(function(X){he[X.feature.name.toLowerCase().replace(/ /g,"_")]={id:X.feature.id,enabled:X.enabled,value:X.feature_state_value}}),te.forEach(function(X){ue[X.trait_key.toLowerCase().replace(/ /g,"_")]={transient:X.transient,value:X.trait_value}}),h.oldFlags=s({},h.flags);var we=d(h.oldFlags,he),Ze=d(($=h.evaluationContext.identity)===null||$===void 0?void 0:$.traits,ue);if((ne||Object.keys(ue).length)&&(h.evaluationContext.identity={traits:ue},ne&&(h.evaluationContext.identity.identifier=ne)),h.flags=he,h.updateStorage(),h._onChange(h.oldFlags,{isFromServer:!0,flagsChanged:we,traitsChanged:Ze},h._loadedState(null,c.SERVER)),h.datadogRum)try{if(h.datadogRum.trackTraits){var et={};Object.keys(((_=h.evaluationContext.identity)===null||_===void 0?void 0:_.traits)||{}).map(function(X){et[L+X]=h.getTrait(X)});var We=s(s(s({},h.datadogRum.client.getUser()),{id:h.datadogRum.client.getUser().id||((W=h.evaluationContext.identity)===null||W===void 0?void 0:W.identifier)}),et);h.log("Setting Datadog user",We),h.datadogRum.client.setUser(We)}}catch(X){console.error(X)}if(h.dtrum)try{var re={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(h.flags).map(function(X){p(re,N+X,h.getValue(X,{skipAnalytics:!0})),p(re,O+X,h.hasFeature(X,{skipAnalytics:!0}))}),Object.keys(((ee=h.evaluationContext.identity)===null||ee===void 0?void 0:ee.traits)||{}).map(function(X){p(re,L+X,h.getTrait(X))}),h.log("Sending javaLongOrObject traits to dynatrace",re.javaLongOrObject),h.log("Sending date traits to dynatrace",re.date),h.log("Sending shortString traits to dynatrace",re.shortString),h.log("Sending javaDouble to dynatrace",re.javaDouble),h.dtrum.sendSessionProperties(re.javaLongOrObject,re.date,re.shortString,re.javaDouble)}catch(X){console.error(X)}}};return w.identity?Promise.all([w.identity.traits&&Object.keys(w.identity.traits).length||!w.identity.identifier?h.getJSON(g+"identities/","POST",JSON.stringify({identifier:w.identity.identifier,transient:w.identity.transient,traits:Object.entries(w.identity.traits).map(function(M){var $=M[0],_=M[1];return{trait_key:$,trait_value:_==null?void 0:_.value,transient:_==null?void 0:_.transient}}).filter(function(M){return M.trait_value!==void 0||(h.log("Warning - attempted to set an undefined trait value for key",M.trait_key),!1)})})):h.getJSON(g+"identities/?identifier="+encodeURIComponent(w.identity.identifier)+(w.identity.transient?"&transient=true":""))]).then(function(M){return h.evaluationContext.identity=s(s({},h.evaluationContext.identity),{traits:{}}),R(M==null?void 0:M[0])}).catch(function(M){var $=M.message,_=new Error($);return Promise.reject(_)}):h.getJSON(g+"flags/").then(function(M){return R({flags:M,traits:void 0})})},this.analyticsFlags=function(){var m=h.api;if(h.evaluationEvent&&h.evaluationContext.environment&&h.evaluationEvent[h.evaluationContext.environment.apiKey])return h.evaluationEvent&&Object.getOwnPropertyNames(h.evaluationEvent).length!==0&&Object.getOwnPropertyNames(h.evaluationEvent[h.evaluationContext.environment.apiKey]).length!==0?h.getJSON(m+"analytics/flags/","POST",JSON.stringify(h.evaluationEvent[h.evaluationContext.environment.apiKey])).then(function(g){if(h.evaluationContext.environment){var w=h.getState();h.evaluationEvent||(h.evaluationEvent={}),h.evaluationEvent[h.evaluationContext.environment.apiKey]={},h.setState(s(s({},w),{evaluationEvent:h.evaluationEvent})),h.updateEventStorage()}}).catch(function(g){h.log("Exception fetching evaluationEvent",g)}):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:c.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.ts=null,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1},this.getValue=function(m,g,w){var x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=null;if(x&&(R=x.value),g!=null&&g.skipAnalytics||w||h.evaluateFlag(m,"VALUE"),R===null&&(g==null?void 0:g.fallback)!==void 0)return g.fallback;if(g!=null&&g.json)try{return R===null?(h.log("Tried to parse null flag as JSON: "+m),null):JSON.parse(R)}catch{return g.fallback}return R},this.getTrait=function(m){var g,w;return((g=h.evaluationContext.identity)===null||g===void 0?void 0:g.traits)&&((w=h.evaluationContext.identity.traits[m.toLowerCase().replace(/ /g,"_")])===null||w===void 0?void 0:w.value)},this.getAllTraits=function(){var m;return Object.fromEntries(Object.entries(((m=h.evaluationContext.identity)===null||m===void 0?void 0:m.traits)||{}).map(function(g){var w=g[0],x=g[1];return[w,x==null?void 0:x.value]}))},this.setContext=function(m){var g=v(m);return h.evaluationContext=s(s({},g),{environment:g.environment||h.evaluationContext.environment}),h.initialised?h.getFlags():Promise.resolve()},this.getContext=function(){return h.evaluationContext},this.updateContext=function(m){return h.setContext(s(s({},h.getContext()),m))},this.setTrait=function(m,g){var w;if(h.api)return h.setContext(s(s({},h.evaluationContext),{identity:s(s({},h.evaluationContext.identity),{traits:s(s({},(w=h.evaluationContext.identity)===null||w===void 0?void 0:w.traits),S(Object.fromEntries([[m,g]])))})}))},this.setTraits=function(m){var g;if(h.api)return h.setContext(s(s({},h.evaluationContext),{identity:s(s({},h.evaluationContext.identity),{traits:s(s({},(g=h.evaluationContext.identity)===null||g===void 0?void 0:g.traits),Object.fromEntries(Object.entries(m).map(function(w){var x=w[0],R=w[1];return[x,y(R)?R:{value:R}]})))})}));console.error("Attempted to setTraits a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(m,g){var w=typeof g=="object",x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=!1;return!x&&w&&g.fallback!==void 0?R=g==null?void 0:g.fallback:x&&x.enabled&&(R=!0),(w&&!g.skipAnalytics||!g)&&h.evaluateFlag(m,"ENABLED"),R},this.getJSON=function(m,g,w){var x,R=h;R.evaluationContext;var M=R.headers,$={method:g||"GET",body:w,cache:"no-cache",headers:{}};h.evaluationContext.environment&&($.headers["X-Environment-Key"]=h.evaluationContext.environment.apiKey),g&&g!=="GET"&&($.headers["Content-Type"]="application/json; charset=utf-8"),M&&Object.assign($.headers,M),u||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var _="".concat((x=h.evaluationContext.identity)===null||x===void 0?void 0:x.identifier);return u(m,$).then(function(W){var ee,ae,te="".concat((ee=h.evaluationContext.identity)===null||ee===void 0?void 0:ee.identifier);if(_===te){var ne=(ae=W.headers)===null||ae===void 0?void 0:ae.get("x-flagsmith-document-updated-at");if(ne)try{var he=parseFloat(ne);if(isNaN(he))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");h.timestamp=he}catch(ue){h.log(ue,"Failed to parse x-flagsmith-document-updated-at",ne)}return h.log("Fetch response: "+W.status+" "+(g||"GET")+0+m),W.text().then(function(ue){var we=ue;try{we=JSON.parse(ue)}catch{}return!we&&W.status&&(we="API Response: ".concat(W.status)),W.status&&W.status>=200&&W.status<300?we:Promise.reject(new Error(we))})}h.log("Received response with identity mismatch, ignoring response. Requested: ".concat(_,", Current: ").concat(te))})},this.evaluateFlag=function(m,g){if(h.datadogRum&&(h.datadogRum.client.addFeatureFlagEvaluation?g==="VALUE"?h.datadogRum.client.addFeatureFlagEvaluation(N+m,h.getValue(m,{},!0)):h.datadogRum.client.addFeatureFlagEvaluation(O+m,h.hasFeature(m,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),h.enableAnalytics){if(!h.evaluationEvent||!h.evaluationContext.environment)return;h.evaluationEvent[h.evaluationContext.environment.apiKey]||(h.evaluationEvent[h.evaluationContext.environment.apiKey]={}),h.evaluationEvent[h.evaluationContext.environment.apiKey][m]===void 0&&(h.evaluationEvent[h.evaluationContext.environment.apiKey][m]=0),h.evaluationEvent[h.evaluationContext.environment.apiKey][m]+=1}h.updateEventStorage()},this._onChange=function(m,g,w){var x,R;h.setLoadingState(w),(x=h.onChange)===null||x===void 0||x.call(h,m,g,h.loadingState),(R=h._trigger)===null||R===void 0||R.call(h)},u=f.fetch?f.fetch:typeof fetch<"u"?fetch:Fe==null?void 0:Fe.fetch,this.canUseStorage=typeof window<"u"||!!f.browserlessStorage,this.log("Constructing flagsmith instance "+f),f.eventSource&&(T=f.eventSource),f.AsyncStorage&&(A=f.AsyncStorage)}return b.prototype.init=function(f){var h,m,g;return r(this,void 0,void 0,function(){var w,x,R,M,$,_,W,ee,ae,te,ne,he,ue,we,Ze,et,We,re,X,En,tt,ks,nt,In,Ts,Es,Cn,Is,_n,it,Ge,Cs,oe=this;return o(this,function(ge){switch(ge.label){case 0:w=v(f.evaluationContext||this.evaluationContext),ge.label=1;case 1:if(ge.trys.push([1,13,,14]),x=f.environmentID,R=f.api,M=R===void 0?k:R,$=f.headers,_=f.onChange,W=f.cacheFlags,ee=f.datadogRum,ae=f.onError,te=f.defaultFlags,ne=f.fetch,he=f.preventFetch,ue=f.enableLogs,we=f.enableDynatrace,Ze=f.enableAnalytics,et=f.realtime,We=f.eventSourceUrl,re=We===void 0?"https://realtime.flagsmith.com/":We,X=f.AsyncStorage,En=f.identity,tt=f.traits,ks=f.state,nt=f.cacheOptions,In=f.angularHttpClient,Ts=f._trigger,Es=f._triggerLoadingState,w.environment=x?{apiKey:x}:w.environment,!w.environment||!w.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(w.identity=En||tt?{identifier:En,traits:tt?Object.fromEntries(Object.entries(tt).map(function(fe){return[fe[0],{value:fe[1]}]})):{}}:w.identity,this.evaluationContext=w,this.api=M,this.headers=$,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=_,Cn="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=Ts||this._trigger,this._triggerLoadingState=Es||this._triggerLoadingState,this.onError=function(fe){oe.setLoadingState(s(s({},oe.loadingState),{isFetching:!1,isLoading:!1,error:fe})),ae==null||ae(fe)},this.enableLogs=ue||!1,this.cacheOptions=nt?{skipAPI:!!nt.skipAPI,ttl:nt.ttl||0,loadStale:!!nt.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),ne&&(u=ne),this.enableAnalytics=Ze||!1,this.flags=Object.assign({},te)||{},this.datadogRum=ee||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?new Date().valueOf():null,this.cacheFlags=A!==void 0&&!!W,X&&(A=X),et&&typeof window<"u"&&this.setupRealtime(re,w.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=s(s({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(ks),this.log("Initialising with properties",f,this),we&&(typeof dtrum>"u"?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),In&&(u=function(fe){return function(Se,xe){var Ne=xe.headers,Y=xe.method,Ve=xe.body;return new Promise(function(Le){switch(Y){case"GET":return fe.get(Se,{headers:Ne}).subscribe(function(Te){Le({ok:!0,text:function(){return Promise.resolve(Te)}})});case"POST":case"PUT":return fe.post(Se,Ve,{headers:Ne}).subscribe(function(Te){Le({ok:!0,text:function(){return Promise.resolve(Te)}})})}})}}(In)),A&&this.canUseStorage&&A.getItem(D).then(function(fe){try{oe.evaluationEvent=JSON.parse(fe)||{}}catch{oe.evaluationEvent={}}oe.analyticsInterval=setInterval(oe.analyticsFlags,oe.ticks)}),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),A&&this.canUseStorage&&A.getItem(D,function(fe,Se){if(Se&&oe.evaluationContext.environment){var xe=JSON.parse(Se);if(xe[oe.evaluationContext.environment.apiKey]){var Ne=oe.getState();oe.log("Retrieved events from cache",Se),oe.setState(s(s({},Ne),{evaluationEvent:xe[oe.evaluationContext.environment.apiKey]}))}}})),!W)return[3,9];if(!A||!this.canUseStorage)return[3,8];Is=function(fe,Se){return r(oe,void 0,void 0,function(){var xe,Ne,Y,Ve,Le,Te,Nn,_s,On,Rn,An,Dn,Ln,Fn,Mn,Pn,Bn,jn,zn,Un,Hn,$n,qn,Wn;return o(this,function(Oe){switch(Oe.label){case 0:if(!Se)return[3,7];xe=null,Ne=null,Oe.label=1;case 1:return Oe.trys.push([1,5,,6]),Y=JSON.parse(Se),Ve=!1,Le=!1,Y&&Y.api===this.api&&((Rn=(On=Y.evaluationContext)===null||On===void 0?void 0:On.environment)===null||Rn===void 0?void 0:Rn.apiKey)===((An=this.evaluationContext.environment)===null||An===void 0?void 0:An.apiKey)&&(Te=!0,this.evaluationContext.identity&&((Ln=(Dn=Y.evaluationContext)===null||Dn===void 0?void 0:Dn.identity)===null||Ln===void 0?void 0:Ln.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+((Mn=(Fn=Y.evaluationContext)===null||Fn===void 0?void 0:Fn.identity)===null||Mn===void 0?void 0:Mn.identifier)+" to "+this.evaluationContext.identity.identifier),Te=!1),this.cacheOptions.ttl&&(!Y.ts||new Date().valueOf()-Y.ts>this.cacheOptions.ttl)&&(Y.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+Y.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-Y.ts)+"ms"),Te=!1):Y.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+Y.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-Y.ts)+"ms"),Le=!0,Te=!0)),Te&&(Ve=!0,Ne=d((Pn=this.evaluationContext.identity)===null||Pn===void 0?void 0:Pn.traits,(jn=(Bn=Y.evaluationContext)===null||Bn===void 0?void 0:Bn.identity)===null||jn===void 0?void 0:jn.traits),xe=d(this.flags,Y.flags),this.setState(s(s({},Y),{evaluationContext:v(s(s({},Y.evaluationContext),{identity:!((zn=Y.evaluationContext)===null||zn===void 0)&&zn.identity?s(s({},(Un=Y.evaluationContext)===null||Un===void 0?void 0:Un.identity),{traits:s(s({},(($n=(Hn=Y.evaluationContext)===null||Hn===void 0?void 0:Hn.identity)===null||$n===void 0?void 0:$n.traits)||{}),tt||{})}):void 0}))})),this.log("Retrieved flags from cache",Y))),Ve?(Nn=!he&&(!this.cacheOptions.skipAPI||Le),this._onChange(null,{isFromServer:!1,flagsChanged:xe,traitsChanged:Ne},this._loadedState(null,c.CACHE,Nn)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&Ve&&!Le&&this.log("Skipping API, using cache"),Nn&&this.getFlags(),[3,4]):[3,2];case 2:return he?[3,4]:[4,this.getFlags()];case 3:Oe.sent(),Oe.label=4;case 4:return[3,6];case 5:return _s=Oe.sent(),this.log("Exception fetching cached logs",_s),[3,6];case 6:return[3,10];case 7:return he?[3,9]:[4,this.getFlags()];case 8:return Oe.sent(),[3,10];case 9:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(qn=this.evaluationContext.identity)===null||qn===void 0?void 0:qn.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(Cn);this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(Wn=this.evaluationContext.identity)===null||Wn===void 0?void 0:Wn.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}Oe.label=10;case 10:return[2]}})})},ge.label=2;case 2:return ge.trys.push([2,7,,8]),A.getItemSync?(_n=A.getItemSync(B),[3,5]):[3,3];case 3:return[4,A.getItem(B)];case 4:_n=ge.sent(),ge.label=5;case 5:return[4,Is(null,_n)];case 6:case 7:return ge.sent(),[3,8];case 8:return[3,12];case 9:return he?[3,11]:[4,this.getFlags()];case 10:return ge.sent(),[3,12];case 11:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:d({},te),traitsChanged:d({},(h=w.identity)===null||h===void 0?void 0:h.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(it=null,Object.keys(this.flags).length===0&&(it=Cn),this._onChange(null,{isFromServer:!1,flagsChanged:d({},this.flags),traitsChanged:d({},(m=w.identity)===null||m===void 0?void 0:m.traits)},this._loadedState(it,c.DEFAULT_FLAGS)),it))throw new Error(it);ge.label=12;case 12:return[3,14];case 13:throw Ge=ge.sent(),this.log("Error during initialisation ",Ge),Cs=Ge instanceof Error?Ge:new Error("".concat(Ge)),(g=this.onError)===null||g===void 0||g.call(this,Cs),Ge;case 14:return[2]}})})},b.prototype._loadedState=function(f,h,m){return f===void 0&&(f=null),m===void 0&&(m=!1),{error:f,isFetching:m,isLoading:!1,source:h}},b.prototype.getAllFlags=function(){return this.flags},b.prototype.identify=function(f,h,m){return this.evaluationContext.identity={identifier:f,transient:m,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==f?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=f,this.log("Identify: "+this.evaluationContext.identity.identifier),h&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(h).map(function(g){var w=g[0],x=g[1];return[w,y(x)?x:{value:x}]}))),this.initialised?this.getFlags():Promise.resolve()},b.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,evaluationEvent:this.evaluationEvent}},b.prototype.setState=function(f){f&&(this.initialised=!0,this.api=f.api||this.api||k,this.flags=f.flags||this.flags,this.evaluationContext=f.evaluationContext||this.evaluationContext,this.evaluationEvent=f.evaluationEvent||this.evaluationEvent,this.log("setState called",this))},b.prototype.logout=function(){return this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},b.prototype.startListening=function(f){f===void 0&&(f=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,f)},b.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},b.prototype.log=function(){for(var f=[],h=0;h<arguments.length;h++)f[h]=arguments[h];this.enableLogs&&console.log.apply(this,l(["FLAGSMITH:",new Date().valueOf()-(this.timer||0),"ms"],f,!0))},b.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=new Date().valueOf();var f=JSON.stringify(this.getState());this.log("Setting storage",f),A.setItem(B,f)}},b.prototype.updateEventStorage=function(){if(this.enableAnalytics){var f=JSON.stringify(this.getState().evaluationEvent);A.setItem(D,f)}},b.prototype.setLoadingState=function(f){var h;a(f,this.loadingState)||(this.loadingState=s({},f),this.log("Loading state changed",f),(h=this._triggerLoadingState)===null||h===void 0||h.call(this))},b.prototype.setupRealtime=function(f,h){var m=this,g=f+"sse/environments/"+h+"/stream";T?this.eventSource||(this.log("Creating event source with url "+g),this.eventSource=new T(g),this.eventSource.addEventListener("environment_updated",function(w){var x;try{x=JSON.parse(w.data).updated_at}catch(R){m.log("Could not parse sse event",R)}x?!m.timestamp||x>m.timestamp?m.isLoading?m.log("updated_at is new, but flags are loading",w.data,m.timestamp):(m.log("updated_at is new, fetching flags",w.data,m.timestamp),m.getFlags()):m.log("updated_at is outdated, skipping get flags",w.data,m.timestamp):m.log("No updated_at received, fetching flags",w)})):this.log("Error, EventSource is undefined")},b}();function E(b){var f=b.fetch,h=b.AsyncStorage,m=b.eventSource;return new I({fetch:f,AsyncStorage:h,eventSource:m})}var P,V=(P=function(b,f){return P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,m){h.__proto__=m}||function(h,m){for(var g in m)Object.prototype.hasOwnProperty.call(m,g)&&(h[g]=m[g])},P(b,f)},function(b,f){if(typeof f!="function"&&f!==null)throw new TypeError("Class extends value "+String(f)+" is not a constructor or null");function h(){this.constructor=b}P(b,f),b.prototype=f===null?Object.create(f):(h.prototype=f.prototype,new h)}),j=function(b){var f=typeof Symbol=="function"&&Symbol.iterator,h=f&&b[f],m=0;if(h)return h.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&m>=b.length&&(b=void 0),{value:b&&b[m++],done:!b}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},q=function(b,f){var h=typeof Symbol=="function"&&b[Symbol.iterator];if(!h)return b;var m,g,w=h.call(b),x=[];try{for(;(f===void 0||f-- >0)&&!(m=w.next()).done;)x.push(m.value)}catch(R){g={error:R}}finally{try{m&&!m.done&&(h=w.return)&&h.call(w)}finally{if(g)throw g.error}}return x},C=function(b,f,h){if(h||arguments.length===2)for(var m,g=0,w=f.length;g<w;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return b.concat(m||Array.prototype.slice.call(f))},F=function(b){function f(){return b.call(this,`EventSource not available.
|
|
648
|
+
Consider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.`)||this}return V(f,b),f}(Error),G=function(){function b(f,h){var m=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=h!=null?Object.assign({},h):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=f.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,this._configuration!=null&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),this.eventSourceClass==null||typeof this.eventSourceClass!="function")throw new F;this._onevent_wrapped=function(g){m._onevent(g)},this._start()}return b.prototype.dispatchEvent=function(f){throw new Error("Method not implemented.")},b.prototype._start=function(){var f,h,m=this,g=this.url;this._lastEventId&&(g.indexOf("?")===-1?g+="?":g+="&",g+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(g,this._configuration),this._eventSource.onopen=function(M){m._onopen(M)},this._eventSource.onerror=function(M){m._onerror(M)},this._eventSource.onmessage=function(M){m.onmessage(M)};try{for(var w=j(Object.keys(this._listeners)),x=w.next();!x.done;x=w.next()){var R=x.value;this._eventSource.addEventListener(R,this._onevent_wrapped)}}catch(M){f={error:M}}finally{try{x&&!x.done&&(h=w.return)&&h.call(w)}finally{if(f)throw f.error}}},b.prototype._onopen=function(f){this.readyState===0&&(this.readyState=1,this.onopen(f))},b.prototype._onerror=function(f){var h=this;if(this.readyState===1&&(this.readyState=0,this.onerror(f)),this._eventSource){this._eventSource.close(),this._eventSource=null;var m=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout(function(){return h._start()},m)}},b.prototype._onevent=function(f){var h,m;f&&f.lastEventId&&(this._lastEventId=f.lastEventId);var g=this._listeners[f.type];if(g!=null)try{for(var w=j(C([],q(g),!1)),x=w.next();!x.done;x=w.next())x.value.call(this,f)}catch(R){h={error:R}}finally{try{x&&!x.done&&(m=w.return)&&m.call(w)}finally{if(h)throw h.error}}f.type==="message"&&this.onmessage(f)},b.prototype.onopen=function(f){},b.prototype.onerror=function(f){},b.prototype.onmessage=function(f){},b.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},b.prototype.addEventListener=function(f,h,m){this._listeners[f]==null&&(this._listeners[f]=[],this._eventSource!=null&&this._eventSource.addEventListener(f,this._onevent_wrapped));var g=this._listeners[f];g.includes(h)||(this._listeners[f]=C(C([],q(g),!1),[h],!1))},b.prototype.removeEventListener=function(f,h,m){var g=this._listeners[f];this._listeners[f]=g.filter(function(w){return w!==h})},b}();globalThis.FlagsmithEventSource=typeof EventSource<"u"?EventSource:null;var K=function(b,f){return f=f||{},new Promise(function(h,m){var g=new XMLHttpRequest,w=[],x=[],R={},M=function(){return{ok:(g.status/100|0)==2,statusText:g.statusText,status:g.status,url:g.responseURL,text:function(){return Promise.resolve(g.responseText)},json:function(){return Promise.resolve(g.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([g.response]))},clone:M,headers:{keys:function(){return w},entries:function(){return x},get:function(_){return R[_.toLowerCase()]},has:function(_){return _.toLowerCase()in R}}}};for(var $ in g.open(f.method||"get",b,!0),g.onload=function(){g.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(_,W,ee){w.push(W=W.toLowerCase()),x.push([W,ee]),R[W]=R[W]?R[W]+","+ee:ee}),h(M())},g.onerror=m,g.withCredentials=f.credentials=="include",f.headers)g.setRequestHeader($,f.headers[$]);g.send(f.body||null)})},U=E({AsyncStorage:i,fetch:K,eventSource:G});typeof window<"u"&&(window.flagsmith=U),n.createFlagsmithInstance=function(){return E({AsyncStorage:i,fetch:K,eventSource:G})},n.default=U,Object.defineProperty(n,"__esModule",{value:!0})})})(Lt,Lt.exports);var Ms=Lt.exports;const Xn=Kn(Ms);var Jn={},Ps=function(t,e,n,i,s){var r=new Worker(Jn[e]||(Jn[e]=URL.createObjectURL(new Blob([t+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return r.onmessage=function(o){var l=o.data,a=l.$e$;if(a){var d=new Error(a[0]);d.code=a[1],d.stack=a[2],s(d,null)}else s(null,l)},r.postMessage(n,i),r},ce=Uint8Array,se=Uint16Array,ot=Int32Array,at=new ce([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ct=new ce([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ft=new ce([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yn=function(t,e){for(var n=new se(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];for(var s=new ot(n[30]),i=1;i<30;++i)for(var r=n[i];r<n[i+1];++r)s[r]=r-n[i]<<5|i;return{b:n,r:s}},Qn=Yn(at,2),Bs=Qn.b,lt=Qn.r;Bs[28]=258,lt[258]=28;for(var js=Yn(ct,0),Mt=js.r,dt=new se(32768),J=0;J<32768;++J){var Ee=(J&43690)>>1|(J&21845)<<1;Ee=(Ee&52428)>>2|(Ee&13107)<<2,Ee=(Ee&61680)>>4|(Ee&3855)<<4,dt[J]=((Ee&65280)>>8|(Ee&255)<<8)>>1}for(var Me=function(t,e,n){for(var i=t.length,s=0,r=new se(e);s<i;++s)t[s]&&++r[t[s]-1];var o=new se(e);for(s=1;s<e;++s)o[s]=o[s-1]+r[s-1]<<1;var l;if(n){l=new se(1<<e);var a=15-e;for(s=0;s<i;++s)if(t[s])for(var d=s<<4|t[s],c=e-t[s],u=o[t[s]-1]++<<c,p=u|(1<<c)-1;u<=p;++u)l[dt[u]>>a]=d}else for(l=new se(i),s=0;s<i;++s)t[s]&&(l[s]=dt[o[t[s]-1]++]>>15-t[s]);return l},Ie=new ce(288),J=0;J<144;++J)Ie[J]=8;for(var J=144;J<256;++J)Ie[J]=9;for(var J=256;J<280;++J)Ie[J]=7;for(var J=280;J<288;++J)Ie[J]=8;for(var Xe=new ce(32),J=0;J<32;++J)Xe[J]=5;var Zn=Me(Ie,9,0),ei=Me(Xe,5,0),Pt=function(t){return(t+7)/8|0},ti=function(t,e,n){return(e==null||e<0)&&(e=0),(n==null||n>t.length)&&(n=t.length),new ce(t.subarray(e,n))},zs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ni=function(t,e,n){var i=new Error(e||zs[t]);if(i.code=t,Error.captureStackTrace&&Error.captureStackTrace(i,ni),!n)throw i;return i},me=function(t,e,n){n<<=e&7;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8},Pe=function(t,e,n){n<<=e&7;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8,t[i+2]|=n>>16},ht=function(t,e){for(var n=[],i=0;i<t.length;++i)t[i]&&n.push({s:i,f:t[i]});var s=n.length,r=n.slice();if(!s)return{t:Ut,l:0};if(s==1){var o=new ce(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(N,O){return N.f-O.f}),n.push({s:-1,f:25001});var l=n[0],a=n[1],d=0,c=1,u=2;for(n[0]={s:-1,f:l.f+a.f,l,r:a};c!=s-1;)l=n[n[d].f<n[u].f?d++:u++],a=n[d!=c&&n[d].f<n[u].f?d++:u++],n[c++]={s:-1,f:l.f+a.f,l,r:a};for(var p=r[0].s,i=1;i<s;++i)r[i].s>p&&(p=r[i].s);var y=new se(p+1),S=ut(n[c-1],y,0);if(S>e){var i=0,v=0,T=S-e,A=1<<T;for(r.sort(function(O,L){return y[L.s]-y[O.s]||O.f-L.f});i<s;++i){var B=r[i].s;if(y[B]>e)v+=A-(1<<S-y[B]),y[B]=e;else break}for(v>>=T;v>0;){var D=r[i].s;y[D]<e?v-=1<<e-y[D]++-1:++i}for(;i>=0&&v;--i){var k=r[i].s;y[k]==e&&(--y[k],++v)}S=e}return{t:new ce(y),l:S}},ut=function(t,e,n){return t.s==-1?Math.max(ut(t.l,e,n+1),ut(t.r,e,n+1)):e[t.s]=n},Bt=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new se(++e),i=0,s=t[0],r=1,o=function(a){n[i++]=a},l=1;l<=e;++l)if(t[l]==s&&l!=e)++r;else{if(!s&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(s),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(s);r=1,s=t[l]}return{c:n.subarray(0,i),n:e}},Be=function(t,e){for(var n=0,i=0;i<e.length;++i)n+=t[i]*e[i];return n},jt=function(t,e,n){var i=n.length,s=Pt(e+2);t[s]=i&255,t[s+1]=i>>8,t[s+2]=t[s]^255,t[s+3]=t[s+1]^255;for(var r=0;r<i;++r)t[s+r+4]=n[r];return(s+4+i)*8},zt=function(t,e,n,i,s,r,o,l,a,d,c){me(e,c++,n),++s[256];for(var u=ht(s,15),p=u.t,y=u.l,S=ht(r,15),v=S.t,T=S.l,A=Bt(p),B=A.c,D=A.n,k=Bt(v),N=k.c,O=k.n,L=new se(19),I=0;I<B.length;++I)++L[B[I]&31];for(var I=0;I<N.length;++I)++L[N[I]&31];for(var E=ht(L,7),P=E.t,V=E.l,j=19;j>4&&!P[Ft[j-1]];--j);var q=d+5<<3,C=Be(s,Ie)+Be(r,Xe)+o,F=Be(s,p)+Be(r,v)+o+14+3*j+Be(L,P)+2*L[16]+3*L[17]+7*L[18];if(a>=0&&q<=C&&q<=F)return jt(e,c,t.subarray(a,a+d));var G,K,U,b;if(me(e,c,1+(F<C)),c+=2,F<C){G=Me(p,y,0),K=p,U=Me(v,T,0),b=v;var f=Me(P,V,0);me(e,c,D-257),me(e,c+5,O-1),me(e,c+10,j-4),c+=14;for(var I=0;I<j;++I)me(e,c+3*I,P[Ft[I]]);c+=3*j;for(var h=[B,N],m=0;m<2;++m)for(var g=h[m],I=0;I<g.length;++I){var w=g[I]&31;me(e,c,f[w]),c+=P[w],w>15&&(me(e,c,g[I]>>5&127),c+=g[I]>>12)}}else G=Zn,K=Ie,U=ei,b=Xe;for(var I=0;I<l;++I){var x=i[I];if(x>255){var w=x>>18&31;Pe(e,c,G[w+257]),c+=K[w+257],w>7&&(me(e,c,x>>23&31),c+=at[w]);var R=x&31;Pe(e,c,U[R]),c+=b[R],R>3&&(Pe(e,c,x>>5&8191),c+=ct[R])}else Pe(e,c,G[x]),c+=K[x]}return Pe(e,c,G[256]),c+K[256]},ii=new ot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ut=new ce(0),si=function(t,e,n,i,s,r){var o=r.z||t.length,l=new ce(i+o+5*(1+Math.ceil(o/7e3))+s),a=l.subarray(i,l.length-s),d=r.l,c=(r.r||0)&7;if(e){c&&(a[0]=r.r>>3);for(var u=ii[e-1],p=u>>13,y=u&8191,S=(1<<n)-1,v=r.p||new se(32768),T=r.h||new se(S+1),A=Math.ceil(n/3),B=2*A,D=function(ne){return(t[ne]^t[ne+1]<<A^t[ne+2]<<B)&S},k=new ot(25e3),N=new se(288),O=new se(32),L=0,I=0,E=r.i||0,P=0,V=r.w||0,j=0;E+2<o;++E){var q=D(E),C=E&32767,F=T[q];if(v[C]=F,T[q]=C,V<=E){var G=o-E;if((L>7e3||P>24576)&&(G>423||!d)){c=zt(t,a,0,k,N,O,I,P,j,E-j,c),P=L=I=0,j=E;for(var K=0;K<286;++K)N[K]=0;for(var K=0;K<30;++K)O[K]=0}var U=2,b=0,f=y,h=C-F&32767;if(G>2&&q==D(E-h))for(var m=Math.min(p,G)-1,g=Math.min(32767,E),w=Math.min(258,G);h<=g&&--f&&C!=F;){if(t[E+U]==t[E+U-h]){for(var x=0;x<w&&t[E+x]==t[E+x-h];++x);if(x>U){if(U=x,b=h,x>m)break;for(var R=Math.min(h,x-2),M=0,K=0;K<R;++K){var $=E-h+K&32767,_=v[$],W=$-_&32767;W>M&&(M=W,F=$)}}}C=F,F=v[C],h+=C-F&32767}if(b){k[P++]=268435456|lt[U]<<18|Mt[b];var ee=lt[U]&31,ae=Mt[b]&31;I+=at[ee]+ct[ae],++N[257+ee],++O[ae],V=E+U,++L}else k[P++]=t[E],++N[t[E]]}}for(E=Math.max(E,V);E<o;++E)k[P++]=t[E],++N[t[E]];c=zt(t,a,d,k,N,O,I,P,j,E-j,c),d||(r.r=c&7|a[c/8|0]<<3,c-=7,r.h=T,r.p=v,r.i=E,r.w=V)}else{for(var E=r.w||0;E<o+d;E+=65535){var te=E+65535;te>=o&&(a[c/8|0]=d,te=o),c=jt(a,c+1,t.subarray(E,te))}r.i=o}return ti(l,0,i+Pt(c)+s)},ri=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,i=9;--i;)n=(n&1&&-306674912)^n>>>1;t[e]=n}return t}(),oi=function(){var t=-1;return{p:function(e){for(var n=t,i=0;i<e.length;++i)n=ri[n&255^e[i]]^n>>>8;t=n},d:function(){return~t}}},Ht=function(t,e,n,i,s){if(!s&&(s={l:1},e.dictionary)){var r=e.dictionary.subarray(-32768),o=new ce(r.length+t.length);o.set(r),o.set(t,r.length),t=o,s.w=r.length}return si(t,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(t.length)))*1.5):20:12+e.mem,n,i,s)},Us=function(t,e){var n={};for(var i in t)n[i]=t[i];for(var i in e)n[i]=e[i];return n},ai=function(t,e,n){for(var i=t(),s=t.toString(),r=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),o=0;o<i.length;++o){var l=i[o],a=r[o];if(typeof l=="function"){e+=";"+a+"=";var d=l.toString();if(l.prototype)if(d.indexOf("[native code]")!=-1){var c=d.indexOf(" ",8)+1;e+=d.slice(c,d.indexOf("(",c))}else{e+=d;for(var u in l.prototype)e+=";"+a+".prototype."+u+"="+l.prototype[u].toString()}else e+=d}else n[a]=l}return e},ft=[],Hs=function(t){var e=[];for(var n in t)t[n].buffer&&e.push((t[n]=new t[n].constructor(t[n])).buffer);return e},$s=function(t,e,n,i){if(!ft[n]){for(var s="",r={},o=t.length-1,l=0;l<o;++l)s=ai(t[l],s,r);ft[n]={c:ai(t[o],s,r),e:r}}var a=Us({},ft[n].e);return Ps(ft[n].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",n,a,Hs(a),i)},qs=function(){return[ce,se,ot,at,ct,Ft,lt,Mt,Zn,Ie,ei,Xe,dt,ii,Ut,Me,me,Pe,ht,ut,Bt,Be,jt,zt,Pt,ti,si,Ht,Vs,ci]},Ws=function(){return[li,di,pt,oi,ri]},ci=function(t){return postMessage(t,[t.buffer])},Gs=function(t,e,n,i,s,r){var o=$s(n,i,s,function(l,a){o.terminate(),r(l,a)});return o.postMessage([t,e],e.consume?[t.buffer]:[]),function(){o.terminate()}},pt=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8},li=function(t,e){var n=e.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=e.level<2?4:e.level==9?2:0,t[9]=3,e.mtime!=0&&pt(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),n){t[3]=8;for(var i=0;i<=n.length;++i)t[i+10]=n.charCodeAt(i)}},di=function(t){return 10+(t.filename?t.filename.length+1:0)};function Vs(t,e){return Ht(t,e||{},0,0)}function Ks(t,e,n){return n||(n=e,e={}),typeof n!="function"&&ni(7),Gs(t,e,[qs,Ws,function(){return[hi]}],function(i){return ci(hi(i.data[0],i.data[1]))},2,n)}function hi(t,e){e||(e={});var n=oi(),i=t.length;n.p(t);var s=Ht(t,e,di(e),8),r=s.length;return li(s,e),pt(s,r-8,n.d()),pt(s,r-4,i),s}var Xs=typeof TextDecoder<"u"&&new TextDecoder,Js=0;try{Xs.decode(Ut,{stream:!0}),Js=1}catch{}class ui{constructor(){this.idx=1,this.backDict={}}getKey(e){let n=!1;return this.backDict[e]||(n=!0,this.backDict[e]=this.idx++),[this.backDict[e],n]}}class Ys{constructor(e,n){this.app=e,this.isDictDisabled=n,this.dict=new ui}sendSetAttribute(e,n,i){if(this.isDictDisabled){const s=[12,e,n,i];return this.app.send(s)}else{const s=[51,e,this.applyDict(n),this.applyDict(i)];return this.app.send(s)}}applyDict(e){const[n,i]=this.dict.getKey(e);return i&&this.app.send([50,n,e]),n}clear(){this.dict=new ui}}class Qs{constructor(e,n){this.app=e,this.startParams=n,this.conditions=[],this.hasStarted=!1,this.createConditionFromFilter=i=>{if(i.value.length){const s=Zs(i);if(s.type)return s}},this.durationInt=null}setConditions(e){this.conditions=e}async fetchConditions(e,n){try{const i=await fetch(`${this.app.options.ingestPoint}/v1/web/conditions/${e}`,{method:"GET",headers:{Authorization:`Bearer ${n}`}}),{conditions:s}=await i.json(),r=[];s.forEach(o=>{o.filters.forEach(a=>{let d;a.type==="fetch"?(d={type:"network_request",subConditions:[],name:o.name},a.filters.forEach(c=>{const u=this.createConditionFromFilter(c);u&&d.subConditions.push(u)})):d=this.createConditionFromFilter(a),d&&(d.type==="session_duration"&&this.processDuration(d.value[0],o.name),r.push({...d,name:o.name}))})}),this.conditions=r}catch{this.app.debug.error("Critical: cannot fetch start conditions")}}trigger(e){if(!this.hasStarted)try{this.hasStarted=!0,this.app.start(this.startParams,void 0,e)}catch(n){this.app.debug.error(n)}}processMessage(e){if(!this.hasStarted)switch(e[0]){case 78:this.jsExceptionEvent(e);break;case 27:this.customEvent(e);break;case 68:this.clickEvent(e);break;case 122:this.pageLocationEvent(e);break;case 83:this.networkRequest(e);break}}processFlags(e){const n=this.conditions.filter(i=>i.type==="feature_flag");n.length&&n.forEach(i=>{const s=je[i.operator];s&&e.find(r=>s(r.key,i.value))&&this.trigger(i.name)})}processDuration(e,n){this.durationInt=setInterval(()=>{performance.now()>e&&this.trigger(n)},1e3),this.app.attachStopCallback(()=>{this.durationInt&&clearInterval(this.durationInt)})}networkRequest(e){const n=this.conditions.filter(i=>i.type==="network_request");n.length&&n.forEach(i=>{const s=i.subConditions.filter(r=>r.operator!=="isAny");s.length?s.every(o=>{let l;switch(o.key){case"url":l=e[3];break;case"status":l=e[6];break;case"method":l=e[2];break;case"duration":l=e[8];break}const a=je[o.operator];if(a&&a(l,o.value))return!0})&&this.trigger(i.name):s.length===0&&i.subConditions.length&&this.trigger(i.name)})}customEvent(e){const n=this.conditions.filter(i=>i.type==="custom_event");n.length&&n.forEach(i=>{const s=je[i.operator];s&&(s(e[1],i.value)||s(e[2],i.value))&&this.trigger(i.name)})}clickEvent(e){const n=this.conditions.filter(i=>i.type==="click");n.length&&n.forEach(i=>{const s=je[i.operator];s&&(s(e[3],i.value)||s(e[4],i.value))&&this.trigger(i.name)})}pageLocationEvent(e){const n=this.conditions.filter(i=>i.type==="visited_url");n&&n.forEach(i=>{const s=je[i.operator];s&&s(e[1],i.value)&&this.trigger(i.name)})}jsExceptionEvent(e){const n=[e[1],e[2],e[3]],i=this.conditions.filter(s=>s.type==="exception");i&&i.forEach(s=>{const r=je[s.operator];r&&n.some(o=>r(o,s.value))&&this.trigger(s.name)})}}const je={is:(t,e)=>e.some(n=>t.includes(n)),isAny:()=>!0,isNot:(t,e)=>!e.some(n=>t.includes(n)),contains:(t,e)=>e.some(n=>t.includes(n)),notContains:(t,e)=>!e.some(n=>t.includes(n)),startsWith:(t,e)=>e.some(n=>t.startsWith(n)),endsWith:(t,e)=>e.some(n=>t.endsWith(n)),greaterThan:(t,e)=>t>e,greaterOrEqual:(t,e)=>t>=e,lessOrEqual:(t,e)=>t<=e,lessThan:(t,e)=>t<e},Zs=t=>{const e={on:"is",notOn:"isNot",">":"greaterThan","<":"lessThan","=":"is","<=":"lessOrEqual",">=":"greaterOrEqual"},n=s=>{if(Object.keys(e).includes(s))return e[s]};let i={type:"",operator:"",value:t.value,key:""};switch(t.type){case"click":i={type:"click",operator:n(t.operator),value:t.value,key:""};break;case"location":i={type:"visited_url",operator:t.operator,value:t.value,key:""};break;case"custom":i={type:"custom_event",operator:t.operator,value:t.value,key:""};break;case"metadata":i={type:t.source==="featureFlag"?"feature_flag":t.type,operator:t.operator,value:t.value,key:""};break;case"error":i={type:"exception",operator:t.operator,value:t.value,key:""};break;case"duration":i={type:"session_duration",value:t.value[0],key:""};break;case"fetchUrl":i={type:"network_request",key:"url",operator:t.operator,value:t.value};break;case"fetchStatusCode":i={type:"network_request",key:"status",operator:n(t.operator),value:t.value};break;case"fetchMethod":i={type:"network_request",key:"method",operator:n(t.operator),value:t.value};break;case"fetchDuration":i={type:"network_request",key:"duration",operator:n(t.operator),value:t.value};break}return i};class er{constructor(e){this.app=e,this.flags=[],this.storageKey="__openreplay_flags";const n=this.app.sessionStorage.getItem(this.storageKey);if(n){const i=n.split(";").filter(Boolean);this.flags=i.map(s=>JSON.parse(s))}}getFeatureFlag(e){return this.flags.find(n=>n.key===e)}isFlagEnabled(e){return this.flags.findIndex(n=>n.key===e)!==-1}onFlagsLoad(e){this.onFlagsCb=e}async reloadFlags(e){const n=this.app.sessionStorage.getItem(this.storageKey),i={};n&&n.split(";").filter(Boolean).forEach(c=>{const u=JSON.parse(c);i[u.key]={key:u.key,value:u.value}});const s=this.app.session.getInfo(),r=this.app.session.userInfo,o={projectID:s.projectID,userID:s.userID,metadata:s.metadata,referrer:document.referrer,os:r.userOS,device:r.userDevice,country:r.userCountry,state:r.userState,city:r.userCity,browser:r.userBrowser,persistFlags:i},l=e??this.app.session.getSessionToken(),a=await fetch(this.app.options.ingestPoint+"/v1/web/feature-flags",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(o)});if(a.status===200){const d=await a.json();return this.handleFlags(d.flags)}}handleFlags(e){var r;const n=[];e.forEach(o=>{o.is_persist&&n.push(o)});let i="";return this.diffPersist(n).forEach(o=>{i+=`${JSON.stringify(o)};`}),this.app.sessionStorage.setItem(this.storageKey,i),this.flags=e,(r=this.onFlagsCb)==null?void 0:r.call(this,e)}clearPersistFlags(){this.app.sessionStorage.removeItem(this.storageKey)}diffPersist(e){const n=this.app.sessionStorage.getItem(this.storageKey);if(!n)return e;const s=n.split(";").filter(Boolean).map(r=>JSON.parse(r));return e.filter(r=>s.findIndex(o=>o.key===r.key)===-1)}}const fi={htmlmasked:"hidden",masked:"obscured"},be=!(typeof window>"u"),tr=be&&navigator.userAgent.match(/firefox|fxios/i),nr=1e5;let $t=be?Date.now()-performance.now():0;function qt(){$t=Date.now()-performance.now()}function ze(){return $t}const pe=be&&performance.now?()=>Math.round(performance.now()+$t):()=>Date.now(),Wt="repeat"in String.prototype?t=>"*".repeat(t.length):t=>t.replace(/./g,"*");function pi(t){return t.trim().replace(/\s+/g," ")}function gi(t){return t.startsWith("https://")||t.startsWith("http://")}const gt="https://docs.openreplay.com",mi={};function Ce(t,e,n="/"){mi[t]||(console.warn(`OpenReplay: ${t} is deprecated. ${e?`Please, use ${e} instead.`:""} Visit ${gt}${n} for more information.`),mi[t]=!0)}function Gt(t){let e=t.getAttribute("data-openreplay-label");return e!==null||(e=t.getAttribute("data-asayer-label"),e!==null&&Ce('"data-asayer-label" attribute','"data-openreplay-label" attribute',"/")),e}function Re(t,e){const n=`data-openreplay-${e}`;return t.hasAttribute(n)?(fi[e]&&Ce(`"${n}" attribute`,`"${fi[e]}" attribute`,"/installation/sanitize-data"),!0):!1}function ir(t){try{return!!t.contentDocument}catch{return!1}}function bi(t){return t.toString(16).padStart(2,"0")}function sr(t){const e=new Uint8Array((t||40)/2),n=window.crypto||window.msCrypto;return n?(n.getRandomValues(e),Array.from(e,bi).join("")):Array.from({length:t||40},()=>bi(Math.floor(Math.random()*16))).join("")}function rr(){try{return window.self&&window.top&&window.self!==window.top}catch{return!0}}function Vt(t){return window.Zone&&"__symbol__"in window.Zone?window.Zone.__symbol__(t):t}function yi(t){const e=Vt("MutationObserver");return new window[e](t)}function vi(t,e,n,i){const s=Vt("addEventListener");try{t[s](e,n,i)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}function wi(t,e,n,i){const s=Vt("removeEventListener");try{t[s](e,n,i)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}class or{constructor(){this.taskQueue=[],this.isRunning=!1}addTask(e){this.taskQueue.push(e),this.runTasks()}runTasks(){if(this.isRunning||this.taskQueue.length===0)return;this.isRunning=!0;const e=()=>{if(this.taskQueue.length===0){this.isRunning=!1;return}const n=this.taskQueue.shift();Promise.resolve(n()).then(()=>{requestAnimationFrame(()=>e())})};e()}}const ar=new or;function cr(t){ar.addTask(t)}function Si(t,e){const n={...t};for(const i in e)if(e.hasOwnProperty(i)){const s=e[i],r=t[i];typeof s=="object"&&!Array.isArray(s)&&s!==null?n[i]=Si(r||{},s):n[i]=s}return n}function Ae(t){return[0,t]}function lr(t,e){return[5,t,e]}function dr(t,e){return[6,t,e]}function hr(){return[7]}function ur(t,e,n,i,s){return[8,t,e,n,i,s]}function fr(t,e,n){return[9,t,e,n]}function pr(t,e,n){return[10,t,e,n]}function gr(t){return[11,t]}function xi(t,e){return[13,t,e]}function mr(t,e){return[14,t,e]}function br(t,e,n){return[16,t,e,n]}function yr(t,e,n){return[18,t,e,n]}function vr(t,e){return[19,t,e]}function wr(t,e){return[20,t,e]}function Sr(t,e){return[22,t,e]}function xr(t,e,n,i,s,r,o,l,a){return[23,t,e,n,i,s,r,o,l,a]}function kr(t,e,n){return[24,t,e,n]}function Tr(t,e){return[27,t,e]}function Er(t){return[28,t]}function Ir(t){return[29,t]}function ki(t,e){return[30,t,e]}function Cr(t,e,n,i){return[49,t,e,n,i]}function _r(t,e){return[54,t,e]}function Nr(t){return[55,t]}function Ti(t,e,n,i){return[57,t,e,n,i]}function Ei(t){return[58,t]}function Kt(t,e,n,i){return[60,t,e,n,i]}function Or(t,e,n){return[61,t,e,n]}function Rr(t,e){return[63,t,e]}function Ar(t,e){return[64,t,e]}function Dr(t,e,n,i,s,r){return[68,t,e,n,i,s,r]}function Xt(t,e){return[70,t,e]}function Ii(t,e,n){return[71,t,e,n]}function Jt(t,e,n,i){return[73,t,e,n,i]}function Ci(t,e){return[75,t,e]}function _i(t,e){return[76,t,e]}function Lr(t,e){return[77,t,e]}function Yt(t,e,n,i){return[78,t,e,n,i]}function mt(t,e,n,i,s,r,o,l,a){return[83,t,e,n,i,s,r,o,l,a]}function Fr(t,e,n,i,s,r){return[84,t,e,n,i,s,r]}function Mr(t,e,n,i,s,r){return[112,t,e,n,i,s,r]}function Ni(t,e,n){return[113,t,e,n]}function Pr(t){return[114,t]}function Br(t){return[115,t]}function Oi(t,e,n,i,s,r,o,l,a,d){return[116,t,e,n,i,s,r,o,l,a,d]}function bt(t){return[117,t]}function De(t){return[118,t]}function jr(t,e){return[119,t,e]}function zr(t){return[120,t]}function Ur(t,e,n,i){return[122,t,e,n,i]}const Qt=be&&"performance"in window&&"memory"in performance?performance:{memory:{}},Zt=be?(navigator.deviceMemory||0)*1024:0,en=Qt.memory.jsHeapSizeLimit||0;function Hr(t,e){if(!Object.assign({capturePerformance:!0},e).capturePerformance)return;let i,s;const r=()=>{i===void 0||i===-1||(i++,requestAnimationFrame(r))};t.ticker.attach(()=>{s===void 0||s===-1||s++},0,!1);const o=()=>{i===void 0||s===void 0||(t.send(Cr(i,s,Qt.memory.totalJSHeapSize||0,Qt.memory.usedJSHeapSize||0)),s=i=document.hidden?-1:0)};t.attachStartCallback(()=>{s=i=-1,o(),r()}),t.attachStopCallback(()=>{s=i=void 0}),t.ticker.attach(o,40,!1),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",o,!1,!1)}const Ri="__or__watched_tags__";class $r{constructor(e,n,i){this.sessionStorage=e,this.errLog=n,this.onTag=i,this.intervals={},this.tags=[];const s=JSON.parse(e.getItem(Ri)??"[]");this.setTags(s),this.observer=new IntersectionObserver(r=>{r.forEach(o=>{if(o.isIntersecting&&o.target){const l=o.target.__or_watcher_tagname;l&&this.onTagRendered(l),this.observer.unobserve(o.target)}})})}async fetchTags(e,n){return fetch(`${e}/v1/web/tags`,{method:"GET",headers:{Authorization:`Bearer ${n}`}}).then(i=>i.json()).then(({tags:i})=>{if(i&&i.length){this.setTags(i);const s=JSON.stringify(i);this.sessionStorage.setItem(Ri,s||"")}}).catch(i=>this.errLog(i))}setTags(e){this.tags=e,this.intervals={},e.forEach(n=>{this.intervals[n.id]=setInterval(()=>{const i=document.querySelectorAll(n.selector);if(i.length>0){const s=i[0];s.__or_watcher_tagname=n.id,this.observer.observe(s)}},500)})}onTagRendered(e){this.intervals[e]&&clearInterval(this.intervals[e]),this.onTag(e)}clear(){this.tags.forEach(e=>{clearInterval(this.intervals[e.id])}),this.tags=[],this.intervals={},this.observer.disconnect()}}const qr={position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0, 0, 0, 0.40)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:999999,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"'},Wr={display:"flex",flexDirection:"column",gap:"2rem",alignItems:"center",padding:"1.5rem",borderRadius:"2px",border:"1px solid #D9D9D9",background:"#FFF",width:"22rem"},yt={display:"flex","flex-direction":"column",gap:"unset","align-items":"center",padding:"unset",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',"border-radius":"2px",border:"1px solid #D9D9D9",background:"rgba(255, 255, 255, 0.75)",width:"22rem"},Gr={fontFamily:"Verdana, sans-serif",fontSize:"1.25rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.75rem",color:"rgba(0, 0, 0, 0.85)"},Vr={borderTop:"1px solid rgba(0, 0, 0, 0.06)",borderBottom:"1px solid rgba(0, 0, 0, 0.06)",padding:"1.25rem 0rem",color:"rgba(0, 0, 0, 0.85)",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"400",lineHeight:"auto",whiteSpace:"pre-wrap"},Kr={display:"flex",padding:"0.4rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.625rem",borderRadius:"0.25rem",border:"1px solid #394EFF",background:"#394EFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",color:"#FFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"1rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.5rem",cursor:"pointer"},Ai={fontFamily:"Verdana, sans-serif",fontSize:"13px",fontWeight:"500",lineHeight:"auto",display:"flex",justifyContent:"space-between",width:"100%",cursor:"pointer"},Ue={display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"0.625rem",fontSize:"13px",lineHeight:"auto"},Xr={padding:"0.5rem",gap:"0.5rem",fontFamily:"Verdana, sans-serif",fontSize:"16px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto",color:"white",display:"flex",alignItems:"center",width:"100%",borderRadius:"2px",background:"rgba(0, 0, 0, 0.75)",boxSizing:"border-box"},He={boxSizing:"border-box",display:"block",width:"100%",borderBottom:"1px solid #D9D9D9",background:"#FFF",padding:"0.65rem",alignSelf:"stretch",color:"#000",fontFamily:"Verdana, sans-serif",fontStyle:"normal",fontWeight:"400"},Jr={...He,display:"flex",flexDirection:"column",alignItems:"center",gap:"0.625rem"},Di={fontSize:"1.25rem",fontWeight:"500",cursor:"pointer",color:"#394EFF"},Li={display:"flex",padding:"0.4rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.625rem",borderRadius:"0.25rem",border:"1px solid #394EFF",background:"#394EFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",color:"#FFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"1rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.5rem",width:"100%",boxSizing:"border-box",cursor:"pointer"},Fi={marginTop:"1rem",marginBottom:"1rem",cursor:"pointer",display:"block",fontWeight:"500",fontSize:"13px!important",lineHeight:"auto"},Yr={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",padding:"0.5rem",width:"100%",boxSizing:"border-box"},Mi={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #394EFF",fontSize:"13px",height:"24px",width:"24px"},Qr={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #D2DFFF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",background:"#D2DFFF",fontSize:"13px",height:"24px",width:"24px"},Pi={borderRadius:"0.375rem",border:"1px solid rgba(0, 0, 0, 0.06)",background:"#F5F7FF",boxShadow:"0px 2px 0px 0px rgba(0, 0, 0, 0.04)",display:"flex",flexDirection:"column",padding:"0.625rem 0.9375rem",gap:"0.5rem",alignSelf:"stretch"},Bi={fontWeight:"bold"},Zr={fontSize:"13px",lineHeight:"auto"},ji={marginRight:"0.5rem",cursor:"pointer",color:"#394EFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto"},eo={...ji,display:"flex",padding:"0.25rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.5rem",borderRadius:"0.25rem",border:"1px solid #394EFF"},to={display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",boxSizing:"border-box"},no={border:"4px solid rgba(255, 255, 255, 0.4)",width:"16px",height:"16px",borderRadius:"50%",borderLeftColor:"#fff",animation:"spin 0.5s linear infinite"},zi={Standard:{width:1280,height:720},High:{width:1920,height:1080}};class io{constructor(e){this.app=e,this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this.recStartTs=null}async startRecording(e,n,i,s){this.recStartTs=this.app.timestamp();const r=n;try{this.stream=await navigator.mediaDevices.getUserMedia({video:s?{...r,frameRate:{ideal:e}}:!1,audio:i}),this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/webm;codecs=vp9"}),this.recordedChunks=[],this.mediaRecorder.ondataavailable=o=>{o.data.size>0&&this.recordedChunks.push(o.data)},this.mediaRecorder.start()}catch(o){console.error(o)}}async stopRecording(){return new Promise(e=>{this.mediaRecorder&&(this.mediaRecorder.onstop=()=>{const n=new Blob(this.recordedChunks,{type:"video/webm"});e(n)},this.mediaRecorder.stop())})}async sendToAPI(){const e=await this.stopRecording();return fetch(`${this.app.options.ingestPoint}/v1/web/uxt/upload-url`,{headers:{Authorization:`Bearer ${this.app.session.getSessionToken()}`}}).then(n=>{if(n.ok)return n.json();throw new Error("Failed to get upload url")}).then(({url:n})=>fetch(n,{method:"PUT",headers:{"Content-Type":"video/webm"},body:e})).catch(console.error).finally(()=>{this.discard()})}async saveToFile(e="recorded-video.webm"){const n=await this.stopRecording(),i=URL.createObjectURL(n),s=document.createElement("a");s.style.display="none",s.href=i,s.download=e,document.body.appendChild(s),s.click(),window.URL.revokeObjectURL(i),document.body.removeChild(s)}discard(){var e,n;(e=this.mediaRecorder)==null||e.stop(),(n=this.stream)==null||n.getTracks().forEach(i=>i.stop())}}function so(t,e){e.onmousedown=function(n){const i=t.getBoundingClientRect(),s=n.clientX-i.left,r=n.clientY-i.top;t.style.position="fixed",t.style.zIndex=99999999999999,o(n.pageX,n.pageY);function o(d,c){let u=d-s,p=c-r;u<=5&&(u=5),p<=5&&(p=5),u>=window.innerWidth-i.width&&(u=window.innerWidth-i.width),p>=window.innerHeight-i.height&&(p=window.innerHeight-i.height),t.style.left=`${u}px`,t.style.top=`${p}px`}function l(d){o(d.pageX,d.pageY)}document.addEventListener("mousemove",l);const a=()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",a)};document.addEventListener("mouseup",a)},e.ondragstart=function(){return!1}}function ro(){const t=document.createElement("div");t.className="grid";for(let e=0;e<16;e++){const n=document.createElement("div");Object.assign(n.style,{width:"2px",height:"2px",borderRadius:"10px",background:"white"}),n.className="cell",t.appendChild(n)}return Object.assign(t.style,{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gridTemplateRows:"repeat(4, 1fr)",gap:"2px",cursor:"grab"}),t}function oo(){const t=document.createElement("div");Object.assign(t.style,{width:"0",height:"0",borderLeft:"7px solid transparent",borderRight:"7px solid transparent",borderBottom:"7px solid white"});const e=document.createElement("div");return e.appendChild(t),Object.assign(e.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",cursor:"pointer",marginLeft:"auto",transform:"rotate(180deg)"}),e}function ao(){const t=document.createElement("style");t.type="text/css",t.innerText=`@keyframes spin {
|
|
649
649
|
0% { transform: rotate(0deg); }
|
|
650
650
|
100% { transform: rotate(360deg); }
|
|
651
|
-
}`,document.head.appendChild(t)}function co(){ao();const t=document.createElement("div");return t.classList.add("spinner"),Object.assign(t.style,no),t}function z(t,e,n,s
|
|
651
|
+
}`,document.head.appendChild(t)}function co(){ao();const t=document.createElement("div");return t.classList.add("spinner"),Object.assign(t.style,no),t}function z(t,e,n,i,s){const r=document.createElement(t);return r.className=e,Object.assign(r.style,n),i&&(r.textContent=i),s&&(r.id=s),r}const vt="or_uxt_test_start",tn="or_uxt_task_index",nn="or_uxt_session_id",lo="or_uxt_test_id";class ho{constructor(e,n,i,s,r,o,l,a,d){this.ingestPoint=e,this.getTimestamp=n,this.token=i,this.testId=s,this.storageKey=r,this.setStorageKey=o,this.removeStorageKey=l,this.getStorageKey=a,this.getSessionId=d,this.durations={testStart:0,tasks:[]},this.getDurations=()=>this.durations,this.setDurations=u=>{this.durations.testStart=u.testStart,this.durations.tasks=u.tasks},this.signalTask=(u,p,y)=>{if(!u)return console.error("User Testing: No Task ID Given");const S=this.durations.tasks.find(A=>A.taskId===u),v=this.getTimestamp(),T=S?v-S.started:0;return fetch(`${this.ingestPoint}/v1/web/uxt/signals/task`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},body:JSON.stringify({testId:this.testId,taskId:u,status:p,duration:T,timestamp:v,taskAnswer:y})})},this.signalTest=u=>{const p=this.getTimestamp();if(u==="begin"&&this.testId){const v=this.getSessionId();this.setStorageKey(nn,v),this.setStorageKey(this.storageKey,this.testId.toString()),this.setStorageKey(vt,p.toString())}else this.removeStorageKey(this.storageKey),this.removeStorageKey(tn),this.removeStorageKey(vt);const y=this.durations.testStart||p,S=p-y;return fetch(`${this.ingestPoint}/v1/web/uxt/signals/test`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},body:JSON.stringify({testId:this.testId,status:u,duration:S,timestamp:p})})};const c=this.getStorageKey(vt);c&&(this.durations.testStart=parseInt(c,10))}}class uo{constructor(e,n){this.app=e,this.storageKey=n,this.bg=z("div","bg",qr,void 0,"__or_ut_bg"),this.container=z("div","container",Wr,void 0,"__or_ut_ct"),this.widgetGuidelinesVisible=!0,this.widgetTasksVisible=!1,this.widgetVisible=!0,this.isActive=!1,this.descriptionSection=null,this.taskSection=null,this.endSection=null,this.stopButton=null,this.stopButtonContainer=null,this.test=null,this.testId=null,this.signalManager=null,this.getTest=(o,l,a)=>{this.testId=o;const d=this.app.options.ingestPoint;return fetch(`${d}/v1/web/uxt/test/${o}`,{headers:{Authorization:`Bearer ${l}`}}).then(c=>c.json()).then(({test:c})=>{this.isActive=!0,this.test=c,this.signalManager=new ho(this.app.options.ingestPoint,()=>this.app.timestamp(),l,o,this.storageKey,(u,p)=>this.app.localStorage.setItem(u,p),u=>this.app.localStorage.removeItem(u),u=>this.app.localStorage.getItem(u),()=>this.app.getSessionID()),this.createGreeting(c.title,c.reqMic,c.reqCamera),a&&((c.reqMic||c.reqCamera)&&this.userRecorder.startRecording(30,zi.Standard,c.reqMic,c.reqCamera),this.showWidget(c.description,c.tasks,!0),this.showTaskSection())}).then(()=>o).catch(c=>{console.log("OR: Error fetching test",c)})},this.hideTaskSection=()=>!1,this.showTaskSection=()=>!0,this.collapseWidget=()=>!1,this.removeGreeting=()=>!1,this.toggleDescriptionVisibility=()=>{},this.currentTaskIndex=0,this.userRecorder=new io(e);const i=this.app.getSessionID(),s=this.app.localStorage.getItem(nn);i!==s&&(this.app.localStorage.removeItem(this.storageKey),this.app.localStorage.removeItem(nn),this.app.localStorage.removeItem(lo),this.app.localStorage.removeItem(tn),this.app.localStorage.removeItem(vt));const r=this.app.localStorage.getItem(tn);r&&(this.currentTaskIndex=parseInt(r,10))}getTestId(){return this.testId}createGreeting(e,n,i){const s=z("div","title",Gr,e),r=z("div","description",Vr,`Welcome, you're here to help us improve, not to be judged. Your insights matter!
|
|
652
652
|
|
|
653
653
|
📹 We're recording this browser tab to learn from your experience.
|
|
654
|
-
🎤 Please enable mic and camera if asked, to give us a complete picture.`),o=z("div","button",Kr,"Read guidelines to begin");this.removeGreeting=()=>((n||
|
|
654
|
+
🎤 Please enable mic and camera if asked, to give us a complete picture.`),o=z("div","button",Kr,"Read guidelines to begin");this.removeGreeting=()=>((n||i)&&this.userRecorder.startRecording(30,zi.Standard,n,i),this.container.removeChild(o),this.container.removeChild(r),this.container.removeChild(s),!1),o.onclick=()=>{var a,d,c,u;this.removeGreeting();const l=(a=this.signalManager)==null?void 0:a.getDurations();l&&this.signalManager&&(l.testStart=this.app.timestamp(),this.signalManager.setDurations(l)),(d=this.signalManager)==null||d.signalTest("begin"),this.container.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',Object.assign(this.container.style,yt),this.showWidget(((c=this.test)==null?void 0:c.guidelines)||"",((u=this.test)==null?void 0:u.tasks)||[])},this.container.append(s,r,o),this.bg.appendChild(this.container),document.body.appendChild(this.bg)}showWidget(e,n,i){this.container.innerHTML="",Object.assign(this.bg.style,{position:"fixed",zIndex:99999999999999,right:"8px",left:"unset",width:"fit-content",top:"8px",height:"fit-content",background:"unset",display:"unset",alignItems:"unset",justifyContent:"unset"});const s=this.createTitleSection();this.container.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',Object.assign(this.container.style,yt);const r=this.createDescriptionSection(e),o=this.createTasksSection(n),l=z("div","stop_bn_or",Fi,"Abort Session"),a=z("div","stop_ct_or",{fontSize:"13px!important"});a.style.fontSize="13px",a.append(l),this.container.append(s,r,o,a),this.taskSection=o,this.descriptionSection=r,this.stopButton=l,this.stopButtonContainer=a,l.onclick=()=>{var d;this.userRecorder.discard(),(d=this.signalManager)==null||d.signalTest("skipped"),document.body.removeChild(this.bg),window.close()},i?this.toggleDescriptionVisibility():this.hideTaskSection()}createTitleSection(){var l;const e=z("div","title",Xr),n=ro(),i=z("div","title_text",{maxWidth:"19rem",overflow:"hidden",textOverflow:"ellipsis",width:"100%",fontSize:16,lineHeight:"auto",cursor:"pointer"},(l=this.test)==null?void 0:l.title),s=oo();e.append(n,i,s);const r=a=>(this.widgetVisible=a,this.container.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',Object.assign(this.container.style,this.widgetVisible?yt:{border:"none",background:"none",padding:0}),this.taskSection&&Object.assign(this.taskSection.style,this.widgetVisible?He:{display:"none"}),this.descriptionSection&&Object.assign(this.descriptionSection.style,this.widgetVisible?He:{display:"none"}),this.endSection&&Object.assign(this.endSection.style,this.widgetVisible?He:{display:"none"}),this.stopButton&&Object.assign(this.stopButton.style,this.widgetVisible?Fi:{display:"none"}),a),o=()=>{Object.assign(s.style,{transform:this.widgetVisible?"rotate(0deg)":"rotate(180deg)"}),r(!this.widgetVisible)};return i.onclick=o,s.onclick=o,so(this.bg,n),this.collapseWidget=()=>r(!1),e}createDescriptionSection(e){const n=z("div","description_section_or",He),i=z("div","description_s_title_or",Ai),s=z("div","title",{fontSize:13,fontWeight:500,lineHeight:"auto"},"Introduction & Guidelines"),r=z("div","icon",Di,"-"),o=z("div","content",Ue),l=z("div","text_description",{maxHeight:"250px",overflowY:"auto",whiteSpace:"pre-wrap",fontSize:13,color:"#454545",lineHeight:"auto"});l.innerHTML=e;const a=z("div","button_begin_or",Li,"Begin Test");i.append(s,r),o.append(l,a),n.append(i,o);const d=()=>{this.widgetGuidelinesVisible=!this.widgetGuidelinesVisible,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?Ue:{display:"none"})};return i.onclick=d,this.toggleDescriptionVisibility=()=>{this.widgetGuidelinesVisible=!1,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?Ue:{display:"none"}),o.removeChild(a)},a.onclick=()=>{var c,u,p;if(d(),this.test){const y=(c=this.signalManager)==null?void 0:c.getDurations(),S=y?y.tasks.findIndex(v=>this.test&&v.taskId===this.test.tasks[0].task_id):null;y&&S===-1&&(y.tasks.push({taskId:this.test.tasks[0].task_id,started:this.app.timestamp()}),(u=this.signalManager)==null||u.setDurations(y)),(p=this.signalManager)==null||p.signalTask(this.test.tasks[0].task_id,"begin")}this.showTaskSection(),o.removeChild(a)},n}createTasksSection(e){this.container.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',Object.assign(this.container.style,yt);const n=z("div","task_section_or",He),i=z("div","description_t_title_or",Ai),s=z("div","title",{fontSize:"13px",fontWeight:"500",lineHeight:"auto"},"Tasks"),r=z("div","icon",Di,"-"),o=z("div","content",Ue),l=z("div","pagination",Yr),a=z("div","taskCard",Pi),d=z("div","taskText",Bi),c=z("div","taskDescription",Zr),u=z("div","taskButtons",to),p=z("div","taskText",Bi);p.textContent="Your answer";const y=z("textarea","taskDescription",{resize:"vertical"}),S=z("div","inputArea",Pi);S.append(p,y);const v=z("div","closePanelButton",ji,"Collapse Panel"),T=z("div","nextButton",eo,"Done, Next");i.append(s,r),a.append(d,c),u.append(v,T),o.append(l,a,S,u),n.append(i,o);const A=()=>{const k=e[this.currentTaskIndex];d.textContent=k.title,c.textContent=k.description,k.allow_typing?S.style.display="flex":S.style.display="none"};e.forEach((k,N)=>{const O=z("span",`or_task_${N}`,{outline:"1px solid #efefef",fontSize:"13px",height:"24px",width:"24px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em"},(N+1).toString());O.id=`or_task_${N}`,l.append(O)});const B=()=>{this.widgetTasksVisible=!this.widgetTasksVisible,r.textContent=this.widgetTasksVisible?"-":"+",Object.assign(o.style,this.widgetTasksVisible?Ue:{display:"none"})};this.hideTaskSection=()=>(r.textContent="+",Object.assign(o.style,{display:"none"}),this.widgetTasksVisible=!1,!1),this.showTaskSection=()=>(r.textContent="-",Object.assign(o.style,Ue),this.widgetTasksVisible=!0,!0);const D=()=>{const k=document.getElementById(`or_task_${this.currentTaskIndex}`);k&&Object.assign(k.style,Mi);for(let N=0;N<this.currentTaskIndex;N++){const O=document.getElementById(`or_task_${N}`);O&&Object.assign(O.style,Qr)}};return i.onclick=B,v.onclick=this.collapseWidget,T.onclick=()=>{var N,O,L,I;const k=e[this.currentTaskIndex].allow_typing?y.value:void 0;if(y.value="",(N=this.signalManager)==null||N.signalTask(e[this.currentTaskIndex].task_id,"done",k),this.currentTaskIndex<e.length-1){this.currentTaskIndex++,A();const E=(O=this.signalManager)==null?void 0:O.getDurations();E&&E.tasks.findIndex(P=>P.taskId===e[this.currentTaskIndex].task_id)===-1&&(E.tasks.push({taskId:e[this.currentTaskIndex].task_id,started:this.app.timestamp()}),(L=this.signalManager)==null||L.setDurations(E)),(I=this.signalManager)==null||I.signalTask(e[this.currentTaskIndex].task_id,"begin"),D()}else this.showEndSection();this.app.localStorage.setItem("or_uxt_task_index",this.currentTaskIndex.toString())},setTimeout(()=>{const k=document.getElementById("or_task_0");k&&Object.assign(k.style,Mi),A(),D()},1),n}showEndSection(){var l,a,d,c;let e=!0;(l=this.signalManager)==null||l.signalTest("done");const n=z("div","end_section_or",Jr),i=z("div","end_title_or",{fontSize:"1.25rem",fontWeight:"500"},"Thank you! 👍"),s=z("div","end_description_or",{},((a=this.test)==null?void 0:a.conclusion)??`Thank you for participating in our usability test. Your feedback has been captured and will be used to enhance our website.
|
|
655
655
|
|
|
656
|
-
We appreciate your time and valuable input.`),r=z("div","end_button_or",Ls,"Submitting Feedback"),o=co();r.appendChild(o),(d=this.test)!=null&&d.reqMic||(c=this.test)!=null&&c.reqCamera?this.userRecorder.sendToAPI().then(()=>{r.removeChild(o),r.textContent="End Session",e=!1}).catch(u=>{console.error(u),r.removeChild(o),r.textContent="End Session",e=!1}):(r.removeChild(o),r.textContent="End Session",e=!1),this.taskSection&&this.container.removeChild(this.taskSection),this.descriptionSection&&this.container.removeChild(this.descriptionSection),this.stopButton&&this.stopButtonContainer&&this.container.removeChild(this.stopButtonContainer),r.onclick=()=>{e||(window.close(),document.body.removeChild(this.bg))},n.append(s,i,r),this.endSection=n,this.container.append(n)}}function Us(t){return!!t&&t.nodeType!=null}function sn(t){return t.namespaceURI==="http://www.w3.org/2000/svg"}function ke(t){return t.nodeType===Node.ELEMENT_NODE}function fo(t){return t.nodeType===Node.COMMENT_NODE}function rn(t){return t.nodeType===Node.TEXT_NODE}function wt(t){return t.nodeType===Node.DOCUMENT_NODE}function St(t){return t.nodeType===Node.DOCUMENT_NODE||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Q(t,e){return t.localName===e}class po{constructor(e,n){this.app=e,this.options=n,this.snapshots={},this.intervals=[],this.restartTracking=()=>{this.clear(),this.app.nodes.scanTree(this.captureCanvas)},this.captureCanvas=s=>{const i=this.app.nodes.getID(s);if(!i||!Q(s,"canvas")||this.app.sanitizer.isObscured(i)||this.app.sanitizer.isHidden(i)||!Q(s,"canvas")||this.snapshots[i])return;new IntersectionObserver(l=>{l.forEach(a=>{a.isIntersecting&&(a.target?this.snapshots[i]&&this.snapshots[i].createdAt?this.snapshots[i].paused=!1:this.recordCanvas(a.target,i):this.snapshots[i]&&(this.snapshots[i].paused=!0))})}).observe(s)},this.recordCanvas=(s,i)=>{const r=this.app.timestamp();this.snapshots[i]={images:[],createdAt:r,paused:!1,dummy:document.createElement("canvas")};const o=jr(i.toString(),r);this.app.send(o);const l=d=>{go(d,this.options.quality,this.snapshots[i].dummy,this.options.fixedScaling,this.fileExt,c=>{c&&(this.snapshots[i].images.push({id:this.app.timestamp(),data:c}),this.snapshots[i].images.length>9&&(this.sendSnaps(this.snapshots[i].images,i,this.snapshots[i].createdAt),this.snapshots[i].images=[]))})},a=setInterval(()=>{const d=this.app.nodes.getID(s),c=d?this.app.nodes.getNode(d):void 0;!c||!Q(c,"canvas")||c!==s?(this.app.debug.log("Canvas element not in sync"),clearInterval(a)):this.snapshots[i].paused||(this.options.useAnimationFrame?requestAnimationFrame(()=>{l(c)}):l(c))},this.interval);this.intervals.push(a)},this.fileExt=n.fileExt??"webp",this.interval=1e3/n.fps}startTracking(){setTimeout(()=>{this.app.nodes.scanTree(this.captureCanvas),this.app.nodes.attachNodeCallback(e=>{this.captureCanvas(e)})},500)}sendSnaps(e,n,s){if(Object.keys(this.snapshots).length===0)return;const i=new FormData;e.forEach(r=>{const o=r.data;o&&(i.append("snapshot",o,`${s}_${n}_${r.id}.${this.fileExt}`),this.options.isDebug&&mo(o,`${s}_${n}_${r.id}.${this.fileExt}`))}),fetch(this.app.options.ingestPoint+"/v1/web/images",{method:"POST",headers:{Authorization:`Bearer ${this.app.session.getSessionToken()??""}`},body:i}).then(()=>!0).catch(r=>{this.app.debug.error("error saving canvas",r)})}clear(){this.intervals.forEach(e=>clearInterval(e)),this.snapshots={}}}const Hs={low:.35,medium:.55,high:.8};function go(t,e="medium",n,s=!1,i,r){const o=`image/${i}`;if(s){const l=window.devicePixelRatio||1;n.width=t.width/l,n.height=t.height/l;const a=n.getContext("2d");if(!a)return"";a.clearRect(0,0,n.width,n.height),a.drawImage(t,0,0,n.width,n.height),n.toBlob(r,o,Hs[e])}else t.toBlob(r,o,Hs[e])}function mo(t,e){const n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download=e,s.style.display="none",document.body.appendChild(s),s.click(),document.body.removeChild(s)}const Je={Verbose:5,Log:4,Warnings:3,Errors:2,Silent:0};class bo{constructor(e=Je.Silent){this.shouldLog=n=>this.level>=n,this.log=(...n)=>{this.shouldLog(Je.Log)&&console.log(...n)},this.warn=(...n)=>{this.shouldLog(Je.Warnings)&&console.warn(...n)},this.error=(...n)=>{this.shouldLog(Je.Errors)&&console.error(...n)},this.level=e}}class yo{constructor(e){this.node_id=e,this.nodes=[],this.totalNodeAmount=0,this.nodeCallbacks=[],this.elementListeners=new Map,this.nextNodeId=0,this.scanTree=n=>{this.nodes.forEach(s=>n(s))}}syntheticMode(e){const i=99999999*e;if(i>9007199254740900)throw new Error("Placeholder id overflow");this.nextNodeId=i}attachNodeCallback(e){this.nodeCallbacks.push(e)}attachNodeListener(e,n,s,i=!0){const r=this.getID(e);if(r===void 0)return;vs(e,n,s,i);let o=this.elementListeners.get(r);o===void 0&&(o=[],this.elementListeners.set(r,o)),o.push([n,s,i])}registerNode(e){let n=e[this.node_id];const s=n===void 0;return s&&(n=this.nextNodeId,this.totalNodeAmount++,this.nextNodeId++,this.nodes[n]=e,e[this.node_id]=n),[n,s]}unregisterNode(e){const n=e[this.node_id];if(n!==void 0){e[this.node_id]=void 0,delete e[this.node_id],delete this.nodes[n];const s=this.elementListeners.get(n);s!==void 0&&(this.elementListeners.delete(n),s.forEach(i=>ws(e,i[0],i[1],i[2]))),this.totalNodeAmount--}return n}cleanTree(){for(let e=0;e<this.nodes.length;e++){const n=this.nodes[e];n&&!document.contains(n)&&this.unregisterNode(n)}}callNodeCallbacks(e,n){this.nodeCallbacks.forEach(s=>s(e,n))}getID(e){if(e)return e[this.node_id]}getNode(e){return this.nodes[e]}getNodeCount(){return this.totalNodeAmount}clear(){for(let e=0;e<this.nodes.length;e++){const n=this.nodes[e];n&&this.unregisterNode(n)}this.nextNodeId=0,this.nodes.length=0}}function on(t){if(fo(t))return!0;if(rn(t))return!1;if(!ke(t))return!0;const e=t.tagName.toUpperCase();if(e==="LINK"){const n=t.getAttribute("rel"),s=t.getAttribute("as");return!(n!=null&&n.includes("stylesheet")||s==="style"||s==="font")}return e==="SCRIPT"||e==="NOSCRIPT"||e==="META"||e==="TITLE"||e==="BASE"}function an(t){return St(t)?!0:!on(t)}var ye;(function(t){t[t.New=0]="New",t[t.Removed=1]="Removed",t[t.Changed=2]="Changed"})(ye||(ye={}));class cn{constructor(e,n=!1){this.app=e,this.isTopContext=n,this.commited=[],this.recents=new Map,this.indexes=[],this.attributesMap=new Map,this.textSet=new Set,this.observer=ys(this.app.safe(s=>{for(const i of s){const r=i.target,o=i.type;if(!an(r))continue;if(o==="childList"){for(let a=0;a<i.removedNodes.length;a++)an(i.removedNodes[a])&&this.bindNode(i.removedNodes[a]);for(let a=0;a<i.addedNodes.length;a++)this.bindTree(i.addedNodes[a]);continue}const l=this.app.nodes.getID(r);if(l!==void 0){if(this.recents.has(l)||this.recents.set(l,ye.Changed),o==="attributes"){const a=i.attributeName;if(a===null)continue;let d=this.attributesMap.get(l);d===void 0&&this.attributesMap.set(l,d=new Set),d.add(a);continue}if(o==="characterData"){this.textSet.add(l);continue}}}this.commitNodes()}))}clear(){this.commited.length=0,this.recents.clear(),this.indexes.length=1,this.attributesMap.clear(),this.textSet.clear()}sendNodeAttribute(e,n,s,i){if(sn(n)){s.substr(0,6)==="xlink:"&&(s=s.substr(6)),i===null?this.app.send(xs(e,s)):s==="href"?(i.length>1e5&&(i=""),this.app.send(Kt(e,s,i,this.app.getBaseHref()))):this.app.attributeSender.sendSetAttribute(e,s,i);return}if(!(s==="src"||s==="srcset"||s==="integrity"||s==="crossorigin"||s==="autocomplete"||s.substr(0,2)==="on")&&!(s==="value"&&Q(n,"input")&&n.type!=="button"&&n.type!=="reset"&&n.type!=="submit")){if(i===null){this.app.send(xs(e,s));return}if(s==="style"||s==="href"&&Q(n,"link")){this.app.send(Kt(e,s,i,this.app.getBaseHref()));return}(s==="href"||i.length>1e5)&&(i=""),this.app.attributeSender.sendSetAttribute(e,s,i)}}sendNodeData(e,n,s){if(Q(n,"style")){this.app.send(Or(e,s,this.app.getBaseHref()));return}s=this.app.sanitizer.sanitize(e,s),this.app.send(mr(e,s))}bindNode(e){const[n,s]=this.app.nodes.registerNode(e);s?this.recents.set(n,ye.New):this.recents.get(n)!==ye.New&&this.recents.set(n,ye.Removed)}bindTree(e){if(!an(e))return;this.bindNode(e);const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:s=>(this.app.nodes.getID(s)!==void 0&&this.app.debug.error("! Node is already bound",s),on(s)||this.app.nodes.getID(s)!==void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT)},!1);for(;n.nextNode();)this.bindNode(n.currentNode)}unbindTree(e){const n=this.app.nodes.unregisterNode(e);if(n!==void 0&&this.recents.get(n)===ye.Removed){this.app.send(gr(n));const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:l=>on(l)||this.app.nodes.getID(l)===void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},!1);let i=0;const r=this.app.nodes.getNodeCount();for(;s.nextNode();)i+=1,this.app.nodes.unregisterNode(s.currentNode);const o=Math.floor(i/r*100);o>30&&this.app.send(Br(o))}}_commitNode(e,n){if(St(n))return!0;const s=n.parentNode;let i;if(!Q(n,"html")||!this.isTopContext){if(s===null)return this.unbindTree(n),!1;if(i=this.app.nodes.getID(s),i===void 0)return this.unbindTree(n),!1;if(!this.commitNode(i))return this.unbindTree(n),!1;if(this.app.sanitizer.handleNode(e,i,n),this.app.sanitizer.isHidden(i))return!1}let r=n.previousSibling;for(;r!==null;){const c=this.app.nodes.getID(r);if(c!==void 0){this.commitNode(c),this.indexes[e]=this.indexes[c]+1;break}r=r.previousSibling}r===null&&(this.indexes[e]=0);const o=this.recents.get(e),l=o===ye.New,a=this.indexes[e];if(a===void 0)throw"commitNode: missing node index";if(l){if(ke(n)){let c=n;if(i!==void 0){if(this.app.sanitizer.isHidden(e)){const u=c.clientWidth,p=c.clientHeight;c=n.cloneNode(),c.style.width=`${u}px`,c.style.height=`${p}px`}this.app.send(ur(e,i,a,c.tagName,sn(n)))}for(let u=0;u<c.attributes.length;u++){const p=c.attributes[u];this.sendNodeAttribute(e,c,p.nodeName,p.value)}}else rn(n)&&(this.app.send(fr(e,i,a)),this.sendNodeData(e,s,n.data));return!0}o===ye.Removed&&i!==void 0&&this.app.send(pr(e,i,a));const d=this.attributesMap.get(e);if(d!==void 0){if(!ke(n))throw"commitNode: node is not an element";for(const c of d)this.sendNodeAttribute(e,n,c,n.getAttribute(c))}if(this.textSet.has(e)){if(!rn(n))throw"commitNode: node is not a text";this.sendNodeData(e,s,n.data)}return!0}commitNode(e){const n=this.app.nodes.getNode(e);if(n===void 0)return!1;const s=this.commited[e];return s!==void 0?s:this.commited[e]=this._commitNode(e,n)}commitNodes(e=!1){let n;this.recents.forEach((s,i)=>{this.commitNode(i),s===ye.New&&(n=this.app.nodes.getNode(i))&&this.app.nodes.callNodeCallbacks(n,e)}),this.clear()}observeRoot(e,n,s=e){this.observer.observe(e,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!1,characterDataOldValue:!1}),this.bindTree(s),n(this.app.nodes.getID(e)),this.commitNodes(!0)}disconnect(){this.observer.disconnect(),this.clear()}}class $s extends cn{observe(e){const n=e.contentDocument,s=this.app.nodes.getID(e);!n||s===void 0||this.observeRoot(n,i=>{if(i===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(s,i))})}syntheticObserve(e,n){this.observeRoot(n,s=>{if(s===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(e,s))})}}class vo extends cn{observe(e){const n=e.shadowRoot,s=this.app.nodes.getID(e);!n||s===void 0||this.observeRoot(n,i=>{if(i===void 0){this.app.debug.error("OpenReplay: Shadow Root was not bound");return}this.app.send(Xt(s,i))})}}class wo{constructor(){this.states=new Map}calcOffset(e){let n=0,s=0;if(e.parent&&([n,s]=this.calcOffset(e.parent)),!e.offset){const{left:o,top:l}=e.iFrame.getBoundingClientRect();e.offset=[o,l]}const[i,r]=e.offset;return[n+i,s+r]}getDocumentOffset(e){const n=this.states.get(e);return n?this.calcOffset(n):[0,0]}observe(e){var l;const n=e.contentDocument;if(!n)return;const s=e.ownerDocument,i=this.states.get(s),r={offset:null,iFrame:e,parent:i||null,clear:()=>{var a;s.removeEventListener("scroll",o),(a=s.defaultView)==null||a.removeEventListener("resize",o)}},o=()=>{r.offset=null};s.addEventListener("scroll",o),(l=s.defaultView)==null||l.addEventListener("resize",o),this.states.set(n,r)}clear(){this.states.forEach(e=>e.clear()),this.states.clear()}}const ln=be?Element.prototype.attachShadow:()=>new ShadowRoot;class So extends cn{constructor(e,n){super(e,!0),this.iframeOffsets=new wo,this.contextCallbacks=[],this.contextsSet=new Set,this.iframeObservers=[],this.shadowRootObservers=[],this.options=Object.assign({captureIFrames:!0},n),this.app.nodes.attachNodeCallback(s=>{Q(s,"iframe")&&(this.options.captureIFrames&&!Re(s,"obscured")||Re(s,"capture"))&&this.handleIframe(s)}),this.app.nodes.attachNodeCallback(s=>{ke(s)&&s.shadowRoot!==null&&this.handleShadowRoot(s.shadowRoot)})}attachContextCallback(e){this.contextCallbacks.push(e)}getDocumentOffset(e){return this.iframeOffsets.getDocumentOffset(e)}handleIframe(e){let n=null;const s=this.app.safe(()=>setTimeout(()=>{if(this.app.nodes.getID(e)===void 0||!sr(e))return;const r=e.contentWindow,o=e.contentDocument;if(o&&o!==n){const l=new $s(this.app);this.iframeObservers.push(l),l.observe(e),n=o,this.iframeOffsets.observe(e)}r&&r===r.window&&!this.contextsSet.has(r)&&(this.contextsSet.add(r),this.contextCallbacks.forEach(l=>l(r)))},100));e.addEventListener("load",s),s()}handleShadowRoot(e){const n=new vo(this.app);this.shadowRootObservers.push(n),n.observe(e.host)}observe(){const e=this;Element.prototype.attachShadow=function(){const n=ln.apply(this,arguments);return e.handleShadowRoot(n),n},this.app.nodes.clear(),this.observeRoot(window.document,()=>{this.app.send(hr()),this.app.nodes.callNodeCallbacks(document,!0)},window.document.documentElement)}crossdomainObserve(e,n){const s=this;Element.prototype.attachShadow=function(){const r=ln.apply(this,arguments);return s.handleShadowRoot(r),r},this.app.nodes.clear(),this.app.nodes.syntheticMode(n);const i=new $s(this.app);this.iframeObservers.push(i),i.syntheticObserve(e,window.document)}disconnect(){this.iframeOffsets.clear(),Element.prototype.attachShadow=ln,this.iframeObservers.forEach(e=>e.disconnect()),this.iframeObservers=[],this.shadowRootObservers.forEach(e=>e.disconnect()),this.shadowRootObservers=[],super.disconnect()}}var xt;(function(t){t[t.Plain=0]="Plain",t[t.Obscured=1]="Obscured",t[t.Hidden=2]="Hidden"})(xt||(xt={}));const xo=t=>t.trim().replace(/[^\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/g,"█");class ko{constructor(e,n){this.app=e,this.obscured=new Set,this.hidden=new Set,this.options=Object.assign({obscureTextEmails:!0,obscureTextNumbers:!1},n)}handleNode(e,n,s){if((this.obscured.has(n)||ke(s)&&(Re(s,"masked")||Re(s,"obscured")))&&this.obscured.add(e),(this.hidden.has(n)||ke(s)&&(Re(s,"htmlmasked")||Re(s,"hidden")))&&this.hidden.add(e),this.options.domSanitizer!==void 0&&ke(s)){const i=this.options.domSanitizer(s);i===xt.Obscured&&this.obscured.add(e),i===xt.Hidden&&this.hidden.add(e)}}sanitize(e,n){return this.obscured.has(e)?xo(n):(this.options.obscureTextNumbers&&(n=n.replace(/\d/g,"0")),this.options.obscureTextEmails&&(n=n.replace(/^\w+([+.-]\w+)*@\w+([.-]\w+)*\.\w{2,3}$/g,s=>{const[i,r]=s.split("@"),[o,l]=r.split(".");return`${Wt(i)}@${Wt(o)}.${Wt(l)}`})),n)}isObscured(e){return this.obscured.has(e)}isHidden(e){return this.hidden.has(e)}getInnerTextSecure(e){const n=this.app.nodes.getID(e);return n?this.sanitize(n,e.innerText):""}clear(){this.obscured.clear(),this.hidden.clear()}}class To{constructor(e,n){this.app=e,this.options=n,this.metadata={},this.userID=null,this.callbacks=[],this.timestamp=0,this.createTabId()}attachUpdateCallback(e){this.callbacks.push(e)}handleUpdate(e){e.userID==null&&delete e.userID,e.sessionID==null&&delete e.sessionID,this.callbacks.forEach(n=>n(e))}assign(e){e.userID!==void 0&&(this.userID=e.userID),e.metadata!==void 0&&Object.entries(e.metadata).forEach(([n,s])=>this.metadata[n]=s),e.sessionID!==void 0&&(this.sessionID=e.sessionID),e.timestamp!==void 0&&(this.timestamp=e.timestamp),e.projectID!==void 0&&(this.projectID=e.projectID),this.handleUpdate(e)}setMetadata(e,n){this.metadata[e]=n,this.handleUpdate({metadata:{[e]:n}})}setUserID(e){this.userID=e,this.handleUpdate({userID:e})}setUserInfo(e){this.userInfo=e}getPageNumber(){const e=this.app.sessionStorage.getItem(this.options.session_pageno_key);if(e!=null)return parseInt(e)}incPageNo(){let e=this.getPageNumber();return e===void 0?e=0:e++,this.app.sessionStorage.setItem(this.options.session_pageno_key,e.toString()),e}getSessionToken(){return this.app.sessionStorage.getItem(this.options.session_token_key)||void 0}setSessionToken(e){this.app.sessionStorage.setItem(this.options.session_token_key,e)}applySessionHash(e){const n=decodeURI(e).split("&");let s=e,i="100500";n.length==2&&([i,s]=n),!(!i||!s)&&(this.app.sessionStorage.setItem(this.options.session_token_key,s),this.app.sessionStorage.setItem(this.options.session_pageno_key,i))}getSessionHash(){const e=this.getPageNumber(),n=this.getSessionToken();if(!(e===void 0||n===void 0))return encodeURI(String(e)+"&"+n)}getTabId(){return this.tabId||this.createTabId(),this.tabId}regenerateTabId(){const e=ir(12);this.app.sessionStorage.setItem(this.options.session_tabid_key,e),this.tabId=e}createTabId(){const e=this.app.sessionStorage.getItem(this.options.session_tabid_key);e?this.tabId=e:this.regenerateTabId()}getInfo(){return{sessionID:this.sessionID,metadata:this.metadata,userID:this.userID,timestamp:this.timestamp,projectID:this.projectID}}reset(){this.app.sessionStorage.removeItem(this.options.session_token_key),this.metadata={},this.userID=null,this.sessionID=void 0,this.timestamp=0}}function Eo(t,e){let n=0;return()=>{n++>=e&&(n=0,t())}}class Io{constructor(e){this.app=e,this.timer=null,this.callbacks=[]}attach(e,n=0,s=!0,i){i&&(e=e.bind(i)),s&&(e=this.app.safe(e)),this.callbacks.unshift(n?Eo(e,n):e)-1}start(){this.timer===null&&(this.timer=setInterval(()=>this.callbacks.forEach(e=>{e&&e()}),30))}stop(){this.timer!==null&&(clearInterval(this.timer),this.timer=null)}}const Ye="canceled",qs="or_uxt_active",dn="or_buffer_1",_e=t=>({reason:t,success:!1}),Co=t=>({...t,success:!0});var Z;(function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Active=2]="Active",t[t.ColdStart=3]="ColdStart"})(Z||(Z={}));const Ws="https://api.openreplay.com/ingest";function hn(){const t=new Date().getTimezoneOffset()*-1,e=t>=0?"+":"-",n=Math.floor(Math.abs(t)/60),s=Math.abs(t)%60;return`UTC${e}${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}`}const _o=t=>new Promise(e=>setTimeout(e,t)),le={ask:"never-gonna-give-you-up",resp:"never-gonna-let-you-down",reg:"never-gonna-run-around-and-desert-you",iframeSignal:"never-gonna-make-you-cry",iframeId:"never-gonna-say-goodbye",iframeBatch:"never-gonna-tell-a-lie-and-hurt-you"};let No=class{constructor(e,n,s,i,r){this.signalError=i,this.insideIframe=r,this.messages=[],this.bufferedMessages1=[],this.bufferedMessages2=[],this.startCallbacks=[],this.stopCallbacks=[],this.commitCallbacks=[],this.activityState=Z.NotActive,this.version="14.0.4",this.socketMode=!1,this.compressionThreshold=24*1e3,this.bc=null,this.canvasRecorder=null,this.conditionsManager=null,this.canStart=!1,this.rootId=null,this.pageFrames=[],this.frameOderNumber=0,this.initialHostName=location.hostname,this.startTimeout=null,this.coldStartCommitN=0,this.delay=0,this.coldInterval=null,this.orderNumber=0,this.coldStartTs=0,this.singleBuffer=!1,this.onSessionSent=()=>{},this.restartCanvasTracking=()=>{var a;(a=this.canvasRecorder)==null||a.restartTracking()},this.flushBuffer=async a=>new Promise(d=>{let c=!1;const u=[a.shift()];for(;!c;){const p=a[0];!p||p[0]===0?c=!0:u.push(a.shift())}this.postToWorker(u),d(null)}),this.onUxtCb=[],this.contextId=Math.random().toString(36).slice(2),this.projectKey=e,Object.keys(s).findIndex(a=>["fixedCanvasScaling","disableCanvas"].includes(a))!==-1&&(console.warn('Openreplay: canvas options are moving to separate key "canvas" in next update. Please update your configuration.'),s={...s,canvas:{__save_canvas_locally:s.__save_canvas_locally,fixedCanvasScaling:s.fixedCanvasScaling,disableCanvas:s.disableCanvas}}),this.networkOptions=s.network;const o={revID:"",node_id:"__openreplay_id",session_token_key:"__openreplay_token",session_pageno_key:"__openreplay_pageno",session_reset_key:"__openreplay_reset",session_tabid_key:"__openreplay_tabid",local_uuid_key:"__openreplay_uuid",ingestPoint:Ws,resourceBaseHref:null,__is_snippet:!1,__debug_report_edp:null,__debug__:Je.Silent,__save_canvas_locally:!1,localStorage:null,sessionStorage:null,disableStringDict:!1,forceSingleTab:!1,assistSocketHost:"",fixedCanvasScaling:!1,disableCanvas:!1,captureIFrames:!0,obscureTextEmails:!0,obscureTextNumbers:!1,crossdomain:{parentDomain:"*"},canvas:{disableCanvas:!1,fixedCanvasScaling:!1,__save_canvas_locally:!1,useAnimationFrame:!1}};if(this.options=Ss(o,s),!this.insideIframe&&!this.options.forceSingleTab&&globalThis&&"BroadcastChannel"in globalThis){const a=location.hostname.split(".").slice(-2).join("_");this.bc=new BroadcastChannel(`rick_${a}`)}this.revID=this.options.revID,this.localStorage=this.options.localStorage??window.localStorage,this.sessionStorage=this.options.sessionStorage??window.sessionStorage,this.sanitizer=new ko(this,s),this.nodes=new yo(this.options.node_id),this.observer=new So(this,s),this.ticker=new Io(this),this.ticker.attach(()=>this.commit()),this.debug=new bo(this.options.__debug__),this.session=new To(this,this.options),this.attributeSender=new Yi(this,!!this.options.disableStringDict),this.featureFlags=new er(this),this.tagWatcher=new $r(this.sessionStorage,this.debug.error,a=>{this.send(zr(a))}),this.session.attachUpdateCallback(({userID:a,metadata:d})=>{a!=null&&this.send(Er(a)),d!=null&&Object.entries(d).forEach(([c,u])=>this.send(ks(c,u)))}),n!=null&&this.session.applySessionHash(n),this.initWorker();const l=this.session.getTabId();if(this.insideIframe){const a=c=>{const{data:u}=c;u.line===le.iframeId&&(this.rootId=u.id,this.session.setSessionToken(u.token),this.frameOderNumber=u.frameOrderNumber,this.debug.log("starting iframe tracking",u),this.allowAppStart())};window.addEventListener("message",a),this.attachStopCallback(()=>{window.removeEventListener("message",a)});const d=this.initialHostName;window.parent.postMessage({line:le.iframeSignal,source:l,context:this.contextId,domain:d},"*")}else{let a=0;const d=c=>{const{data:u}=c;if(u.line===le.iframeSignal){const p=u.domain,y=Array.from(document.querySelectorAll("iframe"));this.pageFrames=y,(async()=>{let v=0;for(;v<10;){const T=this.checkNodeId(y,p);if(T){this.waitStarted().then(()=>{var D;a++;const A=this.session.getSessionToken(),B={line:le.iframeId,context:this.contextId,domain:p,id:T,token:A,frameOrderNumber:a};this.debug.log("iframe_data",B),(D=c.source)==null||D.postMessage(B,"*")}).catch(console.error),v=10;break}v++,await _o(100)}})()}if(u.line===le.iframeBatch){const y=u.messages.map(S=>{if(S[0]===20){let v=S;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[A,B,D]=S,{left:k,top:N}=T.getBoundingClientRect();v=[A,B+k,D+N]}}),v}if(S[0]===68){let v=S;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[A,B,D,k,N,O,L]=S,{left:I,top:E,width:P,height:V}=T.getBoundingClientRect(),j=document.documentElement.scrollWidth,q=document.documentElement.scrollHeight,C=O/100*P+I,F=L/100*V+E,G=C/j,K=F/q;v=[A,B,D,k,N,Math.round(G*1e3)/10,Math.round(K*1e3)/10]}}),v}return S});this.messages.push(...y)}};window.addEventListener("message",d),this.attachStopCallback(()=>{window.removeEventListener("message",d)})}this.bc!==null&&(this.bc.postMessage({line:le.ask,source:l,context:this.contextId}),this.startTimeout=setTimeout(()=>{this.allowAppStart()},500),this.bc.onmessage=a=>{if(a.data.context!==this.contextId){if(a.data.line===le.resp){const d=a.data.token;this.session.setSessionToken(d),this.allowAppStart()}if(a.data.line===le.reg){const d=a.data.token;this.session.regenerateTabId(),this.session.setSessionToken(d),this.allowAppStart()}if(a.data.line===le.ask){const d=this.session.getSessionToken();d&&this.bc&&this.bc.postMessage({line:a.data.source===l?le.reg:le.resp,token:d,source:l,context:this.contextId})}}})}allowAppStart(){this.canStart=!0,this.startTimeout&&(clearTimeout(this.startTimeout),this.startTimeout=null)}checkNodeId(e,n){for(const s of e)if(s.dataset.domain===n)return s[this.options.node_id];return null}initWorker(){try{this.worker=new Worker(URL.createObjectURL(new Blob(['"use strict";class t{constructor(t,s,i,e=10,n=250,h,r){this.onUnauthorised=s,this.onFailure=i,this.MAX_ATTEMPTS_COUNT=e,this.ATTEMPT_TIMEOUT=n,this.onCompress=h,this.pageNo=r,this.attemptsCount=0,this.busy=!1,this.queue=[],this.token=null,this.lastBatchNum=0,this.ingestURL=t+"/v1/web/i",this.isCompressing=void 0!==h}getQueueStatus(){return 0===this.queue.length&&!this.busy}authorise(t){this.token=t,this.busy||this.sendNext()}push(t){if(this.busy||!this.token)this.queue.push(t);else if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}}sendNext(){const t=this.queue.shift();if(t)if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}else this.busy=!1}retry(t,s,i){this.attemptsCount>=this.MAX_ATTEMPTS_COUNT?this.onFailure(`Failed to send batch after ${this.attemptsCount} attempts.`):(this.attemptsCount++,setTimeout((()=>this.sendBatch(t,s,i)),this.ATTEMPT_TIMEOUT*this.attemptsCount))}sendBatch(t,s,i){const e=i?.toString().replace(/^([^_]+)_([^_]+).*/,"$1_$2_$3");this.busy=!0;const n={Authorization:`Bearer ${this.token}`};s&&(n["Content-Encoding"]="gzip"),null!==this.token?fetch(`${this.ingestURL}?batch=${this.pageNo??"noPageNum"}_${e??"noBatchNum"}`,{body:t,method:"POST",headers:n,keepalive:t.length<65536}).then((e=>{if(401===e.status)return this.busy=!1,void this.onUnauthorised();e.status>=400?this.retry(t,s,`${i??"noBatchNum"}_network:${e.status}`):(this.attemptsCount=0,this.sendNext())})).catch((e=>{console.warn("OpenReplay:",e),this.retry(t,s,`${i??"noBatchNum"}_reject:${e.message}`)})):setTimeout((()=>{this.sendBatch(t,s,`${i??"noBatchNum"}_newToken`)}),500)}sendCompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!0,s)}sendUncompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}clean(){this.sendNext(),setTimeout((()=>{this.token=null,this.queue.length=0}),10)}}const s="function"==typeof TextEncoder?new TextEncoder:{encode(t){const s=t.length,i=new Uint8Array(3*s);let e=-1;for(let n=0,h=0,r=0;r!==s;){if(n=t.charCodeAt(r),r+=1,n>=55296&&n<=56319){if(r===s){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;break}if(h=t.charCodeAt(r),!(h>=56320&&h<=57343)){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;continue}if(n=1024*(n-55296)+h-56320+65536,r+=1,n>65535){i[e+=1]=240|n>>>18,i[e+=1]=128|n>>>12&63,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n;continue}}n<=127?i[e+=1]=0|n:n<=2047?(i[e+=1]=192|n>>>6,i[e+=1]=128|63&n):(i[e+=1]=224|n>>>12,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n)}return i.subarray(0,e+1)}};class i{constructor(t){this.size=t,this.offset=0,this.checkpointOffset=0,this.data=new Uint8Array(t)}getCurrentOffset(){return this.offset}checkpoint(){this.checkpointOffset=this.offset}get isEmpty(){return 0===this.offset}skip(t){return this.offset+=t,this.offset<=this.size}set(t,s){this.data.set(t,s)}boolean(t){return this.data[this.offset++]=+t,this.offset<=this.size}uint(t){for((t<0||t>Number.MAX_SAFE_INTEGER)&&(t=0);t>=128;)this.data[this.offset++]=t%256|128,t=Math.floor(t/128);return this.data[this.offset++]=t,this.offset<=this.size}int(t){return t=Math.round(t),this.uint(t>=0?2*t:-2*t-1)}string(t){const i=s.encode(t),e=i.byteLength;return!(!this.uint(e)||this.offset+e>this.size)&&(this.data.set(i,this.offset),this.offset+=e,!0)}reset(){this.offset=0,this.checkpointOffset=0}flush(){const t=this.data.slice(0,this.checkpointOffset);return this.reset(),t}}class e extends i{encode(t){switch(t[0]){case 0:case 11:case 114:case 115:return this.uint(t[1]);case 4:case 44:case 47:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 5:case 20:case 38:case 70:case 75:case 76:case 77:case 82:return this.uint(t[1])&&this.uint(t[2]);case 6:return this.int(t[1])&&this.int(t[2]);case 7:return!0;case 8:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.string(t[4])&&this.boolean(t[5]);case 9:case 10:case 24:case 51:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 12:case 61:case 71:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 13:case 14:case 17:case 50:case 54:return this.uint(t[1])&&this.string(t[2]);case 16:return this.uint(t[1])&&this.int(t[2])&&this.int(t[3]);case 18:return this.uint(t[1])&&this.string(t[2])&&this.int(t[3]);case 19:return this.uint(t[1])&&this.boolean(t[2]);case 21:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8]);case 22:case 27:case 30:case 41:case 45:case 46:case 63:case 64:case 79:return this.string(t[1])&&this.string(t[2]);case 23:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 28:case 29:case 42:case 117:case 118:return this.string(t[1]);case 37:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3]);case 39:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7]);case 40:return this.string(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 48:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.int(t[5]);case 49:return this.int(t[1])&&this.int(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 53:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8]);case 55:return this.boolean(t[1]);case 57:case 60:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 58:case 120:return this.int(t[1]);case 59:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6])&&this.string(t[7]);case 67:case 73:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 68:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6]);case 69:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 78:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 81:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.int(t[4])&&this.string(t[5]);case 83:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 84:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6]);case 112:return this.uint(t[1])&&this.string(t[2])&&this.boolean(t[3])&&this.string(t[4])&&this.int(t[5])&&this.int(t[6]);case 113:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3]);case 116:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8])&&this.uint(t[9])&&this.boolean(t[10]);case 119:return this.string(t[1])&&this.uint(t[2]);case 121:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 122:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 123:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])}}}class n{constructor(t,s,i,n,h,r){this.pageNo=t,this.timestamp=s,this.url=i,this.onBatch=n,this.tabId=h,this.onOfflineEnd=r,this.nextIndex=0,this.beaconSize=2e5,this.encoder=new e(this.beaconSize),this.sizeBuffer=new Uint8Array(3),this.isEmpty=!0,this.beaconSizeLimit=1e6,this.prepare()}writeType(t){return this.encoder.uint(t[0])}writeFields(t){return this.encoder.encode(t)}writeSizeAt(t,s){for(let s=0;s<3;s++)this.sizeBuffer[s]=t>>8*s;this.encoder.set(this.sizeBuffer,s)}prepare(){if(!this.encoder.isEmpty)return;const t=[81,1,this.pageNo,this.nextIndex,this.timestamp,this.url],s=[118,this.tabId];this.writeType(t),this.writeFields(t),this.writeWithSize(s),this.isEmpty=!0}writeWithSize(t){const s=this.encoder;if(!this.writeType(t)||!s.skip(3))return!1;const i=s.getCurrentOffset(),e=this.writeFields(t);if(e){const e=s.getCurrentOffset()-i;if(e>16777215)return console.warn("OpenReplay: max message size overflow."),!1;this.writeSizeAt(e,i-3),s.checkpoint(),this.isEmpty=this.isEmpty&&0===t[0],this.nextIndex++}return e}setBeaconSizeLimit(t){this.beaconSizeLimit=t}writeMessage(t){if("q_end"===t[0])return this.finaliseBatch(),this.onOfflineEnd();0===t[0]&&(this.timestamp=t[1]),122===t[0]&&(this.url=t[1]),this.writeWithSize(t)||(this.finaliseBatch(),this.writeWithSize(t)||(this.encoder=new e(this.beaconSizeLimit),this.prepare(),this.writeWithSize(t)?this.finaliseBatch():console.warn("OpenReplay: beacon size overflow. Skipping large message.",t,this),this.encoder=new e(this.beaconSize),this.prepare()))}finaliseBatch(){if(this.isEmpty)return;const t=this.encoder.flush();this.onBatch(t),this.prepare()}clean(){this.encoder.reset()}}var h;!function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Stopping=2]="Stopping",t[t.Active=3]="Active",t[t.Stopped=4]="Stopped"}(h||(h={}));let r=null,a=null,u=h.NotActive;function o(){a&&a.finaliseBatch()}function c(){return new Promise((t=>{u=h.Stopping,null!==l&&(clearInterval(l),l=null),a&&(a.clean(),a=null),r&&(r.clean(),setTimeout((()=>{r=null}),20)),setTimeout((()=>{u=h.NotActive,t(null)}),100)}))}function g(){u!==h.Stopped&&(postMessage("a_stop"),c().then((()=>{postMessage("a_start")})))}let p,l=null;self.onmessage=({data:s})=>{if(null!=s){if("stop"===s)return o(),void c().then((()=>{u=h.Stopped}));if("forceFlushBatch"!==s){if(!Array.isArray(s)){if("compressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Compressed batch."),void g();s.batch&&r.sendCompressed(s.batch)}if("uncompressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Uncompressed batch."),void g();s.batch&&r.sendUncompressed(s.batch)}return"start"===s.type?(u=h.Starting,r=new t(s.ingestPoint,(()=>{g()}),(t=>{!function(t){postMessage({type:"failure",reason:t}),c()}(t)}),s.connAttemptCount,s.connAttemptGap,(t=>{postMessage({type:"compress",batch:t},[t.buffer])}),s.pageNo),a=new n(s.pageNo,s.timestamp,s.url,(t=>{r&&r.push(t)}),s.tabId,(()=>postMessage({type:"queue_empty"}))),null===l&&(l=setInterval(o,1e4)),u=h.Active):"auth"===s.type?r?a?(r.authorise(s.token),void(s.beaconSizeLimit&&a.setBeaconSizeLimit(s.beaconSizeLimit))):(console.debug("OR WebWorker: writer not initialised. Received auth."),void g()):(console.debug("OR WebWorker: sender not initialised. Received auth."),void g()):void 0}if(a){const t=a;s.forEach((s=>{55===s[0]&&(s[1]?p=setTimeout((()=>g()),18e5):clearTimeout(p)),t.writeMessage(s)}))}else postMessage("not_init"),g()}else o()}else o()};'],{type:"text/javascript"}))),this.worker.onerror=n=>{this._debug("webworker_error",n)},this.worker.onmessage=({data:n})=>{this.handleWorkerMsg(n)};const e=()=>{this.worker&&this.worker.postMessage(null)};this.attachEventListener(window,"beforeunload",e,!1),this.attachEventListener(document.body,"mouseleave",e,!1,!1),this.attachEventListener(document,"visibilitychange",e,!1)}catch(e){this._debug("worker_start",e)}}handleWorkerMsg(e){var n;if(e==="a_stop")this.stop(!1);else if(e==="a_start")this.start({},!0);else if(e==="not_init")this.debug.warn("OR WebWorker: writer not initialised. Restarting tracker");else if(e.type==="failure")this.stop(!1),this.debug.error("worker_failed",e.reason),this._debug("worker_failed",e.reason);else if(e.type==="compress"){const s=e.batch;s.byteLength>this.compressionThreshold?Ki(e.batch,{mtime:0},(r,o)=>{var l,a;r?(this.debug.error("Openreplay compression error:",r),(l=this.worker)==null||l.postMessage({type:"uncompressed",batch:s})):(a=this.worker)==null||a.postMessage({type:"compressed",batch:o})}):(n=this.worker)==null||n.postMessage({type:"uncompressed",batch:s})}else e.type==="queue_empty"&&this.onSessionSent()}_debug(e,n){this.options.__debug_report_edp!==null&&fetch(this.options.__debug_report_edp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({context:e,error:`${n}`})}),this.debug.error("OpenReplay error: ",e,n)}send(e,n=!1){var s;this.activityState!==Z.NotActive&&(this.activityState===Z.ColdStart?(this.bufferedMessages1.push(e),this.singleBuffer||this.bufferedMessages2.push(e),(s=this.conditionsManager)==null||s.processMessage(e)):this.messages.push(e),this.activityState===Z.Active&&n&&this.commit())}_nCommit(){if(this.socketMode){this.messages.unshift(De(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),this.commitCallbacks.forEach(e=>e(this.messages)),this.messages.length=0;return}if(!(this.worker===void 0||!this.messages.length)){if(this.insideIframe){window.parent.postMessage({line:le.iframeBatch,messages:this.messages,domain:this.initialHostName},"*"),this.commitCallbacks.forEach(e=>e(this.messages)),this.messages.length=0;return}try{cr(()=>{var e;this.messages.unshift(De(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),(e=this.worker)==null||e.postMessage(this.messages),this.commitCallbacks.forEach(n=>n(this.messages)),this.messages.length=0})}catch(e){this._debug("worker_commit",e),this.stop(!0),setTimeout(()=>{this.start()},500)}}}_cStartCommit(){this.coldStartCommitN+=1,this.coldStartCommitN===2&&(this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId())),this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(De(this.session.getTabId())),this.coldStartCommitN=0)}commit(){this.activityState===Z.ColdStart?this._cStartCommit():this._nCommit()}postToWorker(e){var n;(n=this.worker)==null||n.postMessage(e),this.commitCallbacks.forEach(s=>s(e)),e.length=0}timestamp(){return pe()+this.delay}safe(e){const n=this;return function(...s){try{e.apply(this,s)}catch(i){n._debug("safe_fn_call",i)}}}attachCommitCallback(e){this.commitCallbacks.push(e)}attachStartCallback(e,n=!1){n&&(e=this.safe(e)),this.startCallbacks.push(e)}attachStopCallback(e,n=!1){n&&(e=this.safe(e)),this.stopCallbacks.push(e)}attachEventListener(e,n,s,i=!0,r=!0){i&&(s=this.safe(s));const o=()=>e?vs(e,n,s,r):null,l=()=>e?ws(e,n,s,r):null;this.attachStartCallback(o,i),this.attachStopCallback(l,i)}checkRequiredVersion(e){const n=e.split(/[.-]/),s=this.version.split(/[.-]/);for(let i=0;i<3;i++){if(isNaN(Number(s[i]))||isNaN(Number(n[i])))return!1;if(Number(s[i])>Number(n[i]))return!0;if(Number(s[i])<Number(n[i]))return!1}return!0}getTrackerInfo(){return{userUUID:this.localStorage.getItem(this.options.local_uuid_key),projectKey:this.projectKey,revID:this.revID,trackerVersion:this.version,isSnippet:this.options.__is_snippet}}getSessionInfo(){return{...this.session.getInfo(),...this.getTrackerInfo()}}getSessionToken(){return this.session.getSessionToken()}getSessionID(){return this.session.getInfo().sessionID||void 0}getSessionURL(e){const{projectID:n,sessionID:s,timestamp:i}=this.session.getInfo();if(!n||!s){this.debug.error("OpenReplay error: Unable to build session URL");return}const r=this.options.ingestPoint,a=(/api\.openreplay\.com/.test(r)?"https://app.openreplay.com/ingest":r).replace(/ingest$/,`${n}/session/${s}`);if(e!=null&&e.withCurrentTime){const d=pe()-i;return`${a}?jumpto=${d}`}return a}getHost(){return new URL(this.options.ingestPoint).host}getProjectKey(){return this.projectKey}getBaseHref(){var e,n;return typeof this.options.resourceBaseHref=="string"?this.options.resourceBaseHref:(this.options.resourceBaseHref,document.baseURI?document.baseURI:((n=(e=document.head)==null?void 0:e.getElementsByTagName("base")[0])==null?void 0:n.getAttribute("href"))||location.origin+location.pathname)}resolveResourceURL(e){const n=new URL(this.getBaseHref());return n.pathname+="/"+new URL(e).pathname,n.pathname.replace(/\/+/g,"/"),n.toString()}isServiceURL(e){return e.startsWith(this.options.ingestPoint)}active(){return this.activityState===Z.Active}resetNextPageSession(e){e?this.sessionStorage.setItem(this.options.session_reset_key,"t"):this.sessionStorage.removeItem(this.options.session_reset_key)}checkSessionToken(e){const n=this.sessionStorage.getItem(this.options.session_reset_key)!==null,s=e||n,i=this.session.getSessionToken();return s||!i}async coldStart(e={},n){this.singleBuffer=!1;const s=1e3,i=this.checkSessionToken(e.forceNew);n&&await this.setupConditionalStart(e);const r=()=>{this.orderNumber+=1,qt(),this.coldStartTs=pe(),this.orderNumber%2===0?(this.bufferedMessages1.length=0,this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId()))):(this.bufferedMessages2.length=0,this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(De(this.session.getTabId()))),this.stop(!1),this.activityState=Z.ColdStart,e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata}),i||(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(bt(this.session.getTabId()))),this.observer.observe(),this.ticker.start()};this.coldInterval=setInterval(()=>{r()},30*s),r()}async setupConditionalStart(e){var p,y;this.conditionsManager=new Qi(this,e);const n=await fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:pe(),doNotRecord:!0,bufferDiff:0,userID:this.session.getInfo().userID,token:void 0,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn(),width:window.screen.width,height:window.screen.height})}),{token:s,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d,projectID:c}=await n.json();this.session.assign({projectID:c}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d});const u={sessionToken:s,userUUID:"",sessionID:""};this.startCallbacks.forEach(S=>S(u)),await((p=this.conditionsManager)==null?void 0:p.fetchConditions(c,s)),await this.featureFlags.reloadFlags(s),await this.tagWatcher.fetchTags(this.options.ingestPoint,s),(y=this.conditionsManager)==null||y.processFlags(this.featureFlags.flags)}offlineRecording(e={},n){this.onSessionSent=n,this.singleBuffer=!0;const s=this.checkSessionToken(e.forceNew);qt(),this.coldStartTs=pe();const i=this.localStorage.getItem(dn);if(i){const o=JSON.parse(i);this.bufferedMessages1=Array.isArray(o)?o:this.bufferedMessages1,this.localStorage.removeItem(dn)}this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId())),this.activityState=Z.ColdStart,e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata});const r={sessionToken:"",userUUID:"",sessionID:""};return this.startCallbacks.forEach(o=>o(r)),s||this.send(bt(this.session.getTabId())),this.observer.observe(),this.ticker.start(),{saveBuffer:this.saveBuffer,getBuffer:this.getBuffer,setBuffer:this.setBuffer}}saveBuffer(){this.localStorage.setItem(dn,JSON.stringify(this.bufferedMessages1))}getBuffer(){return this.bufferedMessages1}setBuffer(e){this.bufferedMessages1=e}async uploadOfflineRecording(){var p,y;this.stop(!1);const e=pe();(p=this.worker)==null||p.postMessage({type:"start",pageNo:this.session.incPageNo(),ingestPoint:this.options.ingestPoint,timestamp:this.coldStartTs,url:document.URL,connAttemptCount:this.options.connAttemptCount,connAttemptGap:this.options.connAttemptGap,tabId:this.session.getTabId()});const n=await fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:e,doNotRecord:!1,bufferDiff:e-this.coldStartTs,userID:this.session.getInfo().userID,token:void 0,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn()})}),{token:s,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d,beaconSizeLimit:c,projectID:u}=await n.json();for((y=this.worker)==null||y.postMessage({type:"auth",token:s,beaconSizeLimit:c}),this.session.assign({projectID:u}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d});this.bufferedMessages1.length>0;)await this.flushBuffer(this.bufferedMessages1);this.postToWorker([["q_end"]]),this.clearBuffers()}async _start(e={},n=!1,s){const i=this.activityState===Z.ColdStart;if(i&&this.coldInterval&&clearInterval(this.coldInterval),!this.worker){const a="No worker found: perhaps, CSP is not set.";return this.signalError(a,[]),Promise.resolve(_e(a))}if(this.activityState===Z.Active||this.activityState===Z.Starting)return Promise.resolve(_e("OpenReplay: trying to call `start()` on the instance that has been started already."));this.activityState=Z.Starting,i||qt(),e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata});const r=pe();this.worker.postMessage({type:"start",pageNo:this.session.incPageNo(),ingestPoint:this.options.ingestPoint,timestamp:i?this.coldStartTs:r,url:document.URL,connAttemptCount:this.options.connAttemptCount,connAttemptGap:this.options.connAttemptGap,tabId:this.session.getTabId()});const o=this.session.getSessionToken(),l=this.checkSessionToken(e.forceNew);this.sessionStorage.removeItem(this.options.session_reset_key),this.debug.log("OpenReplay: starting session; need new session id?",l,"session token: ",o);try{const a=await window.fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:r,doNotRecord:!1,bufferDiff:r-this.coldStartTs,userID:this.session.getInfo().userID,token:l?void 0:o,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn(),condition:s,assistOnly:e.assistOnly??this.socketMode,width:window.screen.width,height:window.screen.height})});if(a.status!==200){const C=await a.text(),F=C===Ye?Ye:`Server error: ${a.status}. ${C}`;return _e(F)}if(!this.worker){const C="no worker found after start request (this should not happen in real world)";return this.signalError(C,[]),_e(C)}const{token:d,userUUID:c,projectID:u,beaconSizeLimit:p,compressionThreshold:y,delay:S,sessionID:v,startTimestamp:T,userBrowser:A,userCity:B,userCountry:D,userDevice:k,userOS:N,userState:O,canvasEnabled:L,canvasQuality:I,canvasFPS:E,assistOnly:P}=await a.json();if(typeof d!="string"||typeof c!="string"||typeof T!="number"&&typeof T<"u"||typeof v!="string"||typeof S!="number"||typeof p!="number"&&typeof p<"u"){const C=`Incorrect server response: ${JSON.stringify(a)}`;return this.signalError(C,[]),_e(C)}this.delay=S,this.session.setSessionToken(d),this.session.setUserInfo({userBrowser:A,userCity:B,userCountry:D,userDevice:k,userOS:N,userState:O}),this.session.assign({sessionID:v,timestamp:T||r,projectID:u}),P?(this.socketMode=!0,this.worker.postMessage("stop")):this.worker.postMessage({type:"auth",token:d,beaconSizeLimit:p}),!l&&d===o&&(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(bt(this.session.getTabId()))),Object.entries(this.session.getInfo().metadata).forEach(([C,F])=>this.send(ks(C,F))),this.localStorage.setItem(this.options.local_uuid_key,c),this.compressionThreshold=y;const V={sessionToken:d,userUUID:c,sessionID:v};if(this.startCallbacks.forEach(C=>C(V)),this.featureFlags.reloadFlags(),await this.tagWatcher.fetchTags(this.options.ingestPoint,d),this.activityState=Z.Active,L&&!this.options.canvas.disableCanvas&&(this.canvasRecorder=this.canvasRecorder??new po(this,{fps:E,quality:I,isDebug:this.options.canvas.__save_canvas_locally,fixedScaling:this.options.canvas.fixedCanvasScaling,useAnimationFrame:this.options.canvas.useAnimationFrame}),this.canvasRecorder.startTracking()),i){const C=this.bufferedMessages1.length>this.bufferedMessages2.length?this.bufferedMessages1:this.bufferedMessages2;for(;C.length>0;)await this.flushBuffer(C);this.clearBuffers(),this.commit()}else this.insideIframe&&this.rootId?this.observer.crossdomainObserve(this.rootId,this.frameOderNumber):this.observer.observe(),this.ticker.start();this.uxtManager=this.uxtManager?this.uxtManager:new uo(this,qs);let j;const q=this.localStorage.getItem(qs);if(q&&(j=parseInt(q,10)),location!=null&&location.search){const C=new URLSearchParams(location.search);if(C.has("oruxt")){const F=C.get("oruxt");j=F?parseInt(F,10):void 0}}return j&&(this.uxtManager.isActive?this.onUxtCb.forEach(C=>C(j)):this.uxtManager.getTest(j,d,!!q).then(C=>{C&&this.onUxtCb.forEach(F=>F(C))})),Co(V)}catch(a){if(this.stop(),this.session.reset(),a===Ye)return this.signalError(Ye,[]),_e(Ye);this._debug("session_start",a);const d=a instanceof Error?a.message:a.toString();return this.signalError(d,[]),_e(d)}}addOnUxtCb(e){this.onUxtCb.push(e)}getUxtId(){var e;return(e=this.uxtManager)==null?void 0:e.getTestId()}async waitStart(){return new Promise(e=>{const n=()=>{this.canStart?e(!0):setTimeout(n,25)};n()})}async waitStarted(){return new Promise(e=>{const n=()=>{this.activityState===Z.Active?e(!0):setTimeout(n,25)};n()})}async start(...e){return this.activityState===Z.Active||this.activityState===Z.Starting?Promise.resolve(_e("OpenReplay: trying to call `start()` on the instance that has been started already.")):document.hidden?new Promise(n=>{const s=async()=>{document.hidden||(await this.waitStart(),document.removeEventListener("visibilitychange",s),n(this._start(...e)))};document.addEventListener("visibilitychange",s)}):(await this.waitStart(),this._start(...e))}forceFlushBatch(){var e;(e=this.worker)==null||e.postMessage("forceFlushBatch")}getTabId(){return this.session.getTabId()}clearBuffers(){this.bufferedMessages1.length=0,this.bufferedMessages2.length=0}trackWs(e){const n=e;return(s,i,r="down")=>{typeof s!="string"||typeof i!="string"||i.length>5*1024*1024||s.length>255||this.send(Fr("websocket",n,i,this.timestamp(),r,s))}}stop(e=!0){var n;if(this.activityState!==Z.NotActive)try{this.attributeSender.clear(),this.sanitizer.clear(),this.observer.disconnect(),this.nodes.clear(),this.ticker.stop(),this.stopCallbacks.forEach(s=>s()),this.debug.log("OpenReplay tracking stopped."),this.tagWatcher.clear(),this.worker&&e&&this.worker.postMessage("stop"),(n=this.canvasRecorder)==null||n.clear()}finally{this.activityState=Z.NotActive}}};function Oo(t){const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e===void 0)return;const n=()=>t.send(_r(Math.round(e.downlink*1e3),e.type||"unknown"));n(),e.addEventListener("change",n)}const Gs=be&&"InstallTrigger"in window?t=>t.message+`
|
|
657
|
-
`+t.stack:t=>t.stack||t.message;function un(t){return t===void 0?"undefined":t===null?"null":t instanceof Error?
|
|
658
|
-
`).filter(function(c){return!!c.match(r)},this);return d.map(function(c){c.indexOf("(eval ")>-1&&(c=c.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var u=c.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=u.match(/ (\(.+\)$)/);u=p?u.replace(p[0],""):u;var y=this.extractLocation(p?p[1]:u),S=p&&u||void 0,v=["eval","<anonymous>"].indexOf(y[0])>-1?void 0:y[0];return new
|
|
659
|
-
`).filter(function(c){return!c.match(o)},this);return d.map(function(c){if(c.indexOf(" > eval")>-1&&(c=c.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),c.indexOf("@")===-1&&c.indexOf(":")===-1)return new
|
|
656
|
+
We appreciate your time and valuable input.`),r=z("div","end_button_or",Li,"Submitting Feedback"),o=co();r.appendChild(o),(d=this.test)!=null&&d.reqMic||(c=this.test)!=null&&c.reqCamera?this.userRecorder.sendToAPI().then(()=>{r.removeChild(o),r.textContent="End Session",e=!1}).catch(u=>{console.error(u),r.removeChild(o),r.textContent="End Session",e=!1}):(r.removeChild(o),r.textContent="End Session",e=!1),this.taskSection&&this.container.removeChild(this.taskSection),this.descriptionSection&&this.container.removeChild(this.descriptionSection),this.stopButton&&this.stopButtonContainer&&this.container.removeChild(this.stopButtonContainer),r.onclick=()=>{e||(window.close(),document.body.removeChild(this.bg))},n.append(i,s,r),this.endSection=n,this.container.append(n)}}function Ui(t){return!!t&&t.nodeType!=null}function sn(t){return t.namespaceURI==="http://www.w3.org/2000/svg"}function ke(t){return t.nodeType===Node.ELEMENT_NODE}function fo(t){return t.nodeType===Node.COMMENT_NODE}function rn(t){return t.nodeType===Node.TEXT_NODE}function wt(t){return t.nodeType===Node.DOCUMENT_NODE}function St(t){return t.nodeType===Node.DOCUMENT_NODE||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Q(t,e){return t.localName===e}class po{constructor(e,n){this.app=e,this.options=n,this.snapshots={},this.intervals=[],this.restartTracking=()=>{this.clear(),this.app.nodes.scanTree(this.captureCanvas)},this.captureCanvas=i=>{const s=this.app.nodes.getID(i);if(!s||!Q(i,"canvas")||this.app.sanitizer.isObscured(s)||this.app.sanitizer.isHidden(s)||!Q(i,"canvas")||this.snapshots[s])return;new IntersectionObserver(l=>{l.forEach(a=>{a.isIntersecting&&(a.target?this.snapshots[s]&&this.snapshots[s].createdAt?this.snapshots[s].paused=!1:this.recordCanvas(a.target,s):this.snapshots[s]&&(this.snapshots[s].paused=!0))})}).observe(i)},this.recordCanvas=(i,s)=>{const r=this.app.timestamp();this.snapshots[s]={images:[],createdAt:r,paused:!1,dummy:document.createElement("canvas")};const o=jr(s.toString(),r);this.app.send(o);const l=d=>{go(d,this.options.quality,this.snapshots[s].dummy,this.options.fixedScaling,this.fileExt,c=>{c&&(this.snapshots[s].images.push({id:this.app.timestamp(),data:c}),this.snapshots[s].images.length>9&&(this.sendSnaps(this.snapshots[s].images,s,this.snapshots[s].createdAt),this.snapshots[s].images=[]))})},a=setInterval(()=>{const d=this.app.nodes.getID(i),c=d?this.app.nodes.getNode(d):void 0;!c||!Q(c,"canvas")||c!==i?(this.app.debug.log("Canvas element not in sync"),clearInterval(a)):this.snapshots[s].paused||(this.options.useAnimationFrame?requestAnimationFrame(()=>{l(c)}):l(c))},this.interval);this.intervals.push(a)},this.fileExt=n.fileExt??"webp",this.interval=1e3/n.fps}startTracking(){setTimeout(()=>{this.app.nodes.scanTree(this.captureCanvas),this.app.nodes.attachNodeCallback(e=>{this.captureCanvas(e)})},500)}sendSnaps(e,n,i){if(Object.keys(this.snapshots).length===0)return;const s=new FormData;e.forEach(r=>{const o=r.data;o&&(s.append("snapshot",o,`${i}_${n}_${r.id}.${this.fileExt}`),this.options.isDebug&&mo(o,`${i}_${n}_${r.id}.${this.fileExt}`))}),fetch(this.app.options.ingestPoint+"/v1/web/images",{method:"POST",headers:{Authorization:`Bearer ${this.app.session.getSessionToken()??""}`},body:s}).then(()=>!0).catch(r=>{this.app.debug.error("error saving canvas",r)})}clear(){this.intervals.forEach(e=>clearInterval(e)),this.snapshots={}}}const Hi={low:.35,medium:.55,high:.8};function go(t,e="medium",n,i=!1,s,r){const o=`image/${s}`;if(i){const l=window.devicePixelRatio||1;n.width=t.width/l,n.height=t.height/l;const a=n.getContext("2d");if(!a)return"";a.clearRect(0,0,n.width,n.height),a.drawImage(t,0,0,n.width,n.height),n.toBlob(r,o,Hi[e])}else t.toBlob(r,o,Hi[e])}function mo(t,e){const n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const Je={Verbose:5,Log:4,Warnings:3,Errors:2,Silent:0};class bo{constructor(e=Je.Silent){this.shouldLog=n=>this.level>=n,this.log=(...n)=>{this.shouldLog(Je.Log)&&console.log(...n)},this.warn=(...n)=>{this.shouldLog(Je.Warnings)&&console.warn(...n)},this.error=(...n)=>{this.shouldLog(Je.Errors)&&console.error(...n)},this.level=e}}class yo{constructor(e){this.node_id=e,this.nodes=[],this.totalNodeAmount=0,this.nodeCallbacks=[],this.elementListeners=new Map,this.nextNodeId=0,this.scanTree=n=>{this.nodes.forEach(i=>n(i))}}syntheticMode(e){const s=99999999*e;if(s>9007199254740900)throw new Error("Placeholder id overflow");this.nextNodeId=s}attachNodeCallback(e){this.nodeCallbacks.push(e)}attachNodeListener(e,n,i,s=!0){const r=this.getID(e);if(r===void 0)return;vi(e,n,i,s);let o=this.elementListeners.get(r);o===void 0&&(o=[],this.elementListeners.set(r,o)),o.push([n,i,s])}registerNode(e){let n=e[this.node_id];const i=n===void 0;return i&&(n=this.nextNodeId,this.totalNodeAmount++,this.nextNodeId++,this.nodes[n]=e,e[this.node_id]=n),[n,i]}unregisterNode(e){const n=e[this.node_id];if(n!==void 0){e[this.node_id]=void 0,delete e[this.node_id],delete this.nodes[n];const i=this.elementListeners.get(n);i!==void 0&&(this.elementListeners.delete(n),i.forEach(s=>wi(e,s[0],s[1],s[2]))),this.totalNodeAmount--}return n}cleanTree(){for(let e=0;e<this.nodes.length;e++){const n=this.nodes[e];n&&!document.contains(n)&&this.unregisterNode(n)}}callNodeCallbacks(e,n){this.nodeCallbacks.forEach(i=>i(e,n))}getID(e){if(e)return e[this.node_id]}getNode(e){return this.nodes[e]}getNodeCount(){return this.totalNodeAmount}clear(){for(let e=0;e<this.nodes.length;e++){const n=this.nodes[e];n&&this.unregisterNode(n)}this.nextNodeId=0,this.nodes.length=0}}function on(t){if(fo(t))return!0;if(rn(t))return!1;if(!ke(t))return!0;const e=t.tagName.toUpperCase();if(e==="LINK"){const n=t.getAttribute("rel"),i=t.getAttribute("as");return!(n!=null&&n.includes("stylesheet")||i==="style"||i==="font")}return e==="SCRIPT"||e==="NOSCRIPT"||e==="META"||e==="TITLE"||e==="BASE"}function an(t){return St(t)?!0:!on(t)}var ye;(function(t){t[t.New=0]="New",t[t.Removed=1]="Removed",t[t.Changed=2]="Changed"})(ye||(ye={}));class cn{constructor(e,n=!1){this.app=e,this.isTopContext=n,this.commited=[],this.recents=new Map,this.indexes=[],this.attributesMap=new Map,this.textSet=new Set,this.observer=yi(this.app.safe(i=>{for(const s of i){const r=s.target,o=s.type;if(!an(r))continue;if(o==="childList"){for(let a=0;a<s.removedNodes.length;a++)an(s.removedNodes[a])&&this.bindNode(s.removedNodes[a]);for(let a=0;a<s.addedNodes.length;a++)this.bindTree(s.addedNodes[a]);continue}const l=this.app.nodes.getID(r);if(l!==void 0){if(this.recents.has(l)||this.recents.set(l,ye.Changed),o==="attributes"){const a=s.attributeName;if(a===null)continue;let d=this.attributesMap.get(l);d===void 0&&this.attributesMap.set(l,d=new Set),d.add(a);continue}if(o==="characterData"){this.textSet.add(l);continue}}}this.commitNodes()}))}clear(){this.commited.length=0,this.recents.clear(),this.indexes.length=1,this.attributesMap.clear(),this.textSet.clear()}sendNodeAttribute(e,n,i,s){if(sn(n)){i.substr(0,6)==="xlink:"&&(i=i.substr(6)),s===null?this.app.send(xi(e,i)):i==="href"?(s.length>1e5&&(s=""),this.app.send(Kt(e,i,s,this.app.getBaseHref()))):this.app.attributeSender.sendSetAttribute(e,i,s);return}if(!(i==="src"||i==="srcset"||i==="integrity"||i==="crossorigin"||i==="autocomplete"||i.substr(0,2)==="on")&&!(i==="value"&&Q(n,"input")&&n.type!=="button"&&n.type!=="reset"&&n.type!=="submit")){if(s===null){this.app.send(xi(e,i));return}if(i==="style"||i==="href"&&Q(n,"link")){this.app.send(Kt(e,i,s,this.app.getBaseHref()));return}(i==="href"||s.length>1e5)&&(s=""),this.app.attributeSender.sendSetAttribute(e,i,s)}}sendNodeData(e,n,i){if(Q(n,"style")){this.app.send(Or(e,i,this.app.getBaseHref()));return}i=this.app.sanitizer.sanitize(e,i),this.app.send(mr(e,i))}bindNode(e){const[n,i]=this.app.nodes.registerNode(e);i?this.recents.set(n,ye.New):this.recents.get(n)!==ye.New&&this.recents.set(n,ye.Removed)}bindTree(e){if(!an(e))return;this.bindNode(e);const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:i=>(this.app.nodes.getID(i)!==void 0&&this.app.debug.error("! Node is already bound",i),on(i)||this.app.nodes.getID(i)!==void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT)},!1);for(;n.nextNode();)this.bindNode(n.currentNode)}unbindTree(e){const n=this.app.nodes.unregisterNode(e);if(n!==void 0&&this.recents.get(n)===ye.Removed){this.app.send(gr(n));const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:l=>on(l)||this.app.nodes.getID(l)===void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},!1);let s=0;const r=this.app.nodes.getNodeCount();for(;i.nextNode();)s+=1,this.app.nodes.unregisterNode(i.currentNode);const o=Math.floor(s/r*100);o>30&&this.app.send(Br(o))}}_commitNode(e,n){if(St(n))return!0;const i=n.parentNode;let s;if(!Q(n,"html")||!this.isTopContext){if(i===null)return this.unbindTree(n),!1;if(s=this.app.nodes.getID(i),s===void 0)return this.unbindTree(n),!1;if(!this.commitNode(s))return this.unbindTree(n),!1;if(this.app.sanitizer.handleNode(e,s,n),this.app.sanitizer.isHidden(s))return!1}let r=n.previousSibling;for(;r!==null;){const c=this.app.nodes.getID(r);if(c!==void 0){this.commitNode(c),this.indexes[e]=this.indexes[c]+1;break}r=r.previousSibling}r===null&&(this.indexes[e]=0);const o=this.recents.get(e),l=o===ye.New,a=this.indexes[e];if(a===void 0)throw"commitNode: missing node index";if(l){if(ke(n)){let c=n;if(s!==void 0){if(this.app.sanitizer.isHidden(e)){const u=c.clientWidth,p=c.clientHeight;c=n.cloneNode(),c.style.width=`${u}px`,c.style.height=`${p}px`}this.app.send(ur(e,s,a,c.tagName,sn(n)))}for(let u=0;u<c.attributes.length;u++){const p=c.attributes[u];this.sendNodeAttribute(e,c,p.nodeName,p.value)}}else rn(n)&&(this.app.send(fr(e,s,a)),this.sendNodeData(e,i,n.data));return!0}o===ye.Removed&&s!==void 0&&this.app.send(pr(e,s,a));const d=this.attributesMap.get(e);if(d!==void 0){if(!ke(n))throw"commitNode: node is not an element";for(const c of d)this.sendNodeAttribute(e,n,c,n.getAttribute(c))}if(this.textSet.has(e)){if(!rn(n))throw"commitNode: node is not a text";this.sendNodeData(e,i,n.data)}return!0}commitNode(e){const n=this.app.nodes.getNode(e);if(n===void 0)return!1;const i=this.commited[e];return i!==void 0?i:this.commited[e]=this._commitNode(e,n)}commitNodes(e=!1){let n;this.recents.forEach((i,s)=>{this.commitNode(s),i===ye.New&&(n=this.app.nodes.getNode(s))&&this.app.nodes.callNodeCallbacks(n,e)}),this.clear()}observeRoot(e,n,i=e){this.observer.observe(e,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!1,characterDataOldValue:!1}),this.bindTree(i),n(this.app.nodes.getID(e)),this.commitNodes(!0)}disconnect(){this.observer.disconnect(),this.clear()}}class $i extends cn{observe(e){const n=e.contentDocument,i=this.app.nodes.getID(e);!n||i===void 0||this.observeRoot(n,s=>{if(s===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(i,s))})}syntheticObserve(e,n){this.observeRoot(n,i=>{if(i===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(e,i))})}}class vo extends cn{observe(e){const n=e.shadowRoot,i=this.app.nodes.getID(e);!n||i===void 0||this.observeRoot(n,s=>{if(s===void 0){this.app.debug.error("OpenReplay: Shadow Root was not bound");return}this.app.send(Xt(i,s))})}}class wo{constructor(){this.states=new Map}calcOffset(e){let n=0,i=0;if(e.parent&&([n,i]=this.calcOffset(e.parent)),!e.offset){const{left:o,top:l}=e.iFrame.getBoundingClientRect();e.offset=[o,l]}const[s,r]=e.offset;return[n+s,i+r]}getDocumentOffset(e){const n=this.states.get(e);return n?this.calcOffset(n):[0,0]}observe(e){var l;const n=e.contentDocument;if(!n)return;const i=e.ownerDocument,s=this.states.get(i),r={offset:null,iFrame:e,parent:s||null,clear:()=>{var a;i.removeEventListener("scroll",o),(a=i.defaultView)==null||a.removeEventListener("resize",o)}},o=()=>{r.offset=null};i.addEventListener("scroll",o),(l=i.defaultView)==null||l.addEventListener("resize",o),this.states.set(n,r)}clear(){this.states.forEach(e=>e.clear()),this.states.clear()}}const ln=be?Element.prototype.attachShadow:()=>new ShadowRoot;class So extends cn{constructor(e,n){super(e,!0),this.iframeOffsets=new wo,this.contextCallbacks=[],this.contextsSet=new Set,this.iframeObservers=[],this.shadowRootObservers=[],this.options=Object.assign({captureIFrames:!0},n),this.app.nodes.attachNodeCallback(i=>{Q(i,"iframe")&&(this.options.captureIFrames&&!Re(i,"obscured")||Re(i,"capture"))&&this.handleIframe(i)}),this.app.nodes.attachNodeCallback(i=>{ke(i)&&i.shadowRoot!==null&&this.handleShadowRoot(i.shadowRoot)})}attachContextCallback(e){this.contextCallbacks.push(e)}getDocumentOffset(e){return this.iframeOffsets.getDocumentOffset(e)}handleIframe(e){let n=null;const i=this.app.safe(()=>setTimeout(()=>{if(this.app.nodes.getID(e)===void 0||!ir(e))return;const r=e.contentWindow,o=e.contentDocument;if(o&&o!==n){const l=new $i(this.app);this.iframeObservers.push(l),l.observe(e),n=o,this.iframeOffsets.observe(e)}r&&r===r.window&&!this.contextsSet.has(r)&&(this.contextsSet.add(r),this.contextCallbacks.forEach(l=>l(r)))},100));e.addEventListener("load",i),i()}handleShadowRoot(e){const n=new vo(this.app);this.shadowRootObservers.push(n),n.observe(e.host)}observe(){const e=this;Element.prototype.attachShadow=function(){const n=ln.apply(this,arguments);return e.handleShadowRoot(n),n},this.app.nodes.clear(),this.observeRoot(window.document,()=>{this.app.send(hr()),this.app.nodes.callNodeCallbacks(document,!0)},window.document.documentElement)}crossdomainObserve(e,n){const i=this;Element.prototype.attachShadow=function(){const r=ln.apply(this,arguments);return i.handleShadowRoot(r),r},this.app.nodes.clear(),this.app.nodes.syntheticMode(n);const s=new $i(this.app);this.iframeObservers.push(s),s.syntheticObserve(e,window.document)}disconnect(){this.iframeOffsets.clear(),Element.prototype.attachShadow=ln,this.iframeObservers.forEach(e=>e.disconnect()),this.iframeObservers=[],this.shadowRootObservers.forEach(e=>e.disconnect()),this.shadowRootObservers=[],super.disconnect()}}var xt;(function(t){t[t.Plain=0]="Plain",t[t.Obscured=1]="Obscured",t[t.Hidden=2]="Hidden"})(xt||(xt={}));const xo=t=>t.trim().replace(/[^\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/g,"█");class ko{constructor(e,n){this.app=e,this.obscured=new Set,this.hidden=new Set,this.options=Object.assign({obscureTextEmails:!0,obscureTextNumbers:!1},n)}handleNode(e,n,i){if((this.obscured.has(n)||ke(i)&&(Re(i,"masked")||Re(i,"obscured")))&&this.obscured.add(e),(this.hidden.has(n)||ke(i)&&(Re(i,"htmlmasked")||Re(i,"hidden")))&&this.hidden.add(e),this.options.domSanitizer!==void 0&&ke(i)){const s=this.options.domSanitizer(i);s===xt.Obscured&&this.obscured.add(e),s===xt.Hidden&&this.hidden.add(e)}}sanitize(e,n){return this.obscured.has(e)?xo(n):(this.options.obscureTextNumbers&&(n=n.replace(/\d/g,"0")),this.options.obscureTextEmails&&(n=n.replace(/^\w+([+.-]\w+)*@\w+([.-]\w+)*\.\w{2,3}$/g,i=>{const[s,r]=i.split("@"),[o,l]=r.split(".");return`${Wt(s)}@${Wt(o)}.${Wt(l)}`})),n)}isObscured(e){return this.obscured.has(e)}isHidden(e){return this.hidden.has(e)}getInnerTextSecure(e){const n=this.app.nodes.getID(e);return n?this.sanitize(n,e.innerText):""}clear(){this.obscured.clear(),this.hidden.clear()}}class To{constructor(e,n){this.app=e,this.options=n,this.metadata={},this.userID=null,this.callbacks=[],this.timestamp=0,this.createTabId()}attachUpdateCallback(e){this.callbacks.push(e)}handleUpdate(e){e.userID==null&&delete e.userID,e.sessionID==null&&delete e.sessionID,this.callbacks.forEach(n=>n(e))}assign(e){e.userID!==void 0&&(this.userID=e.userID),e.metadata!==void 0&&Object.entries(e.metadata).forEach(([n,i])=>this.metadata[n]=i),e.sessionID!==void 0&&(this.sessionID=e.sessionID),e.timestamp!==void 0&&(this.timestamp=e.timestamp),e.projectID!==void 0&&(this.projectID=e.projectID),this.handleUpdate(e)}setMetadata(e,n){this.metadata[e]=n,this.handleUpdate({metadata:{[e]:n}})}setUserID(e){this.userID=e,this.handleUpdate({userID:e})}setUserInfo(e){this.userInfo=e}getPageNumber(){const e=this.app.sessionStorage.getItem(this.options.session_pageno_key);if(e!=null)return parseInt(e)}incPageNo(){let e=this.getPageNumber();return e===void 0?e=0:e++,this.app.sessionStorage.setItem(this.options.session_pageno_key,e.toString()),e}getSessionToken(){return this.app.sessionStorage.getItem(this.options.session_token_key)||void 0}setSessionToken(e){this.app.sessionStorage.setItem(this.options.session_token_key,e)}applySessionHash(e){const n=decodeURI(e).split("&");let i=e,s="100500";n.length==2&&([s,i]=n),!(!s||!i)&&(this.app.sessionStorage.setItem(this.options.session_token_key,i),this.app.sessionStorage.setItem(this.options.session_pageno_key,s))}getSessionHash(){const e=this.getPageNumber(),n=this.getSessionToken();if(!(e===void 0||n===void 0))return encodeURI(String(e)+"&"+n)}getTabId(){return this.tabId||this.createTabId(),this.tabId}regenerateTabId(){const e=sr(12);this.app.sessionStorage.setItem(this.options.session_tabid_key,e),this.tabId=e}createTabId(){const e=this.app.sessionStorage.getItem(this.options.session_tabid_key);e?this.tabId=e:this.regenerateTabId()}getInfo(){return{sessionID:this.sessionID,metadata:this.metadata,userID:this.userID,timestamp:this.timestamp,projectID:this.projectID}}reset(){this.app.sessionStorage.removeItem(this.options.session_token_key),this.metadata={},this.userID=null,this.sessionID=void 0,this.timestamp=0}}function Eo(t,e){let n=0;return()=>{n++>=e&&(n=0,t())}}class Io{constructor(e){this.app=e,this.timer=null,this.callbacks=[]}attach(e,n=0,i=!0,s){s&&(e=e.bind(s)),i&&(e=this.app.safe(e)),this.callbacks.unshift(n?Eo(e,n):e)-1}start(){this.timer===null&&(this.timer=setInterval(()=>this.callbacks.forEach(e=>{e&&e()}),30))}stop(){this.timer!==null&&(clearInterval(this.timer),this.timer=null)}}const Ye="canceled",qi="or_uxt_active",dn="or_buffer_1",_e=t=>({reason:t,success:!1}),Co=t=>({...t,success:!0});var Z;(function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Active=2]="Active",t[t.ColdStart=3]="ColdStart"})(Z||(Z={}));const Wi="https://api.openreplay.com/ingest";function hn(){const t=new Date().getTimezoneOffset()*-1,e=t>=0?"+":"-",n=Math.floor(Math.abs(t)/60),i=Math.abs(t)%60;return`UTC${e}${String(n).padStart(2,"0")}:${String(i).padStart(2,"0")}`}const _o=t=>new Promise(e=>setTimeout(e,t)),le={ask:"never-gonna-give-you-up",resp:"never-gonna-let-you-down",reg:"never-gonna-run-around-and-desert-you",iframeSignal:"never-gonna-make-you-cry",iframeId:"never-gonna-say-goodbye",iframeBatch:"never-gonna-tell-a-lie-and-hurt-you"};let No=class{constructor(e,n,i,s,r){this.signalError=s,this.insideIframe=r,this.messages=[],this.bufferedMessages1=[],this.bufferedMessages2=[],this.startCallbacks=[],this.stopCallbacks=[],this.commitCallbacks=[],this.activityState=Z.NotActive,this.version="14.0.4",this.socketMode=!1,this.compressionThreshold=24*1e3,this.bc=null,this.canvasRecorder=null,this.conditionsManager=null,this.canStart=!1,this.rootId=null,this.pageFrames=[],this.frameOderNumber=0,this.initialHostName=location.hostname,this.startTimeout=null,this.coldStartCommitN=0,this.delay=0,this.coldInterval=null,this.orderNumber=0,this.coldStartTs=0,this.singleBuffer=!1,this.onSessionSent=()=>{},this.restartCanvasTracking=()=>{var a;(a=this.canvasRecorder)==null||a.restartTracking()},this.flushBuffer=async a=>new Promise(d=>{let c=!1;const u=[a.shift()];for(;!c;){const p=a[0];!p||p[0]===0?c=!0:u.push(a.shift())}this.postToWorker(u),d(null)}),this.onUxtCb=[],this.contextId=Math.random().toString(36).slice(2),this.projectKey=e,Object.keys(i).findIndex(a=>["fixedCanvasScaling","disableCanvas"].includes(a))!==-1&&(console.warn('Openreplay: canvas options are moving to separate key "canvas" in next update. Please update your configuration.'),i={...i,canvas:{__save_canvas_locally:i.__save_canvas_locally,fixedCanvasScaling:i.fixedCanvasScaling,disableCanvas:i.disableCanvas}}),this.networkOptions=i.network;const o={revID:"",node_id:"__openreplay_id",session_token_key:"__openreplay_token",session_pageno_key:"__openreplay_pageno",session_reset_key:"__openreplay_reset",session_tabid_key:"__openreplay_tabid",local_uuid_key:"__openreplay_uuid",ingestPoint:Wi,resourceBaseHref:null,__is_snippet:!1,__debug_report_edp:null,__debug__:Je.Silent,__save_canvas_locally:!1,localStorage:null,sessionStorage:null,disableStringDict:!1,forceSingleTab:!1,assistSocketHost:"",fixedCanvasScaling:!1,disableCanvas:!1,captureIFrames:!0,obscureTextEmails:!0,obscureTextNumbers:!1,crossdomain:{parentDomain:"*"},canvas:{disableCanvas:!1,fixedCanvasScaling:!1,__save_canvas_locally:!1,useAnimationFrame:!1}};if(this.options=Si(o,i),!this.insideIframe&&!this.options.forceSingleTab&&globalThis&&"BroadcastChannel"in globalThis){const a=location.hostname.split(".").slice(-2).join("_");this.bc=new BroadcastChannel(`rick_${a}`)}this.revID=this.options.revID,this.localStorage=this.options.localStorage??window.localStorage,this.sessionStorage=this.options.sessionStorage??window.sessionStorage,this.sanitizer=new ko(this,i),this.nodes=new yo(this.options.node_id),this.observer=new So(this,i),this.ticker=new Io(this),this.ticker.attach(()=>this.commit()),this.debug=new bo(this.options.__debug__),this.session=new To(this,this.options),this.attributeSender=new Ys(this,!!this.options.disableStringDict),this.featureFlags=new er(this),this.tagWatcher=new $r(this.sessionStorage,this.debug.error,a=>{this.send(zr(a))}),this.session.attachUpdateCallback(({userID:a,metadata:d})=>{a!=null&&this.send(Er(a)),d!=null&&Object.entries(d).forEach(([c,u])=>this.send(ki(c,u)))}),n!=null&&this.session.applySessionHash(n),this.initWorker();const l=this.session.getTabId();if(this.insideIframe){const a=c=>{const{data:u}=c;u.line===le.iframeId&&(this.rootId=u.id,this.session.setSessionToken(u.token),this.frameOderNumber=u.frameOrderNumber,this.debug.log("starting iframe tracking",u),this.allowAppStart())};window.addEventListener("message",a),this.attachStopCallback(()=>{window.removeEventListener("message",a)});const d=this.initialHostName;window.parent.postMessage({line:le.iframeSignal,source:l,context:this.contextId,domain:d},"*")}else{let a=0;const d=c=>{const{data:u}=c;if(u.line===le.iframeSignal){const p=u.domain,y=Array.from(document.querySelectorAll("iframe"));this.pageFrames=y,(async()=>{let v=0;for(;v<10;){const T=this.checkNodeId(y,p);if(T){this.waitStarted().then(()=>{var D;a++;const A=this.session.getSessionToken(),B={line:le.iframeId,context:this.contextId,domain:p,id:T,token:A,frameOrderNumber:a};this.debug.log("iframe_data",B),(D=c.source)==null||D.postMessage(B,"*")}).catch(console.error),v=10;break}v++,await _o(100)}})()}if(u.line===le.iframeBatch){const y=u.messages.map(S=>{if(S[0]===20){let v=S;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[A,B,D]=S,{left:k,top:N}=T.getBoundingClientRect();v=[A,B+k,D+N]}}),v}if(S[0]===68){let v=S;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[A,B,D,k,N,O,L]=S,{left:I,top:E,width:P,height:V}=T.getBoundingClientRect(),j=document.documentElement.scrollWidth,q=document.documentElement.scrollHeight,C=O/100*P+I,F=L/100*V+E,G=C/j,K=F/q;v=[A,B,D,k,N,Math.round(G*1e3)/10,Math.round(K*1e3)/10]}}),v}return S});this.messages.push(...y)}};window.addEventListener("message",d),this.attachStopCallback(()=>{window.removeEventListener("message",d)})}this.bc!==null&&(this.bc.postMessage({line:le.ask,source:l,context:this.contextId}),this.startTimeout=setTimeout(()=>{this.allowAppStart()},500),this.bc.onmessage=a=>{if(a.data.context!==this.contextId){if(a.data.line===le.resp){const d=a.data.token;this.session.setSessionToken(d),this.allowAppStart()}if(a.data.line===le.reg){const d=a.data.token;this.session.regenerateTabId(),this.session.setSessionToken(d),this.allowAppStart()}if(a.data.line===le.ask){const d=this.session.getSessionToken();d&&this.bc&&this.bc.postMessage({line:a.data.source===l?le.reg:le.resp,token:d,source:l,context:this.contextId})}}})}allowAppStart(){this.canStart=!0,this.startTimeout&&(clearTimeout(this.startTimeout),this.startTimeout=null)}checkNodeId(e,n){for(const i of e)if(i.dataset.domain===n)return i[this.options.node_id];return null}initWorker(){try{this.worker=new Worker(URL.createObjectURL(new Blob(['"use strict";class t{constructor(t,s,i,e=10,n=250,h,r){this.onUnauthorised=s,this.onFailure=i,this.MAX_ATTEMPTS_COUNT=e,this.ATTEMPT_TIMEOUT=n,this.onCompress=h,this.pageNo=r,this.attemptsCount=0,this.busy=!1,this.queue=[],this.token=null,this.lastBatchNum=0,this.ingestURL=t+"/v1/web/i",this.isCompressing=void 0!==h}getQueueStatus(){return 0===this.queue.length&&!this.busy}authorise(t){this.token=t,this.busy||this.sendNext()}push(t){if(this.busy||!this.token)this.queue.push(t);else if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}}sendNext(){const t=this.queue.shift();if(t)if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}else this.busy=!1}retry(t,s,i){this.attemptsCount>=this.MAX_ATTEMPTS_COUNT?this.onFailure(`Failed to send batch after ${this.attemptsCount} attempts.`):(this.attemptsCount++,setTimeout((()=>this.sendBatch(t,s,i)),this.ATTEMPT_TIMEOUT*this.attemptsCount))}sendBatch(t,s,i){const e=i?.toString().replace(/^([^_]+)_([^_]+).*/,"$1_$2_$3");this.busy=!0;const n={Authorization:`Bearer ${this.token}`};s&&(n["Content-Encoding"]="gzip"),null!==this.token?fetch(`${this.ingestURL}?batch=${this.pageNo??"noPageNum"}_${e??"noBatchNum"}`,{body:t,method:"POST",headers:n,keepalive:t.length<65536}).then((e=>{if(401===e.status)return this.busy=!1,void this.onUnauthorised();e.status>=400?this.retry(t,s,`${i??"noBatchNum"}_network:${e.status}`):(this.attemptsCount=0,this.sendNext())})).catch((e=>{console.warn("OpenReplay:",e),this.retry(t,s,`${i??"noBatchNum"}_reject:${e.message}`)})):setTimeout((()=>{this.sendBatch(t,s,`${i??"noBatchNum"}_newToken`)}),500)}sendCompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!0,s)}sendUncompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}clean(){this.sendNext(),setTimeout((()=>{this.token=null,this.queue.length=0}),10)}}const s="function"==typeof TextEncoder?new TextEncoder:{encode(t){const s=t.length,i=new Uint8Array(3*s);let e=-1;for(let n=0,h=0,r=0;r!==s;){if(n=t.charCodeAt(r),r+=1,n>=55296&&n<=56319){if(r===s){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;break}if(h=t.charCodeAt(r),!(h>=56320&&h<=57343)){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;continue}if(n=1024*(n-55296)+h-56320+65536,r+=1,n>65535){i[e+=1]=240|n>>>18,i[e+=1]=128|n>>>12&63,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n;continue}}n<=127?i[e+=1]=0|n:n<=2047?(i[e+=1]=192|n>>>6,i[e+=1]=128|63&n):(i[e+=1]=224|n>>>12,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n)}return i.subarray(0,e+1)}};class i{constructor(t){this.size=t,this.offset=0,this.checkpointOffset=0,this.data=new Uint8Array(t)}getCurrentOffset(){return this.offset}checkpoint(){this.checkpointOffset=this.offset}get isEmpty(){return 0===this.offset}skip(t){return this.offset+=t,this.offset<=this.size}set(t,s){this.data.set(t,s)}boolean(t){return this.data[this.offset++]=+t,this.offset<=this.size}uint(t){for((t<0||t>Number.MAX_SAFE_INTEGER)&&(t=0);t>=128;)this.data[this.offset++]=t%256|128,t=Math.floor(t/128);return this.data[this.offset++]=t,this.offset<=this.size}int(t){return t=Math.round(t),this.uint(t>=0?2*t:-2*t-1)}string(t){const i=s.encode(t),e=i.byteLength;return!(!this.uint(e)||this.offset+e>this.size)&&(this.data.set(i,this.offset),this.offset+=e,!0)}reset(){this.offset=0,this.checkpointOffset=0}flush(){const t=this.data.slice(0,this.checkpointOffset);return this.reset(),t}}class e extends i{encode(t){switch(t[0]){case 0:case 11:case 114:case 115:return this.uint(t[1]);case 4:case 44:case 47:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 5:case 20:case 38:case 70:case 75:case 76:case 77:case 82:return this.uint(t[1])&&this.uint(t[2]);case 6:return this.int(t[1])&&this.int(t[2]);case 7:return!0;case 8:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.string(t[4])&&this.boolean(t[5]);case 9:case 10:case 24:case 51:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 12:case 61:case 71:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 13:case 14:case 17:case 50:case 54:return this.uint(t[1])&&this.string(t[2]);case 16:return this.uint(t[1])&&this.int(t[2])&&this.int(t[3]);case 18:return this.uint(t[1])&&this.string(t[2])&&this.int(t[3]);case 19:return this.uint(t[1])&&this.boolean(t[2]);case 21:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8]);case 22:case 27:case 30:case 41:case 45:case 46:case 63:case 64:case 79:return this.string(t[1])&&this.string(t[2]);case 23:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 28:case 29:case 42:case 117:case 118:return this.string(t[1]);case 37:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3]);case 39:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7]);case 40:return this.string(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 48:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.int(t[5]);case 49:return this.int(t[1])&&this.int(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 53:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8]);case 55:return this.boolean(t[1]);case 57:case 60:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 58:case 120:return this.int(t[1]);case 59:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6])&&this.string(t[7]);case 67:case 73:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 68:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6]);case 69:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 78:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 81:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.int(t[4])&&this.string(t[5]);case 83:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 84:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6]);case 112:return this.uint(t[1])&&this.string(t[2])&&this.boolean(t[3])&&this.string(t[4])&&this.int(t[5])&&this.int(t[6]);case 113:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3]);case 116:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8])&&this.uint(t[9])&&this.boolean(t[10]);case 119:return this.string(t[1])&&this.uint(t[2]);case 121:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 122:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 123:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])}}}class n{constructor(t,s,i,n,h,r){this.pageNo=t,this.timestamp=s,this.url=i,this.onBatch=n,this.tabId=h,this.onOfflineEnd=r,this.nextIndex=0,this.beaconSize=2e5,this.encoder=new e(this.beaconSize),this.sizeBuffer=new Uint8Array(3),this.isEmpty=!0,this.beaconSizeLimit=1e6,this.prepare()}writeType(t){return this.encoder.uint(t[0])}writeFields(t){return this.encoder.encode(t)}writeSizeAt(t,s){for(let s=0;s<3;s++)this.sizeBuffer[s]=t>>8*s;this.encoder.set(this.sizeBuffer,s)}prepare(){if(!this.encoder.isEmpty)return;const t=[81,1,this.pageNo,this.nextIndex,this.timestamp,this.url],s=[118,this.tabId];this.writeType(t),this.writeFields(t),this.writeWithSize(s),this.isEmpty=!0}writeWithSize(t){const s=this.encoder;if(!this.writeType(t)||!s.skip(3))return!1;const i=s.getCurrentOffset(),e=this.writeFields(t);if(e){const e=s.getCurrentOffset()-i;if(e>16777215)return console.warn("OpenReplay: max message size overflow."),!1;this.writeSizeAt(e,i-3),s.checkpoint(),this.isEmpty=this.isEmpty&&0===t[0],this.nextIndex++}return e}setBeaconSizeLimit(t){this.beaconSizeLimit=t}writeMessage(t){if("q_end"===t[0])return this.finaliseBatch(),this.onOfflineEnd();0===t[0]&&(this.timestamp=t[1]),122===t[0]&&(this.url=t[1]),this.writeWithSize(t)||(this.finaliseBatch(),this.writeWithSize(t)||(this.encoder=new e(this.beaconSizeLimit),this.prepare(),this.writeWithSize(t)?this.finaliseBatch():console.warn("OpenReplay: beacon size overflow. Skipping large message.",t,this),this.encoder=new e(this.beaconSize),this.prepare()))}finaliseBatch(){if(this.isEmpty)return;const t=this.encoder.flush();this.onBatch(t),this.prepare()}clean(){this.encoder.reset()}}var h;!function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Stopping=2]="Stopping",t[t.Active=3]="Active",t[t.Stopped=4]="Stopped"}(h||(h={}));let r=null,a=null,u=h.NotActive;function o(){a&&a.finaliseBatch()}function c(){return new Promise((t=>{u=h.Stopping,null!==l&&(clearInterval(l),l=null),a&&(a.clean(),a=null),r&&(r.clean(),setTimeout((()=>{r=null}),20)),setTimeout((()=>{u=h.NotActive,t(null)}),100)}))}function g(){u!==h.Stopped&&(postMessage("a_stop"),c().then((()=>{postMessage("a_start")})))}let p,l=null;self.onmessage=({data:s})=>{if(null!=s){if("stop"===s)return o(),void c().then((()=>{u=h.Stopped}));if("forceFlushBatch"!==s){if(!Array.isArray(s)){if("compressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Compressed batch."),void g();s.batch&&r.sendCompressed(s.batch)}if("uncompressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Uncompressed batch."),void g();s.batch&&r.sendUncompressed(s.batch)}return"start"===s.type?(u=h.Starting,r=new t(s.ingestPoint,(()=>{g()}),(t=>{!function(t){postMessage({type:"failure",reason:t}),c()}(t)}),s.connAttemptCount,s.connAttemptGap,(t=>{postMessage({type:"compress",batch:t},[t.buffer])}),s.pageNo),a=new n(s.pageNo,s.timestamp,s.url,(t=>{r&&r.push(t)}),s.tabId,(()=>postMessage({type:"queue_empty"}))),null===l&&(l=setInterval(o,1e4)),u=h.Active):"auth"===s.type?r?a?(r.authorise(s.token),void(s.beaconSizeLimit&&a.setBeaconSizeLimit(s.beaconSizeLimit))):(console.debug("OR WebWorker: writer not initialised. Received auth."),void g()):(console.debug("OR WebWorker: sender not initialised. Received auth."),void g()):void 0}if(a){const t=a;s.forEach((s=>{55===s[0]&&(s[1]?p=setTimeout((()=>g()),18e5):clearTimeout(p)),t.writeMessage(s)}))}else postMessage("not_init"),g()}else o()}else o()};'],{type:"text/javascript"}))),this.worker.onerror=n=>{this._debug("webworker_error",n)},this.worker.onmessage=({data:n})=>{this.handleWorkerMsg(n)};const e=()=>{this.worker&&this.worker.postMessage(null)};this.attachEventListener(window,"beforeunload",e,!1),this.attachEventListener(document.body,"mouseleave",e,!1,!1),this.attachEventListener(document,"visibilitychange",e,!1)}catch(e){this._debug("worker_start",e)}}handleWorkerMsg(e){var n;if(e==="a_stop")this.stop(!1);else if(e==="a_start")this.start({},!0);else if(e==="not_init")this.debug.warn("OR WebWorker: writer not initialised. Restarting tracker");else if(e.type==="failure")this.stop(!1),this.debug.error("worker_failed",e.reason),this._debug("worker_failed",e.reason);else if(e.type==="compress"){const i=e.batch;i.byteLength>this.compressionThreshold?Ks(e.batch,{mtime:0},(r,o)=>{var l,a;r?(this.debug.error("Openreplay compression error:",r),(l=this.worker)==null||l.postMessage({type:"uncompressed",batch:i})):(a=this.worker)==null||a.postMessage({type:"compressed",batch:o})}):(n=this.worker)==null||n.postMessage({type:"uncompressed",batch:i})}else e.type==="queue_empty"&&this.onSessionSent()}_debug(e,n){this.options.__debug_report_edp!==null&&fetch(this.options.__debug_report_edp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({context:e,error:`${n}`})}),this.debug.error("OpenReplay error: ",e,n)}send(e,n=!1){var i;this.activityState!==Z.NotActive&&(this.activityState===Z.ColdStart?(this.bufferedMessages1.push(e),this.singleBuffer||this.bufferedMessages2.push(e),(i=this.conditionsManager)==null||i.processMessage(e)):this.messages.push(e),this.activityState===Z.Active&&n&&this.commit())}_nCommit(){if(this.socketMode){this.messages.unshift(De(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),this.commitCallbacks.forEach(e=>e(this.messages)),this.messages.length=0;return}if(!(this.worker===void 0||!this.messages.length)){if(this.insideIframe){window.parent.postMessage({line:le.iframeBatch,messages:this.messages,domain:this.initialHostName},"*"),this.commitCallbacks.forEach(e=>e(this.messages)),this.messages.length=0;return}try{cr(()=>{var e;this.messages.unshift(De(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),(e=this.worker)==null||e.postMessage(this.messages),this.commitCallbacks.forEach(n=>n(this.messages)),this.messages.length=0})}catch(e){this._debug("worker_commit",e),this.stop(!0),setTimeout(()=>{this.start()},500)}}}_cStartCommit(){this.coldStartCommitN+=1,this.coldStartCommitN===2&&(this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId())),this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(De(this.session.getTabId())),this.coldStartCommitN=0)}commit(){this.activityState===Z.ColdStart?this._cStartCommit():this._nCommit()}postToWorker(e){var n;(n=this.worker)==null||n.postMessage(e),this.commitCallbacks.forEach(i=>i(e)),e.length=0}timestamp(){return pe()+this.delay}safe(e){const n=this;return function(...i){try{e.apply(this,i)}catch(s){n._debug("safe_fn_call",s)}}}attachCommitCallback(e){this.commitCallbacks.push(e)}attachStartCallback(e,n=!1){n&&(e=this.safe(e)),this.startCallbacks.push(e)}attachStopCallback(e,n=!1){n&&(e=this.safe(e)),this.stopCallbacks.push(e)}attachEventListener(e,n,i,s=!0,r=!0){s&&(i=this.safe(i));const o=()=>e?vi(e,n,i,r):null,l=()=>e?wi(e,n,i,r):null;this.attachStartCallback(o,s),this.attachStopCallback(l,s)}checkRequiredVersion(e){const n=e.split(/[.-]/),i=this.version.split(/[.-]/);for(let s=0;s<3;s++){if(isNaN(Number(i[s]))||isNaN(Number(n[s])))return!1;if(Number(i[s])>Number(n[s]))return!0;if(Number(i[s])<Number(n[s]))return!1}return!0}getTrackerInfo(){return{userUUID:this.localStorage.getItem(this.options.local_uuid_key),projectKey:this.projectKey,revID:this.revID,trackerVersion:this.version,isSnippet:this.options.__is_snippet}}getSessionInfo(){return{...this.session.getInfo(),...this.getTrackerInfo()}}getSessionToken(){return this.session.getSessionToken()}getSessionID(){return this.session.getInfo().sessionID||void 0}getSessionURL(e){const{projectID:n,sessionID:i,timestamp:s}=this.session.getInfo();if(!n||!i){this.debug.error("OpenReplay error: Unable to build session URL");return}const r=this.options.ingestPoint,a=(/api\.openreplay\.com/.test(r)?"https://app.openreplay.com/ingest":r).replace(/ingest$/,`${n}/session/${i}`);if(e!=null&&e.withCurrentTime){const d=pe()-s;return`${a}?jumpto=${d}`}return a}getHost(){return new URL(this.options.ingestPoint).host}getProjectKey(){return this.projectKey}getBaseHref(){var e,n;return typeof this.options.resourceBaseHref=="string"?this.options.resourceBaseHref:(this.options.resourceBaseHref,document.baseURI?document.baseURI:((n=(e=document.head)==null?void 0:e.getElementsByTagName("base")[0])==null?void 0:n.getAttribute("href"))||location.origin+location.pathname)}resolveResourceURL(e){const n=new URL(this.getBaseHref());return n.pathname+="/"+new URL(e).pathname,n.pathname.replace(/\/+/g,"/"),n.toString()}isServiceURL(e){return e.startsWith(this.options.ingestPoint)}active(){return this.activityState===Z.Active}resetNextPageSession(e){e?this.sessionStorage.setItem(this.options.session_reset_key,"t"):this.sessionStorage.removeItem(this.options.session_reset_key)}checkSessionToken(e){const n=this.sessionStorage.getItem(this.options.session_reset_key)!==null,i=e||n,s=this.session.getSessionToken();return i||!s}async coldStart(e={},n){this.singleBuffer=!1;const i=1e3,s=this.checkSessionToken(e.forceNew);n&&await this.setupConditionalStart(e);const r=()=>{this.orderNumber+=1,qt(),this.coldStartTs=pe(),this.orderNumber%2===0?(this.bufferedMessages1.length=0,this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId()))):(this.bufferedMessages2.length=0,this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(De(this.session.getTabId()))),this.stop(!1),this.activityState=Z.ColdStart,e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata}),s||(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(bt(this.session.getTabId()))),this.observer.observe(),this.ticker.start()};this.coldInterval=setInterval(()=>{r()},30*i),r()}async setupConditionalStart(e){var p,y;this.conditionsManager=new Qs(this,e);const n=await fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:pe(),doNotRecord:!0,bufferDiff:0,userID:this.session.getInfo().userID,token:void 0,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn(),width:window.screen.width,height:window.screen.height})}),{token:i,userBrowser:s,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d,projectID:c}=await n.json();this.session.assign({projectID:c}),this.session.setUserInfo({userBrowser:s,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d});const u={sessionToken:i,userUUID:"",sessionID:""};this.startCallbacks.forEach(S=>S(u)),await((p=this.conditionsManager)==null?void 0:p.fetchConditions(c,i)),await this.featureFlags.reloadFlags(i),await this.tagWatcher.fetchTags(this.options.ingestPoint,i),(y=this.conditionsManager)==null||y.processFlags(this.featureFlags.flags)}offlineRecording(e={},n){this.onSessionSent=n,this.singleBuffer=!0;const i=this.checkSessionToken(e.forceNew);qt(),this.coldStartTs=pe();const s=this.localStorage.getItem(dn);if(s){const o=JSON.parse(s);this.bufferedMessages1=Array.isArray(o)?o:this.bufferedMessages1,this.localStorage.removeItem(dn)}this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(De(this.session.getTabId())),this.activityState=Z.ColdStart,e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata});const r={sessionToken:"",userUUID:"",sessionID:""};return this.startCallbacks.forEach(o=>o(r)),i||this.send(bt(this.session.getTabId())),this.observer.observe(),this.ticker.start(),{saveBuffer:this.saveBuffer,getBuffer:this.getBuffer,setBuffer:this.setBuffer}}saveBuffer(){this.localStorage.setItem(dn,JSON.stringify(this.bufferedMessages1))}getBuffer(){return this.bufferedMessages1}setBuffer(e){this.bufferedMessages1=e}async uploadOfflineRecording(){var p,y;this.stop(!1);const e=pe();(p=this.worker)==null||p.postMessage({type:"start",pageNo:this.session.incPageNo(),ingestPoint:this.options.ingestPoint,timestamp:this.coldStartTs,url:document.URL,connAttemptCount:this.options.connAttemptCount,connAttemptGap:this.options.connAttemptGap,tabId:this.session.getTabId()});const n=await fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:e,doNotRecord:!1,bufferDiff:e-this.coldStartTs,userID:this.session.getInfo().userID,token:void 0,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn()})}),{token:i,userBrowser:s,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d,beaconSizeLimit:c,projectID:u}=await n.json();for((y=this.worker)==null||y.postMessage({type:"auth",token:i,beaconSizeLimit:c}),this.session.assign({projectID:u}),this.session.setUserInfo({userBrowser:s,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:d});this.bufferedMessages1.length>0;)await this.flushBuffer(this.bufferedMessages1);this.postToWorker([["q_end"]]),this.clearBuffers()}async _start(e={},n=!1,i){const s=this.activityState===Z.ColdStart;if(s&&this.coldInterval&&clearInterval(this.coldInterval),!this.worker){const a="No worker found: perhaps, CSP is not set.";return this.signalError(a,[]),Promise.resolve(_e(a))}if(this.activityState===Z.Active||this.activityState===Z.Starting)return Promise.resolve(_e("OpenReplay: trying to call `start()` on the instance that has been started already."));this.activityState=Z.Starting,s||qt(),e.sessionHash&&this.session.applySessionHash(e.sessionHash),e.forceNew&&this.session.reset(),this.session.assign({userID:e.userID,metadata:e.metadata});const r=pe();this.worker.postMessage({type:"start",pageNo:this.session.incPageNo(),ingestPoint:this.options.ingestPoint,timestamp:s?this.coldStartTs:r,url:document.URL,connAttemptCount:this.options.connAttemptCount,connAttemptGap:this.options.connAttemptGap,tabId:this.session.getTabId()});const o=this.session.getSessionToken(),l=this.checkSessionToken(e.forceNew);this.sessionStorage.removeItem(this.options.session_reset_key),this.debug.log("OpenReplay: starting session; need new session id?",l,"session token: ",o);try{const a=await window.fetch(this.options.ingestPoint+"/v1/web/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...this.getTrackerInfo(),timestamp:r,doNotRecord:!1,bufferDiff:r-this.coldStartTs,userID:this.session.getInfo().userID,token:l?void 0:o,deviceMemory:Zt,jsHeapSizeLimit:en,timezone:hn(),condition:i,assistOnly:e.assistOnly??this.socketMode,width:window.screen.width,height:window.screen.height})});if(a.status!==200){const C=await a.text(),F=C===Ye?Ye:`Server error: ${a.status}. ${C}`;return _e(F)}if(!this.worker){const C="no worker found after start request (this should not happen in real world)";return this.signalError(C,[]),_e(C)}const{token:d,userUUID:c,projectID:u,beaconSizeLimit:p,compressionThreshold:y,delay:S,sessionID:v,startTimestamp:T,userBrowser:A,userCity:B,userCountry:D,userDevice:k,userOS:N,userState:O,canvasEnabled:L,canvasQuality:I,canvasFPS:E,assistOnly:P}=await a.json();if(typeof d!="string"||typeof c!="string"||typeof T!="number"&&typeof T<"u"||typeof v!="string"||typeof S!="number"||typeof p!="number"&&typeof p<"u"){const C=`Incorrect server response: ${JSON.stringify(a)}`;return this.signalError(C,[]),_e(C)}this.delay=S,this.session.setSessionToken(d),this.session.setUserInfo({userBrowser:A,userCity:B,userCountry:D,userDevice:k,userOS:N,userState:O}),this.session.assign({sessionID:v,timestamp:T||r,projectID:u}),P?(this.socketMode=!0,this.worker.postMessage("stop")):this.worker.postMessage({type:"auth",token:d,beaconSizeLimit:p}),!l&&d===o&&(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(bt(this.session.getTabId()))),Object.entries(this.session.getInfo().metadata).forEach(([C,F])=>this.send(ki(C,F))),this.localStorage.setItem(this.options.local_uuid_key,c),this.compressionThreshold=y;const V={sessionToken:d,userUUID:c,sessionID:v};if(this.startCallbacks.forEach(C=>C(V)),this.featureFlags.reloadFlags(),await this.tagWatcher.fetchTags(this.options.ingestPoint,d),this.activityState=Z.Active,L&&!this.options.canvas.disableCanvas&&(this.canvasRecorder=this.canvasRecorder??new po(this,{fps:E,quality:I,isDebug:this.options.canvas.__save_canvas_locally,fixedScaling:this.options.canvas.fixedCanvasScaling,useAnimationFrame:this.options.canvas.useAnimationFrame}),this.canvasRecorder.startTracking()),s){const C=this.bufferedMessages1.length>this.bufferedMessages2.length?this.bufferedMessages1:this.bufferedMessages2;for(;C.length>0;)await this.flushBuffer(C);this.clearBuffers(),this.commit()}else this.insideIframe&&this.rootId?this.observer.crossdomainObserve(this.rootId,this.frameOderNumber):this.observer.observe(),this.ticker.start();this.uxtManager=this.uxtManager?this.uxtManager:new uo(this,qi);let j;const q=this.localStorage.getItem(qi);if(q&&(j=parseInt(q,10)),location!=null&&location.search){const C=new URLSearchParams(location.search);if(C.has("oruxt")){const F=C.get("oruxt");j=F?parseInt(F,10):void 0}}return j&&(this.uxtManager.isActive?this.onUxtCb.forEach(C=>C(j)):this.uxtManager.getTest(j,d,!!q).then(C=>{C&&this.onUxtCb.forEach(F=>F(C))})),Co(V)}catch(a){if(this.stop(),this.session.reset(),a===Ye)return this.signalError(Ye,[]),_e(Ye);this._debug("session_start",a);const d=a instanceof Error?a.message:a.toString();return this.signalError(d,[]),_e(d)}}addOnUxtCb(e){this.onUxtCb.push(e)}getUxtId(){var e;return(e=this.uxtManager)==null?void 0:e.getTestId()}async waitStart(){return new Promise(e=>{const n=()=>{this.canStart?e(!0):setTimeout(n,25)};n()})}async waitStarted(){return new Promise(e=>{const n=()=>{this.activityState===Z.Active?e(!0):setTimeout(n,25)};n()})}async start(...e){return this.activityState===Z.Active||this.activityState===Z.Starting?Promise.resolve(_e("OpenReplay: trying to call `start()` on the instance that has been started already.")):document.hidden?new Promise(n=>{const i=async()=>{document.hidden||(await this.waitStart(),document.removeEventListener("visibilitychange",i),n(this._start(...e)))};document.addEventListener("visibilitychange",i)}):(await this.waitStart(),this._start(...e))}forceFlushBatch(){var e;(e=this.worker)==null||e.postMessage("forceFlushBatch")}getTabId(){return this.session.getTabId()}clearBuffers(){this.bufferedMessages1.length=0,this.bufferedMessages2.length=0}trackWs(e){const n=e;return(i,s,r="down")=>{typeof i!="string"||typeof s!="string"||s.length>5*1024*1024||i.length>255||this.send(Fr("websocket",n,s,this.timestamp(),r,i))}}stop(e=!0){var n;if(this.activityState!==Z.NotActive)try{this.attributeSender.clear(),this.sanitizer.clear(),this.observer.disconnect(),this.nodes.clear(),this.ticker.stop(),this.stopCallbacks.forEach(i=>i()),this.debug.log("OpenReplay tracking stopped."),this.tagWatcher.clear(),this.worker&&e&&this.worker.postMessage("stop"),(n=this.canvasRecorder)==null||n.clear()}finally{this.activityState=Z.NotActive}}};function Oo(t){const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e===void 0)return;const n=()=>t.send(_r(Math.round(e.downlink*1e3),e.type||"unknown"));n(),e.addEventListener("change",n)}const Gi=be&&"InstallTrigger"in window?t=>t.message+`
|
|
657
|
+
`+t.stack:t=>t.stack||t.message;function un(t){return t===void 0?"undefined":t===null?"null":t instanceof Error?Gi(t):Array.isArray(t)?`Array(${t.length})`:String(t)}function Ro(t){return typeof t!="number"?"NaN":t.toString()}function Ao(t){return typeof t!="number"?"NaN":Math.floor(t).toString()}function Vi(t){if(t===void 0)return"undefined";if(t===null)return"null";if(t instanceof Error)return Gi(t);if(Array.isArray(t)){const e=t.length,n=t.slice(0,10).map(un).join(", ");return`Array(${e})[${n}]`}if(typeof t=="object"){const e=[];let n=0;for(const i in t){if(++n===10)break;const s=t[i];e.push(i+": "+un(s))}return"{"+e.join(", ")+"}"}return t.toString()}function Do(t){return typeof t[0]=="string"&&t.unshift(t.shift().replace(/%(o|s|f|d|i)/g,(e,n)=>{const i=t.shift();if(i===void 0)return e;switch(n){case"o":return Vi(i);case"s":return un(i);case"f":return Ro(i);case"d":case"i":return Ao(i);default:return e}})),t.map(Vi).join(" ")}const Ki=["log","info","warn","error","debug","assert"];function Lo(t,e){const n=Object.assign({consoleMethods:Ki,consoleThrottling:30},e);if(!Array.isArray(n.consoleMethods)||n.consoleMethods.length===0)return;const i=t.safe((a,d)=>t.send(Sr(a,Do(d))));let s=0;const r=()=>{s=0};t.attachStartCallback(r),t.ticker.attach(r,33,!1);const o=(a,d)=>{const c={apply:function(u,p,y){Reflect.apply(u,d,y),s=s+1,!(s>n.consoleThrottling)&&i(u.name,y)}};n.consoleMethods.forEach(u=>{if(Ki.indexOf(u)===-1){t.debug.error(`OpenReplay: unsupported console method "${u}"`);return}const p=d.console[u];a[u]=new Proxy(p,c)})},l=t.safe(a=>o(a.console,a));l(window),t.observer.attachContextCallback(l)}var Xi={exports:{}},fn={exports:{}},Ji;function Fo(){return Ji||(Ji=1,function(t,e){(function(n,i){t.exports=i()})(Fe,function(){function n(v){return!isNaN(parseFloat(v))&&isFinite(v)}function i(v){return v.charAt(0).toUpperCase()+v.substring(1)}function s(v){return function(){return this[v]}}var r=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],l=["fileName","functionName","source"],a=["args"],d=["evalOrigin"],c=r.concat(o,l,a,d);function u(v){if(v)for(var T=0;T<c.length;T++)v[c[T]]!==void 0&&this["set"+i(c[T])](v[c[T]])}u.prototype={getArgs:function(){return this.args},setArgs:function(v){if(Object.prototype.toString.call(v)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=v},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(v){if(v instanceof u)this.evalOrigin=v;else if(v instanceof Object)this.evalOrigin=new u(v);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var v=this.getFileName()||"",T=this.getLineNumber()||"",A=this.getColumnNumber()||"",B=this.getFunctionName()||"";return this.getIsEval()?v?"[eval] ("+v+":"+T+":"+A+")":"[eval]:"+T+":"+A:B?B+" ("+v+":"+T+":"+A+")":v+":"+T+":"+A}},u.fromString=function(T){var A=T.indexOf("("),B=T.lastIndexOf(")"),D=T.substring(0,A),k=T.substring(A+1,B).split(","),N=T.substring(B+1);if(N.indexOf("@")===0)var O=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(N,""),L=O[1],I=O[2],E=O[3];return new u({functionName:D,args:k||void 0,fileName:L,lineNumber:I||void 0,columnNumber:E||void 0})};for(var p=0;p<r.length;p++)u.prototype["get"+i(r[p])]=s(r[p]),u.prototype["set"+i(r[p])]=function(v){return function(T){this[v]=!!T}}(r[p]);for(var y=0;y<o.length;y++)u.prototype["get"+i(o[y])]=s(o[y]),u.prototype["set"+i(o[y])]=function(v){return function(T){if(!n(T))throw new TypeError(v+" must be a Number");this[v]=Number(T)}}(o[y]);for(var S=0;S<l.length;S++)u.prototype["get"+i(l[S])]=s(l[S]),u.prototype["set"+i(l[S])]=function(v){return function(T){this[v]=String(T)}}(l[S]);return u})}(fn)),fn.exports}(function(t,e){(function(n,i){t.exports=i(Fo())})(Fe,function(i){var s=/(^|@)\S+:\d+/,r=/^\s*at .*(\S+:\d+|\(native\))/m,o=/^(eval@)?(\[native code])?$/;return{parse:function(a){if(typeof a.stacktrace<"u"||typeof a["opera#sourceloc"]<"u")return this.parseOpera(a);if(a.stack&&a.stack.match(r))return this.parseV8OrIE(a);if(a.stack)return this.parseFFOrSafari(a);throw new Error("Cannot parse given Error object")},extractLocation:function(a){if(a.indexOf(":")===-1)return[a];var d=/(.+?)(?::(\d+))?(?::(\d+))?$/,c=d.exec(a.replace(/[()]/g,""));return[c[1],c[2]||void 0,c[3]||void 0]},parseV8OrIE:function(a){var d=a.stack.split(`
|
|
658
|
+
`).filter(function(c){return!!c.match(r)},this);return d.map(function(c){c.indexOf("(eval ")>-1&&(c=c.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var u=c.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=u.match(/ (\(.+\)$)/);u=p?u.replace(p[0],""):u;var y=this.extractLocation(p?p[1]:u),S=p&&u||void 0,v=["eval","<anonymous>"].indexOf(y[0])>-1?void 0:y[0];return new i({functionName:S,fileName:v,lineNumber:y[1],columnNumber:y[2],source:c})},this)},parseFFOrSafari:function(a){var d=a.stack.split(`
|
|
659
|
+
`).filter(function(c){return!c.match(o)},this);return d.map(function(c){if(c.indexOf(" > eval")>-1&&(c=c.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),c.indexOf("@")===-1&&c.indexOf(":")===-1)return new i({functionName:c});var u=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=c.match(u),y=p&&p[1]?p[1]:void 0,S=this.extractLocation(c.replace(u,""));return new i({functionName:y,fileName:S[0],lineNumber:S[1],columnNumber:S[2],source:c})},this)},parseOpera:function(a){return!a.stacktrace||a.message.indexOf(`
|
|
660
660
|
`)>-1&&a.message.split(`
|
|
661
661
|
`).length>a.stacktrace.split(`
|
|
662
662
|
`).length?this.parseOpera9(a):a.stack?this.parseOpera11(a):this.parseOpera10(a)},parseOpera9:function(a){for(var d=/Line (\d+).*script (?:in )?(\S+)/i,c=a.message.split(`
|
|
663
|
-
`),u=[],p=2,y=c.length;p<y;p+=2){var S=d.exec(c[p]);S&&u.push(new
|
|
664
|
-
`),u=[],p=0,y=c.length;p<y;p+=2){var S=d.exec(c[p]);S&&u.push(new
|
|
665
|
-
`).filter(function(c){return!!c.match(i)&&!c.match(/^Error created at/)},this);return d.map(function(c){var u=c.split("@"),p=this.extractLocation(u.pop()),y=u.shift()||"",S=y.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;y.match(/\(([^)]*)\)/)&&(v=y.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var T=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new s({functionName:S,args:T,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:c})},this)}}})})(Xs);var Mo=Xs.exports;const Po=Kn(Mo);function Ys(t){return[{columnNumber:t.colno,lineNumber:t.lineno,fileName:t.filename,functionName:"",source:""}]}function kt(t,e,n={}){let s=e;try{s=Po.parse(t)}catch{}return Yt(t.name,t.message,JSON.stringify(s),JSON.stringify(n))}function Qs(t,e=window,n={}){if(t instanceof ErrorEvent){if(t.error instanceof Error)return kt(t.error,Ys(t),n);{let[s,i]=t.message.split(":");return i||(s="Error",i=t.message),Yt(s,i,JSON.stringify(Ys(t)),JSON.stringify(n))}}else if("PromiseRejectionEvent"in e&&t instanceof e.PromiseRejectionEvent){if(t.reason instanceof Error)return kt(t.reason,[],n);{let s;try{s=JSON.stringify(t.reason)}catch{s=String(t.reason)}return Yt("Unhandled Promise Rejection",s,"[]",JSON.stringify(n))}}return null}function Bo(t,e){const n=Object.assign({captureExceptions:!0},e);function s(i){function r(o){const l=Qs(o,i);l!=null&&t.send(l)}t.attachEventListener(i,"unhandledrejection",r),t.attachEventListener(i,"error",r)}n.captureExceptions&&(t.observer.attachContextCallback(s),s(window))}function Zs(t,e=document.location){return t=t.trim(),t.startsWith("//")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("data:")?t:t.startsWith("/")?e.origin+t:e.origin+e.pathname+t}function jo(t){return tr&&(t.startsWith("data:image/svg+xml")||t.match(/.svg$|/i))}const zo="https://static.openreplay.com/tracker/placeholder.jpeg";function Uo(t){function e(l,a){t.attributeSender.sendSetAttribute(l,"src",zo);const{width:d,height:c}=a.getBoundingClientRect();a.hasAttribute("width")||t.attributeSender.sendSetAttribute(l,"width",String(d)),a.hasAttribute("height")||t.attributeSender.sendSetAttribute(l,"height",String(c))}const n=function(l,a){const{srcset:d}=a;if(!d)return;const c=d.split(d.match(/,\s+/)?/,\s+/:",").map(u=>Zs(u)).join(", ");t.attributeSender.sendSetAttribute(l,"srcset",c)},s=function(l,a){a.src.length>nr&&e(l,a),t.send(Kt(l,"src",a.src,t.getBaseHref()))},i=t.safe(function(l){const a=Zs(l.src||"");gs(a)&&t.send(Os(t.timestamp(),0,0,0,0,0,a,"img",0,!1))}),r=t.safe(function(l){const a=t.nodes.getID(l);a!==void 0&&l.complete&&(l.naturalHeight===0&&l.naturalWidth===0&&!jo(l.src)?i(l):t.sanitizer.isHidden(a)||t.sanitizer.isObscured(a)?e(a,l):(s(a,l),n(a,l)))}),o=ys(t.safe(l=>{for(const a of l)if(a.type==="attributes"){const d=a.target,c=t.nodes.getID(d);if(c===void 0)return;a.attributeName==="src"&&s(c,d),a.attributeName==="srcset"&&n(c,d)}}));t.attachStopCallback(()=>{o.disconnect()}),t.nodes.attachNodeCallback(l=>{Q(l,"img")&&(t.nodes.attachNodeListener(l,"error",()=>i(l)),t.nodes.attachNodeListener(l,"load",()=>r(l)),r(l),o.observe(l,{attributes:!0,attributeFilter:["src","srcset"]}))})}const Ho=["text","password","email","search","number","range","date","tel","time"];function $o(t){return Q(t,"textarea")?!0:Q(t,"input")?Ho.includes(t.type):!1}function qo(t){if(!Q(t,"input"))return!1;const e=t.type;return e==="checkbox"||e==="radio"}const Wo=be&&"labels"in HTMLInputElement.prototype?t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Q(e,"label"))return e;const n=t.labels;if(n!==null&&n.length===1)return n[0]}:t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Q(e,"label"))return e;const n=t.id;if(n){const s=t.ownerDocument.querySelectorAll('label[for="'+n+'"]');if(s!==null&&s.length===1)return s[0]}};function ei(t){let e=Gt(t);if(e===null){const n=Wo(t);e=n&&n.innerText||t.placeholder||t.name||t.id||t.className||t.type}return ps(e).slice(0,100)}const $e={Plain:0,Obscured:1,Hidden:2};function Go(t,e){const n=Object.assign({obscureInputNumbers:!0,obscureInputEmails:!0,defaultInputMode:$e.Obscured,obscureInputDates:!1},e);function s(c,u){let p=u.value,y=n.defaultInputMode;u.type==="password"||t.sanitizer.isHidden(c)?y=$e.Hidden:(t.sanitizer.isObscured(c)||y===$e.Plain&&(n.obscureInputNumbers&&u.type!=="date"&&/\d\d\d\d/.test(p)||n.obscureInputDates&&u.type==="date"||n.obscureInputEmails&&(u.type==="email"||~p.indexOf("@"))))&&(y=$e.Obscured);let S=0;switch(y){case $e.Hidden:S=-1,p="";break;case $e.Obscured:S=p.length,p="";break}return{value:p,mask:S}}function i(c,u){const{value:p,mask:y}=s(c,u);t.send(yr(c,p,y))}const r=new Map,o=new Map;t.attachStopCallback(()=>{r.clear(),o.clear()});function l(c,u){r.get(c)!==u.value&&(r.set(c,u.value),i(c,u))}function a(c,u){o.get(c)!==u&&(o.set(c,u),t.send(vr(c,u)))}t.ticker.attach(()=>{r.forEach((c,u)=>{const p=t.nodes.getNode(u);if(!p)return r.delete(u);l(u,p)}),o.forEach((c,u)=>{const p=t.nodes.getNode(u);if(!p)return o.delete(u);a(u,p.checked)})},3);function d(c,u,p,y){const{value:S,mask:v}=s(c,u),T=ei(u);t.send(Mr(c,S,v!==0,T,p,y))}t.nodes.attachNodeCallback(t.safe(c=>{const u=t.nodes.getID(c);if(u!==void 0){if(Q(c,"select")&&(i(u,c),t.nodes.attachNodeListener(c,"change",()=>i(u,c))),$o(c)){l(u,c);let p=0,y=0,S=0;const v=()=>{p=pe()},T=()=>{y===0&&p!==0&&(y=pe()-p)},A=()=>{p!==0&&(S=pe()-p),d(u,c,y,S),y=0,S=0,p=0};t.nodes.attachNodeListener(c,"focus",v),t.nodes.attachNodeListener(c,"input",T),t.nodes.attachNodeListener(c,"change",A);return}if(qo(c)){a(u,c.checked),t.nodes.attachNodeListener(c,"change",()=>a(u,c.checked));return}}}))}let de,pn,ti;function Vo(t,e){if(ti=new Date,t.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(t.tagName.toLowerCase()==="html")return"html";const n={root:document.body,idName:i=>!0,className:i=>!0,tagName:i=>!0,attr:(i,r)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};de={...n,...e},pn=Ko(de.root,n);let s=Tt(t,"all",()=>Tt(t,"two",()=>Tt(t,"one",()=>Tt(t,"none"))));if(s){const i=ai(ci(s,t));return i.length>0&&(s=i[0]),Et(s)}else throw new Error("Selector was not found.")}function Ko(t,e){return t.nodeType===Node.DOCUMENT_NODE?t:t===e.root?t.ownerDocument:t}function Tt(t,e,n){let s=null,i=[],r=t,o=0;for(;r;){const l=new Date().getTime()-ti.getTime();if(de.timeoutMs!==void 0&&l>de.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${l}ms`);let a=Ct(Xo(r))||Ct(...Jo(r))||Ct(...Yo(r))||Ct(Qo(r))||[ri()];const d=Zo(r);if(e=="all")d&&(a=a.concat(a.filter(gn).map(c=>It(c,d))));else if(e=="two")a=a.slice(0,1),d&&(a=a.concat(a.filter(gn).map(c=>It(c,d))));else if(e=="one"){const[c]=a=a.slice(0,1);d&&gn(c)&&(a=[It(c,d)])}else e=="none"&&(a=[ri()],d&&(a=[It(a[0],d)]));for(let c of a)c.level=o;if(i.push(a),i.length>=de.seedMinLength&&(s=ni(i,n),s))break;r=r.parentElement,o++}return s||(s=ni(i,n)),!s&&n?n():s}function ni(t,e){const n=ai(oi(t));if(n.length>de.threshold)return e?e():null;for(let s of n)if(ii(s))return s;return null}function Et(t){let e=t[0],n=e.name;for(let s=1;s<t.length;s++){const i=t[s].level||0;e.level===i-1?n=`${t[s].name} > ${n}`:n=`${t[s].name} ${n}`,e=t[s]}return n}function si(t){return t.map(e=>e.penalty).reduce((e,n)=>e+n,0)}function ii(t){const e=Et(t);switch(pn.querySelectorAll(e).length){case 0:throw new Error(`Can't select any node with this selector: ${e}`);case 1:return!0;default:return!1}}function Xo(t){const e=t.getAttribute("id");return e&&de.idName(e)?{name:"#"+CSS.escape(e),penalty:0}:null}function Jo(t){return Array.from(t.attributes).filter(n=>de.attr(n.name,n.value)).map(n=>({name:`[${CSS.escape(n.name)}="${CSS.escape(n.value)}"]`,penalty:.5}))}function Yo(t){return Array.from(t.classList).filter(de.className).map(n=>({name:"."+CSS.escape(n),penalty:1}))}function Qo(t){const e=t.tagName.toLowerCase();return de.tagName(e)?{name:e,penalty:2}:null}function ri(){return{name:"*",penalty:3}}function Zo(t){const e=t.parentNode;if(!e)return null;let n=e.firstChild;if(!n)return null;let s=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&s++,n!==t);)n=n.nextSibling;return s}function It(t,e){return{name:t.name+`:nth-child(${e})`,penalty:t.penalty+1}}function gn(t){return t.name!=="html"&&!t.name.startsWith("#")}function Ct(...t){const e=t.filter(ea);return e.length>0?e:null}function ea(t){return t!=null}function*oi(t,e=[]){if(t.length>0)for(let n of t[0])yield*oi(t.slice(1,t.length),e.concat(n));else yield e}function ai(t){return[...t].sort((e,n)=>si(e)-si(n))}function*ci(t,e,n={counter:0,visited:new Map}){if(t.length>2&&t.length>de.optimizedMinLength)for(let s=1;s<t.length-1;s++){if(n.counter>de.maxNumberOfTries)return;n.counter+=1;const i=[...t];i.splice(s,1);const r=Et(i);if(n.visited.has(r))return;ii(i)&&ta(i,e)&&(yield i,n.visited.set(r,!0),yield*ci(i,e,n))}}function ta(t,e){return pn.querySelector(Et(t))===e}function na(t,e,n){return Vo(t,{root:e.body,seedMinLength:3,optimizedMinLength:(n==null?void 0:n.minSelectorDepth)||2,threshold:(n==null?void 0:n.nthThreshold)||1e3,maxNumberOfTries:(n==null?void 0:n.maxOptimiseTries)||1e4})}function mn(t){const e=t.tagName.toUpperCase();return e==="BUTTON"||e==="A"||e==="LI"||e==="SELECT"||e==="TR"||e==="TH"||t.onclick!=null||t.getAttribute("role")==="button"}function li(t,e){return t instanceof Element?sa(t,e):null}function sa(t,e){let n=t;for(;n!==null&&n!==e.documentElement;){if(Re(n,"masked"))return null;n=n.parentElement}if(sn(t)){let s=t.ownerSVGElement;for(;s!==null;)t=s,s=s.ownerSVGElement}for(n=t;n!==null&&n!==e.documentElement;){const s=n.tagName.toUpperCase();if(s==="LABEL")return null;if(s==="INPUT"||mn(n)||Gt(n)!==null)return n;n=n.parentElement}return t===e.documentElement?null:t}function ia(t,e){const{disableClickmaps:n=!1}=e||{};function s(k){const N=Gt(k);if(N!==null)return N;if(Q(k,"input"))return ei(k);if(mn(k)){let O="";return k instanceof HTMLElement&&(O=t.sanitizer.getInnerTextSecure(k)),O=O||k.id||k.className,ps(O).slice(0,100)}return""}let i=-1,r=-1,o=!1,l=null,a=0,d={},c=0,u=0,p=0,y=0,S;const v=.008,T=225;function A(){const k=y/T;if(!c){c=k;return}const N=(k-c)/T;p>4&&N>v&&t.send(Pr(pe())),y=0,p=0,c=k}t.attachStartCallback(()=>{S=setInterval(()=>A(),T)}),t.attachStopCallback(()=>{i=-1,r=-1,o=!1,l=null,d={},S&&clearInterval(S)});const B=()=>{o&&(t.send(wr(i,r)),o=!1)},D=(k,N=!1)=>{function O(I,E,P){return d[I]=d[I]||na(E,k,P)}const L=N?t.attachEventListener.bind(t):t.nodes.attachNodeListener.bind(t.nodes);L(k.documentElement,"mouseover",I=>{const E=li(I.target,k);E!==l&&(l=E,a=performance.now())}),L(k,"mousemove",I=>{const[E,P]=t.observer.getDocumentOffset(k);i=I.clientX+E,r=I.clientY+P,o=!0;const V=Math.sign(I.movementX);y+=Math.abs(I.movementX)+Math.abs(I.movementY),V!==u&&(u=V,p++)},!1),L(k,"click",I=>{const E=li(I.target,k);if(!I.clientX&&!I.clientY||E===null)return;const P=t.nodes.getID(E);if(P!==void 0){const V=I.pageX,j=I.pageY,q=k.documentElement.scrollWidth,C=k.documentElement.scrollHeight,F=di(V/q),G=di(j/C);B(),t.send(Dr(P,l===E?Math.round(performance.now()-a):0,s(E),mn(E)&&!n?O(P,E,e):"",F,G),!0)}l=null})};t.nodes.attachNodeCallback(k=>{wt(k)&&D(k)}),D(document,!0),t.ticker.attach(B,(e==null?void 0:e.trackingOffset)||7)}function di(t){return Math.round(t*1e4)}function ra(t){const e=[],n=document.getElementsByTagName("*"),s=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let i=0;i<n.length;i++){const r=n[i];let o="";if(Q(r,"img")&&(o=r.currentSrc||r.src),!o){const S=getComputedStyle(r).getPropertyValue("background-image");if(S){const v=s.exec(S);v!==null&&(o=v[1],(o.startsWith('"')||o.startsWith("'"))&&(o=o.substr(1,o.length-2)))}}if(!o)continue;const l=o.substr(0,10)==="data:image"?0:t[o];if(l===void 0)continue;const a=r.getBoundingClientRect(),d=Math.max(a.top,0),c=Math.max(a.left,0),u=Math.min(a.bottom,window.innerHeight||document.documentElement&&document.documentElement.clientHeight||0),p=Math.min(a.right,window.innerWidth||document.documentElement&&document.documentElement.clientWidth||0);if(u<=d||p<=c)continue;const y=(u-d)*(p-c);e.push({time:l,area:y})}return e}function oa(t,e){let n=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,s=n*t;for(let i=0;i<e.length;i++){const{time:r,area:o}=e[i];n+=o,s+=o*(r>t?r:t)}return n===0?0:s/n}function aa(t,e){const n=Object.assign({captureResourceTimings:!0,capturePageLoadTimings:!0,capturePageRenderTimings:!0,excludedResourceUrls:[]},e);if("PerformanceObserver"in window||(n.captureResourceTimings=!1),!n.captureResourceTimings)return;let s={};function i(d){var u;if(d.duration<0||!gs(d.name)||t.isServiceURL(d.name))return;s!==null&&(s[d.name]=d.startTime+d.duration);let c=!1;(u=n.excludedResourceUrls)==null||u.forEach(p=>{if(d.name.startsWith(p)){c=!0;return}}),!c&&t.send(Os(d.startTime+ze(),d.duration,d.responseStart&&d.startTime?d.responseStart-d.startTime:0,d.transferSize>d.encodedBodySize?d.transferSize-d.encodedBodySize:0,d.encodedBodySize||0,d.decodedBodySize||0,d.name,d.initiatorType,d.transferSize,d.responseStatus&&d.responseStatus===304||d.transferSize===0))}const r=new PerformanceObserver(d=>d.getEntries().forEach(i));let o;t.attachStartCallback(function({sessionID:d}){d!==o&&(performance.getEntriesByType("resource").forEach(i),o=d),r.observe({entryTypes:["resource"]})}),t.attachStopCallback(function(){r.disconnect()});let l=0,a=0;if(n.capturePageLoadTimings){let d=!1;t.ticker.attach(()=>{if(!d&&((l===0||a===0)&&performance.getEntriesByType("paint").forEach(c=>{const{name:u,startTime:p}=c;switch(u){case"first-paint":l=p;break;case"first-contentful-paint":a=p;break}}),performance.timing.loadEventEnd||performance.now()>3e4)){d=!0;const{navigationStart:c,requestStart:u,responseStart:p,responseEnd:y,domContentLoadedEventStart:S,domContentLoadedEventEnd:v,loadEventStart:T,loadEventEnd:A}=performance.timing;t.send(xr(u-c||0,p-c||0,y-c||0,S-c||0,v-c||0,T-c||0,A-c||0,l,a))}},30)}if(n.capturePageRenderTimings){let d=0,c=0,u=0,p=null,y=!1;t.ticker.attach(()=>{if(y)return;const S=performance.now();if(s!==null&&(d=Math.max.apply(null,Object.keys(s).map(v=>s[v])),S-d>1e3&&(p=ra(s),s=null)),u!==null&&(S-u>50&&(c=S),u=S-c>5e3?null:S),p!==null&&u===null||S>3e4){y=!0,s=null;const v=p===null?0:oa(a||l,p),{domContentLoadedEventEnd:T,navigationStart:A}=performance.timing,B=u===null?Math.max(c,a,T-A||0):0;t.send(kr(v,a>d?a:d,B))}})}}function bn(t){const e=t.defaultView;return[e&&e.scrollX||t.documentElement&&t.documentElement.scrollLeft||t.body&&t.body.scrollLeft||0,e&&e.scrollY||t.documentElement&&t.documentElement.scrollTop||t.body&&t.body.scrollTop||0]}function ca(t,e){let n=!1;const s=new Map;function i(l){Us(l)&&(ke(l)&&s.set(l,[l.scrollLeft,l.scrollTop]),wt(l)&&s.set(l,bn(l)))}const r=t.safe(()=>{e||t.send(dr(...bn(document)))}),o=t.safe((l,a)=>{const d=t.nodes.getID(a);d!==void 0&&t.send(br(d,l[0],l[1]))});t.attachStartCallback(r),t.attachStopCallback(()=>{n=!1,s.clear()}),t.nodes.attachNodeCallback((l,a)=>{a&&(ke(l)&&l.scrollLeft+l.scrollTop>0?s.set(l,[l.scrollLeft,l.scrollTop]):wt(l)&&s.set(l,bn(l))),St(l)&&t.nodes.attachNodeListener(l,"scroll",d=>{i(d.target)})}),t.attachEventListener(document,"scroll",l=>{const a=l.target;if(a===document){n=!0;return}i(a)}),t.ticker.attach(()=>{n&&(r(),n=!1),s.forEach(o),s.clear()},5,!1)}function la(t){let e,n,s,i,r=document.referrer;const o=t.safe(()=>{const{URL:d}=document;d!==e&&(e=d,t.send(Ur(e,r,i,document.title)),i=0,r=e)}),l=t.safe(()=>{const{innerWidth:d,innerHeight:c}=window;(d!==n||c!==s)&&(n=d,s=c,t.send(lr(n,s)))}),a=document.hidden===void 0?Function.prototype:t.safe(()=>t.send(Nr(document.hidden)));t.attachStartCallback(()=>{e=null,i=ze(),n=s=-1,o(),l(),a()}),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",a,!1,!1),t.ticker.attach(o,1,!1),t.ticker.attach(l,5,!1)}function hi(t){return St(t)&&!!t.adoptedStyleSheets}let da=15;function ui(){return da++}const _t=new Map;function ha(t){if(t===null||!hi(document))return;const e=new Map,n=new Map,s=o=>setTimeout(()=>{let l=t.nodes.getID(o);if(o===document&&(l=0),l===void 0)return;let a=n.get(l);a||(a=[]);const d=[],c=o.adoptedStyleSheets;if(c&&Symbol.iterator in c)for(const u of c){let p=e.get(u);const y=!p;if(p||(p=ui(),e.set(u,p)),a.includes(p)||t.send(_s(p,l)),y){const S=u.cssRules;for(let v=0;v<S.length;v++)t.send(Jt(p,S[v].cssText,v,t.getBaseHref()))}d.push(p)}if(Symbol.iterator in a)for(const u of a)d.includes(u)||t.send(Lr(u,l));n.set(l,d)},20);function i(o){const l=Object.getOwnPropertyDescriptor(o,"adoptedStyleSheets");l&&Object.defineProperty(o,"adoptedStyleSheets",{...l,set:function(a){const d=l.set.call(this,a);return s(this),d}})}const r=o=>{if(o.__openreplay_adpss_patched__)return;o.__openreplay_adpss_patched__=!0,i(o.Document.prototype),i(o.ShadowRoot.prototype);const{replace:l,replaceSync:a}=o.CSSStyleSheet.prototype;o.CSSStyleSheet.prototype.replace=function(d){return l.call(this,d).then(c=>{const u=e.get(this);return u&&t.send(Is(u,d,t.getBaseHref())),c})},o.CSSStyleSheet.prototype.replaceSync=function(d){const c=e.get(this);return c&&t.send(Is(c,d,t.getBaseHref())),a.call(this,d)}};r(window),t.observer.attachContextCallback(t.safe(r)),t.attachStopCallback(()=>{e.clear(),n.clear()}),t.attachStartCallback(()=>{s(document)}),t.nodes.attachNodeCallback(o=>{hi(o)&&s(o)})}function ua(t){if(t===null)return;if(!window.CSSStyleSheet){t.send(Rr("no_stylesheet_prototype_in_window",""));return}const e=t.safe((i,r,o)=>{const l=_t.get(i);l&&(typeof o=="string"?t.send(Jt(l,o,r,t.getBaseHref())):t.send(Cs(l,r)))}),n=t.safe(i=>{let r=i;for(;r.parentRule;)r=r.parentRule;const o=r.parentStyleSheet;if(!o){t.debug.warn("No parent StyleSheet found for",r,i);return}const l=_t.get(o);if(!l){t.debug.warn("No sheedID found for",o,_t);return}const a=r.cssText,d=o.cssRules,c=Array.from(d).indexOf(r);c>=0?(t.send(Jt(l,a,c,t.getBaseHref())),t.send(Cs(l,c+1))):t.debug.warn("Rule index not found in",o,r)}),s=t.safe(i=>{const{insertRule:r,deleteRule:o}=i.CSSStyleSheet.prototype,{insertRule:l,deleteRule:a}=i.CSSGroupingRule.prototype;i.CSSStyleSheet.prototype.insertRule=function(d,c=0){return e(this,c,d),r.call(this,d,c)},i.CSSStyleSheet.prototype.deleteRule=function(d){return e(this,d),o.call(this,d)},i.CSSGroupingRule.prototype.insertRule=function(d,c=0){const u=l.call(this,d,c);return n(this),u},i.CSSGroupingRule.prototype.deleteRule=function(d=0){const c=a.call(this,d);return n(this),c}});s(window),t.observer.attachContextCallback(s),t.nodes.attachNodeCallback(i=>{if(!Q(i,"style")||!i.sheet||i.textContent!==null&&i.textContent.trim().length>0)return;const r=t.nodes.getID(i);if(!r)return;const o=i.sheet,l=ui();_t.set(o,l),t.send(_s(l,r));const a=o.cssRules;for(let d=0;d<a.length;d++)e(o,d,a[d].cssText)})}function fa(t){function e(s){const i=t.nodes.getID(s);i!==void 0&&t.send(Es(i))}let n=!1;t.nodes.attachNodeCallback(s=>{Q(s,"body")&&(t.nodes.attachNodeListener(s,"focus",i=>{Us(i.target)&&(e(i.target),n=!1)}),t.nodes.attachNodeListener(s,"blur",i=>{i.relatedTarget===null&&(n=!0,setTimeout(()=>{n&&t.send(Es(-1))},0))}))}),t.attachStartCallback(()=>{let s=document.activeElement;for(;s&&Q(s,"iframe")&&s.contentDocument;)s=s.contentDocument.activeElement;s&&s!==s.ownerDocument.body&&e(s)},!0)}function pa(t){if(!window.FontFace)return;const e=new Map,n=s=>{class i extends s.FontFace{constructor(...o){if(typeof o[1]=="string"){let l="";o[2]&&t.safe(()=>{l=JSON.stringify(o[2])});const a=[o[0],o[1],l],d=e.get(s.document)||[];d.push(a),e.set(s.document,d);const c=s===window?0:t.nodes.getID(s.document);if(c===void 0)return;t.active()&&t.send(Ts(c,...a))}super(...o)}}s.FontFace=i};t.observer.attachContextCallback(n),n(window),t.nodes.attachNodeCallback(t.safe(s=>{if(!wt(s))return;const i=e.get(s);if(!i)return;const r=s.defaultView===window?0:t.nodes.getID(s);r!==void 0&&i.forEach(o=>{t.send(Ts(r,...o))})}))}function ga(t,e,n,s,i){t.debug.log("Openreplay: attaching axios spy to instance",e);function r(p){t.debug.log("Openreplay: capturing axios response data",p);const{headers:y,data:S,method:v,url:T,baseURL:A}=p.config,{data:B,headers:D,status:k,response:N}=p,{data:O,headers:L,status:I}=N||{},E=n.ignoreHeaders,P=Array.isArray(E)?U=>E.includes(U):()=>E;function V(U,b){P(b[0])||(U[b[0]]=b[1])}let j={},q={};y.toJSON?j=y.toJSON():y instanceof Headers?y.forEach((U,b)=>V(j,[b,U])):Array.isArray(y)?y.forEach(U=>V(j,U)):typeof y=="object"&&Object.entries(y).forEach(U=>V(j,U));const C=L||D;C.toJSON?q=C.toJSON():C instanceof Headers?C.forEach((U,b)=>V(q,[b,U])):Array.isArray(C)?C.forEach(U=>V(q,U)):typeof C=="object"&&Object.entries(C).forEach(([U,b])=>{P(U)||(q[U]=b)});const F=s({url:T,method:v||"",status:k||I||0,request:{headers:j,body:S},response:{headers:q,body:O||B}});if(!F){t.debug.log("Openreplay: empty request/response info, skipping");return}const G=p.config.__openreplay_timing,K=performance.now()-G;t.debug.log("Openreplay: final req object",F),t.send(mt("xhr",String(v),String(F.url),i(F.request),i(F.response),F.status,G+ze(),K,0))}function o(p){if(t.debug.log("Openreplay: capturing API request",p),p.__openreplay_timing=performance.now(),n.sessionTokenHeader){const y=typeof n.sessionTokenHeader=="string"?n.sessionTokenHeader:"X-OpenReplay-Session-Token",S=t.getSessionToken();S&&p.headers.set(y,S)}return p}function l(p){return n.failuresOnly||r(p),p}function a(p){return t.debug.log("Openreplay: capturing API request error",p),ma(p)&&p.response?r(p.response):p instanceof Error&&t.send(kt(p,[])),Promise.reject(p)}function d(p){t.debug.log("Openreplay: failed API request, skipping",p)}const c=e.interceptors.request.use(o,d,{synchronous:!0}),u=e.interceptors.response.use(l,a,{synchronous:!0});t.attachStopCallback(()=>{var p,y,S,v;(y=(p=e.interceptors.request).eject)==null||y.call(p,c),(v=(S=e.interceptors.response).eject)==null||v.call(S,u)})}function ma(t){return ba(t)&&t.isAxiosError===!0}function ba(t){return t!==null&&typeof t=="object"}var ve;(function(t){t[t.UNSENT=0]="UNSENT",t[t.OPENED=1]="OPENED",t[t.HEADERS_RECEIVED=2]="HEADERS_RECEIVED",t[t.LOADING=3]="LOADING",t[t.DONE=4]="DONE"})(ve||(ve={}));class yn{constructor(e=[],n,s){this.ignoredHeaders=e,this.setSessionTokenHeader=n,this.sanitize=s,this.id="",this.name="",this.method="",this.url="",this.status=0,this.statusText="",this.cancelState=0,this.readyState=0,this.header={},this.responseType="",this.requestHeader={},this.responseSize=0,this.responseSizeText="",this.startTime=0,this.endTime=0,this.duration=0,this.getData={},this.requestData=null}getMessage(){const{reqHs:e,resHs:n}=this.writeHeaders(),s={headers:e,body:this.method==="GET"?JSON.stringify(this.getData):this.requestData},i={headers:n,body:this.response},r=this.sanitize({url:this.url,method:this.method,status:this.status,request:s,response:i});if(r)return mt(this.requestType,r.method,r.url,JSON.stringify(r.request),JSON.stringify(r.response),r.status,this.startTime+ze(),this.duration,this.responseSize)}writeHeaders(){const e={};Object.entries(this.requestHeader).forEach(([s,i])=>{this.isHeaderIgnored(s)||(e[s]=i)}),this.setSessionTokenHeader((s,i)=>{e[s]=i});const n={};return Object.entries(this.header).forEach(([s,i])=>{this.isHeaderIgnored(s)||(n[s]=i)}),{reqHs:e,resHs:n}}isHeaderIgnored(e){return Array.isArray(this.ignoredHeaders)?this.ignoredHeaders.map(n=>n.toLowerCase()).includes(e.toLowerCase()):this.ignoredHeaders}}const Qe=(t,e)=>{let n="";switch(t){case"":case"text":case"json":typeof e=="string"?n=e:wn(e)||Array.isArray(e)?n=JSON.stringify(e):typeof e<"u"&&(n=Object.prototype.toString.call(e));break;case"blob":case"document":case"arraybuffer":default:typeof e<"u"&&(n=Object.prototype.toString.call(e));break}return n},vn=t=>{if(!t)return null;let e;if(typeof t=="string"){(t[0]==="{"||t[0]==="[")&&(e=t);const n=t.split("&");n.length===1?e=t:e=n.join(",")}else if(va(t)){const n=[];for(const[s,i]of t)n.push(`${s}=${typeof i=="string"?i:"[object Object]"}`);e=n.join(",")}else t instanceof Blob||t instanceof ReadableStream||t instanceof ArrayBuffer?e="byte data":wn(t)?e=t:e=`can't parse body ${typeof t}`;return e},ya=(t,e={})=>{wn(e)||(e={});let n=t?t.split("?"):[];if(n.shift(),n.length>0){n=n.join("?").split("&");for(const s of n){const i=s.split("=");try{e[i[0]]=decodeURIComponent(i[1])}catch{e[i[0]]=i[1]}}}return e};function wn(t){return t!==null&&typeof t=="object"}function va(t){return t==null||ArrayBuffer.isView(t)?!1:typeof Symbol<"u"&&typeof t[Symbol.iterator]=="function"}function Nt(t){return t<=0?"":t>=1e3*1e3?(t/1e3/1e3).toFixed(1)+" MB":t>=1e3?(t/1e3).toFixed(1)+" KB":`${t}B`}const Sn=t=>(t.startsWith("//")&&(t=`${new URL(window.location.href).protocol}${t}`),t.startsWith("http")?new URL(t):new URL(t,window.location.href));class wa{constructor(e,n){this.resp=e,this.item=n,this.mockReader()}set(e,n,s){return Reflect.set(e,n,s)}get(e,n){const s=Reflect.get(e,n);switch(n){case"arrayBuffer":case"blob":case"formData":case"json":case"text":return()=>(this.item.responseType=n.toLowerCase(),s.apply(e).then(i=>(this.item.response=Qe(this.item.responseType,i),i)))}return typeof s=="function"?s.bind(e):s}mockReader(){let e;if(!this.resp.body||typeof this.resp.body.getReader!="function")return;const n=this.resp.body.getReader;this.resp.body.getReader=()=>{const s=n.apply(this.resp.body);if(this.item.readyState===ve.DONE)return s;const i=s.read,r=s.cancel;return this.item.responseType="arraybuffer",s.read=()=>i.apply(s).then(o=>{if(!e)e=new Uint8Array(o.value);else{const l=new Uint8Array(e.length+o.value.length);l.set(e),l.set(o.value,e.length),e=l}return this.item.endTime=performance.now(),this.item.duration=this.item.endTime-(this.item.startTime||this.item.endTime),this.item.readyState=o.done?4:3,this.item.statusText=o.done?String(this.item.status):"Loading",this.item.responseSize=e.length,this.item.responseSizeText=Nt(this.item.responseSize),o.done&&(this.item.response=Qe(this.item.responseType,e)),o}),s.cancel=(...o)=>(this.item.cancelState=2,this.item.statusText="Cancel",this.item.endTime=performance.now(),this.item.duration=this.item.endTime-(this.item.startTime||this.item.endTime),this.item.response=Qe(this.item.responseType,e),r.apply(s,o)),s}}}class Sa{constructor(e,n,s,i,r,o){this.ignoredHeaders=e,this.setSessionTokenHeader=n,this.sanitize=s,this.sendMessage=i,this.isServiceUrl=r,this.tokenUrlMatcher=o}apply(e,n,s){const i=s[0],r=s[1];if(!i||typeof i!="string"&&!(i!=null&&i.url)||(i instanceof URL||typeof i=="string"?this.isServiceUrl(String(i)):this.isServiceUrl(String(i.url))))return e.apply(window,s);const l=new yn(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);return this.beforeFetch(l,i,r),this.setSessionTokenHeader((a,d)=>{if(!(this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(l.url))){if(s[1]===void 0&&s[0]instanceof Request)return s[0].headers.append(a,d);s[1]||(s[1]={}),s[1].headers===void 0&&(s[1]={...s[1],headers:{}}),s[1].headers instanceof Headers?s[1].headers.append(a,d):Array.isArray(s[1].headers)?s[1].headers.push([a,d]):s[1].headers[a]=d}}),e.apply(window,s).then(this.afterFetch(l)).catch(a=>{throw l.endTime=performance.now(),l.duration=l.endTime-(l.startTime||l.endTime),a})}beforeFetch(e,n,s){let i,r="GET",o={};if(typeof n=="string"?(r=(s==null?void 0:s.method)||"GET",i=Sn(n),o=(s==null?void 0:s.headers)||{}):(r=n.method||"GET",i=Sn(n.url),o=n.headers),e.method=r,e.requestType="fetch",e.requestHeader=o,e.url=i.toString(),e.name=(i.pathname.split("/").pop()||"")+i.search,e.status=0,e.statusText="Pending",e.readyState=1,e.startTime||(e.startTime=performance.now()),Object.prototype.toString.call(o)==="[object Headers]"){e.requestHeader={};for(const[l,a]of o)e.requestHeader[l]=a}else e.requestHeader=o;if(i.search&&i.searchParams){e.getData={};for(const[l,a]of i.searchParams)e.getData[l]=a}s!=null&&s.body&&(e.requestData=vn(s.body))}afterFetch(e){return n=>{e.endTime=performance.now(),e.duration=e.endTime-(e.startTime||e.endTime),e.status=n.status,e.statusText=String(n.status);let s=!1;e.header={};for(const[i,r]of n.headers)e.header[i]=r,s=r.toLowerCase().indexOf("chunked")>-1?!0:s;return s?e.readyState=3:(e.readyState=4,this.handleResponseBody(n.clone(),e).then(i=>{e.responseSize=typeof i=="string"?i.length:i.byteLength,e.responseSizeText=Nt(e.responseSize),e.response=Qe(e.responseType,i);const r=e.getMessage();r&&this.sendMessage(r)}).catch(i=>{if(i.name!=="AbortError")throw i})),new Proxy(n,new wa(n,e))}}handleResponseBody(e,n){const s=e.headers.get("content-type");return s&&s.includes("application/json")?(n.responseType="json",e.text()):s&&(s.includes("text/html")||s.includes("text/plain"))?(n.responseType="text",e.text()):(n.responseType="arraybuffer",e.arrayBuffer())}}class xa{static create(e,n,s,i,r,o){return new Proxy(fetch,new Sa(e,n,s,i,r,o))}}class ka{constructor(e,n,s,i,r,o,l){this.ignoredHeaders=n,this.setSessionTokenHeader=s,this.sanitize=i,this.sendMessage=r,this.isServiceUrl=o,this.tokenUrlMatcher=l,this.XMLReq=e,this.XMLReq.onreadystatechange=()=>{this.onReadyStateChange()},this.XMLReq.onabort=()=>{this.onAbort()},this.XMLReq.ontimeout=()=>{this.onTimeout()},this.item=new yn(n,s,i),this.item.requestType="xhr"}get(e,n){switch(n){case"open":return this.getOpen(e);case"send":return this.setSessionTokenHeader((i,r)=>{this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(this.item.url)||e.setRequestHeader(i,r)}),this.getSend(e);case"setRequestHeader":return this.getSetRequestHeader(e);default:const s=Reflect.get(e,n);return typeof s=="function"?s.bind(e):s}}set(e,n,s){switch(n){case"onreadystatechange":return this.setOnReadyStateChange(e,n,s);case"onabort":return this.setOnAbort(e,n,s);case"ontimeout":return this.setOnTimeout(e,n,s)}return Reflect.set(e,n,s)}onReadyStateChange(){if(!(this.item.url&&this.isServiceUrl(this.item.url))&&(this.item.readyState=this.XMLReq.readyState,this.item.responseType=this.XMLReq.responseType,this.item.endTime=performance.now(),this.item.duration=this.item.endTime-this.item.startTime,this.updateItemByReadyState(),setTimeout(()=>{this.item.response=Qe(this.item.responseType,this.item.response)},0),this.XMLReq.readyState===ve.DONE)){const e=this.item.getMessage();e&&this.sendMessage(e)}}onAbort(){this.item.cancelState=1,this.item.statusText="Abort";const e=this.item.getMessage();e&&this.sendMessage(e)}onTimeout(){this.item.cancelState=3,this.item.statusText="Timeout";const e=this.item.getMessage();e&&this.sendMessage(e)}getOpen(e){const n=Reflect.get(e,"open");return(...s)=>{var o,l;const i=s[0],r=s[1];return this.item.method=i?i.toUpperCase():"GET",this.item.url=((o=r.toString)==null?void 0:o.call(r))||"",this.item.name=((l=this.item.url)==null?void 0:l.replace(new RegExp("/*$"),"").split("/").pop())??"",this.item.getData=ya(this.item.url,{}),n.apply(e,s)}}getSend(e){const n=Reflect.get(e,"send");return(...s)=>{const i=s[0];return this.item.requestData=vn(i),n.apply(e,s)}}getSetRequestHeader(e){const n=Reflect.get(e,"setRequestHeader");return(...s)=>(this.item.requestHeader||(this.item.requestHeader={}),this.item.requestHeader[s[0]]=s[1],n.apply(e,s))}setOnReadyStateChange(e,n,s){return Reflect.set(e,n,(...i)=>{this.onReadyStateChange(),s==null||s.apply(e,i)})}setOnAbort(e,n,s){return Reflect.set(e,n,(...i)=>{this.onAbort(),s.apply(e,i)})}setOnTimeout(e,n,s){return Reflect.set(e,n,(...i)=>{this.onTimeout(),s.apply(e,i)})}updateItemByReadyState(){switch(this.XMLReq.readyState){case ve.UNSENT:case ve.OPENED:this.item.status=ve.UNSENT,this.item.statusText="Pending",this.item.startTime||(this.item.startTime=performance.now());break;case ve.HEADERS_RECEIVED:this.item.status=this.XMLReq.status,this.item.statusText="Loading",this.item.header={};const e=this.XMLReq.getAllResponseHeaders()||"",n=e.split(`
|
|
666
|
-
`);for(let
|
|
667
|
-
If you're using serverside rendering in your app, make sure that tracker is loaded dynamically, otherwise ${t} won't be tracked.`);function Ca(t,e,n,s,i,r,o){var l;t.XMLHttpRequest?t.XMLHttpRequest=Ta.create(e,n,s,i,r,o):fi("XMLHttpRequest"),t.fetch?t.fetch=xa.create(e,n,s,i,r,o):fi("fetch"),(l=t==null?void 0:t.navigator)!=null&&l.sendBeacon&&(t.navigator.sendBeacon=qe.create(e,n,s,i,r))}function xn(t){return t.__or_req_data__||(t.__or_req_data__={body:void 0,headers:{}}),t.__or_req_data__}function pi(t){return typeof t=="string"?t.toUpperCase():"GET"}function _a(t,e={}){const n=Object.assign({failuresOnly:!1,ignoreHeaders:["cookie","set-cookie","authorization"],capturePayload:!1,sessionTokenHeader:!1,captureInIframes:!0,axiosInstances:void 0,useProxy:!0},e);n.useProxy===!1&&t.debug.warn("Network module is migrating to proxy api, to gradually migrate and test it set useProxy to true");const s=n.ignoreHeaders,i=Array.isArray(s)?c=>s.includes(c):()=>s,r=n.sessionTokenHeader===!0?"X-OpenReplay-SessionToken":n.sessionTokenHeader;function o(c){if(r){const u=t.getSessionToken();u&&t.safe(c)(r,u)}}function l(c){if(n.capturePayload||(delete c.request.body,delete c.response.body),n.sanitizer){const u=c.response.body;if(typeof u=="string")try{c.response.body=JSON.parse(u)}catch{}return n.sanitizer(c)}return c}function a(c){if(c&&typeof c.body!="string")try{c.body=JSON.stringify(c.body)}catch{c.body="<unable to stringify>",t.notify.warn("Openreplay fetch couldn't stringify body:",c.body)}return JSON.stringify(c)}const d=c=>{if(n.useProxy)return Ca(c,n.ignoreHeaders,o,l,D=>t.send(D),D=>t.isServiceURL(D),n.tokenUrlMatcher);const u=c.fetch.bind(c),p=(D,k={})=>{if(!(typeof D=="string"||D instanceof URL)||t.isServiceURL(String(D)))return u(D,k);o(function(O,L){k.headers===void 0&&(k.headers={}),k.headers instanceof Headers?k.headers.append(O,L):Array.isArray(k.headers)?k.headers.push([O,L]):k.headers[O]=L});const N=performance.now();return u(D,k).then(O=>{const L=performance.now()-N;if(n.failuresOnly&&O.status<400)return O;const I=O.clone();return I.text().then(E=>{const P={},V={};if(s!==!0){const C=([F,G])=>{i(F)||(P[F]=G)};k.headers instanceof Headers?k.headers.forEach((F,G)=>C([G,F])):Array.isArray(k.headers)?k.headers.forEach(C):typeof k.headers=="object"&&Object.entries(k.headers).forEach(C),I.headers.forEach((F,G)=>{i(G)||(V[G]=F)})}const j=pi(k.method),q=l({url:String(D),method:j,status:I.status,request:{headers:P,body:k.body||null},response:{headers:V,body:E}});q&&t.send(mt("fetch",j,String(q.url),a(q.request),a(q.response),I.status,N+ze(),L,0))}).catch(E=>t.debug.error("Could not process Fetch response:",E)),O})};c.fetch=p;const y=c.XMLHttpRequest.prototype.open,S=c.XMLHttpRequest.prototype.setRequestHeader,v=c.XMLHttpRequest.prototype.send;function T(D,k){const N=this;o((L,I)=>N.setRequestHeader(L,I));let O=0;return N.addEventListener("loadstart",L=>{O=L.timeStamp}),N.addEventListener("load",t.safe(L=>{const{headers:I,body:E}=xn(N),P=O>0?L.timeStamp-O:0,j=(N.getAllResponseHeaders()||"").trim().split(/[\r\n]+/),q={};j.forEach(function(G){const K=G.split(": "),U=K.shift();i(U)||(q[U]=K.join(": "))});const C=pi(D),F=l({url:String(k),method:C,status:N.status,request:{headers:I,body:E||null},response:{headers:q,body:N.response}});F&&t.send(mt("xhr",C,String(F.url),a(F.request),a(F.response),N.status,O+ze(),P,0))})),y.apply(this,arguments)}function A(D){const k=xn(this);return k.body=D,v.apply(this,arguments)}function B(D,k){if(!i(D)){const N=xn(this);N.headers[D]=k}return S.apply(this,arguments)}n.axiosInstances||(c.XMLHttpRequest.prototype.open=T,c.XMLHttpRequest.prototype.send=A,c.XMLHttpRequest.prototype.setRequestHeader=B)};d(window),n.axiosInstances&&n.axiosInstances.forEach(c=>{ga(t,c,n,l,a)}),n.captureInIframes&&t.observer.attachContextCallback(t.safe(d))}function Na(t){t.attachEventListener(document,"selectionchange",()=>{const e=document.getSelection();if(e!==null&&!e.isCollapsed){const n=t.nodes.getID(e.anchorNode),s=t.nodes.getID(e.focusNode),i=e.toString().replace(/\s+/g," ");n&&s&&t.send(Ns(n,s,i))}else t.send(Ns(-1,-1,""))})}function Oa(t){function e(){document.hidden||(t.debug.log("Openreplay: tab change to"+t.session.getTabId()),t.send(bt(t.session.getTabId())))}t.attachEventListener(window,"focus",e,!1,!1)}const Ot="/installation/javascript-sdk";function Ra(t){if(t==null)return console.error(`OpenReplay: invalid options argument type. Please, check documentation on ${gt}${Ot}`),!1;if(typeof t.projectKey!="string")if(typeof t.projectKey!="number"){if(typeof t.projectID!="number")return console.error(`OpenReplay: projectKey is missing or wrong type (string is expected). Please, check ${gt}${Ot} for more information.`),!1;t.projectKey=t.projectID.toString(),Ce("`projectID` option","`projectKey` option",Ot)}else console.warn("OpenReplay: projectKey is expected to have a string type."),t.projectKey=t.projectKey.toString();return t.sessionToken!=null&&Ce("`sessionToken` option","`sessionHash` start() option","/"),!0}class Aa{constructor(e){var l;if(this.options=e,this.app=null,this.crossdomainMode=!1,this.checkDoNotTrack=()=>this.options.respectDoNotTrack&&(navigator.doNotTrack=="1"||window.doNotTrack=="1"),this.signalStartIssue=(a,d)=>{const c=this.checkDoNotTrack(),u=new XMLHttpRequest,p=this.options.ingestPoint||Ws;u.open("POST",p+"/v1/web/not-started"),u.send(JSON.stringify({trackerVersion:"14.0.4",projectKey:this.options.projectKey,doNotTrack:c,reason:d.length?`missing api: ${d.join(",")}`:a}))},this.restartCanvasTracking=()=>{this.app!==null&&this.app.restartCanvasTracking()},this.handleError=(a,d={})=>{if(this.app!==null){if(a instanceof Error){const c=kt(a,[],d);this.app.send(c)}else if(a instanceof ErrorEvent||"PromiseRejectionEvent"in window&&a instanceof PromiseRejectionEvent){const c=Qs(a,void 0,d);c!=null&&this.app.send(c)}}},this.crossdomainMode=!!(rr()&&((l=e.crossdomain)!=null&&l.enabled)),!be||!Ra(e))return;if(window.__OPENREPLAY__){console.error("OpenReplay: one tracker instance has been initialised already");return}if(!e.__DISABLE_SECURE_MODE&&location.protocol!=="https:"){console.error("OpenReplay: Your website must be publicly accessible and running on SSL in order for OpenReplay to properly capture and replay the user session. You can disable this check by setting `__DISABLE_SECURE_MODE` option to `true` if you are testing in localhost. Keep in mind, that asset files on a local machine are not available to the outside world. This might affect tracking if you use css files.");return}const n=this.checkDoNotTrack(),s=[],i=["Map","Set","MutationObserver","performance","timing","startsWith","Blob","Worker"];if(n)s.push("doNotTrack");else for(const a of i)if(a==="timing"){if("performance"in window&&!(a in performance)){s.push(a);break}}else if(a==="startsWith"){if(!(a in String.prototype)){s.push(a);break}}else if(!(a in window)){s.push(a);break}if(s.length>0){const a=s.join(",");console.error(`OpenReplay: browser doesn't support API required for tracking or doNotTrack is set to 1. Reason: ${a}`),this.signalStartIssue("missing_api",s);return}const r=new No(e.projectKey,e.sessionToken,e,this.signalStartIssue,this.crossdomainMode);this.app=r,this.crossdomainMode||(la(r),Oo(r),Hr(r,e),Oa(r)),ia(r,e.mouse),ca(r,this.crossdomainMode),ua(r),ha(r),Lo(r,e),Bo(r,e),Uo(r),Go(r,e),aa(r,e),fa(r),pa(r),_a(r,e.network),Na(r),window.__OPENREPLAY__=this,e.flags&&e.flags.onFlagsLoad&&this.onFlagsLoad(e.flags.onFlagsLoad);const o=window.open;(e.autoResetOnWindowOpen||e.resetTabOnWindowOpen)&&(r.attachStartCallback(()=>{const a=r.getTabId(),d=r.sessionStorage??window.sessionStorage;window.open=function(...c){return e.autoResetOnWindowOpen&&r.resetNextPageSession(!0),e.resetTabOnWindowOpen&&d.removeItem(e.session_tabid_key||"__openreplay_tabid"),r.resetNextPageSession(!1),d.setItem(e.session_tabid_key||"__openreplay_tabid",a),o.call(window,...c)}}),r.attachStopCallback(()=>{window.open=o}))}isFlagEnabled(e){return this.featureFlags.isFlagEnabled(e)}onFlagsLoad(e){var n;(n=this.app)==null||n.featureFlags.onFlagsLoad(e)}clearPersistFlags(){var e;(e=this.app)==null||e.featureFlags.clearPersistFlags()}reloadFlags(){var e;return(e=this.app)==null?void 0:e.featureFlags.reloadFlags()}getFeatureFlag(e){var n;return(n=this.app)==null?void 0:n.featureFlags.getFeatureFlag(e)}getAllFeatureFlags(){var e;return(e=this.app)==null?void 0:e.featureFlags.flags}use(e){return e(this.app,this.options)}isActive(){return this.app===null?!1:this.app.active()}trackWs(e){if(this.app!==null)return this.app.trackWs(e)}start(e){return this.browserEnvCheck()?this.app===null?Promise.reject("Browser doesn't support required api, or doNotTrack is active."):this.app.start(e):Promise.reject("Trying to start not in browser.")}browserEnvCheck(){return be?!0:(console.error(`OpenReplay: you are trying to start Tracker on a node.js environment. If you want to use OpenReplay with SSR, please, use componentDidMount or useEffect API for placing the \`tracker.start()\` line. Check documentation on ${gt}${Ot}`),!1)}coldStart(e,n){if(this.browserEnvCheck()){if(this.app===null)return Promise.reject("Tracker not initialized");this.app.coldStart(e,n)}else return Promise.reject("Trying to start not in browser.")}startOfflineRecording(e,n){return this.browserEnvCheck()?this.app===null?Promise.reject("Tracker not initialized"):this.app.offlineRecording(e,n):Promise.reject("Trying to start not in browser.")}uploadOfflineRecording(){if(this.app!==null)return this.app.uploadOfflineRecording()}stop(){if(this.app!==null)return this.app.stop(),this.app.session.getSessionHash()}forceFlushBatch(){this.app!==null&&this.app.forceFlushBatch()}getSessionToken(){return this.app===null?null:this.app.getSessionToken()}getSessionInfo(){return this.app===null?null:this.app.session.getInfo()}getSessionID(){return this.app===null?null:this.app.getSessionID()}getTabId(){return this.app===null?null:this.app.getTabId()}getUxId(){return this.app===null?null:this.app.getUxtId()}sessionID(){return Ce("'sessionID' method","'getSessionID' method","/"),this.getSessionID()}getSessionURL(e){if(this.app!==null)return this.app.getSessionURL(e)}setUserID(e){typeof e=="string"&&this.app!==null&&this.app.session.setUserID(e)}userID(e){Ce("'userID' method","'setUserID' method","/"),this.setUserID(e)}setUserAnonymousID(e){typeof e=="string"&&this.app!==null&&this.app.send(Ir(e))}userAnonymousID(e){Ce("'userAnonymousID' method","'setUserAnonymousID' method","/"),this.setUserAnonymousID(e)}setMetadata(e,n){typeof e=="string"&&typeof n=="string"&&this.app!==null&&this.app.session.setMetadata(e,n)}metadata(e,n){Ce("'metadata' method","'setMetadata' method","/"),this.setMetadata(e,n)}event(e,n=null,s=!1){if(typeof e=="string"&&this.app!==null){if(s)return this.issue(e,n);try{n=JSON.stringify(n)}catch{return}this.app.send(Tr(e,n))}}issue(e,n=null){if(typeof e=="string"&&this.app!==null){try{n=JSON.stringify(n)}catch{return}this.app.send(Ar(e,n))}}}const Da=`
|
|
663
|
+
`),u=[],p=2,y=c.length;p<y;p+=2){var S=d.exec(c[p]);S&&u.push(new i({fileName:S[2],lineNumber:S[1],source:c[p]}))}return u},parseOpera10:function(a){for(var d=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,c=a.stacktrace.split(`
|
|
664
|
+
`),u=[],p=0,y=c.length;p<y;p+=2){var S=d.exec(c[p]);S&&u.push(new i({functionName:S[3]||void 0,fileName:S[2],lineNumber:S[1],source:c[p]}))}return u},parseOpera11:function(a){var d=a.stack.split(`
|
|
665
|
+
`).filter(function(c){return!!c.match(s)&&!c.match(/^Error created at/)},this);return d.map(function(c){var u=c.split("@"),p=this.extractLocation(u.pop()),y=u.shift()||"",S=y.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;y.match(/\(([^)]*)\)/)&&(v=y.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var T=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new i({functionName:S,args:T,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:c})},this)}}})})(Xi);var Mo=Xi.exports;const Po=Kn(Mo);function Yi(t){return[{columnNumber:t.colno,lineNumber:t.lineno,fileName:t.filename,functionName:"",source:""}]}function kt(t,e,n={}){let i=e;try{i=Po.parse(t)}catch{}return Yt(t.name,t.message,JSON.stringify(i),JSON.stringify(n))}function Qi(t,e=window,n={}){if(t instanceof ErrorEvent){if(t.error instanceof Error)return kt(t.error,Yi(t),n);{let[i,s]=t.message.split(":");return s||(i="Error",s=t.message),Yt(i,s,JSON.stringify(Yi(t)),JSON.stringify(n))}}else if("PromiseRejectionEvent"in e&&t instanceof e.PromiseRejectionEvent){if(t.reason instanceof Error)return kt(t.reason,[],n);{let i;try{i=JSON.stringify(t.reason)}catch{i=String(t.reason)}return Yt("Unhandled Promise Rejection",i,"[]",JSON.stringify(n))}}return null}function Bo(t,e){const n=Object.assign({captureExceptions:!0},e);function i(s){function r(o){const l=Qi(o,s);l!=null&&t.send(l)}t.attachEventListener(s,"unhandledrejection",r),t.attachEventListener(s,"error",r)}n.captureExceptions&&(t.observer.attachContextCallback(i),i(window))}function Zi(t,e=document.location){return t=t.trim(),t.startsWith("//")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("data:")?t:t.startsWith("/")?e.origin+t:e.origin+e.pathname+t}function jo(t){return tr&&(t.startsWith("data:image/svg+xml")||t.match(/.svg$|/i))}const zo="https://static.openreplay.com/tracker/placeholder.jpeg";function Uo(t){function e(l,a){t.attributeSender.sendSetAttribute(l,"src",zo);const{width:d,height:c}=a.getBoundingClientRect();a.hasAttribute("width")||t.attributeSender.sendSetAttribute(l,"width",String(d)),a.hasAttribute("height")||t.attributeSender.sendSetAttribute(l,"height",String(c))}const n=function(l,a){const{srcset:d}=a;if(!d)return;const c=d.split(d.match(/,\s+/)?/,\s+/:",").map(u=>Zi(u)).join(", ");t.attributeSender.sendSetAttribute(l,"srcset",c)},i=function(l,a){a.src.length>nr&&e(l,a),t.send(Kt(l,"src",a.src,t.getBaseHref()))},s=t.safe(function(l){const a=Zi(l.src||"");gi(a)&&t.send(Oi(t.timestamp(),0,0,0,0,0,a,"img",0,!1))}),r=t.safe(function(l){const a=t.nodes.getID(l);a!==void 0&&l.complete&&(l.naturalHeight===0&&l.naturalWidth===0&&!jo(l.src)?s(l):t.sanitizer.isHidden(a)||t.sanitizer.isObscured(a)?e(a,l):(i(a,l),n(a,l)))}),o=yi(t.safe(l=>{for(const a of l)if(a.type==="attributes"){const d=a.target,c=t.nodes.getID(d);if(c===void 0)return;a.attributeName==="src"&&i(c,d),a.attributeName==="srcset"&&n(c,d)}}));t.attachStopCallback(()=>{o.disconnect()}),t.nodes.attachNodeCallback(l=>{Q(l,"img")&&(t.nodes.attachNodeListener(l,"error",()=>s(l)),t.nodes.attachNodeListener(l,"load",()=>r(l)),r(l),o.observe(l,{attributes:!0,attributeFilter:["src","srcset"]}))})}const Ho=["text","password","email","search","number","range","date","tel","time"];function $o(t){return Q(t,"textarea")?!0:Q(t,"input")?Ho.includes(t.type):!1}function qo(t){if(!Q(t,"input"))return!1;const e=t.type;return e==="checkbox"||e==="radio"}const Wo=be&&"labels"in HTMLInputElement.prototype?t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Q(e,"label"))return e;const n=t.labels;if(n!==null&&n.length===1)return n[0]}:t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Q(e,"label"))return e;const n=t.id;if(n){const i=t.ownerDocument.querySelectorAll('label[for="'+n+'"]');if(i!==null&&i.length===1)return i[0]}};function es(t){let e=Gt(t);if(e===null){const n=Wo(t);e=n&&n.innerText||t.placeholder||t.name||t.id||t.className||t.type}return pi(e).slice(0,100)}const $e={Plain:0,Obscured:1,Hidden:2};function Go(t,e){const n=Object.assign({obscureInputNumbers:!0,obscureInputEmails:!0,defaultInputMode:$e.Obscured,obscureInputDates:!1},e);function i(c,u){let p=u.value,y=n.defaultInputMode;u.type==="password"||t.sanitizer.isHidden(c)?y=$e.Hidden:(t.sanitizer.isObscured(c)||y===$e.Plain&&(n.obscureInputNumbers&&u.type!=="date"&&/\d\d\d\d/.test(p)||n.obscureInputDates&&u.type==="date"||n.obscureInputEmails&&(u.type==="email"||~p.indexOf("@"))))&&(y=$e.Obscured);let S=0;switch(y){case $e.Hidden:S=-1,p="";break;case $e.Obscured:S=p.length,p="";break}return{value:p,mask:S}}function s(c,u){const{value:p,mask:y}=i(c,u);t.send(yr(c,p,y))}const r=new Map,o=new Map;t.attachStopCallback(()=>{r.clear(),o.clear()});function l(c,u){r.get(c)!==u.value&&(r.set(c,u.value),s(c,u))}function a(c,u){o.get(c)!==u&&(o.set(c,u),t.send(vr(c,u)))}t.ticker.attach(()=>{r.forEach((c,u)=>{const p=t.nodes.getNode(u);if(!p)return r.delete(u);l(u,p)}),o.forEach((c,u)=>{const p=t.nodes.getNode(u);if(!p)return o.delete(u);a(u,p.checked)})},3);function d(c,u,p,y){const{value:S,mask:v}=i(c,u),T=es(u);t.send(Mr(c,S,v!==0,T,p,y))}t.nodes.attachNodeCallback(t.safe(c=>{const u=t.nodes.getID(c);if(u!==void 0){if(Q(c,"select")&&(s(u,c),t.nodes.attachNodeListener(c,"change",()=>s(u,c))),$o(c)){l(u,c);let p=0,y=0,S=0;const v=()=>{p=pe()},T=()=>{y===0&&p!==0&&(y=pe()-p)},A=()=>{p!==0&&(S=pe()-p),d(u,c,y,S),y=0,S=0,p=0};t.nodes.attachNodeListener(c,"focus",v),t.nodes.attachNodeListener(c,"input",T),t.nodes.attachNodeListener(c,"change",A);return}if(qo(c)){a(u,c.checked),t.nodes.attachNodeListener(c,"change",()=>a(u,c.checked));return}}}))}let de,pn,ts;function Vo(t,e){if(ts=new Date,t.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(t.tagName.toLowerCase()==="html")return"html";const n={root:document.body,idName:s=>!0,className:s=>!0,tagName:s=>!0,attr:(s,r)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};de={...n,...e},pn=Ko(de.root,n);let i=Tt(t,"all",()=>Tt(t,"two",()=>Tt(t,"one",()=>Tt(t,"none"))));if(i){const s=as(cs(i,t));return s.length>0&&(i=s[0]),Et(i)}else throw new Error("Selector was not found.")}function Ko(t,e){return t.nodeType===Node.DOCUMENT_NODE?t:t===e.root?t.ownerDocument:t}function Tt(t,e,n){let i=null,s=[],r=t,o=0;for(;r;){const l=new Date().getTime()-ts.getTime();if(de.timeoutMs!==void 0&&l>de.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${l}ms`);let a=Ct(Xo(r))||Ct(...Jo(r))||Ct(...Yo(r))||Ct(Qo(r))||[rs()];const d=Zo(r);if(e=="all")d&&(a=a.concat(a.filter(gn).map(c=>It(c,d))));else if(e=="two")a=a.slice(0,1),d&&(a=a.concat(a.filter(gn).map(c=>It(c,d))));else if(e=="one"){const[c]=a=a.slice(0,1);d&&gn(c)&&(a=[It(c,d)])}else e=="none"&&(a=[rs()],d&&(a=[It(a[0],d)]));for(let c of a)c.level=o;if(s.push(a),s.length>=de.seedMinLength&&(i=ns(s,n),i))break;r=r.parentElement,o++}return i||(i=ns(s,n)),!i&&n?n():i}function ns(t,e){const n=as(os(t));if(n.length>de.threshold)return e?e():null;for(let i of n)if(ss(i))return i;return null}function Et(t){let e=t[0],n=e.name;for(let i=1;i<t.length;i++){const s=t[i].level||0;e.level===s-1?n=`${t[i].name} > ${n}`:n=`${t[i].name} ${n}`,e=t[i]}return n}function is(t){return t.map(e=>e.penalty).reduce((e,n)=>e+n,0)}function ss(t){const e=Et(t);switch(pn.querySelectorAll(e).length){case 0:throw new Error(`Can't select any node with this selector: ${e}`);case 1:return!0;default:return!1}}function Xo(t){const e=t.getAttribute("id");return e&&de.idName(e)?{name:"#"+CSS.escape(e),penalty:0}:null}function Jo(t){return Array.from(t.attributes).filter(n=>de.attr(n.name,n.value)).map(n=>({name:`[${CSS.escape(n.name)}="${CSS.escape(n.value)}"]`,penalty:.5}))}function Yo(t){return Array.from(t.classList).filter(de.className).map(n=>({name:"."+CSS.escape(n),penalty:1}))}function Qo(t){const e=t.tagName.toLowerCase();return de.tagName(e)?{name:e,penalty:2}:null}function rs(){return{name:"*",penalty:3}}function Zo(t){const e=t.parentNode;if(!e)return null;let n=e.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==t);)n=n.nextSibling;return i}function It(t,e){return{name:t.name+`:nth-child(${e})`,penalty:t.penalty+1}}function gn(t){return t.name!=="html"&&!t.name.startsWith("#")}function Ct(...t){const e=t.filter(ea);return e.length>0?e:null}function ea(t){return t!=null}function*os(t,e=[]){if(t.length>0)for(let n of t[0])yield*os(t.slice(1,t.length),e.concat(n));else yield e}function as(t){return[...t].sort((e,n)=>is(e)-is(n))}function*cs(t,e,n={counter:0,visited:new Map}){if(t.length>2&&t.length>de.optimizedMinLength)for(let i=1;i<t.length-1;i++){if(n.counter>de.maxNumberOfTries)return;n.counter+=1;const s=[...t];s.splice(i,1);const r=Et(s);if(n.visited.has(r))return;ss(s)&&ta(s,e)&&(yield s,n.visited.set(r,!0),yield*cs(s,e,n))}}function ta(t,e){return pn.querySelector(Et(t))===e}function na(t,e,n){return Vo(t,{root:e.body,seedMinLength:3,optimizedMinLength:(n==null?void 0:n.minSelectorDepth)||2,threshold:(n==null?void 0:n.nthThreshold)||1e3,maxNumberOfTries:(n==null?void 0:n.maxOptimiseTries)||1e4})}function mn(t){const e=t.tagName.toUpperCase();return e==="BUTTON"||e==="A"||e==="LI"||e==="SELECT"||e==="TR"||e==="TH"||t.onclick!=null||t.getAttribute("role")==="button"}function ls(t,e){return t instanceof Element?ia(t,e):null}function ia(t,e){let n=t;for(;n!==null&&n!==e.documentElement;){if(Re(n,"masked"))return null;n=n.parentElement}if(sn(t)){let i=t.ownerSVGElement;for(;i!==null;)t=i,i=i.ownerSVGElement}for(n=t;n!==null&&n!==e.documentElement;){const i=n.tagName.toUpperCase();if(i==="LABEL")return null;if(i==="INPUT"||mn(n)||Gt(n)!==null)return n;n=n.parentElement}return t===e.documentElement?null:t}function sa(t,e){const{disableClickmaps:n=!1}=e||{};function i(k){const N=Gt(k);if(N!==null)return N;if(Q(k,"input"))return es(k);if(mn(k)){let O="";return k instanceof HTMLElement&&(O=t.sanitizer.getInnerTextSecure(k)),O=O||k.id||k.className,pi(O).slice(0,100)}return""}let s=-1,r=-1,o=!1,l=null,a=0,d={},c=0,u=0,p=0,y=0,S;const v=.008,T=225;function A(){const k=y/T;if(!c){c=k;return}const N=(k-c)/T;p>4&&N>v&&t.send(Pr(pe())),y=0,p=0,c=k}t.attachStartCallback(()=>{S=setInterval(()=>A(),T)}),t.attachStopCallback(()=>{s=-1,r=-1,o=!1,l=null,d={},S&&clearInterval(S)});const B=()=>{o&&(t.send(wr(s,r)),o=!1)},D=(k,N=!1)=>{function O(I,E,P){return d[I]=d[I]||na(E,k,P)}const L=N?t.attachEventListener.bind(t):t.nodes.attachNodeListener.bind(t.nodes);L(k.documentElement,"mouseover",I=>{const E=ls(I.target,k);E!==l&&(l=E,a=performance.now())}),L(k,"mousemove",I=>{const[E,P]=t.observer.getDocumentOffset(k);s=I.clientX+E,r=I.clientY+P,o=!0;const V=Math.sign(I.movementX);y+=Math.abs(I.movementX)+Math.abs(I.movementY),V!==u&&(u=V,p++)},!1),L(k,"click",I=>{const E=ls(I.target,k);if(!I.clientX&&!I.clientY||E===null)return;const P=t.nodes.getID(E);if(P!==void 0){const V=I.pageX,j=I.pageY,q=k.documentElement.scrollWidth,C=k.documentElement.scrollHeight,F=ds(V/q),G=ds(j/C);B(),t.send(Dr(P,l===E?Math.round(performance.now()-a):0,i(E),mn(E)&&!n?O(P,E,e):"",F,G),!0)}l=null})};t.nodes.attachNodeCallback(k=>{wt(k)&&D(k)}),D(document,!0),t.ticker.attach(B,(e==null?void 0:e.trackingOffset)||7)}function ds(t){return Math.round(t*1e4)}function ra(t){const e=[],n=document.getElementsByTagName("*"),i=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let s=0;s<n.length;s++){const r=n[s];let o="";if(Q(r,"img")&&(o=r.currentSrc||r.src),!o){const S=getComputedStyle(r).getPropertyValue("background-image");if(S){const v=i.exec(S);v!==null&&(o=v[1],(o.startsWith('"')||o.startsWith("'"))&&(o=o.substr(1,o.length-2)))}}if(!o)continue;const l=o.substr(0,10)==="data:image"?0:t[o];if(l===void 0)continue;const a=r.getBoundingClientRect(),d=Math.max(a.top,0),c=Math.max(a.left,0),u=Math.min(a.bottom,window.innerHeight||document.documentElement&&document.documentElement.clientHeight||0),p=Math.min(a.right,window.innerWidth||document.documentElement&&document.documentElement.clientWidth||0);if(u<=d||p<=c)continue;const y=(u-d)*(p-c);e.push({time:l,area:y})}return e}function oa(t,e){let n=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,i=n*t;for(let s=0;s<e.length;s++){const{time:r,area:o}=e[s];n+=o,i+=o*(r>t?r:t)}return n===0?0:i/n}function aa(t,e){const n=Object.assign({captureResourceTimings:!0,capturePageLoadTimings:!0,capturePageRenderTimings:!0,excludedResourceUrls:[]},e);if("PerformanceObserver"in window||(n.captureResourceTimings=!1),!n.captureResourceTimings)return;let i={};function s(d){var u;if(d.duration<0||!gi(d.name)||t.isServiceURL(d.name))return;i!==null&&(i[d.name]=d.startTime+d.duration);let c=!1;(u=n.excludedResourceUrls)==null||u.forEach(p=>{if(d.name.startsWith(p)){c=!0;return}}),!c&&t.send(Oi(d.startTime+ze(),d.duration,d.responseStart&&d.startTime?d.responseStart-d.startTime:0,d.transferSize>d.encodedBodySize?d.transferSize-d.encodedBodySize:0,d.encodedBodySize||0,d.decodedBodySize||0,d.name,d.initiatorType,d.transferSize,d.responseStatus&&d.responseStatus===304||d.transferSize===0))}const r=new PerformanceObserver(d=>d.getEntries().forEach(s));let o;t.attachStartCallback(function({sessionID:d}){d!==o&&(performance.getEntriesByType("resource").forEach(s),o=d),r.observe({entryTypes:["resource"]})}),t.attachStopCallback(function(){r.disconnect()});let l=0,a=0;if(n.capturePageLoadTimings){let d=!1;t.ticker.attach(()=>{if(!d&&((l===0||a===0)&&performance.getEntriesByType("paint").forEach(c=>{const{name:u,startTime:p}=c;switch(u){case"first-paint":l=p;break;case"first-contentful-paint":a=p;break}}),performance.timing.loadEventEnd||performance.now()>3e4)){d=!0;const{navigationStart:c,requestStart:u,responseStart:p,responseEnd:y,domContentLoadedEventStart:S,domContentLoadedEventEnd:v,loadEventStart:T,loadEventEnd:A}=performance.timing;t.send(xr(u-c||0,p-c||0,y-c||0,S-c||0,v-c||0,T-c||0,A-c||0,l,a))}},30)}if(n.capturePageRenderTimings){let d=0,c=0,u=0,p=null,y=!1;t.ticker.attach(()=>{if(y)return;const S=performance.now();if(i!==null&&(d=Math.max.apply(null,Object.keys(i).map(v=>i[v])),S-d>1e3&&(p=ra(i),i=null)),u!==null&&(S-u>50&&(c=S),u=S-c>5e3?null:S),p!==null&&u===null||S>3e4){y=!0,i=null;const v=p===null?0:oa(a||l,p),{domContentLoadedEventEnd:T,navigationStart:A}=performance.timing,B=u===null?Math.max(c,a,T-A||0):0;t.send(kr(v,a>d?a:d,B))}})}}function bn(t){const e=t.defaultView;return[e&&e.scrollX||t.documentElement&&t.documentElement.scrollLeft||t.body&&t.body.scrollLeft||0,e&&e.scrollY||t.documentElement&&t.documentElement.scrollTop||t.body&&t.body.scrollTop||0]}function ca(t,e){let n=!1;const i=new Map;function s(l){Ui(l)&&(ke(l)&&i.set(l,[l.scrollLeft,l.scrollTop]),wt(l)&&i.set(l,bn(l)))}const r=t.safe(()=>{e||t.send(dr(...bn(document)))}),o=t.safe((l,a)=>{const d=t.nodes.getID(a);d!==void 0&&t.send(br(d,l[0],l[1]))});t.attachStartCallback(r),t.attachStopCallback(()=>{n=!1,i.clear()}),t.nodes.attachNodeCallback((l,a)=>{a&&(ke(l)&&l.scrollLeft+l.scrollTop>0?i.set(l,[l.scrollLeft,l.scrollTop]):wt(l)&&i.set(l,bn(l))),St(l)&&t.nodes.attachNodeListener(l,"scroll",d=>{s(d.target)})}),t.attachEventListener(document,"scroll",l=>{const a=l.target;if(a===document){n=!0;return}s(a)}),t.ticker.attach(()=>{n&&(r(),n=!1),i.forEach(o),i.clear()},5,!1)}function la(t){let e,n,i,s,r=document.referrer;const o=t.safe(()=>{const{URL:d}=document;d!==e&&(e=d,t.send(Ur(e,r,s,document.title)),s=0,r=e)}),l=t.safe(()=>{const{innerWidth:d,innerHeight:c}=window;(d!==n||c!==i)&&(n=d,i=c,t.send(lr(n,i)))}),a=document.hidden===void 0?Function.prototype:t.safe(()=>t.send(Nr(document.hidden)));t.attachStartCallback(()=>{e=null,s=ze(),n=i=-1,o(),l(),a()}),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",a,!1,!1),t.ticker.attach(o,1,!1),t.ticker.attach(l,5,!1)}function hs(t){return St(t)&&!!t.adoptedStyleSheets}let da=15;function us(){return da++}const _t=new Map;function ha(t){if(t===null||!hs(document))return;const e=new Map,n=new Map,i=o=>setTimeout(()=>{let l=t.nodes.getID(o);if(o===document&&(l=0),l===void 0)return;let a=n.get(l);a||(a=[]);const d=[],c=o.adoptedStyleSheets;if(c&&Symbol.iterator in c)for(const u of c){let p=e.get(u);const y=!p;if(p||(p=us(),e.set(u,p)),a.includes(p)||t.send(_i(p,l)),y){const S=u.cssRules;for(let v=0;v<S.length;v++)t.send(Jt(p,S[v].cssText,v,t.getBaseHref()))}d.push(p)}if(Symbol.iterator in a)for(const u of a)d.includes(u)||t.send(Lr(u,l));n.set(l,d)},20);function s(o){const l=Object.getOwnPropertyDescriptor(o,"adoptedStyleSheets");l&&Object.defineProperty(o,"adoptedStyleSheets",{...l,set:function(a){const d=l.set.call(this,a);return i(this),d}})}const r=o=>{if(o.__openreplay_adpss_patched__)return;o.__openreplay_adpss_patched__=!0,s(o.Document.prototype),s(o.ShadowRoot.prototype);const{replace:l,replaceSync:a}=o.CSSStyleSheet.prototype;o.CSSStyleSheet.prototype.replace=function(d){return l.call(this,d).then(c=>{const u=e.get(this);return u&&t.send(Ii(u,d,t.getBaseHref())),c})},o.CSSStyleSheet.prototype.replaceSync=function(d){const c=e.get(this);return c&&t.send(Ii(c,d,t.getBaseHref())),a.call(this,d)}};r(window),t.observer.attachContextCallback(t.safe(r)),t.attachStopCallback(()=>{e.clear(),n.clear()}),t.attachStartCallback(()=>{i(document)}),t.nodes.attachNodeCallback(o=>{hs(o)&&i(o)})}function ua(t){if(t===null)return;if(!window.CSSStyleSheet){t.send(Rr("no_stylesheet_prototype_in_window",""));return}const e=t.safe((s,r,o)=>{const l=_t.get(s);l&&(typeof o=="string"?t.send(Jt(l,o,r,t.getBaseHref())):t.send(Ci(l,r)))}),n=t.safe(s=>{let r=s;for(;r.parentRule;)r=r.parentRule;const o=r.parentStyleSheet;if(!o){t.debug.warn("No parent StyleSheet found for",r,s);return}const l=_t.get(o);if(!l){t.debug.warn("No sheedID found for",o,_t);return}const a=r.cssText,d=o.cssRules,c=Array.from(d).indexOf(r);c>=0?(t.send(Jt(l,a,c,t.getBaseHref())),t.send(Ci(l,c+1))):t.debug.warn("Rule index not found in",o,r)}),i=t.safe(s=>{const{insertRule:r,deleteRule:o}=s.CSSStyleSheet.prototype,{insertRule:l,deleteRule:a}=s.CSSGroupingRule.prototype;s.CSSStyleSheet.prototype.insertRule=function(d,c=0){return e(this,c,d),r.call(this,d,c)},s.CSSStyleSheet.prototype.deleteRule=function(d){return e(this,d),o.call(this,d)},s.CSSGroupingRule.prototype.insertRule=function(d,c=0){const u=l.call(this,d,c);return n(this),u},s.CSSGroupingRule.prototype.deleteRule=function(d=0){const c=a.call(this,d);return n(this),c}});i(window),t.observer.attachContextCallback(i),t.nodes.attachNodeCallback(s=>{if(!Q(s,"style")||!s.sheet||s.textContent!==null&&s.textContent.trim().length>0)return;const r=t.nodes.getID(s);if(!r)return;const o=s.sheet,l=us();_t.set(o,l),t.send(_i(l,r));const a=o.cssRules;for(let d=0;d<a.length;d++)e(o,d,a[d].cssText)})}function fa(t){function e(i){const s=t.nodes.getID(i);s!==void 0&&t.send(Ei(s))}let n=!1;t.nodes.attachNodeCallback(i=>{Q(i,"body")&&(t.nodes.attachNodeListener(i,"focus",s=>{Ui(s.target)&&(e(s.target),n=!1)}),t.nodes.attachNodeListener(i,"blur",s=>{s.relatedTarget===null&&(n=!0,setTimeout(()=>{n&&t.send(Ei(-1))},0))}))}),t.attachStartCallback(()=>{let i=document.activeElement;for(;i&&Q(i,"iframe")&&i.contentDocument;)i=i.contentDocument.activeElement;i&&i!==i.ownerDocument.body&&e(i)},!0)}function pa(t){if(!window.FontFace)return;const e=new Map,n=i=>{class s extends i.FontFace{constructor(...o){if(typeof o[1]=="string"){let l="";o[2]&&t.safe(()=>{l=JSON.stringify(o[2])});const a=[o[0],o[1],l],d=e.get(i.document)||[];d.push(a),e.set(i.document,d);const c=i===window?0:t.nodes.getID(i.document);if(c===void 0)return;t.active()&&t.send(Ti(c,...a))}super(...o)}}i.FontFace=s};t.observer.attachContextCallback(n),n(window),t.nodes.attachNodeCallback(t.safe(i=>{if(!wt(i))return;const s=e.get(i);if(!s)return;const r=i.defaultView===window?0:t.nodes.getID(i);r!==void 0&&s.forEach(o=>{t.send(Ti(r,...o))})}))}function ga(t,e,n,i,s){t.debug.log("Openreplay: attaching axios spy to instance",e);function r(p){t.debug.log("Openreplay: capturing axios response data",p);const{headers:y,data:S,method:v,url:T,baseURL:A}=p.config,{data:B,headers:D,status:k,response:N}=p,{data:O,headers:L,status:I}=N||{},E=n.ignoreHeaders,P=Array.isArray(E)?U=>E.includes(U):()=>E;function V(U,b){P(b[0])||(U[b[0]]=b[1])}let j={},q={};y.toJSON?j=y.toJSON():y instanceof Headers?y.forEach((U,b)=>V(j,[b,U])):Array.isArray(y)?y.forEach(U=>V(j,U)):typeof y=="object"&&Object.entries(y).forEach(U=>V(j,U));const C=L||D;C.toJSON?q=C.toJSON():C instanceof Headers?C.forEach((U,b)=>V(q,[b,U])):Array.isArray(C)?C.forEach(U=>V(q,U)):typeof C=="object"&&Object.entries(C).forEach(([U,b])=>{P(U)||(q[U]=b)});const F=i({url:T,method:v||"",status:k||I||0,request:{headers:j,body:S},response:{headers:q,body:O||B}});if(!F){t.debug.log("Openreplay: empty request/response info, skipping");return}const G=p.config.__openreplay_timing,K=performance.now()-G;t.debug.log("Openreplay: final req object",F),t.send(mt("xhr",String(v),String(F.url),s(F.request),s(F.response),F.status,G+ze(),K,0))}function o(p){if(t.debug.log("Openreplay: capturing API request",p),p.__openreplay_timing=performance.now(),n.sessionTokenHeader){const y=typeof n.sessionTokenHeader=="string"?n.sessionTokenHeader:"X-OpenReplay-Session-Token",S=t.getSessionToken();S&&p.headers.set(y,S)}return p}function l(p){return n.failuresOnly||r(p),p}function a(p){return t.debug.log("Openreplay: capturing API request error",p),ma(p)&&p.response?r(p.response):p instanceof Error&&t.send(kt(p,[])),Promise.reject(p)}function d(p){t.debug.log("Openreplay: failed API request, skipping",p)}const c=e.interceptors.request.use(o,d,{synchronous:!0}),u=e.interceptors.response.use(l,a,{synchronous:!0});t.attachStopCallback(()=>{var p,y,S,v;(y=(p=e.interceptors.request).eject)==null||y.call(p,c),(v=(S=e.interceptors.response).eject)==null||v.call(S,u)})}function ma(t){return ba(t)&&t.isAxiosError===!0}function ba(t){return t!==null&&typeof t=="object"}var ve;(function(t){t[t.UNSENT=0]="UNSENT",t[t.OPENED=1]="OPENED",t[t.HEADERS_RECEIVED=2]="HEADERS_RECEIVED",t[t.LOADING=3]="LOADING",t[t.DONE=4]="DONE"})(ve||(ve={}));class yn{constructor(e=[],n,i){this.ignoredHeaders=e,this.setSessionTokenHeader=n,this.sanitize=i,this.id="",this.name="",this.method="",this.url="",this.status=0,this.statusText="",this.cancelState=0,this.readyState=0,this.header={},this.responseType="",this.requestHeader={},this.responseSize=0,this.responseSizeText="",this.startTime=0,this.endTime=0,this.duration=0,this.getData={},this.requestData=null}getMessage(){const{reqHs:e,resHs:n}=this.writeHeaders(),i={headers:e,body:this.method==="GET"?JSON.stringify(this.getData):this.requestData},s={headers:n,body:this.response},r=this.sanitize({url:this.url,method:this.method,status:this.status,request:i,response:s});if(r)return mt(this.requestType,r.method,r.url,JSON.stringify(r.request),JSON.stringify(r.response),r.status,this.startTime+ze(),this.duration,this.responseSize)}writeHeaders(){const e={};Object.entries(this.requestHeader).forEach(([i,s])=>{this.isHeaderIgnored(i)||(e[i]=s)}),this.setSessionTokenHeader((i,s)=>{e[i]=s});const n={};return Object.entries(this.header).forEach(([i,s])=>{this.isHeaderIgnored(i)||(n[i]=s)}),{reqHs:e,resHs:n}}isHeaderIgnored(e){return Array.isArray(this.ignoredHeaders)?this.ignoredHeaders.map(n=>n.toLowerCase()).includes(e.toLowerCase()):this.ignoredHeaders}}const Qe=(t,e)=>{let n="";switch(t){case"":case"text":case"json":typeof e=="string"?n=e:wn(e)||Array.isArray(e)?n=JSON.stringify(e):typeof e<"u"&&(n=Object.prototype.toString.call(e));break;case"blob":case"document":case"arraybuffer":default:typeof e<"u"&&(n=Object.prototype.toString.call(e));break}return n},vn=t=>{if(!t)return null;let e;if(typeof t=="string"){(t[0]==="{"||t[0]==="[")&&(e=t);const n=t.split("&");n.length===1?e=t:e=n.join(",")}else if(va(t)){const n=[];for(const[i,s]of t)n.push(`${i}=${typeof s=="string"?s:"[object Object]"}`);e=n.join(",")}else t instanceof Blob||t instanceof ReadableStream||t instanceof ArrayBuffer?e="byte data":wn(t)?e=t:e=`can't parse body ${typeof t}`;return e},ya=(t,e={})=>{wn(e)||(e={});let n=t?t.split("?"):[];if(n.shift(),n.length>0){n=n.join("?").split("&");for(const i of n){const s=i.split("=");try{e[s[0]]=decodeURIComponent(s[1])}catch{e[s[0]]=s[1]}}}return e};function wn(t){return t!==null&&typeof t=="object"}function va(t){return t==null||ArrayBuffer.isView(t)?!1:typeof Symbol<"u"&&typeof t[Symbol.iterator]=="function"}function Nt(t){return t<=0?"":t>=1e3*1e3?(t/1e3/1e3).toFixed(1)+" MB":t>=1e3?(t/1e3).toFixed(1)+" KB":`${t}B`}const Sn=t=>(t.startsWith("//")&&(t=`${new URL(window.location.href).protocol}${t}`),t.startsWith("http")?new URL(t):new URL(t,window.location.href));class wa{constructor(e,n){this.resp=e,this.item=n,this.mockReader()}set(e,n,i){return Reflect.set(e,n,i)}get(e,n){const i=Reflect.get(e,n);switch(n){case"arrayBuffer":case"blob":case"formData":case"json":case"text":return()=>(this.item.responseType=n.toLowerCase(),i.apply(e).then(s=>(this.item.response=Qe(this.item.responseType,s),s)))}return typeof i=="function"?i.bind(e):i}mockReader(){let e;if(!this.resp.body||typeof this.resp.body.getReader!="function")return;const n=this.resp.body.getReader;this.resp.body.getReader=()=>{const i=n.apply(this.resp.body);if(this.item.readyState===ve.DONE)return i;const s=i.read,r=i.cancel;return this.item.responseType="arraybuffer",i.read=()=>s.apply(i).then(o=>{if(!e)e=new Uint8Array(o.value);else{const l=new Uint8Array(e.length+o.value.length);l.set(e),l.set(o.value,e.length),e=l}return this.item.endTime=performance.now(),this.item.duration=this.item.endTime-(this.item.startTime||this.item.endTime),this.item.readyState=o.done?4:3,this.item.statusText=o.done?String(this.item.status):"Loading",this.item.responseSize=e.length,this.item.responseSizeText=Nt(this.item.responseSize),o.done&&(this.item.response=Qe(this.item.responseType,e)),o}),i.cancel=(...o)=>(this.item.cancelState=2,this.item.statusText="Cancel",this.item.endTime=performance.now(),this.item.duration=this.item.endTime-(this.item.startTime||this.item.endTime),this.item.response=Qe(this.item.responseType,e),r.apply(i,o)),i}}}class Sa{constructor(e,n,i,s,r,o){this.ignoredHeaders=e,this.setSessionTokenHeader=n,this.sanitize=i,this.sendMessage=s,this.isServiceUrl=r,this.tokenUrlMatcher=o}apply(e,n,i){const s=i[0],r=i[1];if(!s||typeof s!="string"&&!(s!=null&&s.url)||(s instanceof URL||typeof s=="string"?this.isServiceUrl(String(s)):this.isServiceUrl(String(s.url))))return e.apply(window,i);const l=new yn(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);return this.beforeFetch(l,s,r),this.setSessionTokenHeader((a,d)=>{if(!(this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(l.url))){if(i[1]===void 0&&i[0]instanceof Request)return i[0].headers.append(a,d);i[1]||(i[1]={}),i[1].headers===void 0&&(i[1]={...i[1],headers:{}}),i[1].headers instanceof Headers?i[1].headers.append(a,d):Array.isArray(i[1].headers)?i[1].headers.push([a,d]):i[1].headers[a]=d}}),e.apply(window,i).then(this.afterFetch(l)).catch(a=>{throw l.endTime=performance.now(),l.duration=l.endTime-(l.startTime||l.endTime),a})}beforeFetch(e,n,i){let s,r="GET",o={};if(typeof n=="string"?(r=(i==null?void 0:i.method)||"GET",s=Sn(n),o=(i==null?void 0:i.headers)||{}):(r=n.method||"GET",s=Sn(n.url),o=n.headers),e.method=r,e.requestType="fetch",e.requestHeader=o,e.url=s.toString(),e.name=(s.pathname.split("/").pop()||"")+s.search,e.status=0,e.statusText="Pending",e.readyState=1,e.startTime||(e.startTime=performance.now()),Object.prototype.toString.call(o)==="[object Headers]"){e.requestHeader={};for(const[l,a]of o)e.requestHeader[l]=a}else e.requestHeader=o;if(s.search&&s.searchParams){e.getData={};for(const[l,a]of s.searchParams)e.getData[l]=a}i!=null&&i.body&&(e.requestData=vn(i.body))}afterFetch(e){return n=>{e.endTime=performance.now(),e.duration=e.endTime-(e.startTime||e.endTime),e.status=n.status,e.statusText=String(n.status);let i=!1;e.header={};for(const[s,r]of n.headers)e.header[s]=r,i=r.toLowerCase().indexOf("chunked")>-1?!0:i;return i?e.readyState=3:(e.readyState=4,this.handleResponseBody(n.clone(),e).then(s=>{e.responseSize=typeof s=="string"?s.length:s.byteLength,e.responseSizeText=Nt(e.responseSize),e.response=Qe(e.responseType,s);const r=e.getMessage();r&&this.sendMessage(r)}).catch(s=>{if(s.name!=="AbortError")throw s})),new Proxy(n,new wa(n,e))}}handleResponseBody(e,n){const i=e.headers.get("content-type");return i&&i.includes("application/json")?(n.responseType="json",e.text()):i&&(i.includes("text/html")||i.includes("text/plain"))?(n.responseType="text",e.text()):(n.responseType="arraybuffer",e.arrayBuffer())}}class xa{static create(e,n,i,s,r,o){return new Proxy(fetch,new Sa(e,n,i,s,r,o))}}class ka{constructor(e,n,i,s,r,o,l){this.ignoredHeaders=n,this.setSessionTokenHeader=i,this.sanitize=s,this.sendMessage=r,this.isServiceUrl=o,this.tokenUrlMatcher=l,this.XMLReq=e,this.XMLReq.onreadystatechange=()=>{this.onReadyStateChange()},this.XMLReq.onabort=()=>{this.onAbort()},this.XMLReq.ontimeout=()=>{this.onTimeout()},this.item=new yn(n,i,s),this.item.requestType="xhr"}get(e,n){switch(n){case"open":return this.getOpen(e);case"send":return this.setSessionTokenHeader((s,r)=>{this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(this.item.url)||e.setRequestHeader(s,r)}),this.getSend(e);case"setRequestHeader":return this.getSetRequestHeader(e);default:const i=Reflect.get(e,n);return typeof i=="function"?i.bind(e):i}}set(e,n,i){switch(n){case"onreadystatechange":return this.setOnReadyStateChange(e,n,i);case"onabort":return this.setOnAbort(e,n,i);case"ontimeout":return this.setOnTimeout(e,n,i)}return Reflect.set(e,n,i)}onReadyStateChange(){if(!(this.item.url&&this.isServiceUrl(this.item.url))&&(this.item.readyState=this.XMLReq.readyState,this.item.responseType=this.XMLReq.responseType,this.item.endTime=performance.now(),this.item.duration=this.item.endTime-this.item.startTime,this.updateItemByReadyState(),setTimeout(()=>{this.item.response=Qe(this.item.responseType,this.item.response)},0),this.XMLReq.readyState===ve.DONE)){const e=this.item.getMessage();e&&this.sendMessage(e)}}onAbort(){this.item.cancelState=1,this.item.statusText="Abort";const e=this.item.getMessage();e&&this.sendMessage(e)}onTimeout(){this.item.cancelState=3,this.item.statusText="Timeout";const e=this.item.getMessage();e&&this.sendMessage(e)}getOpen(e){const n=Reflect.get(e,"open");return(...i)=>{var o,l;const s=i[0],r=i[1];return this.item.method=s?s.toUpperCase():"GET",this.item.url=((o=r.toString)==null?void 0:o.call(r))||"",this.item.name=((l=this.item.url)==null?void 0:l.replace(new RegExp("/*$"),"").split("/").pop())??"",this.item.getData=ya(this.item.url,{}),n.apply(e,i)}}getSend(e){const n=Reflect.get(e,"send");return(...i)=>{const s=i[0];return this.item.requestData=vn(s),n.apply(e,i)}}getSetRequestHeader(e){const n=Reflect.get(e,"setRequestHeader");return(...i)=>(this.item.requestHeader||(this.item.requestHeader={}),this.item.requestHeader[i[0]]=i[1],n.apply(e,i))}setOnReadyStateChange(e,n,i){return Reflect.set(e,n,(...s)=>{this.onReadyStateChange(),i==null||i.apply(e,s)})}setOnAbort(e,n,i){return Reflect.set(e,n,(...s)=>{this.onAbort(),i.apply(e,s)})}setOnTimeout(e,n,i){return Reflect.set(e,n,(...s)=>{this.onTimeout(),i.apply(e,s)})}updateItemByReadyState(){switch(this.XMLReq.readyState){case ve.UNSENT:case ve.OPENED:this.item.status=ve.UNSENT,this.item.statusText="Pending",this.item.startTime||(this.item.startTime=performance.now());break;case ve.HEADERS_RECEIVED:this.item.status=this.XMLReq.status,this.item.statusText="Loading",this.item.header={};const e=this.XMLReq.getAllResponseHeaders()||"",n=e.split(`
|
|
666
|
+
`);for(let i=0;i<n.length;i++){const s=n[i];if(!s)continue;const r=s.split(": "),o=r[0];this.item.header[o]=r.slice(1).join(": ")}break;case ve.LOADING:this.item.status=this.XMLReq.status,this.item.statusText="Loading",this.XMLReq.response&&this.XMLReq.response.length&&(this.item.responseSize=this.XMLReq.response.length,this.item.responseSizeText=Nt(this.item.responseSize));break;case ve.DONE:this.item.status=this.XMLReq.status||this.item.status||0,this.item.statusText=String(this.item.status),this.item.endTime=performance.now(),this.item.duration=this.item.endTime-(this.item.startTime||this.item.endTime),this.item.response=this.XMLReq.response,this.XMLReq.response&&this.XMLReq.response.length&&(this.item.responseSize=this.XMLReq.response.length,this.item.responseSizeText=Nt(this.item.responseSize));break;default:this.item.status=this.XMLReq.status,this.item.statusText="Unknown";break}}}class Ta{static create(e,n,i,s,r,o){return new Proxy(XMLHttpRequest,{construct(l){const a=new l;return new Proxy(a,new ka(a,e,n,i,s,r,o))}})}}const Ea=t=>t instanceof Blob?t.type:t instanceof FormData?"multipart/form-data":t instanceof URLSearchParams?"application/x-www-form-urlencoded;charset=UTF-8":"text/plain;charset=UTF-8";class Ia{constructor(e,n,i,s,r){this.ignoredHeaders=e,this.setSessionTokenHeader=n,this.sanitize=i,this.sendMessage=s,this.isServiceUrl=r}apply(e,n,i){const s=i[0],r=i[1],o=new yn(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);if(this.isServiceUrl(s))return e.apply(n,i);const l=Sn(s);if(o.method="POST",o.url=s,o.name=(l.pathname.split("/").pop()||"")+l.search,o.requestType="beacon",o.requestHeader={"Content-Type":Ea(r)},o.status=0,o.statusText="Pending",l.search&&l.searchParams){o.getData={};for(const[c,u]of l.searchParams)o.getData[c]=u}o.requestData=vn(r),o.startTime||(o.startTime=performance.now());const a=e.apply(n,i);a?(o.endTime=performance.now(),o.duration=o.endTime-(o.startTime||o.endTime),o.status=0,o.statusText="Sent",o.readyState=4):(o.status=500,o.statusText="Unknown");const d=o.getMessage();return d&&this.sendMessage(d),a}}class qe{static hasSendBeacon(){return!!qe.origSendBeacon}static create(e,n,i,s,r){if(qe.hasSendBeacon())return new Proxy(qe.origSendBeacon,new Ia(e,n,i,s,r))}}qe.origSendBeacon=(bs=window==null?void 0:window.navigator)==null?void 0:bs.sendBeacon;const fs=t=>console.warn(`Openreplay: Can't find ${t} in global context.
|
|
667
|
+
If you're using serverside rendering in your app, make sure that tracker is loaded dynamically, otherwise ${t} won't be tracked.`);function Ca(t,e,n,i,s,r,o){var l;t.XMLHttpRequest?t.XMLHttpRequest=Ta.create(e,n,i,s,r,o):fs("XMLHttpRequest"),t.fetch?t.fetch=xa.create(e,n,i,s,r,o):fs("fetch"),(l=t==null?void 0:t.navigator)!=null&&l.sendBeacon&&(t.navigator.sendBeacon=qe.create(e,n,i,s,r))}function xn(t){return t.__or_req_data__||(t.__or_req_data__={body:void 0,headers:{}}),t.__or_req_data__}function ps(t){return typeof t=="string"?t.toUpperCase():"GET"}function _a(t,e={}){const n=Object.assign({failuresOnly:!1,ignoreHeaders:["cookie","set-cookie","authorization"],capturePayload:!1,sessionTokenHeader:!1,captureInIframes:!0,axiosInstances:void 0,useProxy:!0},e);n.useProxy===!1&&t.debug.warn("Network module is migrating to proxy api, to gradually migrate and test it set useProxy to true");const i=n.ignoreHeaders,s=Array.isArray(i)?c=>i.includes(c):()=>i,r=n.sessionTokenHeader===!0?"X-OpenReplay-SessionToken":n.sessionTokenHeader;function o(c){if(r){const u=t.getSessionToken();u&&t.safe(c)(r,u)}}function l(c){if(n.capturePayload||(delete c.request.body,delete c.response.body),n.sanitizer){const u=c.response.body;if(typeof u=="string")try{c.response.body=JSON.parse(u)}catch{}return n.sanitizer(c)}return c}function a(c){if(c&&typeof c.body!="string")try{c.body=JSON.stringify(c.body)}catch{c.body="<unable to stringify>",t.notify.warn("Openreplay fetch couldn't stringify body:",c.body)}return JSON.stringify(c)}const d=c=>{if(n.useProxy)return Ca(c,n.ignoreHeaders,o,l,D=>t.send(D),D=>t.isServiceURL(D),n.tokenUrlMatcher);const u=c.fetch.bind(c),p=(D,k={})=>{if(!(typeof D=="string"||D instanceof URL)||t.isServiceURL(String(D)))return u(D,k);o(function(O,L){k.headers===void 0&&(k.headers={}),k.headers instanceof Headers?k.headers.append(O,L):Array.isArray(k.headers)?k.headers.push([O,L]):k.headers[O]=L});const N=performance.now();return u(D,k).then(O=>{const L=performance.now()-N;if(n.failuresOnly&&O.status<400)return O;const I=O.clone();return I.text().then(E=>{const P={},V={};if(i!==!0){const C=([F,G])=>{s(F)||(P[F]=G)};k.headers instanceof Headers?k.headers.forEach((F,G)=>C([G,F])):Array.isArray(k.headers)?k.headers.forEach(C):typeof k.headers=="object"&&Object.entries(k.headers).forEach(C),I.headers.forEach((F,G)=>{s(G)||(V[G]=F)})}const j=ps(k.method),q=l({url:String(D),method:j,status:I.status,request:{headers:P,body:k.body||null},response:{headers:V,body:E}});q&&t.send(mt("fetch",j,String(q.url),a(q.request),a(q.response),I.status,N+ze(),L,0))}).catch(E=>t.debug.error("Could not process Fetch response:",E)),O})};c.fetch=p;const y=c.XMLHttpRequest.prototype.open,S=c.XMLHttpRequest.prototype.setRequestHeader,v=c.XMLHttpRequest.prototype.send;function T(D,k){const N=this;o((L,I)=>N.setRequestHeader(L,I));let O=0;return N.addEventListener("loadstart",L=>{O=L.timeStamp}),N.addEventListener("load",t.safe(L=>{const{headers:I,body:E}=xn(N),P=O>0?L.timeStamp-O:0,j=(N.getAllResponseHeaders()||"").trim().split(/[\r\n]+/),q={};j.forEach(function(G){const K=G.split(": "),U=K.shift();s(U)||(q[U]=K.join(": "))});const C=ps(D),F=l({url:String(k),method:C,status:N.status,request:{headers:I,body:E||null},response:{headers:q,body:N.response}});F&&t.send(mt("xhr",C,String(F.url),a(F.request),a(F.response),N.status,O+ze(),P,0))})),y.apply(this,arguments)}function A(D){const k=xn(this);return k.body=D,v.apply(this,arguments)}function B(D,k){if(!s(D)){const N=xn(this);N.headers[D]=k}return S.apply(this,arguments)}n.axiosInstances||(c.XMLHttpRequest.prototype.open=T,c.XMLHttpRequest.prototype.send=A,c.XMLHttpRequest.prototype.setRequestHeader=B)};d(window),n.axiosInstances&&n.axiosInstances.forEach(c=>{ga(t,c,n,l,a)}),n.captureInIframes&&t.observer.attachContextCallback(t.safe(d))}function Na(t){t.attachEventListener(document,"selectionchange",()=>{const e=document.getSelection();if(e!==null&&!e.isCollapsed){const n=t.nodes.getID(e.anchorNode),i=t.nodes.getID(e.focusNode),s=e.toString().replace(/\s+/g," ");n&&i&&t.send(Ni(n,i,s))}else t.send(Ni(-1,-1,""))})}function Oa(t){function e(){document.hidden||(t.debug.log("Openreplay: tab change to"+t.session.getTabId()),t.send(bt(t.session.getTabId())))}t.attachEventListener(window,"focus",e,!1,!1)}const Ot="/installation/javascript-sdk";function Ra(t){if(t==null)return console.error(`OpenReplay: invalid options argument type. Please, check documentation on ${gt}${Ot}`),!1;if(typeof t.projectKey!="string")if(typeof t.projectKey!="number"){if(typeof t.projectID!="number")return console.error(`OpenReplay: projectKey is missing or wrong type (string is expected). Please, check ${gt}${Ot} for more information.`),!1;t.projectKey=t.projectID.toString(),Ce("`projectID` option","`projectKey` option",Ot)}else console.warn("OpenReplay: projectKey is expected to have a string type."),t.projectKey=t.projectKey.toString();return t.sessionToken!=null&&Ce("`sessionToken` option","`sessionHash` start() option","/"),!0}class Aa{constructor(e){var l;if(this.options=e,this.app=null,this.crossdomainMode=!1,this.checkDoNotTrack=()=>this.options.respectDoNotTrack&&(navigator.doNotTrack=="1"||window.doNotTrack=="1"),this.signalStartIssue=(a,d)=>{const c=this.checkDoNotTrack(),u=new XMLHttpRequest,p=this.options.ingestPoint||Wi;u.open("POST",p+"/v1/web/not-started"),u.send(JSON.stringify({trackerVersion:"14.0.4",projectKey:this.options.projectKey,doNotTrack:c,reason:d.length?`missing api: ${d.join(",")}`:a}))},this.restartCanvasTracking=()=>{this.app!==null&&this.app.restartCanvasTracking()},this.handleError=(a,d={})=>{if(this.app!==null){if(a instanceof Error){const c=kt(a,[],d);this.app.send(c)}else if(a instanceof ErrorEvent||"PromiseRejectionEvent"in window&&a instanceof PromiseRejectionEvent){const c=Qi(a,void 0,d);c!=null&&this.app.send(c)}}},this.crossdomainMode=!!(rr()&&((l=e.crossdomain)!=null&&l.enabled)),!be||!Ra(e))return;if(window.__OPENREPLAY__){console.error("OpenReplay: one tracker instance has been initialised already");return}if(!e.__DISABLE_SECURE_MODE&&location.protocol!=="https:"){console.error("OpenReplay: Your website must be publicly accessible and running on SSL in order for OpenReplay to properly capture and replay the user session. You can disable this check by setting `__DISABLE_SECURE_MODE` option to `true` if you are testing in localhost. Keep in mind, that asset files on a local machine are not available to the outside world. This might affect tracking if you use css files.");return}const n=this.checkDoNotTrack(),i=[],s=["Map","Set","MutationObserver","performance","timing","startsWith","Blob","Worker"];if(n)i.push("doNotTrack");else for(const a of s)if(a==="timing"){if("performance"in window&&!(a in performance)){i.push(a);break}}else if(a==="startsWith"){if(!(a in String.prototype)){i.push(a);break}}else if(!(a in window)){i.push(a);break}if(i.length>0){const a=i.join(",");console.error(`OpenReplay: browser doesn't support API required for tracking or doNotTrack is set to 1. Reason: ${a}`),this.signalStartIssue("missing_api",i);return}const r=new No(e.projectKey,e.sessionToken,e,this.signalStartIssue,this.crossdomainMode);this.app=r,this.crossdomainMode||(la(r),Oo(r),Hr(r,e),Oa(r)),sa(r,e.mouse),ca(r,this.crossdomainMode),ua(r),ha(r),Lo(r,e),Bo(r,e),Uo(r),Go(r,e),aa(r,e),fa(r),pa(r),_a(r,e.network),Na(r),window.__OPENREPLAY__=this,e.flags&&e.flags.onFlagsLoad&&this.onFlagsLoad(e.flags.onFlagsLoad);const o=window.open;(e.autoResetOnWindowOpen||e.resetTabOnWindowOpen)&&(r.attachStartCallback(()=>{const a=r.getTabId(),d=r.sessionStorage??window.sessionStorage;window.open=function(...c){return e.autoResetOnWindowOpen&&r.resetNextPageSession(!0),e.resetTabOnWindowOpen&&d.removeItem(e.session_tabid_key||"__openreplay_tabid"),r.resetNextPageSession(!1),d.setItem(e.session_tabid_key||"__openreplay_tabid",a),o.call(window,...c)}}),r.attachStopCallback(()=>{window.open=o}))}isFlagEnabled(e){return this.featureFlags.isFlagEnabled(e)}onFlagsLoad(e){var n;(n=this.app)==null||n.featureFlags.onFlagsLoad(e)}clearPersistFlags(){var e;(e=this.app)==null||e.featureFlags.clearPersistFlags()}reloadFlags(){var e;return(e=this.app)==null?void 0:e.featureFlags.reloadFlags()}getFeatureFlag(e){var n;return(n=this.app)==null?void 0:n.featureFlags.getFeatureFlag(e)}getAllFeatureFlags(){var e;return(e=this.app)==null?void 0:e.featureFlags.flags}use(e){return e(this.app,this.options)}isActive(){return this.app===null?!1:this.app.active()}trackWs(e){if(this.app!==null)return this.app.trackWs(e)}start(e){return this.browserEnvCheck()?this.app===null?Promise.reject("Browser doesn't support required api, or doNotTrack is active."):this.app.start(e):Promise.reject("Trying to start not in browser.")}browserEnvCheck(){return be?!0:(console.error(`OpenReplay: you are trying to start Tracker on a node.js environment. If you want to use OpenReplay with SSR, please, use componentDidMount or useEffect API for placing the \`tracker.start()\` line. Check documentation on ${gt}${Ot}`),!1)}coldStart(e,n){if(this.browserEnvCheck()){if(this.app===null)return Promise.reject("Tracker not initialized");this.app.coldStart(e,n)}else return Promise.reject("Trying to start not in browser.")}startOfflineRecording(e,n){return this.browserEnvCheck()?this.app===null?Promise.reject("Tracker not initialized"):this.app.offlineRecording(e,n):Promise.reject("Trying to start not in browser.")}uploadOfflineRecording(){if(this.app!==null)return this.app.uploadOfflineRecording()}stop(){if(this.app!==null)return this.app.stop(),this.app.session.getSessionHash()}forceFlushBatch(){this.app!==null&&this.app.forceFlushBatch()}getSessionToken(){return this.app===null?null:this.app.getSessionToken()}getSessionInfo(){return this.app===null?null:this.app.session.getInfo()}getSessionID(){return this.app===null?null:this.app.getSessionID()}getTabId(){return this.app===null?null:this.app.getTabId()}getUxId(){return this.app===null?null:this.app.getUxtId()}sessionID(){return Ce("'sessionID' method","'getSessionID' method","/"),this.getSessionID()}getSessionURL(e){if(this.app!==null)return this.app.getSessionURL(e)}setUserID(e){typeof e=="string"&&this.app!==null&&this.app.session.setUserID(e)}userID(e){Ce("'userID' method","'setUserID' method","/"),this.setUserID(e)}setUserAnonymousID(e){typeof e=="string"&&this.app!==null&&this.app.send(Ir(e))}userAnonymousID(e){Ce("'userAnonymousID' method","'setUserAnonymousID' method","/"),this.setUserAnonymousID(e)}setMetadata(e,n){typeof e=="string"&&typeof n=="string"&&this.app!==null&&this.app.session.setMetadata(e,n)}metadata(e,n){Ce("'metadata' method","'setMetadata' method","/"),this.setMetadata(e,n)}event(e,n=null,i=!1){if(typeof e=="string"&&this.app!==null){if(i)return this.issue(e,n);try{n=JSON.stringify(n)}catch{return}this.app.send(Tr(e,n))}}issue(e,n=null){if(typeof e=="string"&&this.app!==null){try{n=JSON.stringify(n)}catch{return}this.app.send(Ar(e,n))}}}const Da=`
|
|
668
668
|
/* ===================== 1) Переменные и шрифты ===================== */
|
|
669
669
|
:root {
|
|
670
670
|
--wineater-corp-color: #0044FF;
|
|
@@ -703,11 +703,11 @@ body {
|
|
|
703
703
|
box-sizing: border-box;
|
|
704
704
|
}
|
|
705
705
|
|
|
706
|
-
.wine-widget-wrapper {
|
|
706
|
+
#wine-widget-container .wine-widget-wrapper {
|
|
707
707
|
width: 100%;
|
|
708
708
|
}
|
|
709
709
|
|
|
710
|
-
#wine-widget-right {
|
|
710
|
+
#wine-widget-container #wine-widget-right {
|
|
711
711
|
position: relative;
|
|
712
712
|
min-height: 300px;
|
|
713
713
|
}
|
|
@@ -751,7 +751,7 @@ body {
|
|
|
751
751
|
}
|
|
752
752
|
|
|
753
753
|
/* ===================== 5) Иконки и цветные подписи (meal, mood...) ===================== */
|
|
754
|
-
.icon {
|
|
754
|
+
#wine-widget-container .icon {
|
|
755
755
|
display: inline-block;
|
|
756
756
|
width: 1.2em;
|
|
757
757
|
height: 1.2em;
|
|
@@ -761,37 +761,37 @@ body {
|
|
|
761
761
|
background-size: contain;
|
|
762
762
|
}
|
|
763
763
|
|
|
764
|
-
.icon-meal {
|
|
764
|
+
#wine-widget-container .icon-meal {
|
|
765
765
|
background-image: url('https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media//meal1.svg');
|
|
766
766
|
}
|
|
767
|
-
.icon-meal:hover {
|
|
767
|
+
#wine-widget-container .icon-meal:hover {
|
|
768
768
|
background-image: url('https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media//meal3.svg');
|
|
769
769
|
}
|
|
770
|
-
.icon-mood {
|
|
770
|
+
#wine-widget-container .icon-mood {
|
|
771
771
|
background-image: url('https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media//mood.svg');
|
|
772
772
|
}
|
|
773
|
-
.icon-budget {
|
|
773
|
+
#wine-widget-container .icon-budget {
|
|
774
774
|
background-image: url('https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media//budget.svg');
|
|
775
775
|
}
|
|
776
|
-
.icon-occasion {
|
|
776
|
+
#wine-widget-container .icon-occasion {
|
|
777
777
|
background-image: url('https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media//ocasion.svg');
|
|
778
778
|
}
|
|
779
779
|
|
|
780
780
|
/* Подпись к иконкам */
|
|
781
|
-
.icon-label {
|
|
781
|
+
#wine-widget-container .icon-label {
|
|
782
782
|
color: var(--wineater-color);
|
|
783
783
|
font-weight: 500;
|
|
784
784
|
}
|
|
785
785
|
|
|
786
786
|
/* ===================== 6) Поисковая строка (input + кнопка) ===================== */
|
|
787
|
-
#wine-widget-search {
|
|
787
|
+
#wine-widget-container #wine-widget-search {
|
|
788
788
|
position: relative;
|
|
789
789
|
margin: 20px auto;
|
|
790
790
|
display: flex;
|
|
791
791
|
justify-content: center;
|
|
792
792
|
}
|
|
793
793
|
|
|
794
|
-
.search-icon {
|
|
794
|
+
#wine-widget-container .search-icon {
|
|
795
795
|
position: absolute;
|
|
796
796
|
left: 12px;
|
|
797
797
|
top: 50%;
|
|
@@ -804,7 +804,7 @@ body {
|
|
|
804
804
|
z-index: 2;
|
|
805
805
|
}
|
|
806
806
|
|
|
807
|
-
#wine-search-input {
|
|
807
|
+
#wine-widget-container #wine-search-input {
|
|
808
808
|
width: 100%;
|
|
809
809
|
padding: 12px 60px 12px 40px; /* место под иконку и кнопку */
|
|
810
810
|
font-size: 16px;
|
|
@@ -848,25 +848,25 @@ body {
|
|
|
848
848
|
}
|
|
849
849
|
|
|
850
850
|
/* ===================== 7) Фильтр-группы ===================== */
|
|
851
|
-
.filter-group {
|
|
851
|
+
#wine-widget-container .filter-group {
|
|
852
852
|
margin-bottom: 16px;
|
|
853
853
|
display: flex;
|
|
854
854
|
flex-direction: column;
|
|
855
855
|
}
|
|
856
856
|
|
|
857
|
-
.filter-label {
|
|
857
|
+
#wine-widget-container .filter-label {
|
|
858
858
|
font-size: 16px;
|
|
859
859
|
font-weight: bold;
|
|
860
860
|
color: #333;
|
|
861
861
|
margin-bottom: 8px;
|
|
862
862
|
}
|
|
863
863
|
|
|
864
|
-
.filter-buttons {
|
|
864
|
+
#wine-widget-container .filter-buttons {
|
|
865
865
|
display: flex;
|
|
866
866
|
gap: 8px;
|
|
867
867
|
}
|
|
868
868
|
|
|
869
|
-
.filter-buttons button {
|
|
869
|
+
#wine-widget-container .filter-buttons button {
|
|
870
870
|
padding: 10px 16px;
|
|
871
871
|
border: 1px solid #ccc;
|
|
872
872
|
border-radius: 8px;
|
|
@@ -875,18 +875,18 @@ body {
|
|
|
875
875
|
font-size: 14px;
|
|
876
876
|
transition: all 0.2s ease;
|
|
877
877
|
}
|
|
878
|
-
.filter-buttons button:hover {
|
|
878
|
+
#wine-widget-container .filter-buttons button:hover {
|
|
879
879
|
transform: scale(1.05);
|
|
880
880
|
box-shadow: 0 4px 8px rgba(123, 43, 235, 0.15);
|
|
881
881
|
}
|
|
882
|
-
.filter-buttons button.selected {
|
|
882
|
+
#wine-widget-container .filter-buttons button.selected {
|
|
883
883
|
background: linear-gradient(90deg, var(--wineater-color), var(--wineater-corp-color));
|
|
884
884
|
color: white;
|
|
885
885
|
border: none;
|
|
886
886
|
}
|
|
887
887
|
|
|
888
888
|
/* ===================== 8) Карточки рекомендаций (tiles) ===================== */
|
|
889
|
-
.wine-recommendation-tile {
|
|
889
|
+
#wine-widget-container .wine-recommendation-tile {
|
|
890
890
|
display: flex;
|
|
891
891
|
flex-direction: column;
|
|
892
892
|
align-items: center; /* всё по центру */
|
|
@@ -898,11 +898,11 @@ body {
|
|
|
898
898
|
transform: translateY(20px); /* чтобы анимация была заметна */
|
|
899
899
|
transition: opacity 0.3s ease, transform 0.3s ease;
|
|
900
900
|
}
|
|
901
|
-
.wine-recommendation-tile:last-child {
|
|
901
|
+
#wine-widget-container .wine-recommendation-tile:last-child {
|
|
902
902
|
border-right: none;
|
|
903
903
|
}
|
|
904
904
|
|
|
905
|
-
.tile-top {
|
|
905
|
+
#wine-widget-container .tile-top {
|
|
906
906
|
display: flex;
|
|
907
907
|
flex-direction: column;
|
|
908
908
|
align-items: center;
|
|
@@ -912,7 +912,7 @@ body {
|
|
|
912
912
|
|
|
913
913
|
|
|
914
914
|
/* Картинка */
|
|
915
|
-
.wine-image {
|
|
915
|
+
#wine-widget-container .wine-image {
|
|
916
916
|
width: 180px; /* или 200px, на ваш вкус */
|
|
917
917
|
height: auto;
|
|
918
918
|
object-fit: contain; /* чтобы не обрезалось, если нужно */
|
|
@@ -921,7 +921,7 @@ body {
|
|
|
921
921
|
}
|
|
922
922
|
|
|
923
923
|
/* Детальный блок */
|
|
924
|
-
.tile-details {
|
|
924
|
+
#wine-widget-container .tile-details {
|
|
925
925
|
/* Можно дополнительные отступы или нет */
|
|
926
926
|
display: flex;
|
|
927
927
|
flex-direction: column;
|
|
@@ -930,7 +930,7 @@ body {
|
|
|
930
930
|
}
|
|
931
931
|
|
|
932
932
|
/* Заголовок вина */
|
|
933
|
-
.wine-title {
|
|
933
|
+
#wine-widget-container .wine-title {
|
|
934
934
|
font-size: 20px; /* крупнее */
|
|
935
935
|
font-weight: 700;
|
|
936
936
|
margin: 0 0 8px;
|
|
@@ -940,14 +940,14 @@ body {
|
|
|
940
940
|
color: #000;
|
|
941
941
|
}
|
|
942
942
|
|
|
943
|
-
.wine-params {
|
|
943
|
+
#wine-widget-container .wine-params {
|
|
944
944
|
font-size: 14px;
|
|
945
945
|
color: #666;
|
|
946
946
|
white-space: normal;
|
|
947
947
|
text-align: center;
|
|
948
948
|
}
|
|
949
949
|
|
|
950
|
-
.param-chips-container {
|
|
950
|
+
#wine-widget-container .param-chips-container {
|
|
951
951
|
display: flex;
|
|
952
952
|
flex-wrap: wrap; /* чтобы чипсы переносились на новую строку при нехватке места */
|
|
953
953
|
gap: 8px; /* небольшой промежуток между чипсами */
|
|
@@ -955,7 +955,7 @@ body {
|
|
|
955
955
|
margin-bottom: 12px; /* отступ от нижнего блока */
|
|
956
956
|
}
|
|
957
957
|
|
|
958
|
-
.wine-chip {
|
|
958
|
+
#wine-widget-container .wine-chip {
|
|
959
959
|
display: inline-block;
|
|
960
960
|
background: #fff; /* белый фон */
|
|
961
961
|
font-size: 14px;
|
|
@@ -973,7 +973,7 @@ body {
|
|
|
973
973
|
|
|
974
974
|
|
|
975
975
|
|
|
976
|
-
.param-table {
|
|
976
|
+
#wine-widget-container .param-table {
|
|
977
977
|
display: grid;
|
|
978
978
|
/* Две колонки, каждая 50% */
|
|
979
979
|
grid-template-columns: 50% 50%;
|
|
@@ -988,7 +988,7 @@ body {
|
|
|
988
988
|
}
|
|
989
989
|
|
|
990
990
|
/* Каждая ячейка */
|
|
991
|
-
.param-table .cell {
|
|
991
|
+
#wine-widget-container .param-table .cell {
|
|
992
992
|
padding: 8px;
|
|
993
993
|
/* Горизонтальная линия */
|
|
994
994
|
box-sizing: border-box;
|
|
@@ -998,17 +998,17 @@ body {
|
|
|
998
998
|
|
|
999
999
|
/* Вертикальная граница между левым и правым столбцом —
|
|
1000
1000
|
т.е. у всех ячеек, идущих в левой колонке */
|
|
1001
|
-
.param-table .cell:nth-child(2n+1) {
|
|
1001
|
+
#wine-widget-container .param-table .cell:nth-child(2n+1) {
|
|
1002
1002
|
border-right: 1px solid #ddd;
|
|
1003
1003
|
}
|
|
1004
1004
|
|
|
1005
|
-
.param-table .cell:nth-last-child(-n + 2) {
|
|
1005
|
+
#wine-widget-container .param-table .cell:nth-last-child(-n + 2) {
|
|
1006
1006
|
border-bottom: none;
|
|
1007
1007
|
}
|
|
1008
1008
|
|
|
1009
1009
|
|
|
1010
1010
|
/* Нижняя строка (цена + кнопка) */
|
|
1011
|
-
.bottom-row {
|
|
1011
|
+
#wine-widget-container .bottom-row {
|
|
1012
1012
|
margin-top: auto; /* прижимает .bottom-row к низу
|
|
1013
1013
|
display: flex;
|
|
1014
1014
|
align-items: center;
|
|
@@ -1019,14 +1019,14 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1019
1019
|
}
|
|
1020
1020
|
|
|
1021
1021
|
/* Цена */
|
|
1022
|
-
.wine-price {
|
|
1022
|
+
#wine-widget-container .wine-price {
|
|
1023
1023
|
font-size: 16px;
|
|
1024
1024
|
font-weight: 400;
|
|
1025
1025
|
margin-bottom: 8px;
|
|
1026
1026
|
color: #333;
|
|
1027
1027
|
}
|
|
1028
1028
|
|
|
1029
|
-
.buy-btn {
|
|
1029
|
+
#wine-widget-container .buy-btn {
|
|
1030
1030
|
margin: 16px auto 0; /* центрируем и отступ сверху */
|
|
1031
1031
|
background-color: transparent;
|
|
1032
1032
|
color: var(--wineater-color);
|
|
@@ -1041,14 +1041,14 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1041
1041
|
transition: background-color 0.2s, color 0.2s, box-shadow 0.2s;
|
|
1042
1042
|
}
|
|
1043
1043
|
|
|
1044
|
-
.buy-btn:hover {
|
|
1044
|
+
#wine-widget-container .buy-btn:hover {
|
|
1045
1045
|
box-shadow: 0 4px 8px rgba(123, 43, 235, 0.25);
|
|
1046
1046
|
background-color: var(--wineater-color);
|
|
1047
1047
|
color: #fff;
|
|
1048
1048
|
}
|
|
1049
1049
|
|
|
1050
1050
|
/* Аналогично для .more-info-btn (если хотите стилизовать её тоже как кнопку) */
|
|
1051
|
-
.more-info-btn {
|
|
1051
|
+
#wine-widget-container .more-info-btn {
|
|
1052
1052
|
display: inline-block;
|
|
1053
1053
|
background-color: var(--wineater-color);
|
|
1054
1054
|
color: #fff;
|
|
@@ -1061,20 +1061,20 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1061
1061
|
margin-right: 8px;
|
|
1062
1062
|
transition: transform 0.2s, box-shadow 0.2s;
|
|
1063
1063
|
}
|
|
1064
|
-
.more-info-btn:hover {
|
|
1064
|
+
#wine-widget-container .more-info-btn:hover {
|
|
1065
1065
|
transform: scale(1.05);
|
|
1066
1066
|
box-shadow: 0 4px 8px rgba(123, 43, 235, 0.25);
|
|
1067
1067
|
}
|
|
1068
1068
|
|
|
1069
1069
|
|
|
1070
1070
|
/* ===================== 9) Стиль для Somm Selection ===================== */
|
|
1071
|
-
.somm-selection {
|
|
1071
|
+
#wine-widget-container .somm-selection {
|
|
1072
1072
|
position: relative;
|
|
1073
1073
|
// border: 2px solid #FFD700;
|
|
1074
1074
|
// background: linear-gradient(white, #FFF8DC);
|
|
1075
1075
|
// box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
|
|
1076
1076
|
}
|
|
1077
|
-
.somm-selection-badge {
|
|
1077
|
+
#wine-widget-container .somm-selection-badge {
|
|
1078
1078
|
position: absolute;
|
|
1079
1079
|
top: -10px;
|
|
1080
1080
|
left: 10px;
|
|
@@ -1115,7 +1115,7 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1115
1115
|
|
|
1116
1116
|
/* ===================== 12) Бар-версия (при необходимости) ===================== */
|
|
1117
1117
|
/* Грид блюд бара */
|
|
1118
|
-
.dish-grid {
|
|
1118
|
+
#wine-widget-container .dish-grid {
|
|
1119
1119
|
display: grid;
|
|
1120
1120
|
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
|
|
1121
1121
|
gap: 12px;
|
|
@@ -1123,7 +1123,7 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1123
1123
|
}
|
|
1124
1124
|
|
|
1125
1125
|
/* Плитка блюда */
|
|
1126
|
-
.dish-tile {
|
|
1126
|
+
#wine-widget-container .dish-tile {
|
|
1127
1127
|
display: flex;
|
|
1128
1128
|
justify-content: center;
|
|
1129
1129
|
align-items: center;
|
|
@@ -1136,11 +1136,11 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1136
1136
|
cursor: pointer;
|
|
1137
1137
|
transition: all 0.2s ease;
|
|
1138
1138
|
}
|
|
1139
|
-
.dish-tile:hover {
|
|
1139
|
+
#wine-widget-container .dish-tile:hover {
|
|
1140
1140
|
transform: scale(1.05);
|
|
1141
1141
|
box-shadow: 0 4px 8px rgba(123, 43, 235, 0.15);
|
|
1142
1142
|
}
|
|
1143
|
-
.dish-tile.selected {
|
|
1143
|
+
#wine-widget-container .dish-tile.selected {
|
|
1144
1144
|
background: linear-gradient(90deg, var(--wineater-color), var(--wineater-corp-color));
|
|
1145
1145
|
color: #fff;
|
|
1146
1146
|
}
|
|
@@ -1232,19 +1232,19 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1232
1232
|
#wine-widget-header p {
|
|
1233
1233
|
display: none; /* скрываем подзаголовок на мобильных, если не нужен */
|
|
1234
1234
|
}
|
|
1235
|
-
.wine-recommendation-tile {
|
|
1235
|
+
#wine-widget-container .wine-recommendation-tile {
|
|
1236
1236
|
flex: 0 0 auto;
|
|
1237
1237
|
scroll-snap-align: center;
|
|
1238
1238
|
width: 240px;
|
|
1239
1239
|
text-align: center;
|
|
1240
1240
|
}
|
|
1241
|
-
.tile-details {
|
|
1241
|
+
#wine-widget-container .tile-details {
|
|
1242
1242
|
text-align: center;
|
|
1243
1243
|
}
|
|
1244
1244
|
}
|
|
1245
1245
|
|
|
1246
1246
|
/* Пример более узких экранов (i.e. <480px) можно добавить при необходимости */
|
|
1247
|
-
`,kn=document.createElement("link");kn.rel="stylesheet",kn.href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap",document.head.appendChild(kn);const gi=document.createElement("style");document.documentElement.style.setProperty("--wineater-color",((yi=window==null?void 0:window.wineaterData)==null?void 0:yi.COLOR)||"#0044FF"),gi.textContent=Da,document.head.appendChild(gi);const La=["climats","telckel","biobio","weinpoint","vinigrandi","ampely","test"],Fa="HeUw6IXuhvz6tRuXdPEGEbj3SGQ3Q2YtEc1Z8jd41Kg9LtyPb4Epu0to31SYIadG";class Rt{constructor(e){var n;this.baseURL="https://wineater-backend.vercel.app/",this.store=La.find(s=>window.location.href.includes(s)),this.token=((n=window==null?void 0:window.wineaterData)==null?void 0:n.CLIENT_TOKEN)||Fa}async getStoreConfig(e){console.log(e);try{const n=await fetch(`${this.baseURL}stores/store`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({store:e})});if(console.log(n),!n.ok)throw new Error(`HTTP error! Status: ${n.status}`);return await n.json()}catch(n){throw console.error("Error fetching store configuration:",n),n}}async getWineRecommendations(e){console.log(window.location.href);try{const n=await fetch(`${this.baseURL}dish/recommendations`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({text:e,store:this.store?this.store.toString().charAt(0).toUpperCase()+this.store.slice(1):void 0})}),s=await n.json();if(!n.ok)throw new Error(`API call failed with status ${n.status}: ${s.message||"No additional error information"}`);return s}catch(n){throw console.error("Fetching wine recommendations failed:",n.message),new Error(`Error in getWineRecommendations: ${n.message}`)}}async getWineRecommendationsSearch(e){console.log(window.location.href);try{const n=await fetch(`${this.baseURL}dish/recommendations/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({text:e,store:this.store?this.store.toString().charAt(0).toUpperCase()+this.store.slice(1):void 0})}),s=await n.json();if(!n.ok)throw new Error(`API call failed with status ${n.status}: ${s.message||"No additional error information"}`);return s}catch(n){throw console.error("Fetching wine recommendations failed:",n.message),new Error(`Error in getWineRecommendations: ${n.message}`)}}async getPossibleDishesWithMeta(e,n){try{const s=await fetch(`${this.baseURL}dish/possible_dishes`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:e,description:n})}),i=await s.json();if(console.log(i),!s.ok)throw new Error(`API call failed with status ${s.status}: ${i.message||"No additional error information"}`);return i}catch(s){throw console.error("Error fetching possible dishes:",s),s}}async getInstantRecommendations(){console.log("Fetching instant recommendations...");try{const e=await fetch(`${this.baseURL}dish/recommendations/instant`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({store:this.store})}),n=await e.json();if(!e.ok)throw new Error(`API call failed with status ${e.status}: ${n.message||"No additional error information"}`);return console.log("Instant recommendations:",n),n}catch(e){throw console.error("Fetching instant recommendations failed:",e.message),new Error(`Error in getInstantRecommendations: ${e.message}`)}}}class Ma{constructor(){this.api=new Rt,this.language="en",this.translations={fr:{lang:"fr",welcomeMessage:"Quel plat allez-vous déguster ? Décrivez-le-moi et je vous proposerai le vin qui l'accompagnera parfaitement.",noResultsFound:"Aucun résultat trouvé.",somethingWentWrong:"Désolé, quelque chose a mal tourné.",chatButton1:"Trouvez l'accord parfait",chatButton2:"Associez le vin",chatButton3:"Obtenez des conseils",chatTitle:"Accord Mets & Vins 🍷",chatSubtitle:"Décrivez votre plat et obtenez une recommandation en 30 secondes",inputPlaceholder:"ex., Salade de thon",sendButton:"Accorder",poweredBy:"Propulsé par",price:"Prix",region:"Région",type:"Type",reason:"Suggestion",moreInfo:"Plus d'infos",winePairingIntro:"Pour ce vin, voici quelques suggestions de plats :",askForDinner:"Que voulez-vous manger ce soir?",clearChatButton:"Effacer le chat",widgetTitle:"TROUVEZ VOTRE VIN PARFAIT",widgetSubtitle:"Partagez tout ce que vous avez en tête—votre repas, humeur, budget ou occasion—et notre sommelier IA vous recommandera le vin parfait en quelques secondes",searchPlaceholder:"Entrez un mot-clé ou une description",wineDetails:{reason:"Raison",price:"Prix",region:"Région",type:"Type",moreInfo:"Plus d'infos",sommSelection:"Sélection Somm",code:"Code",buy:"Acheter"},searchButton:"Rechercher",priceRange:"Gamme de prix",wineColor:"Couleur du vin",intensity:"Intensité",red:"Rouge",white:"Blanc",rose:"Rosé",light:"Léger",medium:"Moyen",full:"Puissant",barTitle:"Sélection du bar",barSubtitle:"Choisissez vos plats ci-dessous et cliquez sur «Envoyer»",barSendButton:"Envoyer",barResetButton:"Réinitialiser",barName:"Nom du bar",barNotesPlaceholder:"Entrez vos souhaits ici...",placeholderSuggestions:["Vin pour les pâtes","Parfait avec du poisson","Recommandé pour une soirée"],headerLine1:"Partagez tout ce qui vous passe par la tête —",headerLine2:"— et obtenez des recommandations de vin parfait en quelques secondes",headerMeal:"repas",headerMood:"humeur",headerBudget:"budget",headerOccasion:"occasion",headerOr:"ou"},es:{lang:"es",welcomeMessage:"¿Qué vas a comer? Cuéntame tu plato y te recomendaré el maridaje perfecto.",noResultsFound:"No se encontraron resultados.",somethingWentWrong:"Lo sentimos, algo salió mal.",chatButton1:"Encuentra tu maridaje",chatButton2:"Combina vino ya",chatButton3:"Recibe asesoría ahora",chatTitle:"Maridaje de Vinos 🍷",chatSubtitle:"Describe tu comida y obtén una recomendación en 30 segundos",inputPlaceholder:"ej., Ensalada de atún",sendButton:"Combinar",poweredBy:"Desarrollado por",price:"Precio",region:"Región",type:"Tipo",reason:"Sugerencia",moreInfo:"Más info",winePairingIntro:"Para este vino, aquí tienes algunas sugerencias de platos:",askForDinner:"¿Qué te gustaría cenar?",clearChatButton:"Limpiar el chat",widgetTitle:"ENCUENTRA TU VINO PERFECTO",widgetSubtitle:"Comparte cualquier cosa que tengas en mente—tu comida, estado de ánimo, presupuesto o evento—y nuestro sommelier de IA te recomendará el vino perfecto en segundos",searchPlaceholder:"Escribe una palabra clave o descripción",wineDetails:{reason:"Razón",price:"Precio",region:"Región",type:"Tipo",code:"Código",moreInfo:"Más información",sommSelection:"Selección Somm",buy:"Comprar"},searchButton:"Buscar",priceRange:"Rango de precios",wineColor:"Color del vino",intensity:"Intensidad",red:"Tinto",white:"Blanco",rose:"Rosado",light:"Ligero",medium:"Medio",full:"Intenso",barTitle:"Platos de Bar",barSubtitle:"Selecciona de la lista y presiona «Enviar»",barSendButton:"Enviar",barResetButton:"Reiniciar",barName:"Nombre del bar",barNotesPlaceholder:"Agrega tus comentarios aquí...",placeholderSuggestions:["Vino para pasta","Perfecto con pescado","Recomendado para una fiesta"],headerLine1:"Comparte cualquier cosa que tengas en mente —",headerLine2:"— y obtén recomendaciones del vino perfecto en cuestión de segundos",headerMeal:"comida",headerMood:"estado de ánimo",headerBudget:"presupuesto",headerOccasion:"ocasión",headerOr:"o"},en:{lang:"en",welcomeMessage:"What are you planning to eat? Share your dish and I'll recommend the perfect wine pairing for your meal.",noResultsFound:"No results found.",somethingWentWrong:"Sorry, something went wrong.",chatButton1:"Find Your Pairing",chatButton2:"Pair Wine Now",chatButton3:"Get Wine Advice",chatTitle:"Wine Pairing Assistant 🍷",chatSubtitle:"Describe your meal and get a recommendation in 30 seconds",inputPlaceholder:"e.g., Tuna salad",sendButton:"Match",poweredBy:"Powered by",price:"Price",region:"Region",type:"Type",reason:"Suggestion",moreInfo:"More info",winePairingIntro:"For this wine, here are some suggested dishes:",askForDinner:"What would you like to have for dinner?",clearChatButton:"Clear Chat",widgetTitle:"FIND YOUR PERFECT WINE",widgetSubtitle:"Share anything on your mind—your meal, mood, budget, or occasion—and our AI sommelier will recommend the perfect wine in seconds",searchPlaceholder:"Enter a keyword or description",wineDetails:{price:"Price",region:"Region",type:"Type",moreInfo:"More info",reason:"Reason",sommSelection:"Somm Selection",code:"Code",buy:"Buy"},searchButton:"Search",priceRange:"Price Range",wineColor:"Wine Color",intensity:"Intensity",red:"Red",white:"White",rose:"Rosé",light:"Light",medium:"Medium",full:"Full",barTitle:"Bar Dishes",barSubtitle:"Select dishes below and click ‘Send’",barSendButton:"Send",barResetButton:"Reset",barName:"Bar Name",barNotesPlaceholder:"Add your wishes here...",placeholderSuggestions:["Wine for pasta","Perfect with fish","Recommended for a party"],headerLine1:"Share anything on your mind —",headerLine2:"— and get recommendations of the perfect wine in seconds",headerMeal:"meal",headerMood:"mood",headerBudget:"budget",headerOccasion:"occasion",headerOr:"or"},de:{lang:"de",welcomeMessage:"Was möchten Sie essen? Beschreiben Sie Ihr Gericht und ich empfehle Ihnen den perfekten Wein dazu.",noResultsFound:"Keine Ergebnisse gefunden.",somethingWentWrong:"Entschuldigung, etwas ist schief gelaufen.",chatButton1:"Finde Dein Pairing",chatButton2:"Wein jetzt wählen",chatButton3:"Erhalte Weinberatung",chatTitle:"Wein & Speisen 🍷",chatSubtitle:"Beschreiben Sie Ihr Gericht und erhalten Sie in 30 Sekunden eine Empfehlung",inputPlaceholder:"z.B., Thunfischsalat",sendButton:"Kombinieren",poweredBy:"Unterstützt von",price:"Preis",region:"Region",type:"Typ",reason:"Anregung",moreInfo:"Mehr Info",winePairingIntro:"Für diesen Wein gibt es folgende Essensvorschläge:",askForDinner:"Was möchten Sie zum Abendessen essen?",clearChatButton:"Chat löschen",widgetTitle:"FINDEN SIE IHREN PERFEKTEN WEIN",widgetSubtitle:"Teilen Sie alles, was Ihnen in den Sinn kommt—Ihre Mahlzeit, Stimmung, Ihr Budget oder Anlass—und unser KI-Sommelier empfiehlt Ihnen in Sekunden den perfekten Wein",placeholderSuggestions:["Wein für Pasta","Perfekt zu Fisch","Empfohlen für eine Party"],searchPlaceholder:"Geben Sie ein Stichwort oder eine Beschreibung ein",wineDetails:{price:"Preis",region:"Region",type:"Typ",moreInfo:"Mehr Infos",sommSelection:"Somm-Auswahl",reason:"Grund",code:"Code",buy:"Kaufen"},searchButton:"Suche",priceRange:"Preisspanne",wineColor:"Weinfarbe",intensity:"Intensität",red:"Rot",white:"Weiß",rose:"Rosé",light:"Leicht",medium:"Mittel",full:"Voll",barTitle:"Bar-Auswahl",barSubtitle:"Wählen Sie Ihre Gerichte und klicken Sie auf „Senden“",barSendButton:"Senden",barResetButton:"Zurücksetzen",barName:"Name der Bar",headerLine1:"Teilen Sie alles, was Ihnen durch den Kopf geht —",headerLine2:"— und erhalten Sie in Sekundenschnelle Empfehlungen für den perfekten Wein",headerMeal:"Mahlzeit",headerMood:"Stimmung",headerBudget:"Budget",headerOccasion:"Anlass",headerOr:"oder"},ukr:{lang:"ukr",welcomeMessage:"Що ви збираєтесь їсти? Опишіть свою страву, і я порекомендую вам ідеальне вино.",noResultsFound:"Результатів не знайдено.",somethingWentWrong:"Вибачте, щось пішло не так.",chatButton1:"Знайти ідеальне поєднання",chatButton2:"Підібрати вино",chatButton3:"Отримати пораду",chatTitle:"Сомельє-помічник 🍷",chatSubtitle:"Опишіть свою страву і отримайте рекомендацію за 30 секунд",inputPlaceholder:"наприклад, Тунець із салатом",sendButton:"Підібрати",poweredBy:"Розроблено на основі",price:"Ціна",region:"Регіон",type:"Тип",reason:"Рекомендація",moreInfo:"Докладніше",winePairingIntro:"До цього вина підходять такі страви:",askForDinner:"Що ви хочете на вечерю?",clearChatButton:"Очистити чат",widgetTitle:"ЗНАЙДІТЬ ІДЕАЛЬНЕ ВИНО",widgetSubtitle:"Поділіться тим, що у вас на думці—їжа, настрій, бюджет чи подія—і наш AI-сомельє порекомендує вам ідеальне вино за секунди",searchPlaceholder:"Введіть ключове слово або опис",wineDetails:{reason:"Причина",price:"Ціна",region:"Регіон",type:"Тип",moreInfo:"Докладніше",sommSelection:"Вибір сомельє",code:"Код",buy:"Купити"},searchButton:"Пошук",priceRange:"Діапазон цін",wineColor:"Колір вина",intensity:"Інтенсивність",red:"Червоне",white:"Біле",rose:"Рожеве",light:"Легке",medium:"Середнє",full:"Повне",barTitle:"Закуски до вина",barSubtitle:"Виберіть страви нижче та натисніть «Надіслати»",barSendButton:"Надіслати",barResetButton:"Скинути",barName:"Назва бару",barNotesPlaceholder:"Додайте ваші побажання тут...",placeholderSuggestions:["Вино до пасти","Ідеально до риби","Рекомендуємо для вечірки"],headerLine1:"Поділіться будь-якими вашими думками —",headerLine2:"— і отримайте рекомендації щодо ідеального вина за секунди",headerMeal:"страва",headerMood:"настрій",headerBudget:"бюджет",headerOccasion:"подія",headerOr:"або"},ru:{lang:"ru",welcomeMessage:"Что вы планируете поесть? Напишите ваше блюдо, и я подберу идеальное вино к нему.",noResultsFound:"Результаты не найдены.",somethingWentWrong:"Извините, что-то пошло не так.",chatButton1:"Найти сочетание",chatButton2:"Подобрать вино",chatButton3:"Получить совет",chatTitle:"Ассистент по подбору вина 🍷",chatSubtitle:"Опишите ваше блюдо и получите рекомендацию за 30 секунд",inputPlaceholder:"например, Тунец с салатом",sendButton:"Подобрать",poweredBy:"Powered by",price:"Цена",region:"Регион",type:"Тип",reason:"Рекомендация",moreInfo:"Подробнее",winePairingIntro:"К этому вину подходят следующие блюда:",askForDinner:"Что бы вы хотели на ужин?",clearChatButton:"Очистить чат",widgetTitle:"НАЙДИТЕ ИДЕАЛЬНОЕ ВИНО",widgetSubtitle:"Поделитесь вашими предпочтениями — блюдом, настроением, бюджетом или случаем — и наш AI-сомелье подберёт идеальное вино за секунды",searchPlaceholder:"Введите ключевое слово или описание",wineDetails:{price:"Цена",region:"Регион",type:"Тип",moreInfo:"Подробнее",reason:"Причина",sommSelection:"Выбор сомелье",code:"Код",buy:"Купить"},searchButton:"Поиск",priceRange:"Диапазон цен",wineColor:"Цвет вина",intensity:"Интенсивность",red:"Красное",white:"Белое",rose:"Розовое",light:"Лёгкое",medium:"Среднее",full:"Полное",barTitle:"Закуски к вину",barSubtitle:"Выберите блюда ниже и нажмите ‘Отправить’",barSendButton:"Отправить",barResetButton:"Сбросить",barName:"Название бара",barNotesPlaceholder:"Добавьте ваши пожелания здесь...",placeholderSuggestions:["Вино для пасты","Идеально к рыбе","Рекомендуем для вечеринки"],headerLine1:"Поделитесь любыми вашими мыслями —",headerLine2:"— и получите рекомендации по идеальному вину за считанные секунды",headerMeal:"блюдо",headerMood:"настроение",headerBudget:"бюджет",headerOccasion:"случай",headerOr:"или"}}}async fetchConfig(e){try{const n=await this.api.getStoreConfig(e);this.language=n.lang}catch{this.language="en"}}translate(e){const n=e.split(".");let s=this.translations[this.language];for(const i of n)if(s&&typeof s=="object"&&i in s)s=s[i];else return e;return s}}const H=new Ma,Tn={barName:"LENEZ",dishGroups:[{groupTitle:"Entradas",dishes:["Pimientos rojo asado y aceite de oliva con ajo confitado","Ensalada de arúgula y parmesano","Tomate hierloom aliñado","Aceitunas LENEZ","Papatinaz","Croquetas | hongos de temporada | jamón serrano","Carpaccio Cesar","Torreznos","Calamares fritos"]},{groupTitle:"Bocadillos",dishes:["Brioche de pollo frito, col y salsa macha","Baguette de calamares rebozados en salsa brava","Hogaza de cola de res en recado negro y cebollas encurtidas"]},{groupTitle:"Embutidos",dishes:["Jamón Ibérico de bellota","Lomo ibérico","Chorizo ibérico","Plato mixto iberico"]},{groupTitle:"Quesos",dishes:["Selección de quesos (D’Affinois, Brie Ermitage, Manchego semi curado, Roquefort)"]},{groupTitle:"Postres",dishes:["Ate con queso manchego semi curado","Gelato de nata con balsámico","Gelato de ron con pasas y “El candado”, Valdespino PX","Gelato Dua Lipa","Créme Brûlée al Orange"]}]};class Pa{constructor(){var e,n,s,i;this.widgetType=((e=window==null?void 0:window.wineaterData)==null?void 0:e.WIDGET_TYPE)||"store",this.widgetWrapper=((n=window==null?void 0:window.wineaterData)==null?void 0:n.WIDGET_WRAPPER)||"wineater-widget-conteiner",this.titleText=(s=window==null?void 0:window.wineaterData)==null?void 0:s.TITLE_TEXT,this.subtitleText=(i=window==null?void 0:window.wineaterData)==null?void 0:i.SUBTITLE_TEXT,this.api=new Rt,this.selectedFilters={price:null,color:null,intensity:null},this.widgetType==="bar"?(this.barName=Tn.barName,this.barDishes=Tn.dishes):(this.barName="",this.barDishes=[]),this.initializeWidget(),this.initializeSearchAnimation(),this.widgetType==="store"&&this.loadInstantRecommendations()}initializeWidget(){const e=document.getElementById(this.widgetWrapper);if(this.widgetType==="store"){const n=`
|
|
1247
|
+
`,kn=document.createElement("link");kn.rel="stylesheet",kn.href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap",document.head.appendChild(kn);const gs=document.createElement("style");document.documentElement.style.setProperty("--wineater-color",((ys=window==null?void 0:window.wineaterData)==null?void 0:ys.COLOR)||"#7B2BEB"),gs.textContent=Da,document.head.appendChild(gs);const La=["climats","telckel","biobio","weinpoint","vinigrandi","ampely","test"],Fa="HeUw6IXuhvz6tRuXdPEGEbj3SGQ3Q2YtEc1Z8jd41Kg9LtyPb4Epu0to31SYIadG";class Rt{constructor(e){var n;this.baseURL="https://wineater-backend.vercel.app/",this.store=La.find(i=>window.location.href.includes(i)),this.token=((n=window==null?void 0:window.wineaterData)==null?void 0:n.CLIENT_TOKEN)||Fa}async getStoreConfig(e){console.log(e);try{const n=await fetch(`${this.baseURL}stores/store`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({store:e})});if(console.log(n),!n.ok)throw new Error(`HTTP error! Status: ${n.status}`);return await n.json()}catch(n){throw console.error("Error fetching store configuration:",n),n}}async getWineRecommendations(e){console.log(window.location.href);try{const n=await fetch(`${this.baseURL}dish/recommendations`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({text:e,store:this.store?this.store.toString().charAt(0).toUpperCase()+this.store.slice(1):void 0})}),i=await n.json();if(!n.ok)throw new Error(`API call failed with status ${n.status}: ${i.message||"No additional error information"}`);return i}catch(n){throw console.error("Fetching wine recommendations failed:",n.message),new Error(`Error in getWineRecommendations: ${n.message}`)}}async getWineRecommendationsSearch(e){console.log(window.location.href);try{const n=await fetch(`${this.baseURL}dish/recommendations/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({text:e,store:this.store?this.store.toString().charAt(0).toUpperCase()+this.store.slice(1):void 0})}),i=await n.json();if(!n.ok)throw new Error(`API call failed with status ${n.status}: ${i.message||"No additional error information"}`);return i}catch(n){throw console.error("Fetching wine recommendations failed:",n.message),new Error(`Error in getWineRecommendations: ${n.message}`)}}async getPossibleDishesWithMeta(e,n){try{const i=await fetch(`${this.baseURL}dish/possible_dishes`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:e,description:n})}),s=await i.json();if(console.log(s),!i.ok)throw new Error(`API call failed with status ${i.status}: ${s.message||"No additional error information"}`);return s}catch(i){throw console.error("Error fetching possible dishes:",i),i}}async getInstantRecommendations(){console.log("Fetching instant recommendations...");try{const e=await fetch(`${this.baseURL}dish/recommendations/instant`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({store:this.store})}),n=await e.json();if(!e.ok)throw new Error(`API call failed with status ${e.status}: ${n.message||"No additional error information"}`);return console.log("Instant recommendations:",n),n}catch(e){throw console.error("Fetching instant recommendations failed:",e.message),new Error(`Error in getInstantRecommendations: ${e.message}`)}}}class Ma{constructor(){this.api=new Rt,this.language="en",this.translations={fr:{lang:"fr",welcomeMessage:"Quel plat allez-vous déguster ? Décrivez-le-moi et je vous proposerai le vin qui l'accompagnera parfaitement.",noResultsFound:"Aucun résultat trouvé.",somethingWentWrong:"Désolé, quelque chose a mal tourné.",chatButton1:"Trouvez l'accord parfait",chatButton2:"Associez le vin",chatButton3:"Obtenez des conseils",chatTitle:"Accord Mets & Vins 🍷",chatSubtitle:"Décrivez votre plat et obtenez une recommandation en 30 secondes",inputPlaceholder:"ex., Salade de thon",sendButton:"Accorder",poweredBy:"Propulsé par",price:"Prix",region:"Région",type:"Type",reason:"Suggestion",moreInfo:"Plus d'infos",winePairingIntro:"Pour ce vin, voici quelques suggestions de plats :",askForDinner:"Que voulez-vous manger ce soir?",clearChatButton:"Effacer le chat",widgetTitle:"TROUVEZ VOTRE VIN PARFAIT",widgetSubtitle:"Partagez tout ce que vous avez en tête—votre repas, humeur, budget ou occasion—et notre sommelier IA vous recommandera le vin parfait en quelques secondes",searchPlaceholder:"Entrez un mot-clé ou une description",wineDetails:{reason:"Raison",price:"Prix",region:"Région",type:"Type",moreInfo:"Plus d'infos",sommSelection:"Sélection Somm",code:"Code",buy:"Acheter"},searchButton:"Rechercher",priceRange:"Gamme de prix",wineColor:"Couleur du vin",intensity:"Intensité",red:"Rouge",white:"Blanc",rose:"Rosé",light:"Léger",medium:"Moyen",full:"Puissant",barTitle:"Sélection du bar",barSubtitle:"Choisissez vos plats ci-dessous et cliquez sur «Envoyer»",barSendButton:"Envoyer",barResetButton:"Réinitialiser",barName:"Nom du bar",barNotesPlaceholder:"Entrez vos souhaits ici...",placeholderSuggestions:["Vin pour les pâtes","Parfait avec du poisson","Recommandé pour une soirée"],headerLine1:"Partagez tout ce qui vous passe par la tête —",headerLine2:"— et obtenez des recommandations de vin parfait en quelques secondes",headerMeal:"repas",headerMood:"humeur",headerBudget:"budget",headerOccasion:"occasion",headerOr:"ou"},es:{lang:"es",welcomeMessage:"¿Qué vas a comer? Cuéntame tu plato y te recomendaré el maridaje perfecto.",noResultsFound:"No se encontraron resultados.",somethingWentWrong:"Lo sentimos, algo salió mal.",chatButton1:"Encuentra tu maridaje",chatButton2:"Combina vino ya",chatButton3:"Recibe asesoría ahora",chatTitle:"Maridaje de Vinos 🍷",chatSubtitle:"Describe tu comida y obtén una recomendación en 30 segundos",inputPlaceholder:"ej., Ensalada de atún",sendButton:"Combinar",poweredBy:"Desarrollado por",price:"Precio",region:"Región",type:"Tipo",reason:"Sugerencia",moreInfo:"Más info",winePairingIntro:"Para este vino, aquí tienes algunas sugerencias de platos:",askForDinner:"¿Qué te gustaría cenar?",clearChatButton:"Limpiar el chat",widgetTitle:"ENCUENTRA TU VINO PERFECTO",widgetSubtitle:"Comparte cualquier cosa que tengas en mente—tu comida, estado de ánimo, presupuesto o evento—y nuestro sommelier de IA te recomendará el vino perfecto en segundos",searchPlaceholder:"Escribe una palabra clave o descripción",wineDetails:{reason:"Razón",price:"Precio",region:"Región",type:"Tipo",code:"Código",moreInfo:"Más información",sommSelection:"Selección Somm",buy:"Comprar"},searchButton:"Buscar",priceRange:"Rango de precios",wineColor:"Color del vino",intensity:"Intensidad",red:"Tinto",white:"Blanco",rose:"Rosado",light:"Ligero",medium:"Medio",full:"Intenso",barTitle:"Platos de Bar",barSubtitle:"Selecciona de la lista y presiona «Enviar»",barSendButton:"Enviar",barResetButton:"Reiniciar",barName:"Nombre del bar",barNotesPlaceholder:"Agrega tus comentarios aquí...",placeholderSuggestions:["Vino para pasta","Perfecto con pescado","Recomendado para una fiesta"],headerLine1:"Comparte cualquier cosa que tengas en mente —",headerLine2:"— y obtén recomendaciones del vino perfecto en cuestión de segundos",headerMeal:"comida",headerMood:"estado de ánimo",headerBudget:"presupuesto",headerOccasion:"ocasión",headerOr:"o"},en:{lang:"en",welcomeMessage:"What are you planning to eat? Share your dish and I'll recommend the perfect wine pairing for your meal.",noResultsFound:"No results found.",somethingWentWrong:"Sorry, something went wrong.",chatButton1:"Find Your Pairing",chatButton2:"Pair Wine Now",chatButton3:"Get Wine Advice",chatTitle:"Wine Pairing Assistant 🍷",chatSubtitle:"Describe your meal and get a recommendation in 30 seconds",inputPlaceholder:"e.g., Tuna salad",sendButton:"Match",poweredBy:"Powered by",price:"Price",region:"Region",type:"Type",reason:"Suggestion",moreInfo:"More info",winePairingIntro:"For this wine, here are some suggested dishes:",askForDinner:"What would you like to have for dinner?",clearChatButton:"Clear Chat",widgetTitle:"FIND YOUR PERFECT WINE",widgetSubtitle:"Share anything on your mind—your meal, mood, budget, or occasion—and our AI sommelier will recommend the perfect wine in seconds",searchPlaceholder:"Enter a keyword or description",wineDetails:{price:"Price",region:"Region",type:"Type",moreInfo:"More info",reason:"Reason",sommSelection:"Somm Selection",code:"Code",buy:"Buy"},searchButton:"Search",priceRange:"Price Range",wineColor:"Wine Color",intensity:"Intensity",red:"Red",white:"White",rose:"Rosé",light:"Light",medium:"Medium",full:"Full",barTitle:"Bar Dishes",barSubtitle:"Select dishes below and click ‘Send’",barSendButton:"Send",barResetButton:"Reset",barName:"Bar Name",barNotesPlaceholder:"Add your wishes here...",placeholderSuggestions:["Wine for pasta","Perfect with fish","Recommended for a party"],headerLine1:"Share anything on your mind —",headerLine2:"— and get recommendations of the perfect wine in seconds",headerMeal:"meal",headerMood:"mood",headerBudget:"budget",headerOccasion:"occasion",headerOr:"or"},de:{lang:"de",welcomeMessage:"Was möchten Sie essen? Beschreiben Sie Ihr Gericht und ich empfehle Ihnen den perfekten Wein dazu.",noResultsFound:"Keine Ergebnisse gefunden.",somethingWentWrong:"Entschuldigung, etwas ist schief gelaufen.",chatButton1:"Finde Dein Pairing",chatButton2:"Wein jetzt wählen",chatButton3:"Erhalte Weinberatung",chatTitle:"Wein & Speisen 🍷",chatSubtitle:"Beschreiben Sie Ihr Gericht und erhalten Sie in 30 Sekunden eine Empfehlung",inputPlaceholder:"z.B., Thunfischsalat",sendButton:"Kombinieren",poweredBy:"Unterstützt von",price:"Preis",region:"Region",type:"Typ",reason:"Anregung",moreInfo:"Mehr Info",winePairingIntro:"Für diesen Wein gibt es folgende Essensvorschläge:",askForDinner:"Was möchten Sie zum Abendessen essen?",clearChatButton:"Chat löschen",widgetTitle:"FINDEN SIE IHREN PERFEKTEN WEIN",widgetSubtitle:"Teilen Sie alles, was Ihnen in den Sinn kommt—Ihre Mahlzeit, Stimmung, Ihr Budget oder Anlass—und unser KI-Sommelier empfiehlt Ihnen in Sekunden den perfekten Wein",placeholderSuggestions:["Wein für Pasta","Perfekt zu Fisch","Empfohlen für eine Party"],searchPlaceholder:"Geben Sie ein Stichwort oder eine Beschreibung ein",wineDetails:{price:"Preis",region:"Region",type:"Typ",moreInfo:"Mehr Infos",sommSelection:"Somm-Auswahl",reason:"Grund",code:"Code",buy:"Kaufen"},searchButton:"Suche",priceRange:"Preisspanne",wineColor:"Weinfarbe",intensity:"Intensität",red:"Rot",white:"Weiß",rose:"Rosé",light:"Leicht",medium:"Mittel",full:"Voll",barTitle:"Bar-Auswahl",barSubtitle:"Wählen Sie Ihre Gerichte und klicken Sie auf „Senden“",barSendButton:"Senden",barResetButton:"Zurücksetzen",barName:"Name der Bar",headerLine1:"Teilen Sie alles, was Ihnen durch den Kopf geht —",headerLine2:"— und erhalten Sie in Sekundenschnelle Empfehlungen für den perfekten Wein",headerMeal:"Mahlzeit",headerMood:"Stimmung",headerBudget:"Budget",headerOccasion:"Anlass",headerOr:"oder"},ukr:{lang:"ukr",welcomeMessage:"Що ви збираєтесь їсти? Опишіть свою страву, і я порекомендую вам ідеальне вино.",noResultsFound:"Результатів не знайдено.",somethingWentWrong:"Вибачте, щось пішло не так.",chatButton1:"Знайти ідеальне поєднання",chatButton2:"Підібрати вино",chatButton3:"Отримати пораду",chatTitle:"Сомельє-помічник 🍷",chatSubtitle:"Опишіть свою страву і отримайте рекомендацію за 30 секунд",inputPlaceholder:"наприклад, Тунець із салатом",sendButton:"Підібрати",poweredBy:"Розроблено на основі",price:"Ціна",region:"Регіон",type:"Тип",reason:"Рекомендація",moreInfo:"Докладніше",winePairingIntro:"До цього вина підходять такі страви:",askForDinner:"Що ви хочете на вечерю?",clearChatButton:"Очистити чат",widgetTitle:"ЗНАЙДІТЬ ІДЕАЛЬНЕ ВИНО",widgetSubtitle:"Поділіться тим, що у вас на думці—їжа, настрій, бюджет чи подія—і наш AI-сомельє порекомендує вам ідеальне вино за секунди",searchPlaceholder:"Введіть ключове слово або опис",wineDetails:{reason:"Причина",price:"Ціна",region:"Регіон",type:"Тип",moreInfo:"Докладніше",sommSelection:"Вибір сомельє",code:"Код",buy:"Купити"},searchButton:"Пошук",priceRange:"Діапазон цін",wineColor:"Колір вина",intensity:"Інтенсивність",red:"Червоне",white:"Біле",rose:"Рожеве",light:"Легке",medium:"Середнє",full:"Повне",barTitle:"Закуски до вина",barSubtitle:"Виберіть страви нижче та натисніть «Надіслати»",barSendButton:"Надіслати",barResetButton:"Скинути",barName:"Назва бару",barNotesPlaceholder:"Додайте ваші побажання тут...",placeholderSuggestions:["Вино до пасти","Ідеально до риби","Рекомендуємо для вечірки"],headerLine1:"Поділіться будь-якими вашими думками —",headerLine2:"— і отримайте рекомендації щодо ідеального вина за секунди",headerMeal:"страва",headerMood:"настрій",headerBudget:"бюджет",headerOccasion:"подія",headerOr:"або"},ru:{lang:"ru",welcomeMessage:"Что вы планируете поесть? Напишите ваше блюдо, и я подберу идеальное вино к нему.",noResultsFound:"Результаты не найдены.",somethingWentWrong:"Извините, что-то пошло не так.",chatButton1:"Найти сочетание",chatButton2:"Подобрать вино",chatButton3:"Получить совет",chatTitle:"Ассистент по подбору вина 🍷",chatSubtitle:"Опишите ваше блюдо и получите рекомендацию за 30 секунд",inputPlaceholder:"например, Тунец с салатом",sendButton:"Подобрать",poweredBy:"Powered by",price:"Цена",region:"Регион",type:"Тип",reason:"Рекомендация",moreInfo:"Подробнее",winePairingIntro:"К этому вину подходят следующие блюда:",askForDinner:"Что бы вы хотели на ужин?",clearChatButton:"Очистить чат",widgetTitle:"НАЙДИТЕ ИДЕАЛЬНОЕ ВИНО",widgetSubtitle:"Поделитесь вашими предпочтениями — блюдом, настроением, бюджетом или случаем — и наш AI-сомелье подберёт идеальное вино за секунды",searchPlaceholder:"Введите ключевое слово или описание",wineDetails:{price:"Цена",region:"Регион",type:"Тип",moreInfo:"Подробнее",reason:"Причина",sommSelection:"Выбор сомелье",code:"Код",buy:"Купить"},searchButton:"Поиск",priceRange:"Диапазон цен",wineColor:"Цвет вина",intensity:"Интенсивность",red:"Красное",white:"Белое",rose:"Розовое",light:"Лёгкое",medium:"Среднее",full:"Полное",barTitle:"Закуски к вину",barSubtitle:"Выберите блюда ниже и нажмите ‘Отправить’",barSendButton:"Отправить",barResetButton:"Сбросить",barName:"Название бара",barNotesPlaceholder:"Добавьте ваши пожелания здесь...",placeholderSuggestions:["Вино для пасты","Идеально к рыбе","Рекомендуем для вечеринки"],headerLine1:"Поделитесь любыми вашими мыслями —",headerLine2:"— и получите рекомендации по идеальному вину за считанные секунды",headerMeal:"блюдо",headerMood:"настроение",headerBudget:"бюджет",headerOccasion:"случай",headerOr:"или"}}}async fetchConfig(e){try{const n=await this.api.getStoreConfig(e);this.language=n.lang}catch{this.language="en"}}translate(e){const n=e.split(".");let i=this.translations[this.language];for(const s of n)if(i&&typeof i=="object"&&s in i)i=i[s];else return e;return i}}const H=new Ma,Tn={barName:"LENEZ",dishGroups:[{groupTitle:"Entradas",dishes:["Pimientos rojo asado y aceite de oliva con ajo confitado","Ensalada de arúgula y parmesano","Tomate hierloom aliñado","Aceitunas LENEZ","Papatinaz","Croquetas | hongos de temporada | jamón serrano","Carpaccio Cesar","Torreznos","Calamares fritos"]},{groupTitle:"Bocadillos",dishes:["Brioche de pollo frito, col y salsa macha","Baguette de calamares rebozados en salsa brava","Hogaza de cola de res en recado negro y cebollas encurtidas"]},{groupTitle:"Embutidos",dishes:["Jamón Ibérico de bellota","Lomo ibérico","Chorizo ibérico","Plato mixto iberico"]},{groupTitle:"Quesos",dishes:["Selección de quesos (D’Affinois, Brie Ermitage, Manchego semi curado, Roquefort)"]},{groupTitle:"Postres",dishes:["Ate con queso manchego semi curado","Gelato de nata con balsámico","Gelato de ron con pasas y “El candado”, Valdespino PX","Gelato Dua Lipa","Créme Brûlée al Orange"]}]};class Pa{constructor(){var e,n,i,s;this.widgetType=((e=window==null?void 0:window.wineaterData)==null?void 0:e.WIDGET_TYPE)||"store",this.widgetWrapper=((n=window==null?void 0:window.wineaterData)==null?void 0:n.WIDGET_WRAPPER)||"wineater-widget-conteiner",this.titleText=(i=window==null?void 0:window.wineaterData)==null?void 0:i.TITLE_TEXT,this.subtitleText=(s=window==null?void 0:window.wineaterData)==null?void 0:s.SUBTITLE_TEXT,this.api=new Rt,this.selectedFilters={price:null,color:null,intensity:null},this.widgetType==="bar"?(this.barName=Tn.barName,this.barDishes=Tn.dishes):(this.barName="",this.barDishes=[]),this.initializeWidget(),this.initializeSearchAnimation(),this.widgetType==="store"&&this.loadInstantRecommendations()}initializeWidget(){const e=document.getElementById(this.widgetWrapper);if(this.widgetType==="store"){const n=`
|
|
1248
1248
|
<div id="wine-widget-container">
|
|
1249
1249
|
<div class="wine-widget-wrapper">
|
|
1250
1250
|
<div id="wine-widget-header">
|
|
@@ -1299,15 +1299,15 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1299
1299
|
`;e.insertAdjacentHTML("beforeend",n),this.addEventListenersStoreVersion()}else{const n=`
|
|
1300
1300
|
<div id="wine-widget-container" class="bar-widget">
|
|
1301
1301
|
<div id="wine-widget-right">
|
|
1302
|
-
${Tn.dishGroups.map(
|
|
1302
|
+
${Tn.dishGroups.map(i=>`
|
|
1303
1303
|
<!-- Обёртка группы -->
|
|
1304
1304
|
<div class="dish-group">
|
|
1305
1305
|
<!-- Заголовок группы, если нужен -->
|
|
1306
1306
|
<!-- Сетка блюд конкретной группы -->
|
|
1307
1307
|
<div class="dish-grid">
|
|
1308
|
-
${
|
|
1309
|
-
<div class="dish-tile" data-dish="${
|
|
1310
|
-
${
|
|
1308
|
+
${i.dishes.map(s=>`
|
|
1309
|
+
<div class="dish-tile" data-dish="${s}">
|
|
1310
|
+
${s}
|
|
1311
1311
|
</div>
|
|
1312
1312
|
`).join("")}
|
|
1313
1313
|
</div>
|
|
@@ -1339,26 +1339,26 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1339
1339
|
|
|
1340
1340
|
</div>
|
|
1341
1341
|
</div>
|
|
1342
|
-
`;e.insertAdjacentHTML("beforeend",n),this.addEventListenersBarVersion()}this.initializeSearchAnimation()}addEventListenersStoreVersion(){document.getElementById("wine-search-button").addEventListener("click",()=>this.handleSearch()),this.setupFilterButtons("price-buttons","price"),this.setupFilterButtons("color-buttons","color"),this.setupFilterButtons("intensity-buttons","intensity"),document.getElementById("wine-search-input").addEventListener("keydown",e=>{e.key==="Enter"&&this.handleSearch()})}setupFilterButtons(e,n){const
|
|
1343
|
-
<div class="wine-recommendation-tile ${
|
|
1344
|
-
${
|
|
1342
|
+
`;e.insertAdjacentHTML("beforeend",n),this.addEventListenersBarVersion()}this.initializeSearchAnimation()}addEventListenersStoreVersion(){document.getElementById("wine-search-button").addEventListener("click",()=>this.handleSearch()),this.setupFilterButtons("price-buttons","price"),this.setupFilterButtons("color-buttons","color"),this.setupFilterButtons("intensity-buttons","intensity"),document.getElementById("wine-search-input").addEventListener("keydown",e=>{e.key==="Enter"&&this.handleSearch()})}setupFilterButtons(e,n){const i=document.querySelectorAll(`#${e} button`);i.forEach(s=>{s.addEventListener("click",r=>{i.forEach(o=>o.classList.remove("selected")),r.target.classList.add("selected"),this.selectedFilters[n]=r.target.dataset.value,this.handleSearch()})})}async handleSearch(){const e="wine for dish:"+document.getElementById("wine-search-input").value.trim()+";",n=this.selectedFilters,i=[];n.price&&i.push(`price: ${n.price||"any"};`),n.color&&i.push(`color: ${n.color||"any"}; `),n.intensity&&i.push(`intensity: ${n.intensity||"any"}; `);const s=i.length>0?`${e} ${i.join(", ")}`:e;console.log("Searching for:",s),console.log("Applied filters:",n),this.animateCardDisappearance();try{const r=await this.api.getWineRecommendationsSearch(s);r&&r.length>0?(console.log("Recommendations:",r),this.displayResults(r,!0)):(console.log("No recommendations found."),this.displayNoResultsMessage())}catch(r){console.error("Error fetching wine recommendations:",r.message),this.displayErrorMessage()}}displayResults(e,n=!1){const i=document.getElementById("wine-placeholder");this.hideLoadingIndicator(),i.innerHTML="",e.forEach((s,r)=>{const o=[];(s.type||s.Type)&&o.push(s.type||s.Type),(s.country||s.Country)&&o.push(s.country||s.Country),(s.region||s.Region)&&o.push(s.region||s.Region),(s.grape||s.Grape)&&o.push(s.grape||s.Grape);const l=[];(s.type||s.Type)&&l.push(s.type||s.Type),(s.country||s.Country)&&l.push(s.country||s.Country),(s.region||s.Region)&&l.push(s.region||s.Region),(s.grape||s.Grape)&&l.push(s.grape||s.Grape);const a=l.slice(0,3).join(" • "),d=l.slice(3).join(" • "),c=`
|
|
1343
|
+
<div class="wine-recommendation-tile ${s.isSommSelection?"somm-selection":""}">
|
|
1344
|
+
${s.isSommSelection?`<div class="somm-selection-badge">
|
|
1345
1345
|
${H.translate("wineDetails.sommSelection")}
|
|
1346
1346
|
</div>`:""}
|
|
1347
1347
|
|
|
1348
1348
|
<div class="tile-top">
|
|
1349
1349
|
<!-- Большое изображение по центру -->
|
|
1350
|
-
${
|
|
1351
|
-
alt="${
|
|
1350
|
+
${s.image||s.Image?`<img src="${s.image||s.Image}"
|
|
1351
|
+
alt="${s.title||s.Title}"
|
|
1352
1352
|
class="wine-image" />`:""}
|
|
1353
1353
|
|
|
1354
1354
|
<!-- Цена над названием -->
|
|
1355
1355
|
<div class="wine-price">
|
|
1356
|
-
${
|
|
1356
|
+
${s.price||s.Price}
|
|
1357
1357
|
</div>
|
|
1358
1358
|
|
|
1359
1359
|
<!-- Название вина (больше шрифт) -->
|
|
1360
1360
|
<h2 class="wine-title">
|
|
1361
|
-
${
|
|
1361
|
+
${s.title||s.Title}
|
|
1362
1362
|
</h2>
|
|
1363
1363
|
</div>
|
|
1364
1364
|
|
|
@@ -1368,12 +1368,12 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1368
1368
|
|
|
1369
1369
|
<!-- Кнопка Buy, видна только при наведении -->
|
|
1370
1370
|
<div class="bottom-row">
|
|
1371
|
-
<a class="buy-btn" href="${
|
|
1371
|
+
<a class="buy-btn" href="${s.url||s.Url}" target="_blank">
|
|
1372
1372
|
${H.translate("wineDetails.buy")}
|
|
1373
1373
|
</a>
|
|
1374
1374
|
</div>
|
|
1375
1375
|
</div>
|
|
1376
|
-
`;
|
|
1376
|
+
`;i.insertAdjacentHTML("beforeend",c);const u=i.children[r];setTimeout(()=>{u.style.opacity="1",u.style.transform="translateY(0)"},n?r*200:0)})}animateCardDisappearance(){const e=document.querySelectorAll(".wine-recommendation-tile");e.forEach((n,i)=>{setTimeout(()=>{n.style.opacity="0",n.style.transform="translateY(-20px)"},i*100)}),setTimeout(()=>{document.getElementById("wine-placeholder").innerHTML="",this.showLoadingIndicator()},e.length*100+300)}showLoadingIndicator(){document.getElementById("loading-indicator").classList.remove("hidden")}hideLoadingIndicator(){document.getElementById("loading-indicator").classList.add("hidden")}displayNoResultsMessage(){const e=document.getElementById("wine-placeholder");e.innerHTML=`
|
|
1377
1377
|
<div class="no-results">
|
|
1378
1378
|
<p>${H.translate("noResultsMessage")||"No recommendations found for your query."}</p>
|
|
1379
1379
|
</div>
|
|
@@ -1381,17 +1381,17 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1381
1381
|
<div class="error-message">
|
|
1382
1382
|
<p>${H.translate("errorMessage")||"Something went wrong. Please try again later."}</p>
|
|
1383
1383
|
</div>
|
|
1384
|
-
`}async loadInstantRecommendations(){this.showLoadingIndicator();try{const e=await this.api.getInstantRecommendations();this.displayResults(e)}catch(e){console.error("Error loading instant recommendations:",e.message)}}addEventListenersBarVersion(){const e=document.querySelectorAll(".dish-tile");e.forEach(l=>{l.addEventListener("click",()=>{l.classList.toggle("selected")})});const n=document.querySelectorAll(".dish-group"),
|
|
1385
|
-
<strong>${
|
|
1386
|
-
${H.translate("price")}: ${
|
|
1387
|
-
${H.translate("region")}: ${
|
|
1388
|
-
${H.translate("type")}: ${
|
|
1389
|
-
<a href="${
|
|
1390
|
-
`,l.querySelector("a").addEventListener("click",c=>{c.preventDefault(),this.sendAnalytics(
|
|
1384
|
+
`}async loadInstantRecommendations(){this.showLoadingIndicator();try{const e=await this.api.getInstantRecommendations();this.displayResults(e)}catch(e){console.error("Error loading instant recommendations:",e.message)}}addEventListenersBarVersion(){const e=document.querySelectorAll(".dish-tile");e.forEach(l=>{l.addEventListener("click",()=>{l.classList.toggle("selected")})});const n=document.querySelectorAll(".dish-group"),i=document.getElementById("bar-send-button"),s=document.getElementById("bar-reset-button"),r=document.getElementById("bar-notes-input"),o=document.getElementById("wine-placeholder");!i||!s||!r||!o||(i.addEventListener("click",async()=>{n.forEach(u=>u.classList.add("hidden")),this.showLoadingIndicator();const l=[];document.querySelectorAll(".dish-tile.selected").forEach(u=>{l.push(u.dataset.dish)});const a=r.value.trim(),d=[];l.length>0&&d.push(`Dishes: ${l.join(", ")}`),a&&d.push(`Notes: ${a}`);const c=d.join("; ");console.log("Final query =>",c);try{const u=await this.api.getWineRecommendationsSearch(c);u&&u.length>0?this.displayResults(u,!0):this.displayNoResultsMessage(),s.classList.remove("hidden")}catch(u){console.error("Error while fetching bar recommendations:",u),this.displayErrorMessage()}finally{this.hideLoadingIndicator()}}),s.addEventListener("click",()=>{n.forEach(l=>l.classList.remove("hidden")),e.forEach(l=>l.classList.remove("selected")),o.innerHTML="",s.classList.add("hidden"),r.value=""}))}initializeSearchAnimation(){const e=document.getElementById("wine-search-input"),n=H.translate("placeholderSuggestions");let i=0,s=0,r=!0,o=!1;const l=()=>{o||(r?(e.placeholder=n[i].substring(0,s++),s>n[i].length?(r=!1,setTimeout(l,2e3)):setTimeout(l,100)):(e.placeholder=n[i].substring(0,s--),s<0?(r=!0,i=(i+1)%n.length,setTimeout(l,500)):setTimeout(l,50)))};l(),e.addEventListener("focus",()=>{e.placeholder="",o=!0}),e.addEventListener("blur",()=>{o=!1,s=0,r=!0,l()})}}class Ba{constructor(){var n;this.api=new Rt;const e=((n=window==null?void 0:window.wineaterData)==null?void 0:n.FIRST_MESSAGE_TEXT)||H.translate("welcomeMessage");this.displayFirstMessage(e)}initialize(){document.getElementById("send-button").addEventListener("click",()=>this.handleUserInput()),document.getElementById("user-input").addEventListener("keypress",i=>{i.key==="Enter"&&this.handleUserInput()})}displayFirstMessage(e,n="api"){const i=document.getElementById("message-container"),s=document.createElement("div");s.className=`message ${n}`,s.textContent=e,i.appendChild(s),i.scrollTop=i.scrollHeight}async handleUserInput(){const e=document.getElementById("user-input"),n=e.value.trim();if(n){this.displayMessage(n,"user"),e.value="",this.showTypingIndicator();try{Ds(n);const i=await this.api.getWineRecommendations(n);this.hideTypingIndicator(),i&&i.length?this.displayResults(i):this.displayMessage("No results found.","api")}catch{this.hideTypingIndicator(),this.displayMessage(H.translate("somethingWentWrong"),"api")}}}showTypingIndicator(){document.getElementById("typing-indicator").classList.add("visible")}hideTypingIndicator(){document.getElementById("typing-indicator").classList.remove("visible")}displayMessage(e,n){const i=document.getElementById("message-container"),s=document.createElement("div");s.textContent=e,s.className="message "+n,i.appendChild(s),i.scrollTop=i.scrollHeight}sendAnalytics(e){console.log(e),Fs(e)}displayResults(e){console.log(e);const n=document.getElementById("message-container");Ls(e.map(i=>i.Title)),e.forEach(i=>{const s=document.createElement("div");s.className="wine-recommendation";const r=document.createElement("div");r.className="wine-item",s.appendChild(r);const o=document.createElement("img");o.src=i.Image,r.appendChild(o),console.log(r,"wine div");const l=document.createElement("div");l.innerHTML=`
|
|
1385
|
+
<strong>${i.Title}</strong><br>
|
|
1386
|
+
${H.translate("price")}: ${i.Price}<br>
|
|
1387
|
+
${H.translate("region")}: ${i.Region}<br>
|
|
1388
|
+
${H.translate("type")}: ${i.Type}<br>
|
|
1389
|
+
<a href="${i.Url}" target="_blank">${H.translate("moreInfo")}</a>
|
|
1390
|
+
`,l.querySelector("a").addEventListener("click",c=>{c.preventDefault(),this.sendAnalytics(i.Title),window.open(i.Url,"_blank")}),r.appendChild(l);const d=document.createElement("div");d.className="wine-description",d.innerHTML=i.Reason,s.appendChild(d),console.log(s),n.appendChild(s)}),n.scrollTop=n.scrollHeight}}const ja=3;let At=null;function za(){const t=document.getElementById("chat-window"),e=document.getElementById("chat-icon");t.classList.contains("visible")?(Vn(),Ua(),e.style.display="flex"):(At&&(clearTimeout(At),At=null),As(),t.classList.add("visible"),e.style.display="none")}function Ua(){console.log("ghbdtn"),Vn(),document.getElementById("chat-window").classList.remove("visible");let e=parseInt(ie("chatCloseCount"))||0;e+=1,e>=ja?(console.log(e),rt("disableAutoOpen","true",1),Os("chatCloseCount")):(console.log(e),rt("chatCloseCount",e,1))}document.addEventListener("DOMContentLoaded",()=>{setupCloseButton(),setupOutsideClick()});function Ha(t){At=t}new Rt;const Dt={PRODUCT_PAGES:/producto\/[^\/]+\/$/},ms={FESTIVAL_PAGES:/festival/,TASTING_PAGES:/tasting/},$a={FESTIVAL_PAGES:((vs=window.wineaterData)==null?void 0:vs.FESTIVAL_PAGES)||ms.FESTIVAL_PAGES,TASTING_PAGES:((ws=window.wineaterData)==null?void 0:ws.TASTING_PAGES)||ms.TASTING_PAGES},qa={PRODUCT_PAGES:((Ss=window.wineaterData)==null?void 0:Ss.PRODUCT_PAGES)||Dt.PRODUCT_PAGES,CART_PAGE:((xs=window.wineaterData)==null?void 0:xs.CART_PAGE)||(Dt==null?void 0:Dt.CART_PAGE)};async function Wa(){const t=window.location.href;for(const[e,n]of Object.entries($a))if(n.test(t))return!1;for(const[e,n]of Object.entries(qa))if(n.test(t))try{console.log(dishes);const i=setTimeout(()=>{openChatWindow()},15e3);return Ha(i),!0}catch(i){return console.error("Error fetching dishes:",i),!1}return!1}const Ga="HeUw6IXuhvz6tRuXdPEGEbj3SGQ3Q2YtEc1Z8jd41Kg9LtyPb4Epu0to31SYIadG";class Va{constructor(){var e,n;this.stores=["climats","telckel","biobio","weinpoint","vinigrandi","ampely","test"],this.tracker=new Aa({projectKey:"PA8j9fAi49i6g2QnvpNs",__DISABLE_SECURE_MODE:!0}),this.position=((e=window==null?void 0:window.wineaterData)==null?void 0:e.POSITION)||"right-center",this.type=((n=window==null?void 0:window.wineaterData)==null?void 0:n.TYPE)||"chatbot",this.store=this.detectStore()}detectStore(){return this.stores.find(e=>window.location.href.includes(e))||null}async initFlagsmith(){try{await Xn.init({environmentID:"5RfiDoiqb4dHrNdQvzbkfM",cacheFlags:!1,enableAnalytics:!0,identity:ie("uniqueUserID")})}catch(e){console.error("Flagsmith initialization failed:",e)}}async initTranslator(){const e=this.store?this.store.charAt(0).toUpperCase()+this.store.slice(1):"Test";await H.fetchConfig(e||"Test")}initCookies(){var e;rt("chatbotToken",((e=window.wineaterData)==null?void 0:e.CLIENT_TOKEN)||Ga,365),Rs()}async initializeChatbotOrWidget(){this.type==="widget"?new Pa:(this.createChatbotUI(),this.setupChatListeners(),this.setupChatButtonListener(),Ka(this.position),new Ba().initialize())}createChatbotUI(){var s;const e=Xn.getValue("chat-btn-txt"),i=`
|
|
1391
1391
|
<div id="chatbot-container">
|
|
1392
1392
|
<div id="chat-icon">
|
|
1393
1393
|
<img src="https://czvgkhagwvmknscoerfy.supabase.co/storage/v1/object/public/static-media/chat-icon.svg" alt="Chat Icon">
|
|
1394
|
-
<span>${((
|
|
1394
|
+
<span>${((s=window==null?void 0:window.wineaterData)==null?void 0:s.BUTTON_TEXT)||H.translate(`chatButton${e}`)}</span>
|
|
1395
1395
|
</div>
|
|
1396
1396
|
<div id="chat-window" class="hidden">
|
|
1397
1397
|
<div id="chat-header">
|
|
@@ -1415,4 +1415,4 @@ margin-top: auto; /* прижимает .bottom-row к низу
|
|
|
1415
1415
|
</a>
|
|
1416
1416
|
</div>
|
|
1417
1417
|
</div>
|
|
1418
|
-
`;document.body.insertAdjacentHTML("beforeend",
|
|
1418
|
+
`;document.body.insertAdjacentHTML("beforeend",i)}setupChatListeners(){document.getElementById("close-btn").addEventListener("click",za),window.addEventListener("click",n=>{const i=document.getElementById("chat-window"),s=document.getElementById("chat-icon");!i.contains(n.target)&&!s.contains(n.target)&&(i.classList.remove("visible"),s.style.display="flex")})}autoOpenChatIfNeeded(){ie("disableAutoOpen")||Wa()}setupChatButtonListener(){const e=document.getElementById("chat-icon"),n=document.getElementById("chat-window");if(!e||!n){console.error("Chat icon or chat window element not found!");return}e.addEventListener("click",()=>{n.classList.contains("visible")?(n.classList.remove("visible"),e.style.display="flex"):(n.classList.add("visible"),e.style.display="none")})}async initialize(){this.tracker.start(),await this.initFlagsmith(),await this.initTranslator(),this.initCookies(),await this.initializeChatbotOrWidget(),this.autoOpenChatIfNeeded()}}function Ka(t="right-center"){const e=document.getElementById("chat-icon");e&&(e.className=`chat-icon-${t}`)}document.addEventListener("DOMContentLoaded",()=>{new Va().initialize()})});
|