wineater-bot 2.1.2 → 2.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(Ee,Je){typeof exports=="object"&&typeof module<"u"?Je(exports):typeof define=="function"&&define.amd?define(["exports"],Je):(Ee=typeof globalThis<"u"?globalThis:Ee||self,Je(Ee.WineaterChatbot={}))})(this,function(Ee){"use strict";var bi,Si,wi,xi,ki,Ti;const Je=`
1
+ (function(Ee,Je){typeof exports=="object"&&typeof module<"u"?Je(exports):typeof define=="function"&&define.amd?define(["exports"],Je):(Ee=typeof globalThis<"u"?globalThis:Ee||self,Je(Ee.WineaterChatbot={}))})(this,function(Ee){"use strict";var Ti,Ei,Ci,Ii,_i,Oi;const Je=`
2
2
  @font-face {
3
3
  font-family: 'Poppins';
4
4
  src: url('https://fonts.googleapis.com/css2?family=Poppins:wght@400&display=swap');
@@ -10,7 +10,7 @@
10
10
  bottom: 20px;
11
11
  right: 20px;
12
12
  font-family: 'Poppins', sans-serif; /* Use Poppins as the main font */
13
- z-index: 1000; /* Ensure chat is above other content */
13
+ z-index: 10000; /* Ensure chat is above other content */
14
14
  }
15
15
 
16
16
  /* Styling the chat icon */
@@ -28,6 +28,7 @@
28
28
  font-family: 'Poppins', sans-serif;
29
29
  font-size: 16px; /* Увеличенный размер текста */
30
30
  font-weight: bold;
31
+ box-sizing: border-box;
31
32
  transition: transform 0.2s ease, box-shadow 0.2s ease; /* Анимация при наведении */
32
33
  }
33
34
 
@@ -84,14 +85,18 @@
84
85
  /* Chat window styles */
85
86
  #chat-window {
86
87
  position: fixed;
87
- bottom: 20px;
88
- right: 20px;
89
- width: 380px;
90
- background-color: white;
91
- border-radius: 24px;
92
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
93
- display: none;
94
- overflow: hidden;
88
+ bottom: 20px;
89
+ right: 20px;
90
+ width: 380px;
91
+ background-color: white;
92
+ border-radius: 24px;
93
+ border: 2px solid transparent;
94
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
95
+ display: none;
96
+ overflow: hidden;
97
+ background: linear-gradient(white, white) padding-box,
98
+ linear-gradient(90deg, #7B2BEB, #0044FF) border-box;
99
+
95
100
  }
96
101
 
97
102
  #chat-header {
@@ -360,10 +365,17 @@ border-top-left-radius: 4px;
360
365
  }
361
366
 
362
367
  .wine-item a {
363
- color: #0044FF;
364
- text-decoration: none;
365
- font-size: 14px;
366
- font-weight: 500;
368
+ color: #0044FF; /* Синий цвет ссылки */
369
+ text-decoration: underline; /* Подчеркивание для эффекта ссылки */
370
+ font-size: 14px; /* Размер текста */
371
+ font-weight: 500; /* Полужирный текст */
372
+ margin-top: 10px; /* Отступ сверху */
373
+ display: inline-block; /* Чтобы отступы работали корректно */
374
+ }
375
+
376
+ .wine-item a:hover {
377
+ text-decoration: none; /* Убираем подчеркивание при наведении */
378
+ color: #002699; /* Более темный синий для интерактивного эффекта */
367
379
  }
368
380
 
369
381
  .wine-description {
@@ -387,7 +399,7 @@ border-bottom-right-radius: 15px;
387
399
 
388
400
  /* Loader Styles */
389
401
  .loader {
390
- display: none;
402
+ display: none;
391
403
  width: 40px;
392
404
  height: 40px;
393
405
  margin: 20px auto;
@@ -423,7 +435,7 @@ border-bottom-right-radius: 15px;
423
435
  justify-content: center;
424
436
  align-items: center;
425
437
  height: 0;
426
- visibility: hidden;
438
+ visibility: hidden;
427
439
  background-color: white;
428
440
  }
429
441
 
@@ -477,7 +489,7 @@ border-bottom-right-radius: 15px;
477
489
  }
478
490
 
479
491
  #message-container {
480
- height: calc(100vh - 180px); /* Учитываем высоту header и input container */
492
+ height: calc(100vh - 250px); /* Учитываем высоту header и input container */
481
493
  max-height: none;
482
494
  }
483
495
 
@@ -624,43 +636,43 @@ border-bottom-right-radius: 15px;
624
636
  height: 80px;
625
637
  }
626
638
  }
627
- `,Vs=document.createElement("style");Vs.textContent=Je,document.head.appendChild(Vs);function Ri(){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 ot(t,e,s){console.log(t,s);let n="";if(s){const i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3),n="; expires="+i.toUTCString()}document.cookie=t+"="+(e||"")+n+"; path=/; secure; samesite=strict"}function te(t){const e=t+"=",s=document.cookie.split(";");for(let n=0;n<s.length;n++){let i=s[n];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 Di(t){document.cookie=t+"=; Max-Age=-99999999;"}function Ai(){const t="uniqueUserID";let e=te(t);return e||(e=Ri(),ot(t,e,365)),e}function Le(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 Gs(){Le("Chatbot Opened",{distinct_id:te("uniqueUserID"),client:te("chatbotToken")})}function Fi(t){Le("Chatbot Opened Auto",{distinct_id:te("uniqueUserID"),url:t,client:te("chatbotToken")})}function Ks(){Le("Chatbot Closed",{distinct_id:te("uniqueUserID"),client:te("chatbotToken")})}function Mi(t){Le("Message Sent",{distinct_id:te("uniqueUserID"),message_content:t,client:te("chatbotToken")})}function Li(t){Le("Products Got",{distinct_id:te("uniqueUserID"),products:t,client:te("chatbotToken")})}function Pi(t){Le("Product Clicked",{distinct_id:te("uniqueUserID"),product_id:t,client:te("chatbotToken")})}var Pe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ft={exports:{}};(function(t,e){(function(s,n){n(e)})(Pe,function(s){var n={getItemSync:function(v){try{return localStorage.getItem(v)||null}catch{return null}},getItem:function(v,f){var h=this;return new Promise(function(m,g){try{var S=h.getItemSync(v);f==null||f(null,S),m(S)}catch(x){f&&f(x,null),g(x)}})},setItem:function(v,f,h){return new Promise(function(m,g){try{localStorage.setItem(v,f),h&&h(null,f),m(f)}catch(S){h&&h(S,null),g(S)}})}},i=function(){return i=Object.assign||function(v){for(var f,h=1,m=arguments.length;h<m;h++)for(var g in f=arguments[h])Object.prototype.hasOwnProperty.call(f,g)&&(v[g]=f[g]);return v},i.apply(this,arguments)};function r(v,f,h,m){return new(h||(h=Promise))(function(g,S){function x(z){try{L(m.next(z))}catch(_){S(_)}}function R(z){try{L(m.throw(z))}catch(_){S(_)}}function L(z){var _;z.done?g(z.value):(_=z.value,_ instanceof h?_:new h(function($){$(_)})).then(x,R)}L((m=m.apply(v,f||[])).next())})}function o(v,f){var h,m,g,S,x={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return S={next:R(0),throw:R(1),return:R(2)},typeof Symbol=="function"&&(S[Symbol.iterator]=function(){return this}),S;function R(L){return function(z){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(v,x)}catch($){_=[6,$],m=0}finally{h=g=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}([L,z])}}}function l(v,f,h){if(h||arguments.length===2)for(var m,g=0,S=f.length;g<S;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return v.concat(m||Array.prototype.slice.call(f))}var a=function v(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,S;if(Array.isArray(f)){if((m=f.length)!=h.length)return!1;for(g=m;g--!=0;)if(!v(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=(S=Object.keys(f)).length)!==Object.keys(h).length)return!1;for(g=m;g--!=0;)if(!Object.prototype.hasOwnProperty.call(h,S[g]))return!1;for(g=m;g--!=0;){var x=S[g];if(!v(f[x],h[x]))return!1}return!0}return f!=f&&h!=h};function u(v,f){var h=Object.keys(f||{}).filter(function(m){var g=v==null?void 0:v[m],S=f==null?void 0:f[m];return!a(g,S)});return Object.keys(v||{}).filter(function(m){Object.keys(f||{}).includes(m)||h.push(m)}),Object.keys(h).length?h:null}var c,d;function p(v,f,h){var m="shortString",g=!0;typeof h=="number"&&(m="javaDouble",g=!1),v[m]=v[m]||{},v[m][f]=g?h+"":h}function y(v){return!!v&&typeof v=="object"&&v.value!==void 0}function w(v){return Object.fromEntries(Object.entries(v).map(function(f){var h=f[0],m=f[1];return[h,y(m)?m:{value:m}]}))}function b(v){return i(i({},v),{identity:v.identity?i(i({},v.identity),{traits:w(v.identity.traits||{})}):void 0})}(function(v){v.NONE="NONE",v.DEFAULT_FLAGS="DEFAULT_FLAGS",v.CACHE="CACHE",v.SERVER="SERVER"})(c||(c={}));var T,D=null,B="BULLET_TRAIN_DB",A="BULLET_TRAIN_EVENT",k="https://edge.api.flagsmith.com/api/v1/",O="flagsmith_value_",N="flagsmith_enabled_",F="flagsmith_trait_",C=function(){function v(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,S=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(L){var z,_,$,Z;if(L&&x==="".concat(h.getContext().identity)){var ae=L.flags,ee=L.traits,se=L.identifier;h.isLoading=!1;var he={},de={};ee=ee||[],(ae=ae||[]).forEach(function(K){he[K.feature.name.toLowerCase().replace(/ /g,"_")]={id:K.feature.id,enabled:K.enabled,value:K.feature_state_value}}),ee.forEach(function(K){de[K.trait_key.toLowerCase().replace(/ /g,"_")]={transient:K.transient,value:K.trait_value}}),h.oldFlags=i({},h.flags);var Se=u(h.oldFlags,he),tt=u((z=h.evaluationContext.identity)===null||z===void 0?void 0:z.traits,de);if((se||Object.keys(de).length)&&(h.evaluationContext.identity={traits:de},se&&(h.evaluationContext.identity.identifier=se)),h.flags=he,h.updateStorage(),h._onChange(h.oldFlags,{isFromServer:!0,flagsChanged:Se,traitsChanged:tt},h._loadedState(null,c.SERVER)),h.datadogRum)try{if(h.datadogRum.trackTraits){var st={};Object.keys(((_=h.evaluationContext.identity)===null||_===void 0?void 0:_.traits)||{}).map(function(K){st[F+K]=h.getTrait(K)});var Ge=i(i(i({},h.datadogRum.client.getUser()),{id:h.datadogRum.client.getUser().id||(($=h.evaluationContext.identity)===null||$===void 0?void 0:$.identifier)}),st);h.log("Setting Datadog user",Ge),h.datadogRum.client.setUser(Ge)}}catch(K){console.error(K)}if(h.dtrum)try{var re={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(h.flags).map(function(K){p(re,O+K,h.getValue(K,{skipAnalytics:!0})),p(re,N+K,h.hasFeature(K,{skipAnalytics:!0}))}),Object.keys(((Z=h.evaluationContext.identity)===null||Z===void 0?void 0:Z.traits)||{}).map(function(K){p(re,F+K,h.getTrait(K))}),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(K){console.error(K)}}};return S.identity?Promise.all([S.identity.traits&&Object.keys(S.identity.traits).length||!S.identity.identifier?h.getJSON(g+"identities/","POST",JSON.stringify({identifier:S.identity.identifier,transient:S.identity.transient,traits:Object.entries(S.identity.traits).map(function(L){var z=L[0],_=L[1];return{trait_key:z,trait_value:_==null?void 0:_.value,transient:_==null?void 0:_.transient}}).filter(function(L){return L.trait_value!==void 0||(h.log("Warning - attempted to set an undefined trait value for key",L.trait_key),!1)})})):h.getJSON(g+"identities/?identifier="+encodeURIComponent(S.identity.identifier)+(S.identity.transient?"&transient=true":""))]).then(function(L){return h.evaluationContext.identity=i(i({},h.evaluationContext.identity),{traits:{}}),R(L==null?void 0:L[0])}).catch(function(L){var z=L.message,_=new Error(z);return Promise.reject(_)}):h.getJSON(g+"flags/").then(function(L){return R({flags:L,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 S=h.getState();h.evaluationEvent||(h.evaluationEvent={}),h.evaluationEvent[h.evaluationContext.environment.apiKey]={},h.setState(i(i({},S),{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,S){var x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=null;if(x&&(R=x.value),g!=null&&g.skipAnalytics||S||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,S;return((g=h.evaluationContext.identity)===null||g===void 0?void 0:g.traits)&&((S=h.evaluationContext.identity.traits[m.toLowerCase().replace(/ /g,"_")])===null||S===void 0?void 0:S.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 S=g[0],x=g[1];return[S,x==null?void 0:x.value]}))},this.setContext=function(m){var g=b(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 S;if(h.api)return h.setContext(i(i({},h.evaluationContext),{identity:i(i({},h.evaluationContext.identity),{traits:i(i({},(S=h.evaluationContext.identity)===null||S===void 0?void 0:S.traits),w(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(S){var x=S[0],R=S[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 S=typeof g=="object",x=h.flags&&h.flags[m.toLowerCase().replace(/ /g,"_")],R=!1;return!x&&S&&g.fallback!==void 0?R=g==null?void 0:g.fallback:x&&x.enabled&&(R=!0),(S&&!g.skipAnalytics||!g)&&h.evaluateFlag(m,"ENABLED"),R},this.getJSON=function(m,g,S){var x,R=h;R.evaluationContext;var L=R.headers,z={method:g||"GET",body:S,cache:"no-cache",headers:{}};h.evaluationContext.environment&&(z.headers["X-Environment-Key"]=h.evaluationContext.environment.apiKey),g&&g!=="GET"&&(z.headers["Content-Type"]="application/json; charset=utf-8"),L&&Object.assign(z.headers,L),d||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 d(m,z).then(function($){var Z,ae,ee="".concat((Z=h.evaluationContext.identity)===null||Z===void 0?void 0:Z.identifier);if(_===ee){var se=(ae=$.headers)===null||ae===void 0?void 0:ae.get("x-flagsmith-document-updated-at");if(se)try{var he=parseFloat(se);if(isNaN(he))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");h.timestamp=he}catch(de){h.log(de,"Failed to parse x-flagsmith-document-updated-at",se)}return h.log("Fetch response: "+$.status+" "+(g||"GET")+0+m),$.text().then(function(de){var Se=de;try{Se=JSON.parse(de)}catch{}return!Se&&$.status&&(Se="API Response: ".concat($.status)),$.status&&$.status>=200&&$.status<300?Se:Promise.reject(new Error(Se))})}h.log("Received response with identity mismatch, ignoring response. Requested: ".concat(_,", Current: ").concat(ee))})},this.evaluateFlag=function(m,g){if(h.datadogRum&&(h.datadogRum.client.addFeatureFlagEvaluation?g==="VALUE"?h.datadogRum.client.addFeatureFlagEvaluation(O+m,h.getValue(m,{},!0)):h.datadogRum.client.addFeatureFlagEvaluation(N+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,S){var x,R;h.setLoadingState(S),(x=h.onChange)===null||x===void 0||x.call(h,m,g,h.loadingState),(R=h._trigger)===null||R===void 0||R.call(h)},d=f.fetch?f.fetch:typeof fetch<"u"?fetch:Pe==null?void 0:Pe.fetch,this.canUseStorage=typeof window<"u"||!!f.browserlessStorage,this.log("Constructing flagsmith instance "+f),f.eventSource&&(T=f.eventSource),f.AsyncStorage&&(D=f.AsyncStorage)}return v.prototype.init=function(f){var h,m,g;return r(this,void 0,void 0,function(){var S,x,R,L,z,_,$,Z,ae,ee,se,he,de,Se,tt,st,Ge,re,K,Es,nt,Ei,it,Cs,Ci,Ii,Is,_i,_s,rt,Ke,Oi,oe=this;return o(this,function(ge){switch(ge.label){case 0:S=b(f.evaluationContext||this.evaluationContext),ge.label=1;case 1:if(ge.trys.push([1,13,,14]),x=f.environmentID,R=f.api,L=R===void 0?k:R,z=f.headers,_=f.onChange,$=f.cacheFlags,Z=f.datadogRum,ae=f.onError,ee=f.defaultFlags,se=f.fetch,he=f.preventFetch,de=f.enableLogs,Se=f.enableDynatrace,tt=f.enableAnalytics,st=f.realtime,Ge=f.eventSourceUrl,re=Ge===void 0?"https://realtime.flagsmith.com/":Ge,K=f.AsyncStorage,Es=f.identity,nt=f.traits,Ei=f.state,it=f.cacheOptions,Cs=f.angularHttpClient,Ci=f._trigger,Ii=f._triggerLoadingState,S.environment=x?{apiKey:x}:S.environment,!S.environment||!S.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(S.identity=Es||nt?{identifier:Es,traits:nt?Object.fromEntries(Object.entries(nt).map(function(fe){return[fe[0],{value:fe[1]}]})):{}}:S.identity,this.evaluationContext=S,this.api=L,this.headers=z,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=_,Is="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=Ci||this._trigger,this._triggerLoadingState=Ii||this._triggerLoadingState,this.onError=function(fe){oe.setLoadingState(i(i({},oe.loadingState),{isFetching:!1,isLoading:!1,error:fe})),ae==null||ae(fe)},this.enableLogs=de||!1,this.cacheOptions=it?{skipAPI:!!it.skipAPI,ttl:it.ttl||0,loadStale:!!it.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."),se&&(d=se),this.enableAnalytics=tt||!1,this.flags=Object.assign({},ee)||{},this.datadogRum=Z||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?new Date().valueOf():null,this.cacheFlags=D!==void 0&&!!$,K&&(D=K),st&&typeof window<"u"&&this.setupRealtime(re,S.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=i(i({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(Ei),this.log("Initialising with properties",f,this),Se&&(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),Cs&&(d=function(fe){return function(we,xe){var Ne=xe.headers,J=xe.method,Xe=xe.body;return new Promise(function(Me){switch(J){case"GET":return fe.get(we,{headers:Ne}).subscribe(function(Te){Me({ok:!0,text:function(){return Promise.resolve(Te)}})});case"POST":case"PUT":return fe.post(we,Xe,{headers:Ne}).subscribe(function(Te){Me({ok:!0,text:function(){return Promise.resolve(Te)}})})}})}}(Cs)),D&&this.canUseStorage&&D.getItem(A).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),D&&this.canUseStorage&&D.getItem(A,function(fe,we){if(we&&oe.evaluationContext.environment){var xe=JSON.parse(we);if(xe[oe.evaluationContext.environment.apiKey]){var Ne=oe.getState();oe.log("Retrieved events from cache",we),oe.setState(i(i({},Ne),{evaluationEvent:xe[oe.evaluationContext.environment.apiKey]}))}}})),!$)return[3,9];if(!D||!this.canUseStorage)return[3,8];_i=function(fe,we){return r(oe,void 0,void 0,function(){var xe,Ne,J,Xe,Me,Te,Os,Ni,Ns,Rs,Ds,As,Fs,Ms,Ls,Ps,Bs,js,Us,Hs,zs,Ws,$s,qs;return o(this,function(Re){switch(Re.label){case 0:if(!we)return[3,7];xe=null,Ne=null,Re.label=1;case 1:return Re.trys.push([1,5,,6]),J=JSON.parse(we),Xe=!1,Me=!1,J&&J.api===this.api&&((Rs=(Ns=J.evaluationContext)===null||Ns===void 0?void 0:Ns.environment)===null||Rs===void 0?void 0:Rs.apiKey)===((Ds=this.evaluationContext.environment)===null||Ds===void 0?void 0:Ds.apiKey)&&(Te=!0,this.evaluationContext.identity&&((Fs=(As=J.evaluationContext)===null||As===void 0?void 0:As.identity)===null||Fs===void 0?void 0:Fs.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+((Ls=(Ms=J.evaluationContext)===null||Ms===void 0?void 0:Ms.identity)===null||Ls===void 0?void 0:Ls.identifier)+" to "+this.evaluationContext.identity.identifier),Te=!1),this.cacheOptions.ttl&&(!J.ts||new Date().valueOf()-J.ts>this.cacheOptions.ttl)&&(J.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+J.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-J.ts)+"ms"),Te=!1):J.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+J.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-J.ts)+"ms"),Me=!0,Te=!0)),Te&&(Xe=!0,Ne=u((Ps=this.evaluationContext.identity)===null||Ps===void 0?void 0:Ps.traits,(js=(Bs=J.evaluationContext)===null||Bs===void 0?void 0:Bs.identity)===null||js===void 0?void 0:js.traits),xe=u(this.flags,J.flags),this.setState(i(i({},J),{evaluationContext:b(i(i({},J.evaluationContext),{identity:!((Us=J.evaluationContext)===null||Us===void 0)&&Us.identity?i(i({},(Hs=J.evaluationContext)===null||Hs===void 0?void 0:Hs.identity),{traits:i(i({},((Ws=(zs=J.evaluationContext)===null||zs===void 0?void 0:zs.identity)===null||Ws===void 0?void 0:Ws.traits)||{}),nt||{})}):void 0}))})),this.log("Retrieved flags from cache",J))),Xe?(Os=!he&&(!this.cacheOptions.skipAPI||Me),this._onChange(null,{isFromServer:!1,flagsChanged:xe,traitsChanged:Ne},this._loadedState(null,c.CACHE,Os)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&Xe&&!Me&&this.log("Skipping API, using cache"),Os&&this.getFlags(),[3,4]):[3,2];case 2:return he?[3,4]:[4,this.getFlags()];case 3:Re.sent(),Re.label=4;case 4:return[3,6];case 5:return Ni=Re.sent(),this.log("Exception fetching cached logs",Ni),[3,6];case 6:return[3,10];case 7:return he?[3,9]:[4,this.getFlags()];case 8:return Re.sent(),[3,10];case 9:if(ee)this._onChange(null,{isFromServer:!1,flagsChanged:u({},this.flags),traitsChanged:u({},($s=this.evaluationContext.identity)===null||$s===void 0?void 0:$s.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(Is);this._onChange(null,{isFromServer:!1,flagsChanged:u({},this.flags),traitsChanged:u({},(qs=this.evaluationContext.identity)===null||qs===void 0?void 0:qs.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}Re.label=10;case 10:return[2]}})})},ge.label=2;case 2:return ge.trys.push([2,7,,8]),D.getItemSync?(_s=D.getItemSync(B),[3,5]):[3,3];case 3:return[4,D.getItem(B)];case 4:_s=ge.sent(),ge.label=5;case 5:return[4,_i(null,_s)];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(ee)this._onChange(null,{isFromServer:!1,flagsChanged:u({},ee),traitsChanged:u({},(h=S.identity)===null||h===void 0?void 0:h.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(rt=null,Object.keys(this.flags).length===0&&(rt=Is),this._onChange(null,{isFromServer:!1,flagsChanged:u({},this.flags),traitsChanged:u({},(m=S.identity)===null||m===void 0?void 0:m.traits)},this._loadedState(rt,c.DEFAULT_FLAGS)),rt))throw new Error(rt);ge.label=12;case 12:return[3,14];case 13:throw Ke=ge.sent(),this.log("Error during initialisation ",Ke),Oi=Ke instanceof Error?Ke:new Error("".concat(Ke)),(g=this.onError)===null||g===void 0||g.call(this,Oi),Ke;case 14:return[2]}})})},v.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}},v.prototype.getAllFlags=function(){return this.flags},v.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 S=g[0],x=g[1];return[S,y(x)?x:{value:x}]}))),this.initialised?this.getFlags():Promise.resolve()},v.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,evaluationEvent:this.evaluationEvent}},v.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))},v.prototype.logout=function(){return this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},v.prototype.startListening=function(f){f===void 0&&(f=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,f)},v.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},v.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))},v.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=new Date().valueOf();var f=JSON.stringify(this.getState());this.log("Setting storage",f),D.setItem(B,f)}},v.prototype.updateEventStorage=function(){if(this.enableAnalytics){var f=JSON.stringify(this.getState().evaluationEvent);D.setItem(A,f)}},v.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))},v.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(S){var x;try{x=JSON.parse(S.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",S.data,m.timestamp):(m.log("updated_at is new, fetching flags",S.data,m.timestamp),m.getFlags()):m.log("updated_at is outdated, skipping get flags",S.data,m.timestamp):m.log("No updated_at received, fetching flags",S)})):this.log("Error, EventSource is undefined")},v}();function E(v){var f=v.fetch,h=v.AsyncStorage,m=v.eventSource;return new C({fetch:f,AsyncStorage:h,eventSource:m})}var P,V=(P=function(v,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(v,f)},function(v,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=v}P(v,f),v.prototype=f===null?Object.create(f):(h.prototype=f.prototype,new h)}),j=function(v){var f=typeof Symbol=="function"&&Symbol.iterator,h=f&&v[f],m=0;if(h)return h.call(v);if(v&&typeof v.length=="number")return{next:function(){return v&&m>=v.length&&(v=void 0),{value:v&&v[m++],done:!v}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},W=function(v,f){var h=typeof Symbol=="function"&&v[Symbol.iterator];if(!h)return v;var m,g,S=h.call(v),x=[];try{for(;(f===void 0||f-- >0)&&!(m=S.next()).done;)x.push(m.value)}catch(R){g={error:R}}finally{try{m&&!m.done&&(h=S.return)&&h.call(S)}finally{if(g)throw g.error}}return x},I=function(v,f,h){if(h||arguments.length===2)for(var m,g=0,S=f.length;g<S;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return v.concat(m||Array.prototype.slice.call(f))},M=function(v){function f(){return v.call(this,`EventSource not available.
628
- 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,v),f}(Error),q=function(){function v(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 M;this._onevent_wrapped=function(g){m._onevent(g)},this._start()}return v.prototype.dispatchEvent=function(f){throw new Error("Method not implemented.")},v.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(L){m._onopen(L)},this._eventSource.onerror=function(L){m._onerror(L)},this._eventSource.onmessage=function(L){m.onmessage(L)};try{for(var S=j(Object.keys(this._listeners)),x=S.next();!x.done;x=S.next()){var R=x.value;this._eventSource.addEventListener(R,this._onevent_wrapped)}}catch(L){f={error:L}}finally{try{x&&!x.done&&(h=S.return)&&h.call(S)}finally{if(f)throw f.error}}},v.prototype._onopen=function(f){this.readyState===0&&(this.readyState=1,this.onopen(f))},v.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)}},v.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 S=j(I([],W(g),!1)),x=S.next();!x.done;x=S.next())x.value.call(this,f)}catch(R){h={error:R}}finally{try{x&&!x.done&&(m=S.return)&&m.call(S)}finally{if(h)throw h.error}}f.type==="message"&&this.onmessage(f)},v.prototype.onopen=function(f){},v.prototype.onerror=function(f){},v.prototype.onmessage=function(f){},v.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},v.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]=I(I([],W(g),!1),[h],!1))},v.prototype.removeEventListener=function(f,h,m){var g=this._listeners[f];this._listeners[f]=g.filter(function(S){return S!==h})},v}();globalThis.FlagsmithEventSource=typeof EventSource<"u"?EventSource:null;var G=function(v,f){return f=f||{},new Promise(function(h,m){var g=new XMLHttpRequest,S=[],x=[],R={},L=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:L,headers:{keys:function(){return S},entries:function(){return x},get:function(_){return R[_.toLowerCase()]},has:function(_){return _.toLowerCase()in R}}}};for(var z in g.open(f.method||"get",v,!0),g.onload=function(){g.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(_,$,Z){S.push($=$.toLowerCase()),x.push([$,Z]),R[$]=R[$]?R[$]+","+Z:Z}),h(L())},g.onerror=m,g.withCredentials=f.credentials=="include",f.headers)g.setRequestHeader(z,f.headers[z]);g.send(f.body||null)})},H=E({AsyncStorage:n,fetch:G,eventSource:q});typeof window<"u"&&(window.flagsmith=H),s.createFlagsmithInstance=function(){return E({AsyncStorage:n,fetch:G,eventSource:q})},s.default=H,Object.defineProperty(s,"__esModule",{value:!0})})})(Ft,Ft.exports);var Bi=Ft.exports;const Js=Xs(Bi);var Ys={},ji=function(t,e,s,n,i){var r=new Worker(Ys[e]||(Ys[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 u=new Error(a[0]);u.code=a[1],u.stack=a[2],i(u,null)}else i(null,l)},r.postMessage(s,n),r},ce=Uint8Array,ne=Uint16Array,at=Int32Array,ct=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]),lt=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]),Mt=new ce([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Qs=function(t,e){for(var s=new ne(31),n=0;n<31;++n)s[n]=e+=1<<t[n-1];for(var i=new at(s[30]),n=1;n<30;++n)for(var r=s[n];r<s[n+1];++r)i[r]=r-s[n]<<5|n;return{b:s,r:i}},Zs=Qs(ct,2),Ui=Zs.b,ut=Zs.r;Ui[28]=258,ut[258]=28;for(var Hi=Qs(lt,0),Lt=Hi.r,ht=new ne(32768),X=0;X<32768;++X){var Ce=(X&43690)>>1|(X&21845)<<1;Ce=(Ce&52428)>>2|(Ce&13107)<<2,Ce=(Ce&61680)>>4|(Ce&3855)<<4,ht[X]=((Ce&65280)>>8|(Ce&255)<<8)>>1}for(var Be=function(t,e,s){for(var n=t.length,i=0,r=new ne(e);i<n;++i)t[i]&&++r[t[i]-1];var o=new ne(e);for(i=1;i<e;++i)o[i]=o[i-1]+r[i-1]<<1;var l;if(s){l=new ne(1<<e);var a=15-e;for(i=0;i<n;++i)if(t[i])for(var u=i<<4|t[i],c=e-t[i],d=o[t[i]-1]++<<c,p=d|(1<<c)-1;d<=p;++d)l[ht[d]>>a]=u}else for(l=new ne(n),i=0;i<n;++i)t[i]&&(l[i]=ht[o[t[i]-1]++]>>15-t[i]);return l},Ie=new ce(288),X=0;X<144;++X)Ie[X]=8;for(var X=144;X<256;++X)Ie[X]=9;for(var X=256;X<280;++X)Ie[X]=7;for(var X=280;X<288;++X)Ie[X]=8;for(var Ye=new ce(32),X=0;X<32;++X)Ye[X]=5;var en=Be(Ie,9,0),tn=Be(Ye,5,0),Pt=function(t){return(t+7)/8|0},sn=function(t,e,s){return(e==null||e<0)&&(e=0),(s==null||s>t.length)&&(s=t.length),new ce(t.subarray(e,s))},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"],nn=function(t,e,s){var n=new Error(e||zi[t]);if(n.code=t,Error.captureStackTrace&&Error.captureStackTrace(n,nn),!s)throw n;return n},me=function(t,e,s){s<<=e&7;var n=e/8|0;t[n]|=s,t[n+1]|=s>>8},je=function(t,e,s){s<<=e&7;var n=e/8|0;t[n]|=s,t[n+1]|=s>>8,t[n+2]|=s>>16},dt=function(t,e){for(var s=[],n=0;n<t.length;++n)t[n]&&s.push({s:n,f:t[n]});var i=s.length,r=s.slice();if(!i)return{t:Ht,l:0};if(i==1){var o=new ce(s[0].s+1);return o[s[0].s]=1,{t:o,l:1}}s.sort(function(O,N){return O.f-N.f}),s.push({s:-1,f:25001});var l=s[0],a=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:l.f+a.f,l,r:a};c!=i-1;)l=s[s[u].f<s[d].f?u++:d++],a=s[u!=c&&s[u].f<s[d].f?u++:d++],s[c++]={s:-1,f:l.f+a.f,l,r:a};for(var p=r[0].s,n=1;n<i;++n)r[n].s>p&&(p=r[n].s);var y=new ne(p+1),w=ft(s[c-1],y,0);if(w>e){var n=0,b=0,T=w-e,D=1<<T;for(r.sort(function(N,F){return y[F.s]-y[N.s]||N.f-F.f});n<i;++n){var B=r[n].s;if(y[B]>e)b+=D-(1<<w-y[B]),y[B]=e;else break}for(b>>=T;b>0;){var A=r[n].s;y[A]<e?b-=1<<e-y[A]++-1:++n}for(;n>=0&&b;--n){var k=r[n].s;y[k]==e&&(--y[k],++b)}w=e}return{t:new ce(y),l:w}},ft=function(t,e,s){return t.s==-1?Math.max(ft(t.l,e,s+1),ft(t.r,e,s+1)):e[t.s]=s},Bt=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new ne(++e),n=0,i=t[0],r=1,o=function(a){s[n++]=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:s.subarray(0,n),n:e}},Ue=function(t,e){for(var s=0,n=0;n<e.length;++n)s+=t[n]*e[n];return s},jt=function(t,e,s){var n=s.length,i=Pt(e+2);t[i]=n&255,t[i+1]=n>>8,t[i+2]=t[i]^255,t[i+3]=t[i+1]^255;for(var r=0;r<n;++r)t[i+r+4]=s[r];return(i+4+n)*8},Ut=function(t,e,s,n,i,r,o,l,a,u,c){me(e,c++,s),++i[256];for(var d=dt(i,15),p=d.t,y=d.l,w=dt(r,15),b=w.t,T=w.l,D=Bt(p),B=D.c,A=D.n,k=Bt(b),O=k.c,N=k.n,F=new ne(19),C=0;C<B.length;++C)++F[B[C]&31];for(var C=0;C<O.length;++C)++F[O[C]&31];for(var E=dt(F,7),P=E.t,V=E.l,j=19;j>4&&!P[Mt[j-1]];--j);var W=u+5<<3,I=Ue(i,Ie)+Ue(r,Ye)+o,M=Ue(i,p)+Ue(r,b)+o+14+3*j+Ue(F,P)+2*F[16]+3*F[17]+7*F[18];if(a>=0&&W<=I&&W<=M)return jt(e,c,t.subarray(a,a+u));var q,G,H,v;if(me(e,c,1+(M<I)),c+=2,M<I){q=Be(p,y,0),G=p,H=Be(b,T,0),v=b;var f=Be(P,V,0);me(e,c,A-257),me(e,c+5,N-1),me(e,c+10,j-4),c+=14;for(var C=0;C<j;++C)me(e,c+3*C,P[Mt[C]]);c+=3*j;for(var h=[B,O],m=0;m<2;++m)for(var g=h[m],C=0;C<g.length;++C){var S=g[C]&31;me(e,c,f[S]),c+=P[S],S>15&&(me(e,c,g[C]>>5&127),c+=g[C]>>12)}}else q=en,G=Ie,H=tn,v=Ye;for(var C=0;C<l;++C){var x=n[C];if(x>255){var S=x>>18&31;je(e,c,q[S+257]),c+=G[S+257],S>7&&(me(e,c,x>>23&31),c+=ct[S]);var R=x&31;je(e,c,H[R]),c+=v[R],R>3&&(je(e,c,x>>5&8191),c+=lt[R])}else je(e,c,q[x]),c+=G[x]}return je(e,c,q[256]),c+G[256]},rn=new at([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ht=new ce(0),on=function(t,e,s,n,i,r){var o=r.z||t.length,l=new ce(n+o+5*(1+Math.ceil(o/7e3))+i),a=l.subarray(n,l.length-i),u=r.l,c=(r.r||0)&7;if(e){c&&(a[0]=r.r>>3);for(var d=rn[e-1],p=d>>13,y=d&8191,w=(1<<s)-1,b=r.p||new ne(32768),T=r.h||new ne(w+1),D=Math.ceil(s/3),B=2*D,A=function(se){return(t[se]^t[se+1]<<D^t[se+2]<<B)&w},k=new at(25e3),O=new ne(288),N=new ne(32),F=0,C=0,E=r.i||0,P=0,V=r.w||0,j=0;E+2<o;++E){var W=A(E),I=E&32767,M=T[W];if(b[I]=M,T[W]=I,V<=E){var q=o-E;if((F>7e3||P>24576)&&(q>423||!u)){c=Ut(t,a,0,k,O,N,C,P,j,E-j,c),P=F=C=0,j=E;for(var G=0;G<286;++G)O[G]=0;for(var G=0;G<30;++G)N[G]=0}var H=2,v=0,f=y,h=I-M&32767;if(q>2&&W==A(E-h))for(var m=Math.min(p,q)-1,g=Math.min(32767,E),S=Math.min(258,q);h<=g&&--f&&I!=M;){if(t[E+H]==t[E+H-h]){for(var x=0;x<S&&t[E+x]==t[E+x-h];++x);if(x>H){if(H=x,v=h,x>m)break;for(var R=Math.min(h,x-2),L=0,G=0;G<R;++G){var z=E-h+G&32767,_=b[z],$=z-_&32767;$>L&&(L=$,M=z)}}}I=M,M=b[I],h+=I-M&32767}if(v){k[P++]=268435456|ut[H]<<18|Lt[v];var Z=ut[H]&31,ae=Lt[v]&31;C+=ct[Z]+lt[ae],++O[257+Z],++N[ae],V=E+H,++F}else k[P++]=t[E],++O[t[E]]}}for(E=Math.max(E,V);E<o;++E)k[P++]=t[E],++O[t[E]];c=Ut(t,a,u,k,O,N,C,P,j,E-j,c),u||(r.r=c&7|a[c/8|0]<<3,c-=7,r.h=T,r.p=b,r.i=E,r.w=V)}else{for(var E=r.w||0;E<o+u;E+=65535){var ee=E+65535;ee>=o&&(a[c/8|0]=u,ee=o),c=jt(a,c+1,t.subarray(E,ee))}r.i=o}return sn(l,0,n+Pt(c)+i)},an=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var s=e,n=9;--n;)s=(s&1&&-306674912)^s>>>1;t[e]=s}return t}(),cn=function(){var t=-1;return{p:function(e){for(var s=t,n=0;n<e.length;++n)s=an[s&255^e[n]]^s>>>8;t=s},d:function(){return~t}}},zt=function(t,e,s,n,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 on(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,s,n,i)},Wi=function(t,e){var s={};for(var n in t)s[n]=t[n];for(var n in e)s[n]=e[n];return s},ln=function(t,e,s){for(var n=t(),i=t.toString(),r=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),o=0;o<n.length;++o){var l=n[o],a=r[o];if(typeof l=="function"){e+=";"+a+"=";var u=l.toString();if(l.prototype)if(u.indexOf("[native code]")!=-1){var c=u.indexOf(" ",8)+1;e+=u.slice(c,u.indexOf("(",c))}else{e+=u;for(var d in l.prototype)e+=";"+a+".prototype."+d+"="+l.prototype[d].toString()}else e+=u}else s[a]=l}return e},pt=[],$i=function(t){var e=[];for(var s in t)t[s].buffer&&e.push((t[s]=new t[s].constructor(t[s])).buffer);return e},qi=function(t,e,s,n){if(!pt[s]){for(var i="",r={},o=t.length-1,l=0;l<o;++l)i=ln(t[l],i,r);pt[s]={c:ln(t[o],i,r),e:r}}var a=Wi({},pt[s].e);return ji(pt[s].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",s,a,$i(a),n)},Vi=function(){return[ce,ne,at,ct,lt,Mt,ut,Lt,en,Ie,tn,Ye,ht,rn,Ht,Be,me,je,dt,ft,Bt,Ue,jt,Ut,Pt,sn,on,zt,Xi,un]},Gi=function(){return[hn,dn,gt,cn,an]},un=function(t){return postMessage(t,[t.buffer])},Ki=function(t,e,s,n,i,r){var o=qi(s,n,i,function(l,a){o.terminate(),r(l,a)});return o.postMessage([t,e],e.consume?[t.buffer]:[]),function(){o.terminate()}},gt=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8},hn=function(t,e){var s=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&&gt(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),s){t[3]=8;for(var n=0;n<=s.length;++n)t[n+10]=s.charCodeAt(n)}},dn=function(t){return 10+(t.filename?t.filename.length+1:0)};function Xi(t,e){return zt(t,e||{},0,0)}function Ji(t,e,s){return s||(s=e,e={}),typeof s!="function"&&nn(7),Ki(t,e,[Vi,Gi,function(){return[fn]}],function(n){return un(fn(n.data[0],n.data[1]))},2,s)}function fn(t,e){e||(e={});var s=cn(),n=t.length;s.p(t);var i=zt(t,e,dn(e),8),r=i.length;return hn(i,e),gt(i,r-8,s.d()),gt(i,r-4,n),i}var Yi=typeof TextDecoder<"u"&&new TextDecoder,Qi=0;try{Yi.decode(Ht,{stream:!0}),Qi=1}catch{}class pn{constructor(){this.idx=1,this.backDict={}}getKey(e){let s=!1;return this.backDict[e]||(s=!0,this.backDict[e]=this.idx++),[this.backDict[e],s]}}class Zi{constructor(e,s){this.app=e,this.isDictDisabled=s,this.dict=new pn}sendSetAttribute(e,s,n){if(this.isDictDisabled){const i=[12,e,s,n];return this.app.send(i)}else{const i=[51,e,this.applyDict(s),this.applyDict(n)];return this.app.send(i)}}applyDict(e){const[s,n]=this.dict.getKey(e);return n&&this.app.send([50,s,e]),s}clear(){this.dict=new pn}}class er{constructor(e,s){this.app=e,this.startParams=s,this.conditions=[],this.hasStarted=!1,this.createConditionFromFilter=n=>{if(n.value.length){const i=tr(n);if(i.type)return i}},this.durationInt=null}setConditions(e){this.conditions=e}async fetchConditions(e,s){try{const n=await fetch(`${this.app.options.ingestPoint}/v1/web/conditions/${e}`,{method:"GET",headers:{Authorization:`Bearer ${s}`}}),{conditions:i}=await n.json(),r=[];i.forEach(o=>{o.filters.forEach(a=>{let u;a.type==="fetch"?(u={type:"network_request",subConditions:[],name:o.name},a.filters.forEach(c=>{const d=this.createConditionFromFilter(c);d&&u.subConditions.push(d)})):u=this.createConditionFromFilter(a),u&&(u.type==="session_duration"&&this.processDuration(u.value[0],o.name),r.push({...u,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(s){this.app.debug.error(s)}}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 s=this.conditions.filter(n=>n.type==="feature_flag");s.length&&s.forEach(n=>{const i=He[n.operator];i&&e.find(r=>i(r.key,n.value))&&this.trigger(n.name)})}processDuration(e,s){this.durationInt=setInterval(()=>{performance.now()>e&&this.trigger(s)},1e3),this.app.attachStopCallback(()=>{this.durationInt&&clearInterval(this.durationInt)})}networkRequest(e){const s=this.conditions.filter(n=>n.type==="network_request");s.length&&s.forEach(n=>{const i=n.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=He[o.operator];if(a&&a(l,o.value))return!0})&&this.trigger(n.name):i.length===0&&n.subConditions.length&&this.trigger(n.name)})}customEvent(e){const s=this.conditions.filter(n=>n.type==="custom_event");s.length&&s.forEach(n=>{const i=He[n.operator];i&&(i(e[1],n.value)||i(e[2],n.value))&&this.trigger(n.name)})}clickEvent(e){const s=this.conditions.filter(n=>n.type==="click");s.length&&s.forEach(n=>{const i=He[n.operator];i&&(i(e[3],n.value)||i(e[4],n.value))&&this.trigger(n.name)})}pageLocationEvent(e){const s=this.conditions.filter(n=>n.type==="visited_url");s&&s.forEach(n=>{const i=He[n.operator];i&&i(e[1],n.value)&&this.trigger(n.name)})}jsExceptionEvent(e){const s=[e[1],e[2],e[3]],n=this.conditions.filter(i=>i.type==="exception");n&&n.forEach(i=>{const r=He[i.operator];r&&s.some(o=>r(o,i.value))&&this.trigger(i.name)})}}const He={is:(t,e)=>e.some(s=>t.includes(s)),isAny:()=>!0,isNot:(t,e)=>!e.some(s=>t.includes(s)),contains:(t,e)=>e.some(s=>t.includes(s)),notContains:(t,e)=>!e.some(s=>t.includes(s)),startsWith:(t,e)=>e.some(s=>t.startsWith(s)),endsWith:(t,e)=>e.some(s=>t.endsWith(s)),greaterThan:(t,e)=>t>e,greaterOrEqual:(t,e)=>t>=e,lessOrEqual:(t,e)=>t<=e,lessThan:(t,e)=>t<e},tr=t=>{const e={on:"is",notOn:"isNot",">":"greaterThan","<":"lessThan","=":"is","<=":"lessOrEqual",">=":"greaterOrEqual"},s=i=>{if(Object.keys(e).includes(i))return e[i]};let n={type:"",operator:"",value:t.value,key:""};switch(t.type){case"click":n={type:"click",operator:s(t.operator),value:t.value,key:""};break;case"location":n={type:"visited_url",operator:t.operator,value:t.value,key:""};break;case"custom":n={type:"custom_event",operator:t.operator,value:t.value,key:""};break;case"metadata":n={type:t.source==="featureFlag"?"feature_flag":t.type,operator:t.operator,value:t.value,key:""};break;case"error":n={type:"exception",operator:t.operator,value:t.value,key:""};break;case"duration":n={type:"session_duration",value:t.value[0],key:""};break;case"fetchUrl":n={type:"network_request",key:"url",operator:t.operator,value:t.value};break;case"fetchStatusCode":n={type:"network_request",key:"status",operator:s(t.operator),value:t.value};break;case"fetchMethod":n={type:"network_request",key:"method",operator:s(t.operator),value:t.value};break;case"fetchDuration":n={type:"network_request",key:"duration",operator:s(t.operator),value:t.value};break}return n};class sr{constructor(e){this.app=e,this.flags=[],this.storageKey="__openreplay_flags";const s=this.app.sessionStorage.getItem(this.storageKey);if(s){const n=s.split(";").filter(Boolean);this.flags=n.map(i=>JSON.parse(i))}}getFeatureFlag(e){return this.flags.find(s=>s.key===e)}isFlagEnabled(e){return this.flags.findIndex(s=>s.key===e)!==-1}onFlagsLoad(e){this.onFlagsCb=e}async reloadFlags(e){const s=this.app.sessionStorage.getItem(this.storageKey),n={};s&&s.split(";").filter(Boolean).forEach(c=>{const d=JSON.parse(c);n[d.key]={key:d.key,value:d.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:n},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 u=await a.json();return this.handleFlags(u.flags)}}handleFlags(e){var r;const s=[];e.forEach(o=>{o.is_persist&&s.push(o)});let n="";return this.diffPersist(s).forEach(o=>{n+=`${JSON.stringify(o)};`}),this.app.sessionStorage.setItem(this.storageKey,n),this.flags=e,(r=this.onFlagsCb)==null?void 0:r.call(this,e)}clearPersistFlags(){this.app.sessionStorage.removeItem(this.storageKey)}diffPersist(e){const s=this.app.sessionStorage.getItem(this.storageKey);if(!s)return e;const i=s.split(";").filter(Boolean).map(r=>JSON.parse(r));return e.filter(r=>i.findIndex(o=>o.key===r.key)===-1)}}const gn={htmlmasked:"hidden",masked:"obscured"},ve=!(typeof window>"u"),nr=ve&&navigator.userAgent.match(/firefox|fxios/i),ir=1e5;let Wt=ve?Date.now()-performance.now():0;function $t(){Wt=Date.now()-performance.now()}function ze(){return Wt}const pe=ve&&performance.now?()=>Math.round(performance.now()+Wt):()=>Date.now(),qt="repeat"in String.prototype?t=>"*".repeat(t.length):t=>t.replace(/./g,"*");function mn(t){return t.trim().replace(/\s+/g," ")}function vn(t){return t.startsWith("https://")||t.startsWith("http://")}const mt="https://docs.openreplay.com",yn={};function _e(t,e,s="/"){yn[t]||(console.warn(`OpenReplay: ${t} is deprecated. ${e?`Please, use ${e} instead.`:""} Visit ${mt}${s} for more information.`),yn[t]=!0)}function Vt(t){let e=t.getAttribute("data-openreplay-label");return e!==null||(e=t.getAttribute("data-asayer-label"),e!==null&&_e('"data-asayer-label" attribute','"data-openreplay-label" attribute',"/")),e}function De(t,e){const s=`data-openreplay-${e}`;return t.hasAttribute(s)?(gn[e]&&_e(`"${s}" attribute`,`"${gn[e]}" attribute`,"/installation/sanitize-data"),!0):!1}function rr(t){try{return!!t.contentDocument}catch{return!1}}function bn(t){return t.toString(16).padStart(2,"0")}function or(t){const e=new Uint8Array((t||40)/2),s=window.crypto||window.msCrypto;return s?(s.getRandomValues(e),Array.from(e,bn).join("")):Array.from({length:t||40},()=>bn(Math.floor(Math.random()*16))).join("")}function ar(){try{return window.self&&window.top&&window.self!==window.top}catch{return!0}}function Gt(t){return window.Zone&&"__symbol__"in window.Zone?window.Zone.__symbol__(t):t}function Sn(t){const e=Gt("MutationObserver");return new window[e](t)}function wn(t,e,s,n){const i=Gt("addEventListener");try{t[i](e,s,n)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}function xn(t,e,s,n){const i=Gt("removeEventListener");try{t[i](e,s,n)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}class cr{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 s=this.taskQueue.shift();Promise.resolve(s()).then(()=>{requestAnimationFrame(()=>e())})};e()}}const lr=new cr;function ur(t){lr.addTask(t)}function kn(t,e){const s={...t};for(const n in e)if(e.hasOwnProperty(n)){const i=e[n],r=t[n];typeof i=="object"&&!Array.isArray(i)&&i!==null?s[n]=kn(r||{},i):s[n]=i}return s}function Ae(t){return[0,t]}function hr(t,e){return[5,t,e]}function dr(t,e){return[6,t,e]}function fr(){return[7]}function pr(t,e,s,n,i){return[8,t,e,s,n,i]}function gr(t,e,s){return[9,t,e,s]}function mr(t,e,s){return[10,t,e,s]}function vr(t){return[11,t]}function Tn(t,e){return[13,t,e]}function yr(t,e){return[14,t,e]}function br(t,e,s){return[16,t,e,s]}function Sr(t,e,s){return[18,t,e,s]}function wr(t,e){return[19,t,e]}function xr(t,e){return[20,t,e]}function kr(t,e){return[22,t,e]}function Tr(t,e,s,n,i,r,o,l,a){return[23,t,e,s,n,i,r,o,l,a]}function Er(t,e,s){return[24,t,e,s]}function Cr(t,e){return[27,t,e]}function Ir(t){return[28,t]}function _r(t){return[29,t]}function En(t,e){return[30,t,e]}function Or(t,e,s,n){return[49,t,e,s,n]}function Nr(t,e){return[54,t,e]}function Rr(t){return[55,t]}function Cn(t,e,s,n){return[57,t,e,s,n]}function In(t){return[58,t]}function Kt(t,e,s,n){return[60,t,e,s,n]}function Dr(t,e,s){return[61,t,e,s]}function Ar(t,e){return[63,t,e]}function Fr(t,e){return[64,t,e]}function Mr(t,e,s,n,i,r){return[68,t,e,s,n,i,r]}function Xt(t,e){return[70,t,e]}function _n(t,e,s){return[71,t,e,s]}function Jt(t,e,s,n){return[73,t,e,s,n]}function On(t,e){return[75,t,e]}function Nn(t,e){return[76,t,e]}function Lr(t,e){return[77,t,e]}function Yt(t,e,s,n){return[78,t,e,s,n]}function vt(t,e,s,n,i,r,o,l,a){return[83,t,e,s,n,i,r,o,l,a]}function Pr(t,e,s,n,i,r){return[84,t,e,s,n,i,r]}function Br(t,e,s,n,i,r){return[112,t,e,s,n,i,r]}function Rn(t,e,s){return[113,t,e,s]}function jr(t){return[114,t]}function Ur(t){return[115,t]}function Dn(t,e,s,n,i,r,o,l,a,u){return[116,t,e,s,n,i,r,o,l,a,u]}function yt(t){return[117,t]}function Fe(t){return[118,t]}function Hr(t,e){return[119,t,e]}function zr(t){return[120,t]}function Wr(t,e,s,n){return[122,t,e,s,n]}const Qt=ve&&"performance"in window&&"memory"in performance?performance:{memory:{}},Zt=ve?(navigator.deviceMemory||0)*1024:0,es=Qt.memory.jsHeapSizeLimit||0;function $r(t,e){if(!Object.assign({capturePerformance:!0},e).capturePerformance)return;let n,i;const r=()=>{n===void 0||n===-1||(n++,requestAnimationFrame(r))};t.ticker.attach(()=>{i===void 0||i===-1||i++},0,!1);const o=()=>{n===void 0||i===void 0||(t.send(Or(n,i,Qt.memory.totalJSHeapSize||0,Qt.memory.usedJSHeapSize||0)),i=n=document.hidden?-1:0)};t.attachStartCallback(()=>{i=n=-1,o(),r()}),t.attachStopCallback(()=>{i=n=void 0}),t.ticker.attach(o,40,!1),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",o,!1,!1)}const An="__or__watched_tags__";class qr{constructor(e,s,n){this.sessionStorage=e,this.errLog=s,this.onTag=n,this.intervals={},this.tags=[];const i=JSON.parse(e.getItem(An)??"[]");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,s){return fetch(`${e}/v1/web/tags`,{method:"GET",headers:{Authorization:`Bearer ${s}`}}).then(n=>n.json()).then(({tags:n})=>{if(n&&n.length){this.setTags(n);const i=JSON.stringify(n);this.sessionStorage.setItem(An,i||"")}}).catch(n=>this.errLog(n))}setTags(e){this.tags=e,this.intervals={},e.forEach(s=>{this.intervals[s.id]=setInterval(()=>{const n=document.querySelectorAll(s.selector);if(n.length>0){const i=n[0];i.__or_watcher_tagname=s.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 Vr={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"'},Gr={display:"flex",flexDirection:"column",gap:"2rem",alignItems:"center",padding:"1.5rem",borderRadius:"2px",border:"1px solid #D9D9D9",background:"#FFF",width:"22rem"},bt={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"},Kr={fontFamily:"Verdana, sans-serif",fontSize:"1.25rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.75rem",color:"rgba(0, 0, 0, 0.85)"},Xr={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"},Jr={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"},Fn={fontFamily:"Verdana, sans-serif",fontSize:"13px",fontWeight:"500",lineHeight:"auto",display:"flex",justifyContent:"space-between",width:"100%",cursor:"pointer"},We={display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"0.625rem",fontSize:"13px",lineHeight:"auto"},Yr={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"},$e={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"},Qr={...$e,display:"flex",flexDirection:"column",alignItems:"center",gap:"0.625rem"},Mn={fontSize:"1.25rem",fontWeight:"500",cursor:"pointer",color:"#394EFF"},Ln={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"},Pn={marginTop:"1rem",marginBottom:"1rem",cursor:"pointer",display:"block",fontWeight:"500",fontSize:"13px!important",lineHeight:"auto"},Zr={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",padding:"0.5rem",width:"100%",boxSizing:"border-box"},Bn={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #394EFF",fontSize:"13px",height:"24px",width:"24px"},eo={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"},jn={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"},Un={fontWeight:"bold"},to={fontSize:"13px",lineHeight:"auto"},Hn={marginRight:"0.5rem",cursor:"pointer",color:"#394EFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto"},so={...Hn,display:"flex",padding:"0.25rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.5rem",borderRadius:"0.25rem",border:"1px solid #394EFF"},no={display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",boxSizing:"border-box"},io={border:"4px solid rgba(255, 255, 255, 0.4)",width:"16px",height:"16px",borderRadius:"50%",borderLeftColor:"#fff",animation:"spin 0.5s linear infinite"},zn={Standard:{width:1280,height:720},High:{width:1920,height:1080}};class ro{constructor(e){this.app=e,this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this.recStartTs=null}async startRecording(e,s,n,i){this.recStartTs=this.app.timestamp();const r=s;try{this.stream=await navigator.mediaDevices.getUserMedia({video:i?{...r,frameRate:{ideal:e}}:!1,audio:n}),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 s=new Blob(this.recordedChunks,{type:"video/webm"});e(s)},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(s=>{if(s.ok)return s.json();throw new Error("Failed to get upload url")}).then(({url:s})=>fetch(s,{method:"PUT",headers:{"Content-Type":"video/webm"},body:e})).catch(console.error).finally(()=>{this.discard()})}async saveToFile(e="recorded-video.webm"){const s=await this.stopRecording(),n=URL.createObjectURL(s),i=document.createElement("a");i.style.display="none",i.href=n,i.download=e,document.body.appendChild(i),i.click(),window.URL.revokeObjectURL(n),document.body.removeChild(i)}discard(){var e,s;(e=this.mediaRecorder)==null||e.stop(),(s=this.stream)==null||s.getTracks().forEach(n=>n.stop())}}function oo(t,e){e.onmousedown=function(s){const n=t.getBoundingClientRect(),i=s.clientX-n.left,r=s.clientY-n.top;t.style.position="fixed",t.style.zIndex=99999999999999,o(s.pageX,s.pageY);function o(u,c){let d=u-i,p=c-r;d<=5&&(d=5),p<=5&&(p=5),d>=window.innerWidth-n.width&&(d=window.innerWidth-n.width),p>=window.innerHeight-n.height&&(p=window.innerHeight-n.height),t.style.left=`${d}px`,t.style.top=`${p}px`}function l(u){o(u.pageX,u.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 ao(){const t=document.createElement("div");t.className="grid";for(let e=0;e<16;e++){const s=document.createElement("div");Object.assign(s.style,{width:"2px",height:"2px",borderRadius:"10px",background:"white"}),s.className="cell",t.appendChild(s)}return Object.assign(t.style,{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gridTemplateRows:"repeat(4, 1fr)",gap:"2px",cursor:"grab"}),t}function co(){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 lo(){const t=document.createElement("style");t.type="text/css",t.innerText=`@keyframes spin {
639
+ `,Vs=document.createElement("style");Vs.textContent=Je,document.head.appendChild(Vs);function Li(){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 ot(t,e,s){console.log(t,s);let n="";if(s){const i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3),n="; expires="+i.toUTCString()}document.cookie=t+"="+(e||"")+n+"; path=/; secure; samesite=strict"}function ee(t){const e=t+"=",s=document.cookie.split(";");for(let n=0;n<s.length;n++){let i=s[n];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 Pi(t){document.cookie=t+"=; Max-Age=-99999999;"}function Bi(){const t="uniqueUserID";let e=ee(t);return e||(e=Li(),ot(t,e,365)),e}function Le(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 Gs(){Le("Chatbot Opened",{distinct_id:ee("uniqueUserID"),client:ee("chatbotToken")})}function ji(t){Le("Chatbot Opened Auto",{distinct_id:ee("uniqueUserID"),url:t,client:ee("chatbotToken")})}function Ks(){Le("Chatbot Closed",{distinct_id:ee("uniqueUserID"),client:ee("chatbotToken")})}function Ui(t){Le("Message Sent",{distinct_id:ee("uniqueUserID"),message_content:t,client:ee("chatbotToken")})}function Hi(t){Le("Products Got",{distinct_id:ee("uniqueUserID"),products:t,client:ee("chatbotToken")})}function zi(t){Le("Product Clicked",{distinct_id:ee("uniqueUserID"),product_id:t,client:ee("chatbotToken")})}var Pe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ft={exports:{}};(function(t,e){(function(s,n){n(e)})(Pe,function(s){var n={getItemSync:function(v){try{return localStorage.getItem(v)||null}catch{return null}},getItem:function(v,f){var u=this;return new Promise(function(m,g){try{var S=u.getItemSync(v);f==null||f(null,S),m(S)}catch(x){f&&f(x,null),g(x)}})},setItem:function(v,f,u){return new Promise(function(m,g){try{localStorage.setItem(v,f),u&&u(null,f),m(f)}catch(S){u&&u(S,null),g(S)}})}},i=function(){return i=Object.assign||function(v){for(var f,u=1,m=arguments.length;u<m;u++)for(var g in f=arguments[u])Object.prototype.hasOwnProperty.call(f,g)&&(v[g]=f[g]);return v},i.apply(this,arguments)};function r(v,f,u,m){return new(u||(u=Promise))(function(g,S){function x(z){try{L(m.next(z))}catch(_){S(_)}}function R(z){try{L(m.throw(z))}catch(_){S(_)}}function L(z){var _;z.done?g(z.value):(_=z.value,_ instanceof u?_:new u(function($){$(_)})).then(x,R)}L((m=m.apply(v,f||[])).next())})}function o(v,f){var u,m,g,S,x={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return S={next:R(0),throw:R(1),return:R(2)},typeof Symbol=="function"&&(S[Symbol.iterator]=function(){return this}),S;function R(L){return function(z){return function(_){if(u)throw new TypeError("Generator is already executing.");for(;x;)try{if(u=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(v,x)}catch($){_=[6,$],m=0}finally{u=g=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}([L,z])}}}function l(v,f,u){if(u||arguments.length===2)for(var m,g=0,S=f.length;g<S;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return v.concat(m||Array.prototype.slice.call(f))}var a=function v(f,u){if(f===u)return!0;if(f&&u&&typeof f=="object"&&typeof u=="object"){if(f.constructor!==u.constructor)return!1;var m,g,S;if(Array.isArray(f)){if((m=f.length)!=u.length)return!1;for(g=m;g--!=0;)if(!v(f[g],u[g]))return!1;return!0}if(f.constructor===RegExp)return f.source===u.source&&f.flags===u.flags;if(f.valueOf!==Object.prototype.valueOf)return f.valueOf()===u.valueOf();if(f.toString!==Object.prototype.toString)return f.toString()===u.toString();if((m=(S=Object.keys(f)).length)!==Object.keys(u).length)return!1;for(g=m;g--!=0;)if(!Object.prototype.hasOwnProperty.call(u,S[g]))return!1;for(g=m;g--!=0;){var x=S[g];if(!v(f[x],u[x]))return!1}return!0}return f!=f&&u!=u};function h(v,f){var u=Object.keys(f||{}).filter(function(m){var g=v==null?void 0:v[m],S=f==null?void 0:f[m];return!a(g,S)});return Object.keys(v||{}).filter(function(m){Object.keys(f||{}).includes(m)||u.push(m)}),Object.keys(u).length?u:null}var c,d;function p(v,f,u){var m="shortString",g=!0;typeof u=="number"&&(m="javaDouble",g=!1),v[m]=v[m]||{},v[m][f]=g?u+"":u}function y(v){return!!v&&typeof v=="object"&&v.value!==void 0}function w(v){return Object.fromEntries(Object.entries(v).map(function(f){var u=f[0],m=f[1];return[u,y(m)?m:{value:m}]}))}function b(v){return i(i({},v),{identity:v.identity?i(i({},v.identity),{traits:w(v.identity.traits||{})}):void 0})}(function(v){v.NONE="NONE",v.DEFAULT_FLAGS="DEFAULT_FLAGS",v.CACHE="CACHE",v.SERVER="SERVER"})(c||(c={}));var T,D=null,B="BULLET_TRAIN_DB",A="BULLET_TRAIN_EVENT",k="https://edge.api.flagsmith.com/api/v1/",O="flagsmith_value_",N="flagsmith_enabled_",F="flagsmith_trait_",C=function(){function v(f){var u=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var m=u,g=m.api,S=m.evaluationContext;u.log("Get Flags"),u.isLoading=!0,u.loadingState.isFetching||u.setLoadingState(i(i({},u.loadingState),{isFetching:!0}));var x="".concat(u.getContext().identity),R=function(L){var z,_,$,Z;if(L&&x==="".concat(u.getContext().identity)){var oe=L.flags,te=L.traits,se=L.identifier;u.isLoading=!1;var ue={},de={};te=te||[],(oe=oe||[]).forEach(function(K){ue[K.feature.name.toLowerCase().replace(/ /g,"_")]={id:K.feature.id,enabled:K.enabled,value:K.feature_state_value}}),te.forEach(function(K){de[K.trait_key.toLowerCase().replace(/ /g,"_")]={transient:K.transient,value:K.trait_value}}),u.oldFlags=i({},u.flags);var Se=h(u.oldFlags,ue),tt=h((z=u.evaluationContext.identity)===null||z===void 0?void 0:z.traits,de);if((se||Object.keys(de).length)&&(u.evaluationContext.identity={traits:de},se&&(u.evaluationContext.identity.identifier=se)),u.flags=ue,u.updateStorage(),u._onChange(u.oldFlags,{isFromServer:!0,flagsChanged:Se,traitsChanged:tt},u._loadedState(null,c.SERVER)),u.datadogRum)try{if(u.datadogRum.trackTraits){var st={};Object.keys(((_=u.evaluationContext.identity)===null||_===void 0?void 0:_.traits)||{}).map(function(K){st[F+K]=u.getTrait(K)});var Ge=i(i(i({},u.datadogRum.client.getUser()),{id:u.datadogRum.client.getUser().id||(($=u.evaluationContext.identity)===null||$===void 0?void 0:$.identifier)}),st);u.log("Setting Datadog user",Ge),u.datadogRum.client.setUser(Ge)}}catch(K){console.error(K)}if(u.dtrum)try{var ie={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(u.flags).map(function(K){p(ie,O+K,u.getValue(K,{skipAnalytics:!0})),p(ie,N+K,u.hasFeature(K,{skipAnalytics:!0}))}),Object.keys(((Z=u.evaluationContext.identity)===null||Z===void 0?void 0:Z.traits)||{}).map(function(K){p(ie,F+K,u.getTrait(K))}),u.log("Sending javaLongOrObject traits to dynatrace",ie.javaLongOrObject),u.log("Sending date traits to dynatrace",ie.date),u.log("Sending shortString traits to dynatrace",ie.shortString),u.log("Sending javaDouble to dynatrace",ie.javaDouble),u.dtrum.sendSessionProperties(ie.javaLongOrObject,ie.date,ie.shortString,ie.javaDouble)}catch(K){console.error(K)}}};return S.identity?Promise.all([S.identity.traits&&Object.keys(S.identity.traits).length||!S.identity.identifier?u.getJSON(g+"identities/","POST",JSON.stringify({identifier:S.identity.identifier,transient:S.identity.transient,traits:Object.entries(S.identity.traits).map(function(L){var z=L[0],_=L[1];return{trait_key:z,trait_value:_==null?void 0:_.value,transient:_==null?void 0:_.transient}}).filter(function(L){return L.trait_value!==void 0||(u.log("Warning - attempted to set an undefined trait value for key",L.trait_key),!1)})})):u.getJSON(g+"identities/?identifier="+encodeURIComponent(S.identity.identifier)+(S.identity.transient?"&transient=true":""))]).then(function(L){return u.evaluationContext.identity=i(i({},u.evaluationContext.identity),{traits:{}}),R(L==null?void 0:L[0])}).catch(function(L){var z=L.message,_=new Error(z);return Promise.reject(_)}):u.getJSON(g+"flags/").then(function(L){return R({flags:L,traits:void 0})})},this.analyticsFlags=function(){var m=u.api;if(u.evaluationEvent&&u.evaluationContext.environment&&u.evaluationEvent[u.evaluationContext.environment.apiKey])return u.evaluationEvent&&Object.getOwnPropertyNames(u.evaluationEvent).length!==0&&Object.getOwnPropertyNames(u.evaluationEvent[u.evaluationContext.environment.apiKey]).length!==0?u.getJSON(m+"analytics/flags/","POST",JSON.stringify(u.evaluationEvent[u.evaluationContext.environment.apiKey])).then(function(g){if(u.evaluationContext.environment){var S=u.getState();u.evaluationEvent||(u.evaluationEvent={}),u.evaluationEvent[u.evaluationContext.environment.apiKey]={},u.setState(i(i({},S),{evaluationEvent:u.evaluationEvent})),u.updateEventStorage()}}).catch(function(g){u.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,S){var x=u.flags&&u.flags[m.toLowerCase().replace(/ /g,"_")],R=null;if(x&&(R=x.value),g!=null&&g.skipAnalytics||S||u.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?(u.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,S;return((g=u.evaluationContext.identity)===null||g===void 0?void 0:g.traits)&&((S=u.evaluationContext.identity.traits[m.toLowerCase().replace(/ /g,"_")])===null||S===void 0?void 0:S.value)},this.getAllTraits=function(){var m;return Object.fromEntries(Object.entries(((m=u.evaluationContext.identity)===null||m===void 0?void 0:m.traits)||{}).map(function(g){var S=g[0],x=g[1];return[S,x==null?void 0:x.value]}))},this.setContext=function(m){var g=b(m);return u.evaluationContext=i(i({},g),{environment:g.environment||u.evaluationContext.environment}),u.initialised?u.getFlags():Promise.resolve()},this.getContext=function(){return u.evaluationContext},this.updateContext=function(m){return u.setContext(i(i({},u.getContext()),m))},this.setTrait=function(m,g){var S;if(u.api)return u.setContext(i(i({},u.evaluationContext),{identity:i(i({},u.evaluationContext.identity),{traits:i(i({},(S=u.evaluationContext.identity)===null||S===void 0?void 0:S.traits),w(Object.fromEntries([[m,g]])))})}))},this.setTraits=function(m){var g;if(u.api)return u.setContext(i(i({},u.evaluationContext),{identity:i(i({},u.evaluationContext.identity),{traits:i(i({},(g=u.evaluationContext.identity)===null||g===void 0?void 0:g.traits),Object.fromEntries(Object.entries(m).map(function(S){var x=S[0],R=S[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 S=typeof g=="object",x=u.flags&&u.flags[m.toLowerCase().replace(/ /g,"_")],R=!1;return!x&&S&&g.fallback!==void 0?R=g==null?void 0:g.fallback:x&&x.enabled&&(R=!0),(S&&!g.skipAnalytics||!g)&&u.evaluateFlag(m,"ENABLED"),R},this.getJSON=function(m,g,S){var x,R=u;R.evaluationContext;var L=R.headers,z={method:g||"GET",body:S,cache:"no-cache",headers:{}};u.evaluationContext.environment&&(z.headers["X-Environment-Key"]=u.evaluationContext.environment.apiKey),g&&g!=="GET"&&(z.headers["Content-Type"]="application/json; charset=utf-8"),L&&Object.assign(z.headers,L),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var _="".concat((x=u.evaluationContext.identity)===null||x===void 0?void 0:x.identifier);return d(m,z).then(function($){var Z,oe,te="".concat((Z=u.evaluationContext.identity)===null||Z===void 0?void 0:Z.identifier);if(_===te){var se=(oe=$.headers)===null||oe===void 0?void 0:oe.get("x-flagsmith-document-updated-at");if(se)try{var ue=parseFloat(se);if(isNaN(ue))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");u.timestamp=ue}catch(de){u.log(de,"Failed to parse x-flagsmith-document-updated-at",se)}return u.log("Fetch response: "+$.status+" "+(g||"GET")+0+m),$.text().then(function(de){var Se=de;try{Se=JSON.parse(de)}catch{}return!Se&&$.status&&(Se="API Response: ".concat($.status)),$.status&&$.status>=200&&$.status<300?Se:Promise.reject(new Error(Se))})}u.log("Received response with identity mismatch, ignoring response. Requested: ".concat(_,", Current: ").concat(te))})},this.evaluateFlag=function(m,g){if(u.datadogRum&&(u.datadogRum.client.addFeatureFlagEvaluation?g==="VALUE"?u.datadogRum.client.addFeatureFlagEvaluation(O+m,u.getValue(m,{},!0)):u.datadogRum.client.addFeatureFlagEvaluation(N+m,u.hasFeature(m,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),u.enableAnalytics){if(!u.evaluationEvent||!u.evaluationContext.environment)return;u.evaluationEvent[u.evaluationContext.environment.apiKey]||(u.evaluationEvent[u.evaluationContext.environment.apiKey]={}),u.evaluationEvent[u.evaluationContext.environment.apiKey][m]===void 0&&(u.evaluationEvent[u.evaluationContext.environment.apiKey][m]=0),u.evaluationEvent[u.evaluationContext.environment.apiKey][m]+=1}u.updateEventStorage()},this._onChange=function(m,g,S){var x,R;u.setLoadingState(S),(x=u.onChange)===null||x===void 0||x.call(u,m,g,u.loadingState),(R=u._trigger)===null||R===void 0||R.call(u)},d=f.fetch?f.fetch:typeof fetch<"u"?fetch:Pe==null?void 0:Pe.fetch,this.canUseStorage=typeof window<"u"||!!f.browserlessStorage,this.log("Constructing flagsmith instance "+f),f.eventSource&&(T=f.eventSource),f.AsyncStorage&&(D=f.AsyncStorage)}return v.prototype.init=function(f){var u,m,g;return r(this,void 0,void 0,function(){var S,x,R,L,z,_,$,Z,oe,te,se,ue,de,Se,tt,st,Ge,ie,K,Es,nt,Ni,it,Cs,Ri,Di,Is,Ai,_s,rt,Ke,Fi,re=this;return o(this,function(ge){switch(ge.label){case 0:S=b(f.evaluationContext||this.evaluationContext),ge.label=1;case 1:if(ge.trys.push([1,13,,14]),x=f.environmentID,R=f.api,L=R===void 0?k:R,z=f.headers,_=f.onChange,$=f.cacheFlags,Z=f.datadogRum,oe=f.onError,te=f.defaultFlags,se=f.fetch,ue=f.preventFetch,de=f.enableLogs,Se=f.enableDynatrace,tt=f.enableAnalytics,st=f.realtime,Ge=f.eventSourceUrl,ie=Ge===void 0?"https://realtime.flagsmith.com/":Ge,K=f.AsyncStorage,Es=f.identity,nt=f.traits,Ni=f.state,it=f.cacheOptions,Cs=f.angularHttpClient,Ri=f._trigger,Di=f._triggerLoadingState,S.environment=x?{apiKey:x}:S.environment,!S.environment||!S.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(S.identity=Es||nt?{identifier:Es,traits:nt?Object.fromEntries(Object.entries(nt).map(function(fe){return[fe[0],{value:fe[1]}]})):{}}:S.identity,this.evaluationContext=S,this.api=L,this.headers=z,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=_,Is="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=Ri||this._trigger,this._triggerLoadingState=Di||this._triggerLoadingState,this.onError=function(fe){re.setLoadingState(i(i({},re.loadingState),{isFetching:!1,isLoading:!1,error:fe})),oe==null||oe(fe)},this.enableLogs=de||!1,this.cacheOptions=it?{skipAPI:!!it.skipAPI,ttl:it.ttl||0,loadStale:!!it.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."),se&&(d=se),this.enableAnalytics=tt||!1,this.flags=Object.assign({},te)||{},this.datadogRum=Z||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?new Date().valueOf():null,this.cacheFlags=D!==void 0&&!!$,K&&(D=K),st&&typeof window<"u"&&this.setupRealtime(ie,S.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=i(i({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(Ni),this.log("Initialising with properties",f,this),Se&&(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),Cs&&(d=function(fe){return function(we,xe){var Ne=xe.headers,J=xe.method,Xe=xe.body;return new Promise(function(Me){switch(J){case"GET":return fe.get(we,{headers:Ne}).subscribe(function(Te){Me({ok:!0,text:function(){return Promise.resolve(Te)}})});case"POST":case"PUT":return fe.post(we,Xe,{headers:Ne}).subscribe(function(Te){Me({ok:!0,text:function(){return Promise.resolve(Te)}})})}})}}(Cs)),D&&this.canUseStorage&&D.getItem(A).then(function(fe){try{re.evaluationEvent=JSON.parse(fe)||{}}catch{re.evaluationEvent={}}re.analyticsInterval=setInterval(re.analyticsFlags,re.ticks)}),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),D&&this.canUseStorage&&D.getItem(A,function(fe,we){if(we&&re.evaluationContext.environment){var xe=JSON.parse(we);if(xe[re.evaluationContext.environment.apiKey]){var Ne=re.getState();re.log("Retrieved events from cache",we),re.setState(i(i({},Ne),{evaluationEvent:xe[re.evaluationContext.environment.apiKey]}))}}})),!$)return[3,9];if(!D||!this.canUseStorage)return[3,8];Ai=function(fe,we){return r(re,void 0,void 0,function(){var xe,Ne,J,Xe,Me,Te,Os,Mi,Ns,Rs,Ds,As,Fs,Ms,Ls,Ps,Bs,js,Us,Hs,zs,Ws,$s,qs;return o(this,function(Re){switch(Re.label){case 0:if(!we)return[3,7];xe=null,Ne=null,Re.label=1;case 1:return Re.trys.push([1,5,,6]),J=JSON.parse(we),Xe=!1,Me=!1,J&&J.api===this.api&&((Rs=(Ns=J.evaluationContext)===null||Ns===void 0?void 0:Ns.environment)===null||Rs===void 0?void 0:Rs.apiKey)===((Ds=this.evaluationContext.environment)===null||Ds===void 0?void 0:Ds.apiKey)&&(Te=!0,this.evaluationContext.identity&&((Fs=(As=J.evaluationContext)===null||As===void 0?void 0:As.identity)===null||Fs===void 0?void 0:Fs.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+((Ls=(Ms=J.evaluationContext)===null||Ms===void 0?void 0:Ms.identity)===null||Ls===void 0?void 0:Ls.identifier)+" to "+this.evaluationContext.identity.identifier),Te=!1),this.cacheOptions.ttl&&(!J.ts||new Date().valueOf()-J.ts>this.cacheOptions.ttl)&&(J.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+J.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-J.ts)+"ms"),Te=!1):J.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+J.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+(new Date().valueOf()-J.ts)+"ms"),Me=!0,Te=!0)),Te&&(Xe=!0,Ne=h((Ps=this.evaluationContext.identity)===null||Ps===void 0?void 0:Ps.traits,(js=(Bs=J.evaluationContext)===null||Bs===void 0?void 0:Bs.identity)===null||js===void 0?void 0:js.traits),xe=h(this.flags,J.flags),this.setState(i(i({},J),{evaluationContext:b(i(i({},J.evaluationContext),{identity:!((Us=J.evaluationContext)===null||Us===void 0)&&Us.identity?i(i({},(Hs=J.evaluationContext)===null||Hs===void 0?void 0:Hs.identity),{traits:i(i({},((Ws=(zs=J.evaluationContext)===null||zs===void 0?void 0:zs.identity)===null||Ws===void 0?void 0:Ws.traits)||{}),nt||{})}):void 0}))})),this.log("Retrieved flags from cache",J))),Xe?(Os=!ue&&(!this.cacheOptions.skipAPI||Me),this._onChange(null,{isFromServer:!1,flagsChanged:xe,traitsChanged:Ne},this._loadedState(null,c.CACHE,Os)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&Xe&&!Me&&this.log("Skipping API, using cache"),Os&&this.getFlags(),[3,4]):[3,2];case 2:return ue?[3,4]:[4,this.getFlags()];case 3:Re.sent(),Re.label=4;case 4:return[3,6];case 5:return Mi=Re.sent(),this.log("Exception fetching cached logs",Mi),[3,6];case 6:return[3,10];case 7:return ue?[3,9]:[4,this.getFlags()];case 8:return Re.sent(),[3,10];case 9:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:h({},this.flags),traitsChanged:h({},($s=this.evaluationContext.identity)===null||$s===void 0?void 0:$s.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(Is);this._onChange(null,{isFromServer:!1,flagsChanged:h({},this.flags),traitsChanged:h({},(qs=this.evaluationContext.identity)===null||qs===void 0?void 0:qs.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}Re.label=10;case 10:return[2]}})})},ge.label=2;case 2:return ge.trys.push([2,7,,8]),D.getItemSync?(_s=D.getItemSync(B),[3,5]):[3,3];case 3:return[4,D.getItem(B)];case 4:_s=ge.sent(),ge.label=5;case 5:return[4,Ai(null,_s)];case 6:case 7:return ge.sent(),[3,8];case 8:return[3,12];case 9:return ue?[3,11]:[4,this.getFlags()];case 10:return ge.sent(),[3,12];case 11:if(te)this._onChange(null,{isFromServer:!1,flagsChanged:h({},te),traitsChanged:h({},(u=S.identity)===null||u===void 0?void 0:u.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(rt=null,Object.keys(this.flags).length===0&&(rt=Is),this._onChange(null,{isFromServer:!1,flagsChanged:h({},this.flags),traitsChanged:h({},(m=S.identity)===null||m===void 0?void 0:m.traits)},this._loadedState(rt,c.DEFAULT_FLAGS)),rt))throw new Error(rt);ge.label=12;case 12:return[3,14];case 13:throw Ke=ge.sent(),this.log("Error during initialisation ",Ke),Fi=Ke instanceof Error?Ke:new Error("".concat(Ke)),(g=this.onError)===null||g===void 0||g.call(this,Fi),Ke;case 14:return[2]}})})},v.prototype._loadedState=function(f,u,m){return f===void 0&&(f=null),m===void 0&&(m=!1),{error:f,isFetching:m,isLoading:!1,source:u}},v.prototype.getAllFlags=function(){return this.flags},v.prototype.identify=function(f,u,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),u&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(u).map(function(g){var S=g[0],x=g[1];return[S,y(x)?x:{value:x}]}))),this.initialised?this.getFlags():Promise.resolve()},v.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,evaluationEvent:this.evaluationEvent}},v.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))},v.prototype.logout=function(){return this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},v.prototype.startListening=function(f){f===void 0&&(f=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,f)},v.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},v.prototype.log=function(){for(var f=[],u=0;u<arguments.length;u++)f[u]=arguments[u];this.enableLogs&&console.log.apply(this,l(["FLAGSMITH:",new Date().valueOf()-(this.timer||0),"ms"],f,!0))},v.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=new Date().valueOf();var f=JSON.stringify(this.getState());this.log("Setting storage",f),D.setItem(B,f)}},v.prototype.updateEventStorage=function(){if(this.enableAnalytics){var f=JSON.stringify(this.getState().evaluationEvent);D.setItem(A,f)}},v.prototype.setLoadingState=function(f){var u;a(f,this.loadingState)||(this.loadingState=i({},f),this.log("Loading state changed",f),(u=this._triggerLoadingState)===null||u===void 0||u.call(this))},v.prototype.setupRealtime=function(f,u){var m=this,g=f+"sse/environments/"+u+"/stream";T?this.eventSource||(this.log("Creating event source with url "+g),this.eventSource=new T(g),this.eventSource.addEventListener("environment_updated",function(S){var x;try{x=JSON.parse(S.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",S.data,m.timestamp):(m.log("updated_at is new, fetching flags",S.data,m.timestamp),m.getFlags()):m.log("updated_at is outdated, skipping get flags",S.data,m.timestamp):m.log("No updated_at received, fetching flags",S)})):this.log("Error, EventSource is undefined")},v}();function E(v){var f=v.fetch,u=v.AsyncStorage,m=v.eventSource;return new C({fetch:f,AsyncStorage:u,eventSource:m})}var P,V=(P=function(v,f){return P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,m){u.__proto__=m}||function(u,m){for(var g in m)Object.prototype.hasOwnProperty.call(m,g)&&(u[g]=m[g])},P(v,f)},function(v,f){if(typeof f!="function"&&f!==null)throw new TypeError("Class extends value "+String(f)+" is not a constructor or null");function u(){this.constructor=v}P(v,f),v.prototype=f===null?Object.create(f):(u.prototype=f.prototype,new u)}),j=function(v){var f=typeof Symbol=="function"&&Symbol.iterator,u=f&&v[f],m=0;if(u)return u.call(v);if(v&&typeof v.length=="number")return{next:function(){return v&&m>=v.length&&(v=void 0),{value:v&&v[m++],done:!v}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},W=function(v,f){var u=typeof Symbol=="function"&&v[Symbol.iterator];if(!u)return v;var m,g,S=u.call(v),x=[];try{for(;(f===void 0||f-- >0)&&!(m=S.next()).done;)x.push(m.value)}catch(R){g={error:R}}finally{try{m&&!m.done&&(u=S.return)&&u.call(S)}finally{if(g)throw g.error}}return x},I=function(v,f,u){if(u||arguments.length===2)for(var m,g=0,S=f.length;g<S;g++)!m&&g in f||(m||(m=Array.prototype.slice.call(f,0,g)),m[g]=f[g]);return v.concat(m||Array.prototype.slice.call(f))},M=function(v){function f(){return v.call(this,`EventSource not available.
640
+ 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,v),f}(Error),q=function(){function v(f,u){var m=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=u!=null?Object.assign({},u):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 M;this._onevent_wrapped=function(g){m._onevent(g)},this._start()}return v.prototype.dispatchEvent=function(f){throw new Error("Method not implemented.")},v.prototype._start=function(){var f,u,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(L){m._onopen(L)},this._eventSource.onerror=function(L){m._onerror(L)},this._eventSource.onmessage=function(L){m.onmessage(L)};try{for(var S=j(Object.keys(this._listeners)),x=S.next();!x.done;x=S.next()){var R=x.value;this._eventSource.addEventListener(R,this._onevent_wrapped)}}catch(L){f={error:L}}finally{try{x&&!x.done&&(u=S.return)&&u.call(S)}finally{if(f)throw f.error}}},v.prototype._onopen=function(f){this.readyState===0&&(this.readyState=1,this.onopen(f))},v.prototype._onerror=function(f){var u=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 u._start()},m)}},v.prototype._onevent=function(f){var u,m;f&&f.lastEventId&&(this._lastEventId=f.lastEventId);var g=this._listeners[f.type];if(g!=null)try{for(var S=j(I([],W(g),!1)),x=S.next();!x.done;x=S.next())x.value.call(this,f)}catch(R){u={error:R}}finally{try{x&&!x.done&&(m=S.return)&&m.call(S)}finally{if(u)throw u.error}}f.type==="message"&&this.onmessage(f)},v.prototype.onopen=function(f){},v.prototype.onerror=function(f){},v.prototype.onmessage=function(f){},v.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},v.prototype.addEventListener=function(f,u,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(u)||(this._listeners[f]=I(I([],W(g),!1),[u],!1))},v.prototype.removeEventListener=function(f,u,m){var g=this._listeners[f];this._listeners[f]=g.filter(function(S){return S!==u})},v}();globalThis.FlagsmithEventSource=typeof EventSource<"u"?EventSource:null;var G=function(v,f){return f=f||{},new Promise(function(u,m){var g=new XMLHttpRequest,S=[],x=[],R={},L=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:L,headers:{keys:function(){return S},entries:function(){return x},get:function(_){return R[_.toLowerCase()]},has:function(_){return _.toLowerCase()in R}}}};for(var z in g.open(f.method||"get",v,!0),g.onload=function(){g.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(_,$,Z){S.push($=$.toLowerCase()),x.push([$,Z]),R[$]=R[$]?R[$]+","+Z:Z}),u(L())},g.onerror=m,g.withCredentials=f.credentials=="include",f.headers)g.setRequestHeader(z,f.headers[z]);g.send(f.body||null)})},H=E({AsyncStorage:n,fetch:G,eventSource:q});typeof window<"u"&&(window.flagsmith=H),s.createFlagsmithInstance=function(){return E({AsyncStorage:n,fetch:G,eventSource:q})},s.default=H,Object.defineProperty(s,"__esModule",{value:!0})})})(Ft,Ft.exports);var Wi=Ft.exports;const Js=Xs(Wi);var Ys={},$i=function(t,e,s,n,i){var r=new Worker(Ys[e]||(Ys[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 h=new Error(a[0]);h.code=a[1],h.stack=a[2],i(h,null)}else i(null,l)},r.postMessage(s,n),r},ae=Uint8Array,ne=Uint16Array,at=Int32Array,ct=new ae([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]),lt=new ae([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]),Mt=new ae([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Qs=function(t,e){for(var s=new ne(31),n=0;n<31;++n)s[n]=e+=1<<t[n-1];for(var i=new at(s[30]),n=1;n<30;++n)for(var r=s[n];r<s[n+1];++r)i[r]=r-s[n]<<5|n;return{b:s,r:i}},Zs=Qs(ct,2),qi=Zs.b,ht=Zs.r;qi[28]=258,ht[258]=28;for(var Vi=Qs(lt,0),Lt=Vi.r,ut=new ne(32768),X=0;X<32768;++X){var Ce=(X&43690)>>1|(X&21845)<<1;Ce=(Ce&52428)>>2|(Ce&13107)<<2,Ce=(Ce&61680)>>4|(Ce&3855)<<4,ut[X]=((Ce&65280)>>8|(Ce&255)<<8)>>1}for(var Be=function(t,e,s){for(var n=t.length,i=0,r=new ne(e);i<n;++i)t[i]&&++r[t[i]-1];var o=new ne(e);for(i=1;i<e;++i)o[i]=o[i-1]+r[i-1]<<1;var l;if(s){l=new ne(1<<e);var a=15-e;for(i=0;i<n;++i)if(t[i])for(var h=i<<4|t[i],c=e-t[i],d=o[t[i]-1]++<<c,p=d|(1<<c)-1;d<=p;++d)l[ut[d]>>a]=h}else for(l=new ne(n),i=0;i<n;++i)t[i]&&(l[i]=ut[o[t[i]-1]++]>>15-t[i]);return l},Ie=new ae(288),X=0;X<144;++X)Ie[X]=8;for(var X=144;X<256;++X)Ie[X]=9;for(var X=256;X<280;++X)Ie[X]=7;for(var X=280;X<288;++X)Ie[X]=8;for(var Ye=new ae(32),X=0;X<32;++X)Ye[X]=5;var en=Be(Ie,9,0),tn=Be(Ye,5,0),Pt=function(t){return(t+7)/8|0},sn=function(t,e,s){return(e==null||e<0)&&(e=0),(s==null||s>t.length)&&(s=t.length),new ae(t.subarray(e,s))},Gi=["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"],nn=function(t,e,s){var n=new Error(e||Gi[t]);if(n.code=t,Error.captureStackTrace&&Error.captureStackTrace(n,nn),!s)throw n;return n},me=function(t,e,s){s<<=e&7;var n=e/8|0;t[n]|=s,t[n+1]|=s>>8},je=function(t,e,s){s<<=e&7;var n=e/8|0;t[n]|=s,t[n+1]|=s>>8,t[n+2]|=s>>16},dt=function(t,e){for(var s=[],n=0;n<t.length;++n)t[n]&&s.push({s:n,f:t[n]});var i=s.length,r=s.slice();if(!i)return{t:Ht,l:0};if(i==1){var o=new ae(s[0].s+1);return o[s[0].s]=1,{t:o,l:1}}s.sort(function(O,N){return O.f-N.f}),s.push({s:-1,f:25001});var l=s[0],a=s[1],h=0,c=1,d=2;for(s[0]={s:-1,f:l.f+a.f,l,r:a};c!=i-1;)l=s[s[h].f<s[d].f?h++:d++],a=s[h!=c&&s[h].f<s[d].f?h++:d++],s[c++]={s:-1,f:l.f+a.f,l,r:a};for(var p=r[0].s,n=1;n<i;++n)r[n].s>p&&(p=r[n].s);var y=new ne(p+1),w=ft(s[c-1],y,0);if(w>e){var n=0,b=0,T=w-e,D=1<<T;for(r.sort(function(N,F){return y[F.s]-y[N.s]||N.f-F.f});n<i;++n){var B=r[n].s;if(y[B]>e)b+=D-(1<<w-y[B]),y[B]=e;else break}for(b>>=T;b>0;){var A=r[n].s;y[A]<e?b-=1<<e-y[A]++-1:++n}for(;n>=0&&b;--n){var k=r[n].s;y[k]==e&&(--y[k],++b)}w=e}return{t:new ae(y),l:w}},ft=function(t,e,s){return t.s==-1?Math.max(ft(t.l,e,s+1),ft(t.r,e,s+1)):e[t.s]=s},Bt=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new ne(++e),n=0,i=t[0],r=1,o=function(a){s[n++]=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:s.subarray(0,n),n:e}},Ue=function(t,e){for(var s=0,n=0;n<e.length;++n)s+=t[n]*e[n];return s},jt=function(t,e,s){var n=s.length,i=Pt(e+2);t[i]=n&255,t[i+1]=n>>8,t[i+2]=t[i]^255,t[i+3]=t[i+1]^255;for(var r=0;r<n;++r)t[i+r+4]=s[r];return(i+4+n)*8},Ut=function(t,e,s,n,i,r,o,l,a,h,c){me(e,c++,s),++i[256];for(var d=dt(i,15),p=d.t,y=d.l,w=dt(r,15),b=w.t,T=w.l,D=Bt(p),B=D.c,A=D.n,k=Bt(b),O=k.c,N=k.n,F=new ne(19),C=0;C<B.length;++C)++F[B[C]&31];for(var C=0;C<O.length;++C)++F[O[C]&31];for(var E=dt(F,7),P=E.t,V=E.l,j=19;j>4&&!P[Mt[j-1]];--j);var W=h+5<<3,I=Ue(i,Ie)+Ue(r,Ye)+o,M=Ue(i,p)+Ue(r,b)+o+14+3*j+Ue(F,P)+2*F[16]+3*F[17]+7*F[18];if(a>=0&&W<=I&&W<=M)return jt(e,c,t.subarray(a,a+h));var q,G,H,v;if(me(e,c,1+(M<I)),c+=2,M<I){q=Be(p,y,0),G=p,H=Be(b,T,0),v=b;var f=Be(P,V,0);me(e,c,A-257),me(e,c+5,N-1),me(e,c+10,j-4),c+=14;for(var C=0;C<j;++C)me(e,c+3*C,P[Mt[C]]);c+=3*j;for(var u=[B,O],m=0;m<2;++m)for(var g=u[m],C=0;C<g.length;++C){var S=g[C]&31;me(e,c,f[S]),c+=P[S],S>15&&(me(e,c,g[C]>>5&127),c+=g[C]>>12)}}else q=en,G=Ie,H=tn,v=Ye;for(var C=0;C<l;++C){var x=n[C];if(x>255){var S=x>>18&31;je(e,c,q[S+257]),c+=G[S+257],S>7&&(me(e,c,x>>23&31),c+=ct[S]);var R=x&31;je(e,c,H[R]),c+=v[R],R>3&&(je(e,c,x>>5&8191),c+=lt[R])}else je(e,c,q[x]),c+=G[x]}return je(e,c,q[256]),c+G[256]},rn=new at([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ht=new ae(0),on=function(t,e,s,n,i,r){var o=r.z||t.length,l=new ae(n+o+5*(1+Math.ceil(o/7e3))+i),a=l.subarray(n,l.length-i),h=r.l,c=(r.r||0)&7;if(e){c&&(a[0]=r.r>>3);for(var d=rn[e-1],p=d>>13,y=d&8191,w=(1<<s)-1,b=r.p||new ne(32768),T=r.h||new ne(w+1),D=Math.ceil(s/3),B=2*D,A=function(se){return(t[se]^t[se+1]<<D^t[se+2]<<B)&w},k=new at(25e3),O=new ne(288),N=new ne(32),F=0,C=0,E=r.i||0,P=0,V=r.w||0,j=0;E+2<o;++E){var W=A(E),I=E&32767,M=T[W];if(b[I]=M,T[W]=I,V<=E){var q=o-E;if((F>7e3||P>24576)&&(q>423||!h)){c=Ut(t,a,0,k,O,N,C,P,j,E-j,c),P=F=C=0,j=E;for(var G=0;G<286;++G)O[G]=0;for(var G=0;G<30;++G)N[G]=0}var H=2,v=0,f=y,u=I-M&32767;if(q>2&&W==A(E-u))for(var m=Math.min(p,q)-1,g=Math.min(32767,E),S=Math.min(258,q);u<=g&&--f&&I!=M;){if(t[E+H]==t[E+H-u]){for(var x=0;x<S&&t[E+x]==t[E+x-u];++x);if(x>H){if(H=x,v=u,x>m)break;for(var R=Math.min(u,x-2),L=0,G=0;G<R;++G){var z=E-u+G&32767,_=b[z],$=z-_&32767;$>L&&(L=$,M=z)}}}I=M,M=b[I],u+=I-M&32767}if(v){k[P++]=268435456|ht[H]<<18|Lt[v];var Z=ht[H]&31,oe=Lt[v]&31;C+=ct[Z]+lt[oe],++O[257+Z],++N[oe],V=E+H,++F}else k[P++]=t[E],++O[t[E]]}}for(E=Math.max(E,V);E<o;++E)k[P++]=t[E],++O[t[E]];c=Ut(t,a,h,k,O,N,C,P,j,E-j,c),h||(r.r=c&7|a[c/8|0]<<3,c-=7,r.h=T,r.p=b,r.i=E,r.w=V)}else{for(var E=r.w||0;E<o+h;E+=65535){var te=E+65535;te>=o&&(a[c/8|0]=h,te=o),c=jt(a,c+1,t.subarray(E,te))}r.i=o}return sn(l,0,n+Pt(c)+i)},an=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var s=e,n=9;--n;)s=(s&1&&-306674912)^s>>>1;t[e]=s}return t}(),cn=function(){var t=-1;return{p:function(e){for(var s=t,n=0;n<e.length;++n)s=an[s&255^e[n]]^s>>>8;t=s},d:function(){return~t}}},zt=function(t,e,s,n,i){if(!i&&(i={l:1},e.dictionary)){var r=e.dictionary.subarray(-32768),o=new ae(r.length+t.length);o.set(r),o.set(t,r.length),t=o,i.w=r.length}return on(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,s,n,i)},Ki=function(t,e){var s={};for(var n in t)s[n]=t[n];for(var n in e)s[n]=e[n];return s},ln=function(t,e,s){for(var n=t(),i=t.toString(),r=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),o=0;o<n.length;++o){var l=n[o],a=r[o];if(typeof l=="function"){e+=";"+a+"=";var h=l.toString();if(l.prototype)if(h.indexOf("[native code]")!=-1){var c=h.indexOf(" ",8)+1;e+=h.slice(c,h.indexOf("(",c))}else{e+=h;for(var d in l.prototype)e+=";"+a+".prototype."+d+"="+l.prototype[d].toString()}else e+=h}else s[a]=l}return e},pt=[],Xi=function(t){var e=[];for(var s in t)t[s].buffer&&e.push((t[s]=new t[s].constructor(t[s])).buffer);return e},Ji=function(t,e,s,n){if(!pt[s]){for(var i="",r={},o=t.length-1,l=0;l<o;++l)i=ln(t[l],i,r);pt[s]={c:ln(t[o],i,r),e:r}}var a=Ki({},pt[s].e);return $i(pt[s].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",s,a,Xi(a),n)},Yi=function(){return[ae,ne,at,ct,lt,Mt,ht,Lt,en,Ie,tn,Ye,ut,rn,Ht,Be,me,je,dt,ft,Bt,Ue,jt,Ut,Pt,sn,on,zt,er,hn]},Qi=function(){return[un,dn,gt,cn,an]},hn=function(t){return postMessage(t,[t.buffer])},Zi=function(t,e,s,n,i,r){var o=Ji(s,n,i,function(l,a){o.terminate(),r(l,a)});return o.postMessage([t,e],e.consume?[t.buffer]:[]),function(){o.terminate()}},gt=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8},un=function(t,e){var s=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&&gt(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),s){t[3]=8;for(var n=0;n<=s.length;++n)t[n+10]=s.charCodeAt(n)}},dn=function(t){return 10+(t.filename?t.filename.length+1:0)};function er(t,e){return zt(t,e||{},0,0)}function tr(t,e,s){return s||(s=e,e={}),typeof s!="function"&&nn(7),Zi(t,e,[Yi,Qi,function(){return[fn]}],function(n){return hn(fn(n.data[0],n.data[1]))},2,s)}function fn(t,e){e||(e={});var s=cn(),n=t.length;s.p(t);var i=zt(t,e,dn(e),8),r=i.length;return un(i,e),gt(i,r-8,s.d()),gt(i,r-4,n),i}var sr=typeof TextDecoder<"u"&&new TextDecoder,nr=0;try{sr.decode(Ht,{stream:!0}),nr=1}catch{}class pn{constructor(){this.idx=1,this.backDict={}}getKey(e){let s=!1;return this.backDict[e]||(s=!0,this.backDict[e]=this.idx++),[this.backDict[e],s]}}class ir{constructor(e,s){this.app=e,this.isDictDisabled=s,this.dict=new pn}sendSetAttribute(e,s,n){if(this.isDictDisabled){const i=[12,e,s,n];return this.app.send(i)}else{const i=[51,e,this.applyDict(s),this.applyDict(n)];return this.app.send(i)}}applyDict(e){const[s,n]=this.dict.getKey(e);return n&&this.app.send([50,s,e]),s}clear(){this.dict=new pn}}class rr{constructor(e,s){this.app=e,this.startParams=s,this.conditions=[],this.hasStarted=!1,this.createConditionFromFilter=n=>{if(n.value.length){const i=or(n);if(i.type)return i}},this.durationInt=null}setConditions(e){this.conditions=e}async fetchConditions(e,s){try{const n=await fetch(`${this.app.options.ingestPoint}/v1/web/conditions/${e}`,{method:"GET",headers:{Authorization:`Bearer ${s}`}}),{conditions:i}=await n.json(),r=[];i.forEach(o=>{o.filters.forEach(a=>{let h;a.type==="fetch"?(h={type:"network_request",subConditions:[],name:o.name},a.filters.forEach(c=>{const d=this.createConditionFromFilter(c);d&&h.subConditions.push(d)})):h=this.createConditionFromFilter(a),h&&(h.type==="session_duration"&&this.processDuration(h.value[0],o.name),r.push({...h,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(s){this.app.debug.error(s)}}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 s=this.conditions.filter(n=>n.type==="feature_flag");s.length&&s.forEach(n=>{const i=He[n.operator];i&&e.find(r=>i(r.key,n.value))&&this.trigger(n.name)})}processDuration(e,s){this.durationInt=setInterval(()=>{performance.now()>e&&this.trigger(s)},1e3),this.app.attachStopCallback(()=>{this.durationInt&&clearInterval(this.durationInt)})}networkRequest(e){const s=this.conditions.filter(n=>n.type==="network_request");s.length&&s.forEach(n=>{const i=n.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=He[o.operator];if(a&&a(l,o.value))return!0})&&this.trigger(n.name):i.length===0&&n.subConditions.length&&this.trigger(n.name)})}customEvent(e){const s=this.conditions.filter(n=>n.type==="custom_event");s.length&&s.forEach(n=>{const i=He[n.operator];i&&(i(e[1],n.value)||i(e[2],n.value))&&this.trigger(n.name)})}clickEvent(e){const s=this.conditions.filter(n=>n.type==="click");s.length&&s.forEach(n=>{const i=He[n.operator];i&&(i(e[3],n.value)||i(e[4],n.value))&&this.trigger(n.name)})}pageLocationEvent(e){const s=this.conditions.filter(n=>n.type==="visited_url");s&&s.forEach(n=>{const i=He[n.operator];i&&i(e[1],n.value)&&this.trigger(n.name)})}jsExceptionEvent(e){const s=[e[1],e[2],e[3]],n=this.conditions.filter(i=>i.type==="exception");n&&n.forEach(i=>{const r=He[i.operator];r&&s.some(o=>r(o,i.value))&&this.trigger(i.name)})}}const He={is:(t,e)=>e.some(s=>t.includes(s)),isAny:()=>!0,isNot:(t,e)=>!e.some(s=>t.includes(s)),contains:(t,e)=>e.some(s=>t.includes(s)),notContains:(t,e)=>!e.some(s=>t.includes(s)),startsWith:(t,e)=>e.some(s=>t.startsWith(s)),endsWith:(t,e)=>e.some(s=>t.endsWith(s)),greaterThan:(t,e)=>t>e,greaterOrEqual:(t,e)=>t>=e,lessOrEqual:(t,e)=>t<=e,lessThan:(t,e)=>t<e},or=t=>{const e={on:"is",notOn:"isNot",">":"greaterThan","<":"lessThan","=":"is","<=":"lessOrEqual",">=":"greaterOrEqual"},s=i=>{if(Object.keys(e).includes(i))return e[i]};let n={type:"",operator:"",value:t.value,key:""};switch(t.type){case"click":n={type:"click",operator:s(t.operator),value:t.value,key:""};break;case"location":n={type:"visited_url",operator:t.operator,value:t.value,key:""};break;case"custom":n={type:"custom_event",operator:t.operator,value:t.value,key:""};break;case"metadata":n={type:t.source==="featureFlag"?"feature_flag":t.type,operator:t.operator,value:t.value,key:""};break;case"error":n={type:"exception",operator:t.operator,value:t.value,key:""};break;case"duration":n={type:"session_duration",value:t.value[0],key:""};break;case"fetchUrl":n={type:"network_request",key:"url",operator:t.operator,value:t.value};break;case"fetchStatusCode":n={type:"network_request",key:"status",operator:s(t.operator),value:t.value};break;case"fetchMethod":n={type:"network_request",key:"method",operator:s(t.operator),value:t.value};break;case"fetchDuration":n={type:"network_request",key:"duration",operator:s(t.operator),value:t.value};break}return n};class ar{constructor(e){this.app=e,this.flags=[],this.storageKey="__openreplay_flags";const s=this.app.sessionStorage.getItem(this.storageKey);if(s){const n=s.split(";").filter(Boolean);this.flags=n.map(i=>JSON.parse(i))}}getFeatureFlag(e){return this.flags.find(s=>s.key===e)}isFlagEnabled(e){return this.flags.findIndex(s=>s.key===e)!==-1}onFlagsLoad(e){this.onFlagsCb=e}async reloadFlags(e){const s=this.app.sessionStorage.getItem(this.storageKey),n={};s&&s.split(";").filter(Boolean).forEach(c=>{const d=JSON.parse(c);n[d.key]={key:d.key,value:d.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:n},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 h=await a.json();return this.handleFlags(h.flags)}}handleFlags(e){var r;const s=[];e.forEach(o=>{o.is_persist&&s.push(o)});let n="";return this.diffPersist(s).forEach(o=>{n+=`${JSON.stringify(o)};`}),this.app.sessionStorage.setItem(this.storageKey,n),this.flags=e,(r=this.onFlagsCb)==null?void 0:r.call(this,e)}clearPersistFlags(){this.app.sessionStorage.removeItem(this.storageKey)}diffPersist(e){const s=this.app.sessionStorage.getItem(this.storageKey);if(!s)return e;const i=s.split(";").filter(Boolean).map(r=>JSON.parse(r));return e.filter(r=>i.findIndex(o=>o.key===r.key)===-1)}}const gn={htmlmasked:"hidden",masked:"obscured"},ve=!(typeof window>"u"),cr=ve&&navigator.userAgent.match(/firefox|fxios/i),lr=1e5;let Wt=ve?Date.now()-performance.now():0;function $t(){Wt=Date.now()-performance.now()}function ze(){return Wt}const pe=ve&&performance.now?()=>Math.round(performance.now()+Wt):()=>Date.now(),qt="repeat"in String.prototype?t=>"*".repeat(t.length):t=>t.replace(/./g,"*");function mn(t){return t.trim().replace(/\s+/g," ")}function vn(t){return t.startsWith("https://")||t.startsWith("http://")}const mt="https://docs.openreplay.com",yn={};function _e(t,e,s="/"){yn[t]||(console.warn(`OpenReplay: ${t} is deprecated. ${e?`Please, use ${e} instead.`:""} Visit ${mt}${s} for more information.`),yn[t]=!0)}function Vt(t){let e=t.getAttribute("data-openreplay-label");return e!==null||(e=t.getAttribute("data-asayer-label"),e!==null&&_e('"data-asayer-label" attribute','"data-openreplay-label" attribute',"/")),e}function De(t,e){const s=`data-openreplay-${e}`;return t.hasAttribute(s)?(gn[e]&&_e(`"${s}" attribute`,`"${gn[e]}" attribute`,"/installation/sanitize-data"),!0):!1}function hr(t){try{return!!t.contentDocument}catch{return!1}}function bn(t){return t.toString(16).padStart(2,"0")}function ur(t){const e=new Uint8Array((t||40)/2),s=window.crypto||window.msCrypto;return s?(s.getRandomValues(e),Array.from(e,bn).join("")):Array.from({length:t||40},()=>bn(Math.floor(Math.random()*16))).join("")}function dr(){try{return window.self&&window.top&&window.self!==window.top}catch{return!0}}function Gt(t){return window.Zone&&"__symbol__"in window.Zone?window.Zone.__symbol__(t):t}function Sn(t){const e=Gt("MutationObserver");return new window[e](t)}function wn(t,e,s,n){const i=Gt("addEventListener");try{t[i](e,s,n)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}function xn(t,e,s,n){const i=Gt("removeEventListener");try{t[i](e,s,n)}catch(r){const o=r.message;console.debug(`Openreplay: ${o}; if this error is caused by an IframeObserver, ignore it`)}}class fr{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 s=this.taskQueue.shift();Promise.resolve(s()).then(()=>{requestAnimationFrame(()=>e())})};e()}}const pr=new fr;function gr(t){pr.addTask(t)}function kn(t,e){const s={...t};for(const n in e)if(e.hasOwnProperty(n)){const i=e[n],r=t[n];typeof i=="object"&&!Array.isArray(i)&&i!==null?s[n]=kn(r||{},i):s[n]=i}return s}function Ae(t){return[0,t]}function mr(t,e){return[5,t,e]}function vr(t,e){return[6,t,e]}function yr(){return[7]}function br(t,e,s,n,i){return[8,t,e,s,n,i]}function Sr(t,e,s){return[9,t,e,s]}function wr(t,e,s){return[10,t,e,s]}function xr(t){return[11,t]}function Tn(t,e){return[13,t,e]}function kr(t,e){return[14,t,e]}function Tr(t,e,s){return[16,t,e,s]}function Er(t,e,s){return[18,t,e,s]}function Cr(t,e){return[19,t,e]}function Ir(t,e){return[20,t,e]}function _r(t,e){return[22,t,e]}function Or(t,e,s,n,i,r,o,l,a){return[23,t,e,s,n,i,r,o,l,a]}function Nr(t,e,s){return[24,t,e,s]}function Rr(t,e){return[27,t,e]}function Dr(t){return[28,t]}function Ar(t){return[29,t]}function En(t,e){return[30,t,e]}function Fr(t,e,s,n){return[49,t,e,s,n]}function Mr(t,e){return[54,t,e]}function Lr(t){return[55,t]}function Cn(t,e,s,n){return[57,t,e,s,n]}function In(t){return[58,t]}function Kt(t,e,s,n){return[60,t,e,s,n]}function Pr(t,e,s){return[61,t,e,s]}function Br(t,e){return[63,t,e]}function jr(t,e){return[64,t,e]}function Ur(t,e,s,n,i,r){return[68,t,e,s,n,i,r]}function Xt(t,e){return[70,t,e]}function _n(t,e,s){return[71,t,e,s]}function Jt(t,e,s,n){return[73,t,e,s,n]}function On(t,e){return[75,t,e]}function Nn(t,e){return[76,t,e]}function Hr(t,e){return[77,t,e]}function Yt(t,e,s,n){return[78,t,e,s,n]}function vt(t,e,s,n,i,r,o,l,a){return[83,t,e,s,n,i,r,o,l,a]}function zr(t,e,s,n,i,r){return[84,t,e,s,n,i,r]}function Wr(t,e,s,n,i,r){return[112,t,e,s,n,i,r]}function Rn(t,e,s){return[113,t,e,s]}function $r(t){return[114,t]}function qr(t){return[115,t]}function Dn(t,e,s,n,i,r,o,l,a,h){return[116,t,e,s,n,i,r,o,l,a,h]}function yt(t){return[117,t]}function Fe(t){return[118,t]}function Vr(t,e){return[119,t,e]}function Gr(t){return[120,t]}function Kr(t,e,s,n){return[122,t,e,s,n]}const Qt=ve&&"performance"in window&&"memory"in performance?performance:{memory:{}},Zt=ve?(navigator.deviceMemory||0)*1024:0,es=Qt.memory.jsHeapSizeLimit||0;function Xr(t,e){if(!Object.assign({capturePerformance:!0},e).capturePerformance)return;let n,i;const r=()=>{n===void 0||n===-1||(n++,requestAnimationFrame(r))};t.ticker.attach(()=>{i===void 0||i===-1||i++},0,!1);const o=()=>{n===void 0||i===void 0||(t.send(Fr(n,i,Qt.memory.totalJSHeapSize||0,Qt.memory.usedJSHeapSize||0)),i=n=document.hidden?-1:0)};t.attachStartCallback(()=>{i=n=-1,o(),r()}),t.attachStopCallback(()=>{i=n=void 0}),t.ticker.attach(o,40,!1),document.hidden!==void 0&&t.attachEventListener(document,"visibilitychange",o,!1,!1)}const An="__or__watched_tags__";class Jr{constructor(e,s,n){this.sessionStorage=e,this.errLog=s,this.onTag=n,this.intervals={},this.tags=[];const i=JSON.parse(e.getItem(An)??"[]");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,s){return fetch(`${e}/v1/web/tags`,{method:"GET",headers:{Authorization:`Bearer ${s}`}}).then(n=>n.json()).then(({tags:n})=>{if(n&&n.length){this.setTags(n);const i=JSON.stringify(n);this.sessionStorage.setItem(An,i||"")}}).catch(n=>this.errLog(n))}setTags(e){this.tags=e,this.intervals={},e.forEach(s=>{this.intervals[s.id]=setInterval(()=>{const n=document.querySelectorAll(s.selector);if(n.length>0){const i=n[0];i.__or_watcher_tagname=s.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 Yr={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"'},Qr={display:"flex",flexDirection:"column",gap:"2rem",alignItems:"center",padding:"1.5rem",borderRadius:"2px",border:"1px solid #D9D9D9",background:"#FFF",width:"22rem"},bt={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"},Zr={fontFamily:"Verdana, sans-serif",fontSize:"1.25rem",fontStyle:"normal",fontWeight:"500",lineHeight:"1.75rem",color:"rgba(0, 0, 0, 0.85)"},eo={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"},to={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"},Fn={fontFamily:"Verdana, sans-serif",fontSize:"13px",fontWeight:"500",lineHeight:"auto",display:"flex",justifyContent:"space-between",width:"100%",cursor:"pointer"},We={display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"0.625rem",fontSize:"13px",lineHeight:"auto"},so={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"},$e={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"},no={...$e,display:"flex",flexDirection:"column",alignItems:"center",gap:"0.625rem"},Mn={fontSize:"1.25rem",fontWeight:"500",cursor:"pointer",color:"#394EFF"},Ln={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"},Pn={marginTop:"1rem",marginBottom:"1rem",cursor:"pointer",display:"block",fontWeight:"500",fontSize:"13px!important",lineHeight:"auto"},io={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",padding:"0.5rem",width:"100%",boxSizing:"border-box"},Bn={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em",outline:"1px solid #394EFF",fontSize:"13px",height:"24px",width:"24px"},ro={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"},jn={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"},Un={fontWeight:"bold"},oo={fontSize:"13px",lineHeight:"auto"},Hn={marginRight:"0.5rem",cursor:"pointer",color:"#394EFF",textAlign:"center",fontFamily:"Verdana, sans-serif",fontSize:"13px",fontStyle:"normal",fontWeight:"500",lineHeight:"auto"},ao={...Hn,display:"flex",padding:"0.25rem 0.9375rem",justifyContent:"center",alignItems:"center",gap:"0.5rem",borderRadius:"0.25rem",border:"1px solid #394EFF"},co={display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",boxSizing:"border-box"},lo={border:"4px solid rgba(255, 255, 255, 0.4)",width:"16px",height:"16px",borderRadius:"50%",borderLeftColor:"#fff",animation:"spin 0.5s linear infinite"},zn={Standard:{width:1280,height:720},High:{width:1920,height:1080}};class ho{constructor(e){this.app=e,this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this.recStartTs=null}async startRecording(e,s,n,i){this.recStartTs=this.app.timestamp();const r=s;try{this.stream=await navigator.mediaDevices.getUserMedia({video:i?{...r,frameRate:{ideal:e}}:!1,audio:n}),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 s=new Blob(this.recordedChunks,{type:"video/webm"});e(s)},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(s=>{if(s.ok)return s.json();throw new Error("Failed to get upload url")}).then(({url:s})=>fetch(s,{method:"PUT",headers:{"Content-Type":"video/webm"},body:e})).catch(console.error).finally(()=>{this.discard()})}async saveToFile(e="recorded-video.webm"){const s=await this.stopRecording(),n=URL.createObjectURL(s),i=document.createElement("a");i.style.display="none",i.href=n,i.download=e,document.body.appendChild(i),i.click(),window.URL.revokeObjectURL(n),document.body.removeChild(i)}discard(){var e,s;(e=this.mediaRecorder)==null||e.stop(),(s=this.stream)==null||s.getTracks().forEach(n=>n.stop())}}function uo(t,e){e.onmousedown=function(s){const n=t.getBoundingClientRect(),i=s.clientX-n.left,r=s.clientY-n.top;t.style.position="fixed",t.style.zIndex=99999999999999,o(s.pageX,s.pageY);function o(h,c){let d=h-i,p=c-r;d<=5&&(d=5),p<=5&&(p=5),d>=window.innerWidth-n.width&&(d=window.innerWidth-n.width),p>=window.innerHeight-n.height&&(p=window.innerHeight-n.height),t.style.left=`${d}px`,t.style.top=`${p}px`}function l(h){o(h.pageX,h.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 fo(){const t=document.createElement("div");t.className="grid";for(let e=0;e<16;e++){const s=document.createElement("div");Object.assign(s.style,{width:"2px",height:"2px",borderRadius:"10px",background:"white"}),s.className="cell",t.appendChild(s)}return Object.assign(t.style,{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gridTemplateRows:"repeat(4, 1fr)",gap:"2px",cursor:"grab"}),t}function po(){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 go(){const t=document.createElement("style");t.type="text/css",t.innerText=`@keyframes spin {
629
641
  0% { transform: rotate(0deg); }
630
642
  100% { transform: rotate(360deg); }
631
- }`,document.head.appendChild(t)}function uo(){lo();const t=document.createElement("div");return t.classList.add("spinner"),Object.assign(t.style,io),t}function U(t,e,s,n,i){const r=document.createElement(t);return r.className=e,Object.assign(r.style,s),n&&(r.textContent=n),i&&(r.id=i),r}const St="or_uxt_test_start",ts="or_uxt_task_index",ss="or_uxt_session_id",ho="or_uxt_test_id";class fo{constructor(e,s,n,i,r,o,l,a,u){this.ingestPoint=e,this.getTimestamp=s,this.token=n,this.testId=i,this.storageKey=r,this.setStorageKey=o,this.removeStorageKey=l,this.getStorageKey=a,this.getSessionId=u,this.durations={testStart:0,tasks:[]},this.getDurations=()=>this.durations,this.setDurations=d=>{this.durations.testStart=d.testStart,this.durations.tasks=d.tasks},this.signalTask=(d,p,y)=>{if(!d)return console.error("User Testing: No Task ID Given");const w=this.durations.tasks.find(D=>D.taskId===d),b=this.getTimestamp(),T=w?b-w.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:d,status:p,duration:T,timestamp:b,taskAnswer:y})})},this.signalTest=d=>{const p=this.getTimestamp();if(d==="begin"&&this.testId){const b=this.getSessionId();this.setStorageKey(ss,b),this.setStorageKey(this.storageKey,this.testId.toString()),this.setStorageKey(St,p.toString())}else this.removeStorageKey(this.storageKey),this.removeStorageKey(ts),this.removeStorageKey(St);const y=this.durations.testStart||p,w=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:d,duration:w,timestamp:p})})};const c=this.getStorageKey(St);c&&(this.durations.testStart=parseInt(c,10))}}class po{constructor(e,s){this.app=e,this.storageKey=s,this.bg=U("div","bg",Vr,void 0,"__or_ut_bg"),this.container=U("div","container",Gr,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 u=this.app.options.ingestPoint;return fetch(`${u}/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 fo(this.app.options.ingestPoint,()=>this.app.timestamp(),l,o,this.storageKey,(d,p)=>this.app.localStorage.setItem(d,p),d=>this.app.localStorage.removeItem(d),d=>this.app.localStorage.getItem(d),()=>this.app.getSessionID()),this.createGreeting(c.title,c.reqMic,c.reqCamera),a&&((c.reqMic||c.reqCamera)&&this.userRecorder.startRecording(30,zn.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 ro(e);const n=this.app.getSessionID(),i=this.app.localStorage.getItem(ss);n!==i&&(this.app.localStorage.removeItem(this.storageKey),this.app.localStorage.removeItem(ss),this.app.localStorage.removeItem(ho),this.app.localStorage.removeItem(ts),this.app.localStorage.removeItem(St));const r=this.app.localStorage.getItem(ts);r&&(this.currentTaskIndex=parseInt(r,10))}getTestId(){return this.testId}createGreeting(e,s,n){const i=U("div","title",Kr,e),r=U("div","description",Xr,`Welcome, you're here to help us improve, not to be judged. Your insights matter!
643
+ }`,document.head.appendChild(t)}function mo(){go();const t=document.createElement("div");return t.classList.add("spinner"),Object.assign(t.style,lo),t}function U(t,e,s,n,i){const r=document.createElement(t);return r.className=e,Object.assign(r.style,s),n&&(r.textContent=n),i&&(r.id=i),r}const St="or_uxt_test_start",ts="or_uxt_task_index",ss="or_uxt_session_id",vo="or_uxt_test_id";class yo{constructor(e,s,n,i,r,o,l,a,h){this.ingestPoint=e,this.getTimestamp=s,this.token=n,this.testId=i,this.storageKey=r,this.setStorageKey=o,this.removeStorageKey=l,this.getStorageKey=a,this.getSessionId=h,this.durations={testStart:0,tasks:[]},this.getDurations=()=>this.durations,this.setDurations=d=>{this.durations.testStart=d.testStart,this.durations.tasks=d.tasks},this.signalTask=(d,p,y)=>{if(!d)return console.error("User Testing: No Task ID Given");const w=this.durations.tasks.find(D=>D.taskId===d),b=this.getTimestamp(),T=w?b-w.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:d,status:p,duration:T,timestamp:b,taskAnswer:y})})},this.signalTest=d=>{const p=this.getTimestamp();if(d==="begin"&&this.testId){const b=this.getSessionId();this.setStorageKey(ss,b),this.setStorageKey(this.storageKey,this.testId.toString()),this.setStorageKey(St,p.toString())}else this.removeStorageKey(this.storageKey),this.removeStorageKey(ts),this.removeStorageKey(St);const y=this.durations.testStart||p,w=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:d,duration:w,timestamp:p})})};const c=this.getStorageKey(St);c&&(this.durations.testStart=parseInt(c,10))}}class bo{constructor(e,s){this.app=e,this.storageKey=s,this.bg=U("div","bg",Yr,void 0,"__or_ut_bg"),this.container=U("div","container",Qr,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 h=this.app.options.ingestPoint;return fetch(`${h}/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 yo(this.app.options.ingestPoint,()=>this.app.timestamp(),l,o,this.storageKey,(d,p)=>this.app.localStorage.setItem(d,p),d=>this.app.localStorage.removeItem(d),d=>this.app.localStorage.getItem(d),()=>this.app.getSessionID()),this.createGreeting(c.title,c.reqMic,c.reqCamera),a&&((c.reqMic||c.reqCamera)&&this.userRecorder.startRecording(30,zn.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 ho(e);const n=this.app.getSessionID(),i=this.app.localStorage.getItem(ss);n!==i&&(this.app.localStorage.removeItem(this.storageKey),this.app.localStorage.removeItem(ss),this.app.localStorage.removeItem(vo),this.app.localStorage.removeItem(ts),this.app.localStorage.removeItem(St));const r=this.app.localStorage.getItem(ts);r&&(this.currentTaskIndex=parseInt(r,10))}getTestId(){return this.testId}createGreeting(e,s,n){const i=U("div","title",Zr,e),r=U("div","description",eo,`Welcome, you're here to help us improve, not to be judged. Your insights matter!
632
644
 
633
645
  📹 We're recording this browser tab to learn from your experience.
634
- 🎤 Please enable mic and camera if asked, to give us a complete picture.`),o=U("div","button",Jr,"Read guidelines to begin");this.removeGreeting=()=>((s||n)&&this.userRecorder.startRecording(30,zn.Standard,s,n),this.container.removeChild(o),this.container.removeChild(r),this.container.removeChild(i),!1),o.onclick=()=>{var a,u,c,d;this.removeGreeting();const l=(a=this.signalManager)==null?void 0:a.getDurations();l&&this.signalManager&&(l.testStart=this.app.timestamp(),this.signalManager.setDurations(l)),(u=this.signalManager)==null||u.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,bt),this.showWidget(((c=this.test)==null?void 0:c.guidelines)||"",((d=this.test)==null?void 0:d.tasks)||[])},this.container.append(i,r,o),this.bg.appendChild(this.container),document.body.appendChild(this.bg)}showWidget(e,s,n){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 i=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,bt);const r=this.createDescriptionSection(e),o=this.createTasksSection(s),l=U("div","stop_bn_or",Pn,"Abort Session"),a=U("div","stop_ct_or",{fontSize:"13px!important"});a.style.fontSize="13px",a.append(l),this.container.append(i,r,o,a),this.taskSection=o,this.descriptionSection=r,this.stopButton=l,this.stopButtonContainer=a,l.onclick=()=>{var u;this.userRecorder.discard(),(u=this.signalManager)==null||u.signalTest("skipped"),document.body.removeChild(this.bg),window.close()},n?this.toggleDescriptionVisibility():this.hideTaskSection()}createTitleSection(){var l;const e=U("div","title",Yr),s=ao(),n=U("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),i=co();e.append(s,n,i);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?bt:{border:"none",background:"none",padding:0}),this.taskSection&&Object.assign(this.taskSection.style,this.widgetVisible?$e:{display:"none"}),this.descriptionSection&&Object.assign(this.descriptionSection.style,this.widgetVisible?$e:{display:"none"}),this.endSection&&Object.assign(this.endSection.style,this.widgetVisible?$e:{display:"none"}),this.stopButton&&Object.assign(this.stopButton.style,this.widgetVisible?Pn:{display:"none"}),a),o=()=>{Object.assign(i.style,{transform:this.widgetVisible?"rotate(0deg)":"rotate(180deg)"}),r(!this.widgetVisible)};return n.onclick=o,i.onclick=o,oo(this.bg,s),this.collapseWidget=()=>r(!1),e}createDescriptionSection(e){const s=U("div","description_section_or",$e),n=U("div","description_s_title_or",Fn),i=U("div","title",{fontSize:13,fontWeight:500,lineHeight:"auto"},"Introduction & Guidelines"),r=U("div","icon",Mn,"-"),o=U("div","content",We),l=U("div","text_description",{maxHeight:"250px",overflowY:"auto",whiteSpace:"pre-wrap",fontSize:13,color:"#454545",lineHeight:"auto"});l.innerHTML=e;const a=U("div","button_begin_or",Ln,"Begin Test");n.append(i,r),o.append(l,a),s.append(n,o);const u=()=>{this.widgetGuidelinesVisible=!this.widgetGuidelinesVisible,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?We:{display:"none"})};return n.onclick=u,this.toggleDescriptionVisibility=()=>{this.widgetGuidelinesVisible=!1,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?We:{display:"none"}),o.removeChild(a)},a.onclick=()=>{var c,d,p;if(u(),this.test){const y=(c=this.signalManager)==null?void 0:c.getDurations(),w=y?y.tasks.findIndex(b=>this.test&&b.taskId===this.test.tasks[0].task_id):null;y&&w===-1&&(y.tasks.push({taskId:this.test.tasks[0].task_id,started:this.app.timestamp()}),(d=this.signalManager)==null||d.setDurations(y)),(p=this.signalManager)==null||p.signalTask(this.test.tasks[0].task_id,"begin")}this.showTaskSection(),o.removeChild(a)},s}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,bt);const s=U("div","task_section_or",$e),n=U("div","description_t_title_or",Fn),i=U("div","title",{fontSize:"13px",fontWeight:"500",lineHeight:"auto"},"Tasks"),r=U("div","icon",Mn,"-"),o=U("div","content",We),l=U("div","pagination",Zr),a=U("div","taskCard",jn),u=U("div","taskText",Un),c=U("div","taskDescription",to),d=U("div","taskButtons",no),p=U("div","taskText",Un);p.textContent="Your answer";const y=U("textarea","taskDescription",{resize:"vertical"}),w=U("div","inputArea",jn);w.append(p,y);const b=U("div","closePanelButton",Hn,"Collapse Panel"),T=U("div","nextButton",so,"Done, Next");n.append(i,r),a.append(u,c),d.append(b,T),o.append(l,a,w,d),s.append(n,o);const D=()=>{const k=e[this.currentTaskIndex];u.textContent=k.title,c.textContent=k.description,k.allow_typing?w.style.display="flex":w.style.display="none"};e.forEach((k,O)=>{const N=U("span",`or_task_${O}`,{outline:"1px solid #efefef",fontSize:"13px",height:"24px",width:"24px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em"},(O+1).toString());N.id=`or_task_${O}`,l.append(N)});const B=()=>{this.widgetTasksVisible=!this.widgetTasksVisible,r.textContent=this.widgetTasksVisible?"-":"+",Object.assign(o.style,this.widgetTasksVisible?We:{display:"none"})};this.hideTaskSection=()=>(r.textContent="+",Object.assign(o.style,{display:"none"}),this.widgetTasksVisible=!1,!1),this.showTaskSection=()=>(r.textContent="-",Object.assign(o.style,We),this.widgetTasksVisible=!0,!0);const A=()=>{const k=document.getElementById(`or_task_${this.currentTaskIndex}`);k&&Object.assign(k.style,Bn);for(let O=0;O<this.currentTaskIndex;O++){const N=document.getElementById(`or_task_${O}`);N&&Object.assign(N.style,eo)}};return n.onclick=B,b.onclick=this.collapseWidget,T.onclick=()=>{var O,N,F,C;const k=e[this.currentTaskIndex].allow_typing?y.value:void 0;if(y.value="",(O=this.signalManager)==null||O.signalTask(e[this.currentTaskIndex].task_id,"done",k),this.currentTaskIndex<e.length-1){this.currentTaskIndex++,D();const E=(N=this.signalManager)==null?void 0:N.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()}),(F=this.signalManager)==null||F.setDurations(E)),(C=this.signalManager)==null||C.signalTask(e[this.currentTaskIndex].task_id,"begin"),A()}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,Bn),D(),A()},1),s}showEndSection(){var l,a,u,c;let e=!0;(l=this.signalManager)==null||l.signalTest("done");const s=U("div","end_section_or",Qr),n=U("div","end_title_or",{fontSize:"1.25rem",fontWeight:"500"},"Thank you! 👍"),i=U("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.
646
+ 🎤 Please enable mic and camera if asked, to give us a complete picture.`),o=U("div","button",to,"Read guidelines to begin");this.removeGreeting=()=>((s||n)&&this.userRecorder.startRecording(30,zn.Standard,s,n),this.container.removeChild(o),this.container.removeChild(r),this.container.removeChild(i),!1),o.onclick=()=>{var a,h,c,d;this.removeGreeting();const l=(a=this.signalManager)==null?void 0:a.getDurations();l&&this.signalManager&&(l.testStart=this.app.timestamp(),this.signalManager.setDurations(l)),(h=this.signalManager)==null||h.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,bt),this.showWidget(((c=this.test)==null?void 0:c.guidelines)||"",((d=this.test)==null?void 0:d.tasks)||[])},this.container.append(i,r,o),this.bg.appendChild(this.container),document.body.appendChild(this.bg)}showWidget(e,s,n){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 i=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,bt);const r=this.createDescriptionSection(e),o=this.createTasksSection(s),l=U("div","stop_bn_or",Pn,"Abort Session"),a=U("div","stop_ct_or",{fontSize:"13px!important"});a.style.fontSize="13px",a.append(l),this.container.append(i,r,o,a),this.taskSection=o,this.descriptionSection=r,this.stopButton=l,this.stopButtonContainer=a,l.onclick=()=>{var h;this.userRecorder.discard(),(h=this.signalManager)==null||h.signalTest("skipped"),document.body.removeChild(this.bg),window.close()},n?this.toggleDescriptionVisibility():this.hideTaskSection()}createTitleSection(){var l;const e=U("div","title",so),s=fo(),n=U("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),i=po();e.append(s,n,i);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?bt:{border:"none",background:"none",padding:0}),this.taskSection&&Object.assign(this.taskSection.style,this.widgetVisible?$e:{display:"none"}),this.descriptionSection&&Object.assign(this.descriptionSection.style,this.widgetVisible?$e:{display:"none"}),this.endSection&&Object.assign(this.endSection.style,this.widgetVisible?$e:{display:"none"}),this.stopButton&&Object.assign(this.stopButton.style,this.widgetVisible?Pn:{display:"none"}),a),o=()=>{Object.assign(i.style,{transform:this.widgetVisible?"rotate(0deg)":"rotate(180deg)"}),r(!this.widgetVisible)};return n.onclick=o,i.onclick=o,uo(this.bg,s),this.collapseWidget=()=>r(!1),e}createDescriptionSection(e){const s=U("div","description_section_or",$e),n=U("div","description_s_title_or",Fn),i=U("div","title",{fontSize:13,fontWeight:500,lineHeight:"auto"},"Introduction & Guidelines"),r=U("div","icon",Mn,"-"),o=U("div","content",We),l=U("div","text_description",{maxHeight:"250px",overflowY:"auto",whiteSpace:"pre-wrap",fontSize:13,color:"#454545",lineHeight:"auto"});l.innerHTML=e;const a=U("div","button_begin_or",Ln,"Begin Test");n.append(i,r),o.append(l,a),s.append(n,o);const h=()=>{this.widgetGuidelinesVisible=!this.widgetGuidelinesVisible,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?We:{display:"none"})};return n.onclick=h,this.toggleDescriptionVisibility=()=>{this.widgetGuidelinesVisible=!1,r.textContent=this.widgetGuidelinesVisible?"-":"+",Object.assign(o.style,this.widgetGuidelinesVisible?We:{display:"none"}),o.removeChild(a)},a.onclick=()=>{var c,d,p;if(h(),this.test){const y=(c=this.signalManager)==null?void 0:c.getDurations(),w=y?y.tasks.findIndex(b=>this.test&&b.taskId===this.test.tasks[0].task_id):null;y&&w===-1&&(y.tasks.push({taskId:this.test.tasks[0].task_id,started:this.app.timestamp()}),(d=this.signalManager)==null||d.setDurations(y)),(p=this.signalManager)==null||p.signalTask(this.test.tasks[0].task_id,"begin")}this.showTaskSection(),o.removeChild(a)},s}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,bt);const s=U("div","task_section_or",$e),n=U("div","description_t_title_or",Fn),i=U("div","title",{fontSize:"13px",fontWeight:"500",lineHeight:"auto"},"Tasks"),r=U("div","icon",Mn,"-"),o=U("div","content",We),l=U("div","pagination",io),a=U("div","taskCard",jn),h=U("div","taskText",Un),c=U("div","taskDescription",oo),d=U("div","taskButtons",co),p=U("div","taskText",Un);p.textContent="Your answer";const y=U("textarea","taskDescription",{resize:"vertical"}),w=U("div","inputArea",jn);w.append(p,y);const b=U("div","closePanelButton",Hn,"Collapse Panel"),T=U("div","nextButton",ao,"Done, Next");n.append(i,r),a.append(h,c),d.append(b,T),o.append(l,a,w,d),s.append(n,o);const D=()=>{const k=e[this.currentTaskIndex];h.textContent=k.title,c.textContent=k.description,k.allow_typing?w.style.display="flex":w.style.display="none"};e.forEach((k,O)=>{const N=U("span",`or_task_${O}`,{outline:"1px solid #efefef",fontSize:"13px",height:"24px",width:"24px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"6.25em"},(O+1).toString());N.id=`or_task_${O}`,l.append(N)});const B=()=>{this.widgetTasksVisible=!this.widgetTasksVisible,r.textContent=this.widgetTasksVisible?"-":"+",Object.assign(o.style,this.widgetTasksVisible?We:{display:"none"})};this.hideTaskSection=()=>(r.textContent="+",Object.assign(o.style,{display:"none"}),this.widgetTasksVisible=!1,!1),this.showTaskSection=()=>(r.textContent="-",Object.assign(o.style,We),this.widgetTasksVisible=!0,!0);const A=()=>{const k=document.getElementById(`or_task_${this.currentTaskIndex}`);k&&Object.assign(k.style,Bn);for(let O=0;O<this.currentTaskIndex;O++){const N=document.getElementById(`or_task_${O}`);N&&Object.assign(N.style,ro)}};return n.onclick=B,b.onclick=this.collapseWidget,T.onclick=()=>{var O,N,F,C;const k=e[this.currentTaskIndex].allow_typing?y.value:void 0;if(y.value="",(O=this.signalManager)==null||O.signalTask(e[this.currentTaskIndex].task_id,"done",k),this.currentTaskIndex<e.length-1){this.currentTaskIndex++,D();const E=(N=this.signalManager)==null?void 0:N.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()}),(F=this.signalManager)==null||F.setDurations(E)),(C=this.signalManager)==null||C.signalTask(e[this.currentTaskIndex].task_id,"begin"),A()}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,Bn),D(),A()},1),s}showEndSection(){var l,a,h,c;let e=!0;(l=this.signalManager)==null||l.signalTest("done");const s=U("div","end_section_or",no),n=U("div","end_title_or",{fontSize:"1.25rem",fontWeight:"500"},"Thank you! 👍"),i=U("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.
635
647
 
636
- We appreciate your time and valuable input.`),r=U("div","end_button_or",Ln,"Submitting Feedback"),o=uo();r.appendChild(o),(u=this.test)!=null&&u.reqMic||(c=this.test)!=null&&c.reqCamera?this.userRecorder.sendToAPI().then(()=>{r.removeChild(o),r.textContent="End Session",e=!1}).catch(d=>{console.error(d),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))},s.append(n,i,r),this.endSection=s,this.container.append(s)}}function Wn(t){return!!t&&t.nodeType!=null}function ns(t){return t.namespaceURI==="http://www.w3.org/2000/svg"}function ke(t){return t.nodeType===Node.ELEMENT_NODE}function go(t){return t.nodeType===Node.COMMENT_NODE}function is(t){return t.nodeType===Node.TEXT_NODE}function wt(t){return t.nodeType===Node.DOCUMENT_NODE}function xt(t){return t.nodeType===Node.DOCUMENT_NODE||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Y(t,e){return t.localName===e}class mo{constructor(e,s){this.app=e,this.options=s,this.snapshots={},this.intervals=[],this.restartTracking=()=>{this.clear(),this.app.nodes.scanTree(this.captureCanvas)},this.captureCanvas=n=>{const i=this.app.nodes.getID(n);if(!i||!Y(n,"canvas")||this.app.sanitizer.isObscured(i)||this.app.sanitizer.isHidden(i)||!Y(n,"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(n)},this.recordCanvas=(n,i)=>{const r=this.app.timestamp();this.snapshots[i]={images:[],createdAt:r,paused:!1,dummy:document.createElement("canvas")};const o=Hr(i.toString(),r);this.app.send(o);const l=u=>{vo(u,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 u=this.app.nodes.getID(n),c=u?this.app.nodes.getNode(u):void 0;!c||!Y(c,"canvas")||c!==n?(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=s.fileExt??"webp",this.interval=1e3/s.fps}startTracking(){setTimeout(()=>{this.app.nodes.scanTree(this.captureCanvas),this.app.nodes.attachNodeCallback(e=>{this.captureCanvas(e)})},500)}sendSnaps(e,s,n){if(Object.keys(this.snapshots).length===0)return;const i=new FormData;e.forEach(r=>{const o=r.data;o&&(i.append("snapshot",o,`${n}_${s}_${r.id}.${this.fileExt}`),this.options.isDebug&&yo(o,`${n}_${s}_${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 $n={low:.35,medium:.55,high:.8};function vo(t,e="medium",s,n=!1,i,r){const o=`image/${i}`;if(n){const l=window.devicePixelRatio||1;s.width=t.width/l,s.height=t.height/l;const a=s.getContext("2d");if(!a)return"";a.clearRect(0,0,s.width,s.height),a.drawImage(t,0,0,s.width,s.height),s.toBlob(r,o,$n[e])}else t.toBlob(r,o,$n[e])}function yo(t,e){const s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=e,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n)}const Qe={Verbose:5,Log:4,Warnings:3,Errors:2,Silent:0};class bo{constructor(e=Qe.Silent){this.shouldLog=s=>this.level>=s,this.log=(...s)=>{this.shouldLog(Qe.Log)&&console.log(...s)},this.warn=(...s)=>{this.shouldLog(Qe.Warnings)&&console.warn(...s)},this.error=(...s)=>{this.shouldLog(Qe.Errors)&&console.error(...s)},this.level=e}}class So{constructor(e){this.node_id=e,this.nodes=[],this.totalNodeAmount=0,this.nodeCallbacks=[],this.elementListeners=new Map,this.nextNodeId=0,this.scanTree=s=>{this.nodes.forEach(n=>s(n))}}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,s,n,i=!0){const r=this.getID(e);if(r===void 0)return;wn(e,s,n,i);let o=this.elementListeners.get(r);o===void 0&&(o=[],this.elementListeners.set(r,o)),o.push([s,n,i])}registerNode(e){let s=e[this.node_id];const n=s===void 0;return n&&(s=this.nextNodeId,this.totalNodeAmount++,this.nextNodeId++,this.nodes[s]=e,e[this.node_id]=s),[s,n]}unregisterNode(e){const s=e[this.node_id];if(s!==void 0){e[this.node_id]=void 0,delete e[this.node_id],delete this.nodes[s];const n=this.elementListeners.get(s);n!==void 0&&(this.elementListeners.delete(s),n.forEach(i=>xn(e,i[0],i[1],i[2]))),this.totalNodeAmount--}return s}cleanTree(){for(let e=0;e<this.nodes.length;e++){const s=this.nodes[e];s&&!document.contains(s)&&this.unregisterNode(s)}}callNodeCallbacks(e,s){this.nodeCallbacks.forEach(n=>n(e,s))}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 s=this.nodes[e];s&&this.unregisterNode(s)}this.nextNodeId=0,this.nodes.length=0}}function rs(t){if(go(t))return!0;if(is(t))return!1;if(!ke(t))return!0;const e=t.tagName.toUpperCase();if(e==="LINK"){const s=t.getAttribute("rel"),n=t.getAttribute("as");return!(s!=null&&s.includes("stylesheet")||n==="style"||n==="font")}return e==="SCRIPT"||e==="NOSCRIPT"||e==="META"||e==="TITLE"||e==="BASE"}function os(t){return xt(t)?!0:!rs(t)}var ye;(function(t){t[t.New=0]="New",t[t.Removed=1]="Removed",t[t.Changed=2]="Changed"})(ye||(ye={}));class as{constructor(e,s=!1){this.app=e,this.isTopContext=s,this.commited=[],this.recents=new Map,this.indexes=[],this.attributesMap=new Map,this.textSet=new Set,this.observer=Sn(this.app.safe(n=>{for(const i of n){const r=i.target,o=i.type;if(!os(r))continue;if(o==="childList"){for(let a=0;a<i.removedNodes.length;a++)os(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 u=this.attributesMap.get(l);u===void 0&&this.attributesMap.set(l,u=new Set),u.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,s,n,i){if(ns(s)){n.substr(0,6)==="xlink:"&&(n=n.substr(6)),i===null?this.app.send(Tn(e,n)):n==="href"?(i.length>1e5&&(i=""),this.app.send(Kt(e,n,i,this.app.getBaseHref()))):this.app.attributeSender.sendSetAttribute(e,n,i);return}if(!(n==="src"||n==="srcset"||n==="integrity"||n==="crossorigin"||n==="autocomplete"||n.substr(0,2)==="on")&&!(n==="value"&&Y(s,"input")&&s.type!=="button"&&s.type!=="reset"&&s.type!=="submit")){if(i===null){this.app.send(Tn(e,n));return}if(n==="style"||n==="href"&&Y(s,"link")){this.app.send(Kt(e,n,i,this.app.getBaseHref()));return}(n==="href"||i.length>1e5)&&(i=""),this.app.attributeSender.sendSetAttribute(e,n,i)}}sendNodeData(e,s,n){if(Y(s,"style")){this.app.send(Dr(e,n,this.app.getBaseHref()));return}n=this.app.sanitizer.sanitize(e,n),this.app.send(yr(e,n))}bindNode(e){const[s,n]=this.app.nodes.registerNode(e);n?this.recents.set(s,ye.New):this.recents.get(s)!==ye.New&&this.recents.set(s,ye.Removed)}bindTree(e){if(!os(e))return;this.bindNode(e);const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:n=>(this.app.nodes.getID(n)!==void 0&&this.app.debug.error("! Node is already bound",n),rs(n)||this.app.nodes.getID(n)!==void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT)},!1);for(;s.nextNode();)this.bindNode(s.currentNode)}unbindTree(e){const s=this.app.nodes.unregisterNode(e);if(s!==void 0&&this.recents.get(s)===ye.Removed){this.app.send(vr(s));const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:l=>rs(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(;n.nextNode();)i+=1,this.app.nodes.unregisterNode(n.currentNode);const o=Math.floor(i/r*100);o>30&&this.app.send(Ur(o))}}_commitNode(e,s){if(xt(s))return!0;const n=s.parentNode;let i;if(!Y(s,"html")||!this.isTopContext){if(n===null)return this.unbindTree(s),!1;if(i=this.app.nodes.getID(n),i===void 0)return this.unbindTree(s),!1;if(!this.commitNode(i))return this.unbindTree(s),!1;if(this.app.sanitizer.handleNode(e,i,s),this.app.sanitizer.isHidden(i))return!1}let r=s.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(s)){let c=s;if(i!==void 0){if(this.app.sanitizer.isHidden(e)){const d=c.clientWidth,p=c.clientHeight;c=s.cloneNode(),c.style.width=`${d}px`,c.style.height=`${p}px`}this.app.send(pr(e,i,a,c.tagName,ns(s)))}for(let d=0;d<c.attributes.length;d++){const p=c.attributes[d];this.sendNodeAttribute(e,c,p.nodeName,p.value)}}else is(s)&&(this.app.send(gr(e,i,a)),this.sendNodeData(e,n,s.data));return!0}o===ye.Removed&&i!==void 0&&this.app.send(mr(e,i,a));const u=this.attributesMap.get(e);if(u!==void 0){if(!ke(s))throw"commitNode: node is not an element";for(const c of u)this.sendNodeAttribute(e,s,c,s.getAttribute(c))}if(this.textSet.has(e)){if(!is(s))throw"commitNode: node is not a text";this.sendNodeData(e,n,s.data)}return!0}commitNode(e){const s=this.app.nodes.getNode(e);if(s===void 0)return!1;const n=this.commited[e];return n!==void 0?n:this.commited[e]=this._commitNode(e,s)}commitNodes(e=!1){let s;this.recents.forEach((n,i)=>{this.commitNode(i),n===ye.New&&(s=this.app.nodes.getNode(i))&&this.app.nodes.callNodeCallbacks(s,e)}),this.clear()}observeRoot(e,s,n=e){this.observer.observe(e,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!1,characterDataOldValue:!1}),this.bindTree(n),s(this.app.nodes.getID(e)),this.commitNodes(!0)}disconnect(){this.observer.disconnect(),this.clear()}}class qn extends as{observe(e){const s=e.contentDocument,n=this.app.nodes.getID(e);!s||n===void 0||this.observeRoot(s,i=>{if(i===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(n,i))})}syntheticObserve(e,s){this.observeRoot(s,n=>{if(n===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(e,n))})}}class wo extends as{observe(e){const s=e.shadowRoot,n=this.app.nodes.getID(e);!s||n===void 0||this.observeRoot(s,i=>{if(i===void 0){this.app.debug.error("OpenReplay: Shadow Root was not bound");return}this.app.send(Xt(n,i))})}}class xo{constructor(){this.states=new Map}calcOffset(e){let s=0,n=0;if(e.parent&&([s,n]=this.calcOffset(e.parent)),!e.offset){const{left:o,top:l}=e.iFrame.getBoundingClientRect();e.offset=[o,l]}const[i,r]=e.offset;return[s+i,n+r]}getDocumentOffset(e){const s=this.states.get(e);return s?this.calcOffset(s):[0,0]}observe(e){var l;const s=e.contentDocument;if(!s)return;const n=e.ownerDocument,i=this.states.get(n),r={offset:null,iFrame:e,parent:i||null,clear:()=>{var a;n.removeEventListener("scroll",o),(a=n.defaultView)==null||a.removeEventListener("resize",o)}},o=()=>{r.offset=null};n.addEventListener("scroll",o),(l=n.defaultView)==null||l.addEventListener("resize",o),this.states.set(s,r)}clear(){this.states.forEach(e=>e.clear()),this.states.clear()}}const cs=ve?Element.prototype.attachShadow:()=>new ShadowRoot;class ko extends as{constructor(e,s){super(e,!0),this.iframeOffsets=new xo,this.contextCallbacks=[],this.contextsSet=new Set,this.iframeObservers=[],this.shadowRootObservers=[],this.options=Object.assign({captureIFrames:!0},s),this.app.nodes.attachNodeCallback(n=>{Y(n,"iframe")&&(this.options.captureIFrames&&!De(n,"obscured")||De(n,"capture"))&&this.handleIframe(n)}),this.app.nodes.attachNodeCallback(n=>{ke(n)&&n.shadowRoot!==null&&this.handleShadowRoot(n.shadowRoot)})}attachContextCallback(e){this.contextCallbacks.push(e)}getDocumentOffset(e){return this.iframeOffsets.getDocumentOffset(e)}handleIframe(e){let s=null;const n=this.app.safe(()=>setTimeout(()=>{if(this.app.nodes.getID(e)===void 0||!rr(e))return;const r=e.contentWindow,o=e.contentDocument;if(o&&o!==s){const l=new qn(this.app);this.iframeObservers.push(l),l.observe(e),s=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",n),n()}handleShadowRoot(e){const s=new wo(this.app);this.shadowRootObservers.push(s),s.observe(e.host)}observe(){const e=this;Element.prototype.attachShadow=function(){const s=cs.apply(this,arguments);return e.handleShadowRoot(s),s},this.app.nodes.clear(),this.observeRoot(window.document,()=>{this.app.send(fr()),this.app.nodes.callNodeCallbacks(document,!0)},window.document.documentElement)}crossdomainObserve(e,s){const n=this;Element.prototype.attachShadow=function(){const r=cs.apply(this,arguments);return n.handleShadowRoot(r),r},this.app.nodes.clear(),this.app.nodes.syntheticMode(s);const i=new qn(this.app);this.iframeObservers.push(i),i.syntheticObserve(e,window.document)}disconnect(){this.iframeOffsets.clear(),Element.prototype.attachShadow=cs,this.iframeObservers.forEach(e=>e.disconnect()),this.iframeObservers=[],this.shadowRootObservers.forEach(e=>e.disconnect()),this.shadowRootObservers=[],super.disconnect()}}var kt;(function(t){t[t.Plain=0]="Plain",t[t.Obscured=1]="Obscured",t[t.Hidden=2]="Hidden"})(kt||(kt={}));const To=t=>t.trim().replace(/[^\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/g,"█");class Eo{constructor(e,s){this.app=e,this.obscured=new Set,this.hidden=new Set,this.options=Object.assign({obscureTextEmails:!0,obscureTextNumbers:!1},s)}handleNode(e,s,n){if((this.obscured.has(s)||ke(n)&&(De(n,"masked")||De(n,"obscured")))&&this.obscured.add(e),(this.hidden.has(s)||ke(n)&&(De(n,"htmlmasked")||De(n,"hidden")))&&this.hidden.add(e),this.options.domSanitizer!==void 0&&ke(n)){const i=this.options.domSanitizer(n);i===kt.Obscured&&this.obscured.add(e),i===kt.Hidden&&this.hidden.add(e)}}sanitize(e,s){return this.obscured.has(e)?To(s):(this.options.obscureTextNumbers&&(s=s.replace(/\d/g,"0")),this.options.obscureTextEmails&&(s=s.replace(/^\w+([+.-]\w+)*@\w+([.-]\w+)*\.\w{2,3}$/g,n=>{const[i,r]=n.split("@"),[o,l]=r.split(".");return`${qt(i)}@${qt(o)}.${qt(l)}`})),s)}isObscured(e){return this.obscured.has(e)}isHidden(e){return this.hidden.has(e)}getInnerTextSecure(e){const s=this.app.nodes.getID(e);return s?this.sanitize(s,e.innerText):""}clear(){this.obscured.clear(),this.hidden.clear()}}class Co{constructor(e,s){this.app=e,this.options=s,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(s=>s(e))}assign(e){e.userID!==void 0&&(this.userID=e.userID),e.metadata!==void 0&&Object.entries(e.metadata).forEach(([s,n])=>this.metadata[s]=n),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,s){this.metadata[e]=s,this.handleUpdate({metadata:{[e]:s}})}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 s=decodeURI(e).split("&");let n=e,i="100500";s.length==2&&([i,n]=s),!(!i||!n)&&(this.app.sessionStorage.setItem(this.options.session_token_key,n),this.app.sessionStorage.setItem(this.options.session_pageno_key,i))}getSessionHash(){const e=this.getPageNumber(),s=this.getSessionToken();if(!(e===void 0||s===void 0))return encodeURI(String(e)+"&"+s)}getTabId(){return this.tabId||this.createTabId(),this.tabId}regenerateTabId(){const e=or(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 Io(t,e){let s=0;return()=>{s++>=e&&(s=0,t())}}class _o{constructor(e){this.app=e,this.timer=null,this.callbacks=[]}attach(e,s=0,n=!0,i){i&&(e=e.bind(i)),n&&(e=this.app.safe(e)),this.callbacks.unshift(s?Io(e,s):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 Ze="canceled",Vn="or_uxt_active",ls="or_buffer_1",Oe=t=>({reason:t,success:!1}),Oo=t=>({...t,success:!0});var Q;(function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Active=2]="Active",t[t.ColdStart=3]="ColdStart"})(Q||(Q={}));const Gn="https://api.openreplay.com/ingest";function us(){const t=new Date().getTimezoneOffset()*-1,e=t>=0?"+":"-",s=Math.floor(Math.abs(t)/60),n=Math.abs(t)%60;return`UTC${e}${String(s).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const No=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"};class Ro{constructor(e,s,n,i,r){this.signalError=i,this.insideIframe=r,this.messages=[],this.bufferedMessages1=[],this.bufferedMessages2=[],this.startCallbacks=[],this.stopCallbacks=[],this.commitCallbacks=[],this.activityState=Q.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(u=>{let c=!1;const d=[a.shift()];for(;!c;){const p=a[0];!p||p[0]===0?c=!0:d.push(a.shift())}this.postToWorker(d),u(null)}),this.onUxtCb=[],this.contextId=Math.random().toString(36).slice(2),this.projectKey=e,Object.keys(n).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.'),n={...n,canvas:{__save_canvas_locally:n.__save_canvas_locally,fixedCanvasScaling:n.fixedCanvasScaling,disableCanvas:n.disableCanvas}}),this.networkOptions=n.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:Gn,resourceBaseHref:null,__is_snippet:!1,__debug_report_edp:null,__debug__:Qe.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=kn(o,n),!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 Eo(this,n),this.nodes=new So(this.options.node_id),this.observer=new ko(this,n),this.ticker=new _o(this),this.ticker.attach(()=>this.commit()),this.debug=new bo(this.options.__debug__),this.session=new Co(this,this.options),this.attributeSender=new Zi(this,!!this.options.disableStringDict),this.featureFlags=new sr(this),this.tagWatcher=new qr(this.sessionStorage,this.debug.error,a=>{this.send(zr(a))}),this.session.attachUpdateCallback(({userID:a,metadata:u})=>{a!=null&&this.send(Ir(a)),u!=null&&Object.entries(u).forEach(([c,d])=>this.send(En(c,d)))}),s!=null&&this.session.applySessionHash(s),this.initWorker();const l=this.session.getTabId();if(this.insideIframe){const a=c=>{const{data:d}=c;d.line===le.iframeId&&(this.rootId=d.id,this.session.setSessionToken(d.token),this.frameOderNumber=d.frameOrderNumber,this.debug.log("starting iframe tracking",d),this.allowAppStart())};window.addEventListener("message",a),this.attachStopCallback(()=>{window.removeEventListener("message",a)});const u=this.initialHostName;window.parent.postMessage({line:le.iframeSignal,source:l,context:this.contextId,domain:u},"*")}else{let a=0;const u=c=>{const{data:d}=c;if(d.line===le.iframeSignal){const p=d.domain,y=Array.from(document.querySelectorAll("iframe"));this.pageFrames=y,(async()=>{let b=0;for(;b<10;){const T=this.checkNodeId(y,p);if(T){this.waitStarted().then(()=>{var A;a++;const D=this.session.getSessionToken(),B={line:le.iframeId,context:this.contextId,domain:p,id:T,token:D,frameOrderNumber:a};this.debug.log("iframe_data",B),(A=c.source)==null||A.postMessage(B,"*")}).catch(console.error),b=10;break}b++,await No(100)}})()}if(d.line===le.iframeBatch){const y=d.messages.map(w=>{if(w[0]===20){let b=w;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[D,B,A]=w,{left:k,top:O}=T.getBoundingClientRect();b=[D,B+k,A+O]}}),b}if(w[0]===68){let b=w;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[D,B,A,k,O,N,F]=w,{left:C,top:E,width:P,height:V}=T.getBoundingClientRect(),j=document.documentElement.scrollWidth,W=document.documentElement.scrollHeight,I=N/100*P+C,M=F/100*V+E,q=I/j,G=M/W;b=[D,B,A,k,O,Math.round(q*1e3)/10,Math.round(G*1e3)/10]}}),b}return w});this.messages.push(...y)}};window.addEventListener("message",u),this.attachStopCallback(()=>{window.removeEventListener("message",u)})}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 u=a.data.token;this.session.setSessionToken(u),this.allowAppStart()}if(a.data.line===le.reg){const u=a.data.token;this.session.regenerateTabId(),this.session.setSessionToken(u),this.allowAppStart()}if(a.data.line===le.ask){const u=this.session.getSessionToken();u&&this.bc&&this.bc.postMessage({line:a.data.source===l?le.reg:le.resp,token:u,source:l,context:this.contextId})}}})}allowAppStart(){this.canStart=!0,this.startTimeout&&(clearTimeout(this.startTimeout),this.startTimeout=null)}checkNodeId(e,s){for(const n of e)if(n.dataset.domain===s)return n[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=s=>{this._debug("webworker_error",s)},this.worker.onmessage=({data:s})=>{this.handleWorkerMsg(s)};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 s;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 n=e.batch;n.byteLength>this.compressionThreshold?Ji(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:n})):(a=this.worker)==null||a.postMessage({type:"compressed",batch:o})}):(s=this.worker)==null||s.postMessage({type:"uncompressed",batch:n})}else e.type==="queue_empty"&&this.onSessionSent()}_debug(e,s){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:`${s}`})}),this.debug.error("OpenReplay error: ",e,s)}send(e,s=!1){var n;this.activityState!==Q.NotActive&&(this.activityState===Q.ColdStart?(this.bufferedMessages1.push(e),this.singleBuffer||this.bufferedMessages2.push(e),(n=this.conditionsManager)==null||n.processMessage(e)):this.messages.push(e),this.activityState===Q.Active&&s&&this.commit())}_nCommit(){if(this.socketMode){this.messages.unshift(Fe(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{ur(()=>{var e;this.messages.unshift(Fe(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),(e=this.worker)==null||e.postMessage(this.messages),this.commitCallbacks.forEach(s=>s(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(Fe(this.session.getTabId())),this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(Fe(this.session.getTabId())),this.coldStartCommitN=0)}commit(){this.activityState===Q.ColdStart?this._cStartCommit():this._nCommit()}postToWorker(e){var s;(s=this.worker)==null||s.postMessage(e),this.commitCallbacks.forEach(n=>n(e)),e.length=0}timestamp(){return pe()+this.delay}safe(e){const s=this;return function(...n){try{e.apply(this,n)}catch(i){s._debug("safe_fn_call",i)}}}attachCommitCallback(e){this.commitCallbacks.push(e)}attachStartCallback(e,s=!1){s&&(e=this.safe(e)),this.startCallbacks.push(e)}attachStopCallback(e,s=!1){s&&(e=this.safe(e)),this.stopCallbacks.push(e)}attachEventListener(e,s,n,i=!0,r=!0){i&&(n=this.safe(n));const o=()=>e?wn(e,s,n,r):null,l=()=>e?xn(e,s,n,r):null;this.attachStartCallback(o,i),this.attachStopCallback(l,i)}checkRequiredVersion(e){const s=e.split(/[.-]/),n=this.version.split(/[.-]/);for(let i=0;i<3;i++){if(isNaN(Number(n[i]))||isNaN(Number(s[i])))return!1;if(Number(n[i])>Number(s[i]))return!0;if(Number(n[i])<Number(s[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:s,sessionID:n,timestamp:i}=this.session.getInfo();if(!s||!n){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$/,`${s}/session/${n}`);if(e!=null&&e.withCurrentTime){const u=pe()-i;return`${a}?jumpto=${u}`}return a}getHost(){return new URL(this.options.ingestPoint).host}getProjectKey(){return this.projectKey}getBaseHref(){var e,s;return typeof this.options.resourceBaseHref=="string"?this.options.resourceBaseHref:(this.options.resourceBaseHref,document.baseURI?document.baseURI:((s=(e=document.head)==null?void 0:e.getElementsByTagName("base")[0])==null?void 0:s.getAttribute("href"))||location.origin+location.pathname)}resolveResourceURL(e){const s=new URL(this.getBaseHref());return s.pathname+="/"+new URL(e).pathname,s.pathname.replace(/\/+/g,"/"),s.toString()}isServiceURL(e){return e.startsWith(this.options.ingestPoint)}active(){return this.activityState===Q.Active}resetNextPageSession(e){e?this.sessionStorage.setItem(this.options.session_reset_key,"t"):this.sessionStorage.removeItem(this.options.session_reset_key)}checkSessionToken(e){const s=this.sessionStorage.getItem(this.options.session_reset_key)!==null,n=e||s,i=this.session.getSessionToken();return n||!i}async coldStart(e={},s){this.singleBuffer=!1;const n=1e3,i=this.checkSessionToken(e.forceNew);s&&await this.setupConditionalStart(e);const r=()=>{this.orderNumber+=1,$t(),this.coldStartTs=pe(),this.orderNumber%2===0?(this.bufferedMessages1.length=0,this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(Fe(this.session.getTabId()))):(this.bufferedMessages2.length=0,this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(Fe(this.session.getTabId()))),this.stop(!1),this.activityState=Q.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(yt(this.session.getTabId()))),this.observer.observe(),this.ticker.start()};this.coldInterval=setInterval(()=>{r()},30*n),r()}async setupConditionalStart(e){var p,y;this.conditionsManager=new er(this,e);const s=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:es,timezone:us(),width:window.screen.width,height:window.screen.height})}),{token:n,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:u,projectID:c}=await s.json();this.session.assign({projectID:c}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:u});const d={sessionToken:n,userUUID:"",sessionID:""};this.startCallbacks.forEach(w=>w(d)),await((p=this.conditionsManager)==null?void 0:p.fetchConditions(c,n)),await this.featureFlags.reloadFlags(n),await this.tagWatcher.fetchTags(this.options.ingestPoint,n),(y=this.conditionsManager)==null||y.processFlags(this.featureFlags.flags)}offlineRecording(e={},s){this.onSessionSent=s,this.singleBuffer=!0;const n=this.checkSessionToken(e.forceNew);$t(),this.coldStartTs=pe();const i=this.localStorage.getItem(ls);if(i){const o=JSON.parse(i);this.bufferedMessages1=Array.isArray(o)?o:this.bufferedMessages1,this.localStorage.removeItem(ls)}this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(Fe(this.session.getTabId())),this.activityState=Q.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)),n||this.send(yt(this.session.getTabId())),this.observer.observe(),this.ticker.start(),{saveBuffer:this.saveBuffer,getBuffer:this.getBuffer,setBuffer:this.setBuffer}}saveBuffer(){this.localStorage.setItem(ls,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 s=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:es,timezone:us()})}),{token:n,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:u,beaconSizeLimit:c,projectID:d}=await s.json();for((y=this.worker)==null||y.postMessage({type:"auth",token:n,beaconSizeLimit:c}),this.session.assign({projectID:d}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:u});this.bufferedMessages1.length>0;)await this.flushBuffer(this.bufferedMessages1);this.postToWorker([["q_end"]]),this.clearBuffers()}async _start(e={},s=!1,n){const i=this.activityState===Q.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(Oe(a))}if(this.activityState===Q.Active||this.activityState===Q.Starting)return Promise.resolve(Oe("OpenReplay: trying to call `start()` on the instance that has been started already."));this.activityState=Q.Starting,i||$t(),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:es,timezone:us(),condition:n,assistOnly:e.assistOnly??this.socketMode,width:window.screen.width,height:window.screen.height})});if(a.status!==200){const I=await a.text(),M=I===Ze?Ze:`Server error: ${a.status}. ${I}`;return Oe(M)}if(!this.worker){const I="no worker found after start request (this should not happen in real world)";return this.signalError(I,[]),Oe(I)}const{token:u,userUUID:c,projectID:d,beaconSizeLimit:p,compressionThreshold:y,delay:w,sessionID:b,startTimestamp:T,userBrowser:D,userCity:B,userCountry:A,userDevice:k,userOS:O,userState:N,canvasEnabled:F,canvasQuality:C,canvasFPS:E,assistOnly:P}=await a.json();if(typeof u!="string"||typeof c!="string"||typeof T!="number"&&typeof T<"u"||typeof b!="string"||typeof w!="number"||typeof p!="number"&&typeof p<"u"){const I=`Incorrect server response: ${JSON.stringify(a)}`;return this.signalError(I,[]),Oe(I)}this.delay=w,this.session.setSessionToken(u),this.session.setUserInfo({userBrowser:D,userCity:B,userCountry:A,userDevice:k,userOS:O,userState:N}),this.session.assign({sessionID:b,timestamp:T||r,projectID:d}),P?(this.socketMode=!0,this.worker.postMessage("stop")):this.worker.postMessage({type:"auth",token:u,beaconSizeLimit:p}),!l&&u===o&&(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(yt(this.session.getTabId()))),Object.entries(this.session.getInfo().metadata).forEach(([I,M])=>this.send(En(I,M))),this.localStorage.setItem(this.options.local_uuid_key,c),this.compressionThreshold=y;const V={sessionToken:u,userUUID:c,sessionID:b};if(this.startCallbacks.forEach(I=>I(V)),this.featureFlags.reloadFlags(),await this.tagWatcher.fetchTags(this.options.ingestPoint,u),this.activityState=Q.Active,F&&!this.options.canvas.disableCanvas&&(this.canvasRecorder=this.canvasRecorder??new mo(this,{fps:E,quality:C,isDebug:this.options.canvas.__save_canvas_locally,fixedScaling:this.options.canvas.fixedCanvasScaling,useAnimationFrame:this.options.canvas.useAnimationFrame}),this.canvasRecorder.startTracking()),i){const I=this.bufferedMessages1.length>this.bufferedMessages2.length?this.bufferedMessages1:this.bufferedMessages2;for(;I.length>0;)await this.flushBuffer(I);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 po(this,Vn);let j;const W=this.localStorage.getItem(Vn);if(W&&(j=parseInt(W,10)),location!=null&&location.search){const I=new URLSearchParams(location.search);if(I.has("oruxt")){const M=I.get("oruxt");j=M?parseInt(M,10):void 0}}return j&&(this.uxtManager.isActive?this.onUxtCb.forEach(I=>I(j)):this.uxtManager.getTest(j,u,!!W).then(I=>{I&&this.onUxtCb.forEach(M=>M(I))})),Oo(V)}catch(a){if(this.stop(),this.session.reset(),a===Ze)return this.signalError(Ze,[]),Oe(Ze);this._debug("session_start",a);const u=a instanceof Error?a.message:a.toString();return this.signalError(u,[]),Oe(u)}}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 s=()=>{this.canStart?e(!0):setTimeout(s,25)};s()})}async waitStarted(){return new Promise(e=>{const s=()=>{this.activityState===Q.Active?e(!0):setTimeout(s,25)};s()})}async start(...e){return this.activityState===Q.Active||this.activityState===Q.Starting?Promise.resolve(Oe("OpenReplay: trying to call `start()` on the instance that has been started already.")):document.hidden?new Promise(s=>{const n=async()=>{document.hidden||(await this.waitStart(),document.removeEventListener("visibilitychange",n),s(this._start(...e)))};document.addEventListener("visibilitychange",n)}):(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 s=e;return(n,i,r="down")=>{typeof n!="string"||typeof i!="string"||i.length>5*1024*1024||n.length>255||this.send(Pr("websocket",s,i,this.timestamp(),r,n))}}stop(e=!0){var s;if(this.activityState!==Q.NotActive)try{this.attributeSender.clear(),this.sanitizer.clear(),this.observer.disconnect(),this.nodes.clear(),this.ticker.stop(),this.stopCallbacks.forEach(n=>n()),this.debug.log("OpenReplay tracking stopped."),this.tagWatcher.clear(),this.worker&&e&&this.worker.postMessage("stop"),(s=this.canvasRecorder)==null||s.clear()}finally{this.activityState=Q.NotActive}}}function Do(t){const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e===void 0)return;const s=()=>t.send(Nr(Math.round(e.downlink*1e3),e.type||"unknown"));s(),e.addEventListener("change",s)}const Kn=ve&&"InstallTrigger"in window?t=>t.message+`
637
- `+t.stack:t=>t.stack||t.message;function hs(t){return t===void 0?"undefined":t===null?"null":t instanceof Error?Kn(t):Array.isArray(t)?`Array(${t.length})`:String(t)}function Ao(t){return typeof t!="number"?"NaN":t.toString()}function Fo(t){return typeof t!="number"?"NaN":Math.floor(t).toString()}function Xn(t){if(t===void 0)return"undefined";if(t===null)return"null";if(t instanceof Error)return Kn(t);if(Array.isArray(t)){const e=t.length,s=t.slice(0,10).map(hs).join(", ");return`Array(${e})[${s}]`}if(typeof t=="object"){const e=[];let s=0;for(const n in t){if(++s===10)break;const i=t[n];e.push(n+": "+hs(i))}return"{"+e.join(", ")+"}"}return t.toString()}function Mo(t){return typeof t[0]=="string"&&t.unshift(t.shift().replace(/%(o|s|f|d|i)/g,(e,s)=>{const n=t.shift();if(n===void 0)return e;switch(s){case"o":return Xn(n);case"s":return hs(n);case"f":return Ao(n);case"d":case"i":return Fo(n);default:return e}})),t.map(Xn).join(" ")}const Jn=["log","info","warn","error","debug","assert"];function Lo(t,e){const s=Object.assign({consoleMethods:Jn,consoleThrottling:30},e);if(!Array.isArray(s.consoleMethods)||s.consoleMethods.length===0)return;const n=t.safe((a,u)=>t.send(kr(a,Mo(u))));let i=0;const r=()=>{i=0};t.attachStartCallback(r),t.ticker.attach(r,33,!1);const o=(a,u)=>{const c={apply:function(d,p,y){Reflect.apply(d,u,y),i=i+1,!(i>s.consoleThrottling)&&n(d.name,y)}};s.consoleMethods.forEach(d=>{if(Jn.indexOf(d)===-1){t.debug.error(`OpenReplay: unsupported console method "${d}"`);return}const p=u.console[d];a[d]=new Proxy(p,c)})},l=t.safe(a=>o(a.console,a));l(window),t.observer.attachContextCallback(l)}var Yn={exports:{}},ds={exports:{}},Qn;function Po(){return Qn||(Qn=1,function(t,e){(function(s,n){t.exports=n()})(Pe,function(){function s(b){return!isNaN(parseFloat(b))&&isFinite(b)}function n(b){return b.charAt(0).toUpperCase()+b.substring(1)}function i(b){return function(){return this[b]}}var r=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],l=["fileName","functionName","source"],a=["args"],u=["evalOrigin"],c=r.concat(o,l,a,u);function d(b){if(b)for(var T=0;T<c.length;T++)b[c[T]]!==void 0&&this["set"+n(c[T])](b[c[T]])}d.prototype={getArgs:function(){return this.args},setArgs:function(b){if(Object.prototype.toString.call(b)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=b},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(b){if(b instanceof d)this.evalOrigin=b;else if(b instanceof Object)this.evalOrigin=new d(b);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var b=this.getFileName()||"",T=this.getLineNumber()||"",D=this.getColumnNumber()||"",B=this.getFunctionName()||"";return this.getIsEval()?b?"[eval] ("+b+":"+T+":"+D+")":"[eval]:"+T+":"+D:B?B+" ("+b+":"+T+":"+D+")":b+":"+T+":"+D}},d.fromString=function(T){var D=T.indexOf("("),B=T.lastIndexOf(")"),A=T.substring(0,D),k=T.substring(D+1,B).split(","),O=T.substring(B+1);if(O.indexOf("@")===0)var N=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(O,""),F=N[1],C=N[2],E=N[3];return new d({functionName:A,args:k||void 0,fileName:F,lineNumber:C||void 0,columnNumber:E||void 0})};for(var p=0;p<r.length;p++)d.prototype["get"+n(r[p])]=i(r[p]),d.prototype["set"+n(r[p])]=function(b){return function(T){this[b]=!!T}}(r[p]);for(var y=0;y<o.length;y++)d.prototype["get"+n(o[y])]=i(o[y]),d.prototype["set"+n(o[y])]=function(b){return function(T){if(!s(T))throw new TypeError(b+" must be a Number");this[b]=Number(T)}}(o[y]);for(var w=0;w<l.length;w++)d.prototype["get"+n(l[w])]=i(l[w]),d.prototype["set"+n(l[w])]=function(b){return function(T){this[b]=String(T)}}(l[w]);return d})}(ds)),ds.exports}(function(t,e){(function(s,n){t.exports=n(Po())})(Pe,function(n){var i=/(^|@)\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 u=/(.+?)(?::(\d+))?(?::(\d+))?$/,c=u.exec(a.replace(/[()]/g,""));return[c[1],c[2]||void 0,c[3]||void 0]},parseV8OrIE:function(a){var u=a.stack.split(`
638
- `).filter(function(c){return!!c.match(r)},this);return u.map(function(c){c.indexOf("(eval ")>-1&&(c=c.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var d=c.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=d.match(/ (\(.+\)$)/);d=p?d.replace(p[0],""):d;var y=this.extractLocation(p?p[1]:d),w=p&&d||void 0,b=["eval","<anonymous>"].indexOf(y[0])>-1?void 0:y[0];return new n({functionName:w,fileName:b,lineNumber:y[1],columnNumber:y[2],source:c})},this)},parseFFOrSafari:function(a){var u=a.stack.split(`
639
- `).filter(function(c){return!c.match(o)},this);return u.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 n({functionName:c});var d=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=c.match(d),y=p&&p[1]?p[1]:void 0,w=this.extractLocation(c.replace(d,""));return new n({functionName:y,fileName:w[0],lineNumber:w[1],columnNumber:w[2],source:c})},this)},parseOpera:function(a){return!a.stacktrace||a.message.indexOf(`
648
+ We appreciate your time and valuable input.`),r=U("div","end_button_or",Ln,"Submitting Feedback"),o=mo();r.appendChild(o),(h=this.test)!=null&&h.reqMic||(c=this.test)!=null&&c.reqCamera?this.userRecorder.sendToAPI().then(()=>{r.removeChild(o),r.textContent="End Session",e=!1}).catch(d=>{console.error(d),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))},s.append(n,i,r),this.endSection=s,this.container.append(s)}}function Wn(t){return!!t&&t.nodeType!=null}function ns(t){return t.namespaceURI==="http://www.w3.org/2000/svg"}function ke(t){return t.nodeType===Node.ELEMENT_NODE}function So(t){return t.nodeType===Node.COMMENT_NODE}function is(t){return t.nodeType===Node.TEXT_NODE}function wt(t){return t.nodeType===Node.DOCUMENT_NODE}function xt(t){return t.nodeType===Node.DOCUMENT_NODE||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Y(t,e){return t.localName===e}class wo{constructor(e,s){this.app=e,this.options=s,this.snapshots={},this.intervals=[],this.restartTracking=()=>{this.clear(),this.app.nodes.scanTree(this.captureCanvas)},this.captureCanvas=n=>{const i=this.app.nodes.getID(n);if(!i||!Y(n,"canvas")||this.app.sanitizer.isObscured(i)||this.app.sanitizer.isHidden(i)||!Y(n,"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(n)},this.recordCanvas=(n,i)=>{const r=this.app.timestamp();this.snapshots[i]={images:[],createdAt:r,paused:!1,dummy:document.createElement("canvas")};const o=Vr(i.toString(),r);this.app.send(o);const l=h=>{xo(h,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 h=this.app.nodes.getID(n),c=h?this.app.nodes.getNode(h):void 0;!c||!Y(c,"canvas")||c!==n?(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=s.fileExt??"webp",this.interval=1e3/s.fps}startTracking(){setTimeout(()=>{this.app.nodes.scanTree(this.captureCanvas),this.app.nodes.attachNodeCallback(e=>{this.captureCanvas(e)})},500)}sendSnaps(e,s,n){if(Object.keys(this.snapshots).length===0)return;const i=new FormData;e.forEach(r=>{const o=r.data;o&&(i.append("snapshot",o,`${n}_${s}_${r.id}.${this.fileExt}`),this.options.isDebug&&ko(o,`${n}_${s}_${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 $n={low:.35,medium:.55,high:.8};function xo(t,e="medium",s,n=!1,i,r){const o=`image/${i}`;if(n){const l=window.devicePixelRatio||1;s.width=t.width/l,s.height=t.height/l;const a=s.getContext("2d");if(!a)return"";a.clearRect(0,0,s.width,s.height),a.drawImage(t,0,0,s.width,s.height),s.toBlob(r,o,$n[e])}else t.toBlob(r,o,$n[e])}function ko(t,e){const s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=e,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n)}const Qe={Verbose:5,Log:4,Warnings:3,Errors:2,Silent:0};class To{constructor(e=Qe.Silent){this.shouldLog=s=>this.level>=s,this.log=(...s)=>{this.shouldLog(Qe.Log)&&console.log(...s)},this.warn=(...s)=>{this.shouldLog(Qe.Warnings)&&console.warn(...s)},this.error=(...s)=>{this.shouldLog(Qe.Errors)&&console.error(...s)},this.level=e}}class Eo{constructor(e){this.node_id=e,this.nodes=[],this.totalNodeAmount=0,this.nodeCallbacks=[],this.elementListeners=new Map,this.nextNodeId=0,this.scanTree=s=>{this.nodes.forEach(n=>s(n))}}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,s,n,i=!0){const r=this.getID(e);if(r===void 0)return;wn(e,s,n,i);let o=this.elementListeners.get(r);o===void 0&&(o=[],this.elementListeners.set(r,o)),o.push([s,n,i])}registerNode(e){let s=e[this.node_id];const n=s===void 0;return n&&(s=this.nextNodeId,this.totalNodeAmount++,this.nextNodeId++,this.nodes[s]=e,e[this.node_id]=s),[s,n]}unregisterNode(e){const s=e[this.node_id];if(s!==void 0){e[this.node_id]=void 0,delete e[this.node_id],delete this.nodes[s];const n=this.elementListeners.get(s);n!==void 0&&(this.elementListeners.delete(s),n.forEach(i=>xn(e,i[0],i[1],i[2]))),this.totalNodeAmount--}return s}cleanTree(){for(let e=0;e<this.nodes.length;e++){const s=this.nodes[e];s&&!document.contains(s)&&this.unregisterNode(s)}}callNodeCallbacks(e,s){this.nodeCallbacks.forEach(n=>n(e,s))}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 s=this.nodes[e];s&&this.unregisterNode(s)}this.nextNodeId=0,this.nodes.length=0}}function rs(t){if(So(t))return!0;if(is(t))return!1;if(!ke(t))return!0;const e=t.tagName.toUpperCase();if(e==="LINK"){const s=t.getAttribute("rel"),n=t.getAttribute("as");return!(s!=null&&s.includes("stylesheet")||n==="style"||n==="font")}return e==="SCRIPT"||e==="NOSCRIPT"||e==="META"||e==="TITLE"||e==="BASE"}function os(t){return xt(t)?!0:!rs(t)}var ye;(function(t){t[t.New=0]="New",t[t.Removed=1]="Removed",t[t.Changed=2]="Changed"})(ye||(ye={}));class as{constructor(e,s=!1){this.app=e,this.isTopContext=s,this.commited=[],this.recents=new Map,this.indexes=[],this.attributesMap=new Map,this.textSet=new Set,this.observer=Sn(this.app.safe(n=>{for(const i of n){const r=i.target,o=i.type;if(!os(r))continue;if(o==="childList"){for(let a=0;a<i.removedNodes.length;a++)os(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 h=this.attributesMap.get(l);h===void 0&&this.attributesMap.set(l,h=new Set),h.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,s,n,i){if(ns(s)){n.substr(0,6)==="xlink:"&&(n=n.substr(6)),i===null?this.app.send(Tn(e,n)):n==="href"?(i.length>1e5&&(i=""),this.app.send(Kt(e,n,i,this.app.getBaseHref()))):this.app.attributeSender.sendSetAttribute(e,n,i);return}if(!(n==="src"||n==="srcset"||n==="integrity"||n==="crossorigin"||n==="autocomplete"||n.substr(0,2)==="on")&&!(n==="value"&&Y(s,"input")&&s.type!=="button"&&s.type!=="reset"&&s.type!=="submit")){if(i===null){this.app.send(Tn(e,n));return}if(n==="style"||n==="href"&&Y(s,"link")){this.app.send(Kt(e,n,i,this.app.getBaseHref()));return}(n==="href"||i.length>1e5)&&(i=""),this.app.attributeSender.sendSetAttribute(e,n,i)}}sendNodeData(e,s,n){if(Y(s,"style")){this.app.send(Pr(e,n,this.app.getBaseHref()));return}n=this.app.sanitizer.sanitize(e,n),this.app.send(kr(e,n))}bindNode(e){const[s,n]=this.app.nodes.registerNode(e);n?this.recents.set(s,ye.New):this.recents.get(s)!==ye.New&&this.recents.set(s,ye.Removed)}bindTree(e){if(!os(e))return;this.bindNode(e);const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:n=>(this.app.nodes.getID(n)!==void 0&&this.app.debug.error("! Node is already bound",n),rs(n)||this.app.nodes.getID(n)!==void 0?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT)},!1);for(;s.nextNode();)this.bindNode(s.currentNode)}unbindTree(e){const s=this.app.nodes.unregisterNode(e);if(s!==void 0&&this.recents.get(s)===ye.Removed){this.app.send(xr(s));const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT+NodeFilter.SHOW_TEXT,{acceptNode:l=>rs(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(;n.nextNode();)i+=1,this.app.nodes.unregisterNode(n.currentNode);const o=Math.floor(i/r*100);o>30&&this.app.send(qr(o))}}_commitNode(e,s){if(xt(s))return!0;const n=s.parentNode;let i;if(!Y(s,"html")||!this.isTopContext){if(n===null)return this.unbindTree(s),!1;if(i=this.app.nodes.getID(n),i===void 0)return this.unbindTree(s),!1;if(!this.commitNode(i))return this.unbindTree(s),!1;if(this.app.sanitizer.handleNode(e,i,s),this.app.sanitizer.isHidden(i))return!1}let r=s.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(s)){let c=s;if(i!==void 0){if(this.app.sanitizer.isHidden(e)){const d=c.clientWidth,p=c.clientHeight;c=s.cloneNode(),c.style.width=`${d}px`,c.style.height=`${p}px`}this.app.send(br(e,i,a,c.tagName,ns(s)))}for(let d=0;d<c.attributes.length;d++){const p=c.attributes[d];this.sendNodeAttribute(e,c,p.nodeName,p.value)}}else is(s)&&(this.app.send(Sr(e,i,a)),this.sendNodeData(e,n,s.data));return!0}o===ye.Removed&&i!==void 0&&this.app.send(wr(e,i,a));const h=this.attributesMap.get(e);if(h!==void 0){if(!ke(s))throw"commitNode: node is not an element";for(const c of h)this.sendNodeAttribute(e,s,c,s.getAttribute(c))}if(this.textSet.has(e)){if(!is(s))throw"commitNode: node is not a text";this.sendNodeData(e,n,s.data)}return!0}commitNode(e){const s=this.app.nodes.getNode(e);if(s===void 0)return!1;const n=this.commited[e];return n!==void 0?n:this.commited[e]=this._commitNode(e,s)}commitNodes(e=!1){let s;this.recents.forEach((n,i)=>{this.commitNode(i),n===ye.New&&(s=this.app.nodes.getNode(i))&&this.app.nodes.callNodeCallbacks(s,e)}),this.clear()}observeRoot(e,s,n=e){this.observer.observe(e,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!1,characterDataOldValue:!1}),this.bindTree(n),s(this.app.nodes.getID(e)),this.commitNodes(!0)}disconnect(){this.observer.disconnect(),this.clear()}}class qn extends as{observe(e){const s=e.contentDocument,n=this.app.nodes.getID(e);!s||n===void 0||this.observeRoot(s,i=>{if(i===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(n,i))})}syntheticObserve(e,s){this.observeRoot(s,n=>{if(n===void 0){this.app.debug.log("OpenReplay: Iframe document not bound");return}this.app.send(Xt(e,n))})}}class Co extends as{observe(e){const s=e.shadowRoot,n=this.app.nodes.getID(e);!s||n===void 0||this.observeRoot(s,i=>{if(i===void 0){this.app.debug.error("OpenReplay: Shadow Root was not bound");return}this.app.send(Xt(n,i))})}}class Io{constructor(){this.states=new Map}calcOffset(e){let s=0,n=0;if(e.parent&&([s,n]=this.calcOffset(e.parent)),!e.offset){const{left:o,top:l}=e.iFrame.getBoundingClientRect();e.offset=[o,l]}const[i,r]=e.offset;return[s+i,n+r]}getDocumentOffset(e){const s=this.states.get(e);return s?this.calcOffset(s):[0,0]}observe(e){var l;const s=e.contentDocument;if(!s)return;const n=e.ownerDocument,i=this.states.get(n),r={offset:null,iFrame:e,parent:i||null,clear:()=>{var a;n.removeEventListener("scroll",o),(a=n.defaultView)==null||a.removeEventListener("resize",o)}},o=()=>{r.offset=null};n.addEventListener("scroll",o),(l=n.defaultView)==null||l.addEventListener("resize",o),this.states.set(s,r)}clear(){this.states.forEach(e=>e.clear()),this.states.clear()}}const cs=ve?Element.prototype.attachShadow:()=>new ShadowRoot;class _o extends as{constructor(e,s){super(e,!0),this.iframeOffsets=new Io,this.contextCallbacks=[],this.contextsSet=new Set,this.iframeObservers=[],this.shadowRootObservers=[],this.options=Object.assign({captureIFrames:!0},s),this.app.nodes.attachNodeCallback(n=>{Y(n,"iframe")&&(this.options.captureIFrames&&!De(n,"obscured")||De(n,"capture"))&&this.handleIframe(n)}),this.app.nodes.attachNodeCallback(n=>{ke(n)&&n.shadowRoot!==null&&this.handleShadowRoot(n.shadowRoot)})}attachContextCallback(e){this.contextCallbacks.push(e)}getDocumentOffset(e){return this.iframeOffsets.getDocumentOffset(e)}handleIframe(e){let s=null;const n=this.app.safe(()=>setTimeout(()=>{if(this.app.nodes.getID(e)===void 0||!hr(e))return;const r=e.contentWindow,o=e.contentDocument;if(o&&o!==s){const l=new qn(this.app);this.iframeObservers.push(l),l.observe(e),s=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",n),n()}handleShadowRoot(e){const s=new Co(this.app);this.shadowRootObservers.push(s),s.observe(e.host)}observe(){const e=this;Element.prototype.attachShadow=function(){const s=cs.apply(this,arguments);return e.handleShadowRoot(s),s},this.app.nodes.clear(),this.observeRoot(window.document,()=>{this.app.send(yr()),this.app.nodes.callNodeCallbacks(document,!0)},window.document.documentElement)}crossdomainObserve(e,s){const n=this;Element.prototype.attachShadow=function(){const r=cs.apply(this,arguments);return n.handleShadowRoot(r),r},this.app.nodes.clear(),this.app.nodes.syntheticMode(s);const i=new qn(this.app);this.iframeObservers.push(i),i.syntheticObserve(e,window.document)}disconnect(){this.iframeOffsets.clear(),Element.prototype.attachShadow=cs,this.iframeObservers.forEach(e=>e.disconnect()),this.iframeObservers=[],this.shadowRootObservers.forEach(e=>e.disconnect()),this.shadowRootObservers=[],super.disconnect()}}var kt;(function(t){t[t.Plain=0]="Plain",t[t.Obscured=1]="Obscured",t[t.Hidden=2]="Hidden"})(kt||(kt={}));const Oo=t=>t.trim().replace(/[^\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/g,"█");class No{constructor(e,s){this.app=e,this.obscured=new Set,this.hidden=new Set,this.options=Object.assign({obscureTextEmails:!0,obscureTextNumbers:!1},s)}handleNode(e,s,n){if((this.obscured.has(s)||ke(n)&&(De(n,"masked")||De(n,"obscured")))&&this.obscured.add(e),(this.hidden.has(s)||ke(n)&&(De(n,"htmlmasked")||De(n,"hidden")))&&this.hidden.add(e),this.options.domSanitizer!==void 0&&ke(n)){const i=this.options.domSanitizer(n);i===kt.Obscured&&this.obscured.add(e),i===kt.Hidden&&this.hidden.add(e)}}sanitize(e,s){return this.obscured.has(e)?Oo(s):(this.options.obscureTextNumbers&&(s=s.replace(/\d/g,"0")),this.options.obscureTextEmails&&(s=s.replace(/^\w+([+.-]\w+)*@\w+([.-]\w+)*\.\w{2,3}$/g,n=>{const[i,r]=n.split("@"),[o,l]=r.split(".");return`${qt(i)}@${qt(o)}.${qt(l)}`})),s)}isObscured(e){return this.obscured.has(e)}isHidden(e){return this.hidden.has(e)}getInnerTextSecure(e){const s=this.app.nodes.getID(e);return s?this.sanitize(s,e.innerText):""}clear(){this.obscured.clear(),this.hidden.clear()}}class Ro{constructor(e,s){this.app=e,this.options=s,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(s=>s(e))}assign(e){e.userID!==void 0&&(this.userID=e.userID),e.metadata!==void 0&&Object.entries(e.metadata).forEach(([s,n])=>this.metadata[s]=n),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,s){this.metadata[e]=s,this.handleUpdate({metadata:{[e]:s}})}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 s=decodeURI(e).split("&");let n=e,i="100500";s.length==2&&([i,n]=s),!(!i||!n)&&(this.app.sessionStorage.setItem(this.options.session_token_key,n),this.app.sessionStorage.setItem(this.options.session_pageno_key,i))}getSessionHash(){const e=this.getPageNumber(),s=this.getSessionToken();if(!(e===void 0||s===void 0))return encodeURI(String(e)+"&"+s)}getTabId(){return this.tabId||this.createTabId(),this.tabId}regenerateTabId(){const e=ur(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 Do(t,e){let s=0;return()=>{s++>=e&&(s=0,t())}}class Ao{constructor(e){this.app=e,this.timer=null,this.callbacks=[]}attach(e,s=0,n=!0,i){i&&(e=e.bind(i)),n&&(e=this.app.safe(e)),this.callbacks.unshift(s?Do(e,s):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 Ze="canceled",Vn="or_uxt_active",ls="or_buffer_1",Oe=t=>({reason:t,success:!1}),Fo=t=>({...t,success:!0});var Q;(function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Active=2]="Active",t[t.ColdStart=3]="ColdStart"})(Q||(Q={}));const Gn="https://api.openreplay.com/ingest";function hs(){const t=new Date().getTimezoneOffset()*-1,e=t>=0?"+":"-",s=Math.floor(Math.abs(t)/60),n=Math.abs(t)%60;return`UTC${e}${String(s).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const Mo=t=>new Promise(e=>setTimeout(e,t)),ce={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"};class Lo{constructor(e,s,n,i,r){this.signalError=i,this.insideIframe=r,this.messages=[],this.bufferedMessages1=[],this.bufferedMessages2=[],this.startCallbacks=[],this.stopCallbacks=[],this.commitCallbacks=[],this.activityState=Q.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(h=>{let c=!1;const d=[a.shift()];for(;!c;){const p=a[0];!p||p[0]===0?c=!0:d.push(a.shift())}this.postToWorker(d),h(null)}),this.onUxtCb=[],this.contextId=Math.random().toString(36).slice(2),this.projectKey=e,Object.keys(n).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.'),n={...n,canvas:{__save_canvas_locally:n.__save_canvas_locally,fixedCanvasScaling:n.fixedCanvasScaling,disableCanvas:n.disableCanvas}}),this.networkOptions=n.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:Gn,resourceBaseHref:null,__is_snippet:!1,__debug_report_edp:null,__debug__:Qe.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=kn(o,n),!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 No(this,n),this.nodes=new Eo(this.options.node_id),this.observer=new _o(this,n),this.ticker=new Ao(this),this.ticker.attach(()=>this.commit()),this.debug=new To(this.options.__debug__),this.session=new Ro(this,this.options),this.attributeSender=new ir(this,!!this.options.disableStringDict),this.featureFlags=new ar(this),this.tagWatcher=new Jr(this.sessionStorage,this.debug.error,a=>{this.send(Gr(a))}),this.session.attachUpdateCallback(({userID:a,metadata:h})=>{a!=null&&this.send(Dr(a)),h!=null&&Object.entries(h).forEach(([c,d])=>this.send(En(c,d)))}),s!=null&&this.session.applySessionHash(s),this.initWorker();const l=this.session.getTabId();if(this.insideIframe){const a=c=>{const{data:d}=c;d.line===ce.iframeId&&(this.rootId=d.id,this.session.setSessionToken(d.token),this.frameOderNumber=d.frameOrderNumber,this.debug.log("starting iframe tracking",d),this.allowAppStart())};window.addEventListener("message",a),this.attachStopCallback(()=>{window.removeEventListener("message",a)});const h=this.initialHostName;window.parent.postMessage({line:ce.iframeSignal,source:l,context:this.contextId,domain:h},"*")}else{let a=0;const h=c=>{const{data:d}=c;if(d.line===ce.iframeSignal){const p=d.domain,y=Array.from(document.querySelectorAll("iframe"));this.pageFrames=y,(async()=>{let b=0;for(;b<10;){const T=this.checkNodeId(y,p);if(T){this.waitStarted().then(()=>{var A;a++;const D=this.session.getSessionToken(),B={line:ce.iframeId,context:this.contextId,domain:p,id:T,token:D,frameOrderNumber:a};this.debug.log("iframe_data",B),(A=c.source)==null||A.postMessage(B,"*")}).catch(console.error),b=10;break}b++,await Mo(100)}})()}if(d.line===ce.iframeBatch){const y=d.messages.map(w=>{if(w[0]===20){let b=w;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[D,B,A]=w,{left:k,top:O}=T.getBoundingClientRect();b=[D,B+k,A+O]}}),b}if(w[0]===68){let b=w;return this.pageFrames.forEach(T=>{if(T.dataset.domain===c.data.domain){const[D,B,A,k,O,N,F]=w,{left:C,top:E,width:P,height:V}=T.getBoundingClientRect(),j=document.documentElement.scrollWidth,W=document.documentElement.scrollHeight,I=N/100*P+C,M=F/100*V+E,q=I/j,G=M/W;b=[D,B,A,k,O,Math.round(q*1e3)/10,Math.round(G*1e3)/10]}}),b}return w});this.messages.push(...y)}};window.addEventListener("message",h),this.attachStopCallback(()=>{window.removeEventListener("message",h)})}this.bc!==null&&(this.bc.postMessage({line:ce.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===ce.resp){const h=a.data.token;this.session.setSessionToken(h),this.allowAppStart()}if(a.data.line===ce.reg){const h=a.data.token;this.session.regenerateTabId(),this.session.setSessionToken(h),this.allowAppStart()}if(a.data.line===ce.ask){const h=this.session.getSessionToken();h&&this.bc&&this.bc.postMessage({line:a.data.source===l?ce.reg:ce.resp,token:h,source:l,context:this.contextId})}}})}allowAppStart(){this.canStart=!0,this.startTimeout&&(clearTimeout(this.startTimeout),this.startTimeout=null)}checkNodeId(e,s){for(const n of e)if(n.dataset.domain===s)return n[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=s=>{this._debug("webworker_error",s)},this.worker.onmessage=({data:s})=>{this.handleWorkerMsg(s)};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 s;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 n=e.batch;n.byteLength>this.compressionThreshold?tr(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:n})):(a=this.worker)==null||a.postMessage({type:"compressed",batch:o})}):(s=this.worker)==null||s.postMessage({type:"uncompressed",batch:n})}else e.type==="queue_empty"&&this.onSessionSent()}_debug(e,s){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:`${s}`})}),this.debug.error("OpenReplay error: ",e,s)}send(e,s=!1){var n;this.activityState!==Q.NotActive&&(this.activityState===Q.ColdStart?(this.bufferedMessages1.push(e),this.singleBuffer||this.bufferedMessages2.push(e),(n=this.conditionsManager)==null||n.processMessage(e)):this.messages.push(e),this.activityState===Q.Active&&s&&this.commit())}_nCommit(){if(this.socketMode){this.messages.unshift(Fe(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:ce.iframeBatch,messages:this.messages,domain:this.initialHostName},"*"),this.commitCallbacks.forEach(e=>e(this.messages)),this.messages.length=0;return}try{gr(()=>{var e;this.messages.unshift(Fe(this.session.getTabId())),this.messages.unshift(Ae(this.timestamp())),(e=this.worker)==null||e.postMessage(this.messages),this.commitCallbacks.forEach(s=>s(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(Fe(this.session.getTabId())),this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(Fe(this.session.getTabId())),this.coldStartCommitN=0)}commit(){this.activityState===Q.ColdStart?this._cStartCommit():this._nCommit()}postToWorker(e){var s;(s=this.worker)==null||s.postMessage(e),this.commitCallbacks.forEach(n=>n(e)),e.length=0}timestamp(){return pe()+this.delay}safe(e){const s=this;return function(...n){try{e.apply(this,n)}catch(i){s._debug("safe_fn_call",i)}}}attachCommitCallback(e){this.commitCallbacks.push(e)}attachStartCallback(e,s=!1){s&&(e=this.safe(e)),this.startCallbacks.push(e)}attachStopCallback(e,s=!1){s&&(e=this.safe(e)),this.stopCallbacks.push(e)}attachEventListener(e,s,n,i=!0,r=!0){i&&(n=this.safe(n));const o=()=>e?wn(e,s,n,r):null,l=()=>e?xn(e,s,n,r):null;this.attachStartCallback(o,i),this.attachStopCallback(l,i)}checkRequiredVersion(e){const s=e.split(/[.-]/),n=this.version.split(/[.-]/);for(let i=0;i<3;i++){if(isNaN(Number(n[i]))||isNaN(Number(s[i])))return!1;if(Number(n[i])>Number(s[i]))return!0;if(Number(n[i])<Number(s[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:s,sessionID:n,timestamp:i}=this.session.getInfo();if(!s||!n){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$/,`${s}/session/${n}`);if(e!=null&&e.withCurrentTime){const h=pe()-i;return`${a}?jumpto=${h}`}return a}getHost(){return new URL(this.options.ingestPoint).host}getProjectKey(){return this.projectKey}getBaseHref(){var e,s;return typeof this.options.resourceBaseHref=="string"?this.options.resourceBaseHref:(this.options.resourceBaseHref,document.baseURI?document.baseURI:((s=(e=document.head)==null?void 0:e.getElementsByTagName("base")[0])==null?void 0:s.getAttribute("href"))||location.origin+location.pathname)}resolveResourceURL(e){const s=new URL(this.getBaseHref());return s.pathname+="/"+new URL(e).pathname,s.pathname.replace(/\/+/g,"/"),s.toString()}isServiceURL(e){return e.startsWith(this.options.ingestPoint)}active(){return this.activityState===Q.Active}resetNextPageSession(e){e?this.sessionStorage.setItem(this.options.session_reset_key,"t"):this.sessionStorage.removeItem(this.options.session_reset_key)}checkSessionToken(e){const s=this.sessionStorage.getItem(this.options.session_reset_key)!==null,n=e||s,i=this.session.getSessionToken();return n||!i}async coldStart(e={},s){this.singleBuffer=!1;const n=1e3,i=this.checkSessionToken(e.forceNew);s&&await this.setupConditionalStart(e);const r=()=>{this.orderNumber+=1,$t(),this.coldStartTs=pe(),this.orderNumber%2===0?(this.bufferedMessages1.length=0,this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(Fe(this.session.getTabId()))):(this.bufferedMessages2.length=0,this.bufferedMessages2.push(Ae(this.timestamp())),this.bufferedMessages2.push(Fe(this.session.getTabId()))),this.stop(!1),this.activityState=Q.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(yt(this.session.getTabId()))),this.observer.observe(),this.ticker.start()};this.coldInterval=setInterval(()=>{r()},30*n),r()}async setupConditionalStart(e){var p,y;this.conditionsManager=new rr(this,e);const s=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:es,timezone:hs(),width:window.screen.width,height:window.screen.height})}),{token:n,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:h,projectID:c}=await s.json();this.session.assign({projectID:c}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:h});const d={sessionToken:n,userUUID:"",sessionID:""};this.startCallbacks.forEach(w=>w(d)),await((p=this.conditionsManager)==null?void 0:p.fetchConditions(c,n)),await this.featureFlags.reloadFlags(n),await this.tagWatcher.fetchTags(this.options.ingestPoint,n),(y=this.conditionsManager)==null||y.processFlags(this.featureFlags.flags)}offlineRecording(e={},s){this.onSessionSent=s,this.singleBuffer=!0;const n=this.checkSessionToken(e.forceNew);$t(),this.coldStartTs=pe();const i=this.localStorage.getItem(ls);if(i){const o=JSON.parse(i);this.bufferedMessages1=Array.isArray(o)?o:this.bufferedMessages1,this.localStorage.removeItem(ls)}this.bufferedMessages1.push(Ae(this.timestamp())),this.bufferedMessages1.push(Fe(this.session.getTabId())),this.activityState=Q.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)),n||this.send(yt(this.session.getTabId())),this.observer.observe(),this.ticker.start(),{saveBuffer:this.saveBuffer,getBuffer:this.getBuffer,setBuffer:this.setBuffer}}saveBuffer(){this.localStorage.setItem(ls,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 s=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:es,timezone:hs()})}),{token:n,userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:h,beaconSizeLimit:c,projectID:d}=await s.json();for((y=this.worker)==null||y.postMessage({type:"auth",token:n,beaconSizeLimit:c}),this.session.assign({projectID:d}),this.session.setUserInfo({userBrowser:i,userCity:r,userCountry:o,userDevice:l,userOS:a,userState:h});this.bufferedMessages1.length>0;)await this.flushBuffer(this.bufferedMessages1);this.postToWorker([["q_end"]]),this.clearBuffers()}async _start(e={},s=!1,n){const i=this.activityState===Q.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(Oe(a))}if(this.activityState===Q.Active||this.activityState===Q.Starting)return Promise.resolve(Oe("OpenReplay: trying to call `start()` on the instance that has been started already."));this.activityState=Q.Starting,i||$t(),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:es,timezone:hs(),condition:n,assistOnly:e.assistOnly??this.socketMode,width:window.screen.width,height:window.screen.height})});if(a.status!==200){const I=await a.text(),M=I===Ze?Ze:`Server error: ${a.status}. ${I}`;return Oe(M)}if(!this.worker){const I="no worker found after start request (this should not happen in real world)";return this.signalError(I,[]),Oe(I)}const{token:h,userUUID:c,projectID:d,beaconSizeLimit:p,compressionThreshold:y,delay:w,sessionID:b,startTimestamp:T,userBrowser:D,userCity:B,userCountry:A,userDevice:k,userOS:O,userState:N,canvasEnabled:F,canvasQuality:C,canvasFPS:E,assistOnly:P}=await a.json();if(typeof h!="string"||typeof c!="string"||typeof T!="number"&&typeof T<"u"||typeof b!="string"||typeof w!="number"||typeof p!="number"&&typeof p<"u"){const I=`Incorrect server response: ${JSON.stringify(a)}`;return this.signalError(I,[]),Oe(I)}this.delay=w,this.session.setSessionToken(h),this.session.setUserInfo({userBrowser:D,userCity:B,userCountry:A,userDevice:k,userOS:O,userState:N}),this.session.assign({sessionID:b,timestamp:T||r,projectID:d}),P?(this.socketMode=!0,this.worker.postMessage("stop")):this.worker.postMessage({type:"auth",token:h,beaconSizeLimit:p}),!l&&h===o&&(this.debug.log("continuing session on new tab",this.session.getTabId()),this.send(yt(this.session.getTabId()))),Object.entries(this.session.getInfo().metadata).forEach(([I,M])=>this.send(En(I,M))),this.localStorage.setItem(this.options.local_uuid_key,c),this.compressionThreshold=y;const V={sessionToken:h,userUUID:c,sessionID:b};if(this.startCallbacks.forEach(I=>I(V)),this.featureFlags.reloadFlags(),await this.tagWatcher.fetchTags(this.options.ingestPoint,h),this.activityState=Q.Active,F&&!this.options.canvas.disableCanvas&&(this.canvasRecorder=this.canvasRecorder??new wo(this,{fps:E,quality:C,isDebug:this.options.canvas.__save_canvas_locally,fixedScaling:this.options.canvas.fixedCanvasScaling,useAnimationFrame:this.options.canvas.useAnimationFrame}),this.canvasRecorder.startTracking()),i){const I=this.bufferedMessages1.length>this.bufferedMessages2.length?this.bufferedMessages1:this.bufferedMessages2;for(;I.length>0;)await this.flushBuffer(I);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 bo(this,Vn);let j;const W=this.localStorage.getItem(Vn);if(W&&(j=parseInt(W,10)),location!=null&&location.search){const I=new URLSearchParams(location.search);if(I.has("oruxt")){const M=I.get("oruxt");j=M?parseInt(M,10):void 0}}return j&&(this.uxtManager.isActive?this.onUxtCb.forEach(I=>I(j)):this.uxtManager.getTest(j,h,!!W).then(I=>{I&&this.onUxtCb.forEach(M=>M(I))})),Fo(V)}catch(a){if(this.stop(),this.session.reset(),a===Ze)return this.signalError(Ze,[]),Oe(Ze);this._debug("session_start",a);const h=a instanceof Error?a.message:a.toString();return this.signalError(h,[]),Oe(h)}}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 s=()=>{this.canStart?e(!0):setTimeout(s,25)};s()})}async waitStarted(){return new Promise(e=>{const s=()=>{this.activityState===Q.Active?e(!0):setTimeout(s,25)};s()})}async start(...e){return this.activityState===Q.Active||this.activityState===Q.Starting?Promise.resolve(Oe("OpenReplay: trying to call `start()` on the instance that has been started already.")):document.hidden?new Promise(s=>{const n=async()=>{document.hidden||(await this.waitStart(),document.removeEventListener("visibilitychange",n),s(this._start(...e)))};document.addEventListener("visibilitychange",n)}):(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 s=e;return(n,i,r="down")=>{typeof n!="string"||typeof i!="string"||i.length>5*1024*1024||n.length>255||this.send(zr("websocket",s,i,this.timestamp(),r,n))}}stop(e=!0){var s;if(this.activityState!==Q.NotActive)try{this.attributeSender.clear(),this.sanitizer.clear(),this.observer.disconnect(),this.nodes.clear(),this.ticker.stop(),this.stopCallbacks.forEach(n=>n()),this.debug.log("OpenReplay tracking stopped."),this.tagWatcher.clear(),this.worker&&e&&this.worker.postMessage("stop"),(s=this.canvasRecorder)==null||s.clear()}finally{this.activityState=Q.NotActive}}}function Po(t){const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e===void 0)return;const s=()=>t.send(Mr(Math.round(e.downlink*1e3),e.type||"unknown"));s(),e.addEventListener("change",s)}const Kn=ve&&"InstallTrigger"in window?t=>t.message+`
649
+ `+t.stack:t=>t.stack||t.message;function us(t){return t===void 0?"undefined":t===null?"null":t instanceof Error?Kn(t):Array.isArray(t)?`Array(${t.length})`:String(t)}function Bo(t){return typeof t!="number"?"NaN":t.toString()}function jo(t){return typeof t!="number"?"NaN":Math.floor(t).toString()}function Xn(t){if(t===void 0)return"undefined";if(t===null)return"null";if(t instanceof Error)return Kn(t);if(Array.isArray(t)){const e=t.length,s=t.slice(0,10).map(us).join(", ");return`Array(${e})[${s}]`}if(typeof t=="object"){const e=[];let s=0;for(const n in t){if(++s===10)break;const i=t[n];e.push(n+": "+us(i))}return"{"+e.join(", ")+"}"}return t.toString()}function Uo(t){return typeof t[0]=="string"&&t.unshift(t.shift().replace(/%(o|s|f|d|i)/g,(e,s)=>{const n=t.shift();if(n===void 0)return e;switch(s){case"o":return Xn(n);case"s":return us(n);case"f":return Bo(n);case"d":case"i":return jo(n);default:return e}})),t.map(Xn).join(" ")}const Jn=["log","info","warn","error","debug","assert"];function Ho(t,e){const s=Object.assign({consoleMethods:Jn,consoleThrottling:30},e);if(!Array.isArray(s.consoleMethods)||s.consoleMethods.length===0)return;const n=t.safe((a,h)=>t.send(_r(a,Uo(h))));let i=0;const r=()=>{i=0};t.attachStartCallback(r),t.ticker.attach(r,33,!1);const o=(a,h)=>{const c={apply:function(d,p,y){Reflect.apply(d,h,y),i=i+1,!(i>s.consoleThrottling)&&n(d.name,y)}};s.consoleMethods.forEach(d=>{if(Jn.indexOf(d)===-1){t.debug.error(`OpenReplay: unsupported console method "${d}"`);return}const p=h.console[d];a[d]=new Proxy(p,c)})},l=t.safe(a=>o(a.console,a));l(window),t.observer.attachContextCallback(l)}var Yn={exports:{}},ds={exports:{}},Qn;function zo(){return Qn||(Qn=1,function(t,e){(function(s,n){t.exports=n()})(Pe,function(){function s(b){return!isNaN(parseFloat(b))&&isFinite(b)}function n(b){return b.charAt(0).toUpperCase()+b.substring(1)}function i(b){return function(){return this[b]}}var r=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],l=["fileName","functionName","source"],a=["args"],h=["evalOrigin"],c=r.concat(o,l,a,h);function d(b){if(b)for(var T=0;T<c.length;T++)b[c[T]]!==void 0&&this["set"+n(c[T])](b[c[T]])}d.prototype={getArgs:function(){return this.args},setArgs:function(b){if(Object.prototype.toString.call(b)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=b},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(b){if(b instanceof d)this.evalOrigin=b;else if(b instanceof Object)this.evalOrigin=new d(b);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var b=this.getFileName()||"",T=this.getLineNumber()||"",D=this.getColumnNumber()||"",B=this.getFunctionName()||"";return this.getIsEval()?b?"[eval] ("+b+":"+T+":"+D+")":"[eval]:"+T+":"+D:B?B+" ("+b+":"+T+":"+D+")":b+":"+T+":"+D}},d.fromString=function(T){var D=T.indexOf("("),B=T.lastIndexOf(")"),A=T.substring(0,D),k=T.substring(D+1,B).split(","),O=T.substring(B+1);if(O.indexOf("@")===0)var N=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(O,""),F=N[1],C=N[2],E=N[3];return new d({functionName:A,args:k||void 0,fileName:F,lineNumber:C||void 0,columnNumber:E||void 0})};for(var p=0;p<r.length;p++)d.prototype["get"+n(r[p])]=i(r[p]),d.prototype["set"+n(r[p])]=function(b){return function(T){this[b]=!!T}}(r[p]);for(var y=0;y<o.length;y++)d.prototype["get"+n(o[y])]=i(o[y]),d.prototype["set"+n(o[y])]=function(b){return function(T){if(!s(T))throw new TypeError(b+" must be a Number");this[b]=Number(T)}}(o[y]);for(var w=0;w<l.length;w++)d.prototype["get"+n(l[w])]=i(l[w]),d.prototype["set"+n(l[w])]=function(b){return function(T){this[b]=String(T)}}(l[w]);return d})}(ds)),ds.exports}(function(t,e){(function(s,n){t.exports=n(zo())})(Pe,function(n){var i=/(^|@)\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 h=/(.+?)(?::(\d+))?(?::(\d+))?$/,c=h.exec(a.replace(/[()]/g,""));return[c[1],c[2]||void 0,c[3]||void 0]},parseV8OrIE:function(a){var h=a.stack.split(`
650
+ `).filter(function(c){return!!c.match(r)},this);return h.map(function(c){c.indexOf("(eval ")>-1&&(c=c.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var d=c.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=d.match(/ (\(.+\)$)/);d=p?d.replace(p[0],""):d;var y=this.extractLocation(p?p[1]:d),w=p&&d||void 0,b=["eval","<anonymous>"].indexOf(y[0])>-1?void 0:y[0];return new n({functionName:w,fileName:b,lineNumber:y[1],columnNumber:y[2],source:c})},this)},parseFFOrSafari:function(a){var h=a.stack.split(`
651
+ `).filter(function(c){return!c.match(o)},this);return h.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 n({functionName:c});var d=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=c.match(d),y=p&&p[1]?p[1]:void 0,w=this.extractLocation(c.replace(d,""));return new n({functionName:y,fileName:w[0],lineNumber:w[1],columnNumber:w[2],source:c})},this)},parseOpera:function(a){return!a.stacktrace||a.message.indexOf(`
640
652
  `)>-1&&a.message.split(`
641
653
  `).length>a.stacktrace.split(`
642
- `).length?this.parseOpera9(a):a.stack?this.parseOpera11(a):this.parseOpera10(a)},parseOpera9:function(a){for(var u=/Line (\d+).*script (?:in )?(\S+)/i,c=a.message.split(`
643
- `),d=[],p=2,y=c.length;p<y;p+=2){var w=u.exec(c[p]);w&&d.push(new n({fileName:w[2],lineNumber:w[1],source:c[p]}))}return d},parseOpera10:function(a){for(var u=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,c=a.stacktrace.split(`
644
- `),d=[],p=0,y=c.length;p<y;p+=2){var w=u.exec(c[p]);w&&d.push(new n({functionName:w[3]||void 0,fileName:w[2],lineNumber:w[1],source:c[p]}))}return d},parseOpera11:function(a){var u=a.stack.split(`
645
- `).filter(function(c){return!!c.match(i)&&!c.match(/^Error created at/)},this);return u.map(function(c){var d=c.split("@"),p=this.extractLocation(d.pop()),y=d.shift()||"",w=y.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,b;y.match(/\(([^)]*)\)/)&&(b=y.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var T=b===void 0||b==="[arguments not available]"?void 0:b.split(",");return new n({functionName:w,args:T,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:c})},this)}}})})(Yn);var Bo=Yn.exports;const jo=Xs(Bo);function Zn(t){return[{columnNumber:t.colno,lineNumber:t.lineno,fileName:t.filename,functionName:"",source:""}]}function Tt(t,e,s={}){let n=e;try{n=jo.parse(t)}catch{}return Yt(t.name,t.message,JSON.stringify(n),JSON.stringify(s))}function ei(t,e=window,s={}){if(t instanceof ErrorEvent){if(t.error instanceof Error)return Tt(t.error,Zn(t),s);{let[n,i]=t.message.split(":");return i||(n="Error",i=t.message),Yt(n,i,JSON.stringify(Zn(t)),JSON.stringify(s))}}else if("PromiseRejectionEvent"in e&&t instanceof e.PromiseRejectionEvent){if(t.reason instanceof Error)return Tt(t.reason,[],s);{let n;try{n=JSON.stringify(t.reason)}catch{n=String(t.reason)}return Yt("Unhandled Promise Rejection",n,"[]",JSON.stringify(s))}}return null}function Uo(t,e){const s=Object.assign({captureExceptions:!0},e);function n(i){function r(o){const l=ei(o,i);l!=null&&t.send(l)}t.attachEventListener(i,"unhandledrejection",r),t.attachEventListener(i,"error",r)}s.captureExceptions&&(t.observer.attachContextCallback(n),n(window))}function ti(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 Ho(t){return nr&&(t.startsWith("data:image/svg+xml")||t.match(/.svg$|/i))}const zo="https://static.openreplay.com/tracker/placeholder.jpeg";function Wo(t){function e(l,a){t.attributeSender.sendSetAttribute(l,"src",zo);const{width:u,height:c}=a.getBoundingClientRect();a.hasAttribute("width")||t.attributeSender.sendSetAttribute(l,"width",String(u)),a.hasAttribute("height")||t.attributeSender.sendSetAttribute(l,"height",String(c))}const s=function(l,a){const{srcset:u}=a;if(!u)return;const c=u.split(u.match(/,\s+/)?/,\s+/:",").map(d=>ti(d)).join(", ");t.attributeSender.sendSetAttribute(l,"srcset",c)},n=function(l,a){a.src.length>ir&&e(l,a),t.send(Kt(l,"src",a.src,t.getBaseHref()))},i=t.safe(function(l){const a=ti(l.src||"");vn(a)&&t.send(Dn(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&&!Ho(l.src)?i(l):t.sanitizer.isHidden(a)||t.sanitizer.isObscured(a)?e(a,l):(n(a,l),s(a,l)))}),o=Sn(t.safe(l=>{for(const a of l)if(a.type==="attributes"){const u=a.target,c=t.nodes.getID(u);if(c===void 0)return;a.attributeName==="src"&&n(c,u),a.attributeName==="srcset"&&s(c,u)}}));t.attachStopCallback(()=>{o.disconnect()}),t.nodes.attachNodeCallback(l=>{Y(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 $o=["text","password","email","search","number","range","date","tel","time"];function qo(t){return Y(t,"textarea")?!0:Y(t,"input")?$o.includes(t.type):!1}function Vo(t){if(!Y(t,"input"))return!1;const e=t.type;return e==="checkbox"||e==="radio"}const Go=ve&&"labels"in HTMLInputElement.prototype?t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Y(e,"label"))return e;const s=t.labels;if(s!==null&&s.length===1)return s[0]}:t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Y(e,"label"))return e;const s=t.id;if(s){const n=t.ownerDocument.querySelectorAll('label[for="'+s+'"]');if(n!==null&&n.length===1)return n[0]}};function si(t){let e=Vt(t);if(e===null){const s=Go(t);e=s&&s.innerText||t.placeholder||t.name||t.id||t.className||t.type}return mn(e).slice(0,100)}const qe={Plain:0,Obscured:1,Hidden:2};function Ko(t,e){const s=Object.assign({obscureInputNumbers:!0,obscureInputEmails:!0,defaultInputMode:qe.Obscured,obscureInputDates:!1},e);function n(c,d){let p=d.value,y=s.defaultInputMode;d.type==="password"||t.sanitizer.isHidden(c)?y=qe.Hidden:(t.sanitizer.isObscured(c)||y===qe.Plain&&(s.obscureInputNumbers&&d.type!=="date"&&/\d\d\d\d/.test(p)||s.obscureInputDates&&d.type==="date"||s.obscureInputEmails&&(d.type==="email"||~p.indexOf("@"))))&&(y=qe.Obscured);let w=0;switch(y){case qe.Hidden:w=-1,p="";break;case qe.Obscured:w=p.length,p="";break}return{value:p,mask:w}}function i(c,d){const{value:p,mask:y}=n(c,d);t.send(Sr(c,p,y))}const r=new Map,o=new Map;t.attachStopCallback(()=>{r.clear(),o.clear()});function l(c,d){r.get(c)!==d.value&&(r.set(c,d.value),i(c,d))}function a(c,d){o.get(c)!==d&&(o.set(c,d),t.send(wr(c,d)))}t.ticker.attach(()=>{r.forEach((c,d)=>{const p=t.nodes.getNode(d);if(!p)return r.delete(d);l(d,p)}),o.forEach((c,d)=>{const p=t.nodes.getNode(d);if(!p)return o.delete(d);a(d,p.checked)})},3);function u(c,d,p,y){const{value:w,mask:b}=n(c,d),T=si(d);t.send(Br(c,w,b!==0,T,p,y))}t.nodes.attachNodeCallback(t.safe(c=>{const d=t.nodes.getID(c);if(d!==void 0){if(Y(c,"select")&&(i(d,c),t.nodes.attachNodeListener(c,"change",()=>i(d,c))),qo(c)){l(d,c);let p=0,y=0,w=0;const b=()=>{p=pe()},T=()=>{y===0&&p!==0&&(y=pe()-p)},D=()=>{p!==0&&(w=pe()-p),u(d,c,y,w),y=0,w=0,p=0};t.nodes.attachNodeListener(c,"focus",b),t.nodes.attachNodeListener(c,"input",T),t.nodes.attachNodeListener(c,"change",D);return}if(Vo(c)){a(d,c.checked),t.nodes.attachNodeListener(c,"change",()=>a(d,c.checked));return}}}))}let ue,fs,ni;function Xo(t,e){if(ni=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 s={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};ue={...s,...e},fs=Jo(ue.root,s);let n=Et(t,"all",()=>Et(t,"two",()=>Et(t,"one",()=>Et(t,"none"))));if(n){const i=li(ui(n,t));return i.length>0&&(n=i[0]),Ct(n)}else throw new Error("Selector was not found.")}function Jo(t,e){return t.nodeType===Node.DOCUMENT_NODE?t:t===e.root?t.ownerDocument:t}function Et(t,e,s){let n=null,i=[],r=t,o=0;for(;r;){const l=new Date().getTime()-ni.getTime();if(ue.timeoutMs!==void 0&&l>ue.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${l}ms`);let a=_t(Yo(r))||_t(...Qo(r))||_t(...Zo(r))||_t(ea(r))||[ai()];const u=ta(r);if(e=="all")u&&(a=a.concat(a.filter(ps).map(c=>It(c,u))));else if(e=="two")a=a.slice(0,1),u&&(a=a.concat(a.filter(ps).map(c=>It(c,u))));else if(e=="one"){const[c]=a=a.slice(0,1);u&&ps(c)&&(a=[It(c,u)])}else e=="none"&&(a=[ai()],u&&(a=[It(a[0],u)]));for(let c of a)c.level=o;if(i.push(a),i.length>=ue.seedMinLength&&(n=ii(i,s),n))break;r=r.parentElement,o++}return n||(n=ii(i,s)),!n&&s?s():n}function ii(t,e){const s=li(ci(t));if(s.length>ue.threshold)return e?e():null;for(let n of s)if(oi(n))return n;return null}function Ct(t){let e=t[0],s=e.name;for(let n=1;n<t.length;n++){const i=t[n].level||0;e.level===i-1?s=`${t[n].name} > ${s}`:s=`${t[n].name} ${s}`,e=t[n]}return s}function ri(t){return t.map(e=>e.penalty).reduce((e,s)=>e+s,0)}function oi(t){const e=Ct(t);switch(fs.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 Yo(t){const e=t.getAttribute("id");return e&&ue.idName(e)?{name:"#"+CSS.escape(e),penalty:0}:null}function Qo(t){return Array.from(t.attributes).filter(s=>ue.attr(s.name,s.value)).map(s=>({name:`[${CSS.escape(s.name)}="${CSS.escape(s.value)}"]`,penalty:.5}))}function Zo(t){return Array.from(t.classList).filter(ue.className).map(s=>({name:"."+CSS.escape(s),penalty:1}))}function ea(t){const e=t.tagName.toLowerCase();return ue.tagName(e)?{name:e,penalty:2}:null}function ai(){return{name:"*",penalty:3}}function ta(t){const e=t.parentNode;if(!e)return null;let s=e.firstChild;if(!s)return null;let n=0;for(;s&&(s.nodeType===Node.ELEMENT_NODE&&n++,s!==t);)s=s.nextSibling;return n}function It(t,e){return{name:t.name+`:nth-child(${e})`,penalty:t.penalty+1}}function ps(t){return t.name!=="html"&&!t.name.startsWith("#")}function _t(...t){const e=t.filter(sa);return e.length>0?e:null}function sa(t){return t!=null}function*ci(t,e=[]){if(t.length>0)for(let s of t[0])yield*ci(t.slice(1,t.length),e.concat(s));else yield e}function li(t){return[...t].sort((e,s)=>ri(e)-ri(s))}function*ui(t,e,s={counter:0,visited:new Map}){if(t.length>2&&t.length>ue.optimizedMinLength)for(let n=1;n<t.length-1;n++){if(s.counter>ue.maxNumberOfTries)return;s.counter+=1;const i=[...t];i.splice(n,1);const r=Ct(i);if(s.visited.has(r))return;oi(i)&&na(i,e)&&(yield i,s.visited.set(r,!0),yield*ui(i,e,s))}}function na(t,e){return fs.querySelector(Ct(t))===e}function ia(t,e,s){return Xo(t,{root:e.body,seedMinLength:3,optimizedMinLength:(s==null?void 0:s.minSelectorDepth)||2,threshold:(s==null?void 0:s.nthThreshold)||1e3,maxNumberOfTries:(s==null?void 0:s.maxOptimiseTries)||1e4})}function gs(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 hi(t,e){return t instanceof Element?ra(t,e):null}function ra(t,e){let s=t;for(;s!==null&&s!==e.documentElement;){if(De(s,"masked"))return null;s=s.parentElement}if(ns(t)){let n=t.ownerSVGElement;for(;n!==null;)t=n,n=n.ownerSVGElement}for(s=t;s!==null&&s!==e.documentElement;){const n=s.tagName.toUpperCase();if(n==="LABEL")return null;if(n==="INPUT"||gs(s)||Vt(s)!==null)return s;s=s.parentElement}return t===e.documentElement?null:t}function oa(t,e){const{disableClickmaps:s=!1}=e||{};function n(k){const O=Vt(k);if(O!==null)return O;if(Y(k,"input"))return si(k);if(gs(k)){let N="";return k instanceof HTMLElement&&(N=t.sanitizer.getInnerTextSecure(k)),N=N||k.id||k.className,mn(N).slice(0,100)}return""}let i=-1,r=-1,o=!1,l=null,a=0,u={},c=0,d=0,p=0,y=0,w;const b=.008,T=225;function D(){const k=y/T;if(!c){c=k;return}const O=(k-c)/T;p>4&&O>b&&t.send(jr(pe())),y=0,p=0,c=k}t.attachStartCallback(()=>{w=setInterval(()=>D(),T)}),t.attachStopCallback(()=>{i=-1,r=-1,o=!1,l=null,u={},w&&clearInterval(w)});const B=()=>{o&&(t.send(xr(i,r)),o=!1)},A=(k,O=!1)=>{function N(C,E,P){return u[C]=u[C]||ia(E,k,P)}const F=O?t.attachEventListener.bind(t):t.nodes.attachNodeListener.bind(t.nodes);F(k.documentElement,"mouseover",C=>{const E=hi(C.target,k);E!==l&&(l=E,a=performance.now())}),F(k,"mousemove",C=>{const[E,P]=t.observer.getDocumentOffset(k);i=C.clientX+E,r=C.clientY+P,o=!0;const V=Math.sign(C.movementX);y+=Math.abs(C.movementX)+Math.abs(C.movementY),V!==d&&(d=V,p++)},!1),F(k,"click",C=>{const E=hi(C.target,k);if(!C.clientX&&!C.clientY||E===null)return;const P=t.nodes.getID(E);if(P!==void 0){const V=C.pageX,j=C.pageY,W=k.documentElement.scrollWidth,I=k.documentElement.scrollHeight,M=di(V/W),q=di(j/I);B(),t.send(Mr(P,l===E?Math.round(performance.now()-a):0,n(E),gs(E)&&!s?N(P,E,e):"",M,q),!0)}l=null})};t.nodes.attachNodeCallback(k=>{wt(k)&&A(k)}),A(document,!0),t.ticker.attach(B,(e==null?void 0:e.trackingOffset)||7)}function di(t){return Math.round(t*1e4)}function aa(t){const e=[],s=document.getElementsByTagName("*"),n=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let i=0;i<s.length;i++){const r=s[i];let o="";if(Y(r,"img")&&(o=r.currentSrc||r.src),!o){const w=getComputedStyle(r).getPropertyValue("background-image");if(w){const b=n.exec(w);b!==null&&(o=b[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(),u=Math.max(a.top,0),c=Math.max(a.left,0),d=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(d<=u||p<=c)continue;const y=(d-u)*(p-c);e.push({time:l,area:y})}return e}function ca(t,e){let s=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,n=s*t;for(let i=0;i<e.length;i++){const{time:r,area:o}=e[i];s+=o,n+=o*(r>t?r:t)}return s===0?0:n/s}function la(t,e){const s=Object.assign({captureResourceTimings:!0,capturePageLoadTimings:!0,capturePageRenderTimings:!0,excludedResourceUrls:[]},e);if("PerformanceObserver"in window||(s.captureResourceTimings=!1),!s.captureResourceTimings)return;let n={};function i(u){var d;if(u.duration<0||!vn(u.name)||t.isServiceURL(u.name))return;n!==null&&(n[u.name]=u.startTime+u.duration);let c=!1;(d=s.excludedResourceUrls)==null||d.forEach(p=>{if(u.name.startsWith(p)){c=!0;return}}),!c&&t.send(Dn(u.startTime+ze(),u.duration,u.responseStart&&u.startTime?u.responseStart-u.startTime:0,u.transferSize>u.encodedBodySize?u.transferSize-u.encodedBodySize:0,u.encodedBodySize||0,u.decodedBodySize||0,u.name,u.initiatorType,u.transferSize,u.responseStatus&&u.responseStatus===304||u.transferSize===0))}const r=new PerformanceObserver(u=>u.getEntries().forEach(i));let o;t.attachStartCallback(function({sessionID:u}){u!==o&&(performance.getEntriesByType("resource").forEach(i),o=u),r.observe({entryTypes:["resource"]})}),t.attachStopCallback(function(){r.disconnect()});let l=0,a=0;if(s.capturePageLoadTimings){let u=!1;t.ticker.attach(()=>{if(!u&&((l===0||a===0)&&performance.getEntriesByType("paint").forEach(c=>{const{name:d,startTime:p}=c;switch(d){case"first-paint":l=p;break;case"first-contentful-paint":a=p;break}}),performance.timing.loadEventEnd||performance.now()>3e4)){u=!0;const{navigationStart:c,requestStart:d,responseStart:p,responseEnd:y,domContentLoadedEventStart:w,domContentLoadedEventEnd:b,loadEventStart:T,loadEventEnd:D}=performance.timing;t.send(Tr(d-c||0,p-c||0,y-c||0,w-c||0,b-c||0,T-c||0,D-c||0,l,a))}},30)}if(s.capturePageRenderTimings){let u=0,c=0,d=0,p=null,y=!1;t.ticker.attach(()=>{if(y)return;const w=performance.now();if(n!==null&&(u=Math.max.apply(null,Object.keys(n).map(b=>n[b])),w-u>1e3&&(p=aa(n),n=null)),d!==null&&(w-d>50&&(c=w),d=w-c>5e3?null:w),p!==null&&d===null||w>3e4){y=!0,n=null;const b=p===null?0:ca(a||l,p),{domContentLoadedEventEnd:T,navigationStart:D}=performance.timing,B=d===null?Math.max(c,a,T-D||0):0;t.send(Er(b,a>u?a:u,B))}})}}function ms(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 ua(t,e){let s=!1;const n=new Map;function i(l){Wn(l)&&(ke(l)&&n.set(l,[l.scrollLeft,l.scrollTop]),wt(l)&&n.set(l,ms(l)))}const r=t.safe(()=>{e||t.send(dr(...ms(document)))}),o=t.safe((l,a)=>{const u=t.nodes.getID(a);u!==void 0&&t.send(br(u,l[0],l[1]))});t.attachStartCallback(r),t.attachStopCallback(()=>{s=!1,n.clear()}),t.nodes.attachNodeCallback((l,a)=>{a&&(ke(l)&&l.scrollLeft+l.scrollTop>0?n.set(l,[l.scrollLeft,l.scrollTop]):wt(l)&&n.set(l,ms(l))),xt(l)&&t.nodes.attachNodeListener(l,"scroll",u=>{i(u.target)})}),t.attachEventListener(document,"scroll",l=>{const a=l.target;if(a===document){s=!0;return}i(a)}),t.ticker.attach(()=>{s&&(r(),s=!1),n.forEach(o),n.clear()},5,!1)}function ha(t){let e,s,n,i,r=document.referrer;const o=t.safe(()=>{const{URL:u}=document;u!==e&&(e=u,t.send(Wr(e,r,i,document.title)),i=0,r=e)}),l=t.safe(()=>{const{innerWidth:u,innerHeight:c}=window;(u!==s||c!==n)&&(s=u,n=c,t.send(hr(s,n)))}),a=document.hidden===void 0?Function.prototype:t.safe(()=>t.send(Rr(document.hidden)));t.attachStartCallback(()=>{e=null,i=ze(),s=n=-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 fi(t){return xt(t)&&!!t.adoptedStyleSheets}let da=15;function pi(){return da++}const Ot=new Map;function fa(t){if(t===null||!fi(document))return;const e=new Map,s=new Map,n=o=>setTimeout(()=>{let l=t.nodes.getID(o);if(o===document&&(l=0),l===void 0)return;let a=s.get(l);a||(a=[]);const u=[],c=o.adoptedStyleSheets;if(c&&Symbol.iterator in c)for(const d of c){let p=e.get(d);const y=!p;if(p||(p=pi(),e.set(d,p)),a.includes(p)||t.send(Nn(p,l)),y){const w=d.cssRules;for(let b=0;b<w.length;b++)t.send(Jt(p,w[b].cssText,b,t.getBaseHref()))}u.push(p)}if(Symbol.iterator in a)for(const d of a)u.includes(d)||t.send(Lr(d,l));s.set(l,u)},20);function i(o){const l=Object.getOwnPropertyDescriptor(o,"adoptedStyleSheets");l&&Object.defineProperty(o,"adoptedStyleSheets",{...l,set:function(a){const u=l.set.call(this,a);return n(this),u}})}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(u){return l.call(this,u).then(c=>{const d=e.get(this);return d&&t.send(_n(d,u,t.getBaseHref())),c})},o.CSSStyleSheet.prototype.replaceSync=function(u){const c=e.get(this);return c&&t.send(_n(c,u,t.getBaseHref())),a.call(this,u)}};r(window),t.observer.attachContextCallback(t.safe(r)),t.attachStopCallback(()=>{e.clear(),s.clear()}),t.attachStartCallback(()=>{n(document)}),t.nodes.attachNodeCallback(o=>{fi(o)&&n(o)})}function pa(t){if(t===null)return;if(!window.CSSStyleSheet){t.send(Ar("no_stylesheet_prototype_in_window",""));return}const e=t.safe((i,r,o)=>{const l=Ot.get(i);l&&(typeof o=="string"?t.send(Jt(l,o,r,t.getBaseHref())):t.send(On(l,r)))}),s=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=Ot.get(o);if(!l){t.debug.warn("No sheedID found for",o,Ot);return}const a=r.cssText,u=o.cssRules,c=Array.from(u).indexOf(r);c>=0?(t.send(Jt(l,a,c,t.getBaseHref())),t.send(On(l,c+1))):t.debug.warn("Rule index not found in",o,r)}),n=t.safe(i=>{const{insertRule:r,deleteRule:o}=i.CSSStyleSheet.prototype,{insertRule:l,deleteRule:a}=i.CSSGroupingRule.prototype;i.CSSStyleSheet.prototype.insertRule=function(u,c=0){return e(this,c,u),r.call(this,u,c)},i.CSSStyleSheet.prototype.deleteRule=function(u){return e(this,u),o.call(this,u)},i.CSSGroupingRule.prototype.insertRule=function(u,c=0){const d=l.call(this,u,c);return s(this),d},i.CSSGroupingRule.prototype.deleteRule=function(u=0){const c=a.call(this,u);return s(this),c}});n(window),t.observer.attachContextCallback(n),t.nodes.attachNodeCallback(i=>{if(!Y(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=pi();Ot.set(o,l),t.send(Nn(l,r));const a=o.cssRules;for(let u=0;u<a.length;u++)e(o,u,a[u].cssText)})}function ga(t){function e(n){const i=t.nodes.getID(n);i!==void 0&&t.send(In(i))}let s=!1;t.nodes.attachNodeCallback(n=>{Y(n,"body")&&(t.nodes.attachNodeListener(n,"focus",i=>{Wn(i.target)&&(e(i.target),s=!1)}),t.nodes.attachNodeListener(n,"blur",i=>{i.relatedTarget===null&&(s=!0,setTimeout(()=>{s&&t.send(In(-1))},0))}))}),t.attachStartCallback(()=>{let n=document.activeElement;for(;n&&Y(n,"iframe")&&n.contentDocument;)n=n.contentDocument.activeElement;n&&n!==n.ownerDocument.body&&e(n)},!0)}function ma(t){if(!window.FontFace)return;const e=new Map,s=n=>{class i extends n.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],u=e.get(n.document)||[];u.push(a),e.set(n.document,u);const c=n===window?0:t.nodes.getID(n.document);if(c===void 0)return;t.active()&&t.send(Cn(c,...a))}super(...o)}}n.FontFace=i};t.observer.attachContextCallback(s),s(window),t.nodes.attachNodeCallback(t.safe(n=>{if(!wt(n))return;const i=e.get(n);if(!i)return;const r=n.defaultView===window?0:t.nodes.getID(n);r!==void 0&&i.forEach(o=>{t.send(Cn(r,...o))})}))}function va(t,e,s,n,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:w,method:b,url:T,baseURL:D}=p.config,{data:B,headers:A,status:k,response:O}=p,{data:N,headers:F,status:C}=O||{},E=s.ignoreHeaders,P=Array.isArray(E)?H=>E.includes(H):()=>E;function V(H,v){P(v[0])||(H[v[0]]=v[1])}let j={},W={};y.toJSON?j=y.toJSON():y instanceof Headers?y.forEach((H,v)=>V(j,[v,H])):Array.isArray(y)?y.forEach(H=>V(j,H)):typeof y=="object"&&Object.entries(y).forEach(H=>V(j,H));const I=F||A;I.toJSON?W=I.toJSON():I instanceof Headers?I.forEach((H,v)=>V(W,[v,H])):Array.isArray(I)?I.forEach(H=>V(W,H)):typeof I=="object"&&Object.entries(I).forEach(([H,v])=>{P(H)||(W[H]=v)});const M=n({url:T,method:b||"",status:k||C||0,request:{headers:j,body:w},response:{headers:W,body:N||B}});if(!M){t.debug.log("Openreplay: empty request/response info, skipping");return}const q=p.config.__openreplay_timing,G=performance.now()-q;t.debug.log("Openreplay: final req object",M),t.send(vt("xhr",String(b),String(M.url),i(M.request),i(M.response),M.status,q+ze(),G,0))}function o(p){if(t.debug.log("Openreplay: capturing API request",p),p.__openreplay_timing=performance.now(),s.sessionTokenHeader){const y=typeof s.sessionTokenHeader=="string"?s.sessionTokenHeader:"X-OpenReplay-Session-Token",w=t.getSessionToken();w&&p.headers.set(y,w)}return p}function l(p){return s.failuresOnly||r(p),p}function a(p){return t.debug.log("Openreplay: capturing API request error",p),ya(p)&&p.response?r(p.response):p instanceof Error&&t.send(Tt(p,[])),Promise.reject(p)}function u(p){t.debug.log("Openreplay: failed API request, skipping",p)}const c=e.interceptors.request.use(o,u,{synchronous:!0}),d=e.interceptors.response.use(l,a,{synchronous:!0});t.attachStopCallback(()=>{var p,y,w,b;(y=(p=e.interceptors.request).eject)==null||y.call(p,c),(b=(w=e.interceptors.response).eject)==null||b.call(w,d)})}function ya(t){return ba(t)&&t.isAxiosError===!0}function ba(t){return t!==null&&typeof t=="object"}var be;(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"})(be||(be={}));class vs{constructor(e=[],s,n){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,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:s}=this.writeHeaders(),n={headers:e,body:this.method==="GET"?JSON.stringify(this.getData):this.requestData},i={headers:s,body:this.response},r=this.sanitize({url:this.url,method:this.method,status:this.status,request:n,response:i});if(r)return vt(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(([n,i])=>{this.isHeaderIgnored(n)||(e[n]=i)}),this.setSessionTokenHeader((n,i)=>{e[n]=i});const s={};return Object.entries(this.header).forEach(([n,i])=>{this.isHeaderIgnored(n)||(s[n]=i)}),{reqHs:e,resHs:s}}isHeaderIgnored(e){return Array.isArray(this.ignoredHeaders)?this.ignoredHeaders.map(s=>s.toLowerCase()).includes(e.toLowerCase()):this.ignoredHeaders}}const et=(t,e)=>{let s="";switch(t){case"":case"text":case"json":typeof e=="string"?s=e:bs(e)||Array.isArray(e)?s=JSON.stringify(e):typeof e<"u"&&(s=Object.prototype.toString.call(e));break;case"blob":case"document":case"arraybuffer":default:typeof e<"u"&&(s=Object.prototype.toString.call(e));break}return s},ys=t=>{if(!t)return null;let e;if(typeof t=="string"){(t[0]==="{"||t[0]==="[")&&(e=t);const s=t.split("&");s.length===1?e=t:e=s.join(",")}else if(wa(t)){const s=[];for(const[n,i]of t)s.push(`${n}=${typeof i=="string"?i:"[object Object]"}`);e=s.join(",")}else t instanceof Blob||t instanceof ReadableStream||t instanceof ArrayBuffer?e="byte data":bs(t)?e=t:e=`can't parse body ${typeof t}`;return e},Sa=(t,e={})=>{bs(e)||(e={});let s=t?t.split("?"):[];if(s.shift(),s.length>0){s=s.join("?").split("&");for(const n of s){const i=n.split("=");try{e[i[0]]=decodeURIComponent(i[1])}catch{e[i[0]]=i[1]}}}return e};function bs(t){return t!==null&&typeof t=="object"}function wa(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 Ss=t=>(t.startsWith("//")&&(t=`${new URL(window.location.href).protocol}${t}`),t.startsWith("http")?new URL(t):new URL(t,window.location.href));class xa{constructor(e,s){this.resp=e,this.item=s,this.mockReader()}set(e,s,n){return Reflect.set(e,s,n)}get(e,s){const n=Reflect.get(e,s);switch(s){case"arrayBuffer":case"blob":case"formData":case"json":case"text":return()=>(this.item.responseType=s.toLowerCase(),n.apply(e).then(i=>(this.item.response=et(this.item.responseType,i),i)))}return typeof n=="function"?n.bind(e):n}mockReader(){let e;if(!this.resp.body||typeof this.resp.body.getReader!="function")return;const s=this.resp.body.getReader;this.resp.body.getReader=()=>{const n=s.apply(this.resp.body);if(this.item.readyState===be.DONE)return n;const i=n.read,r=n.cancel;return this.item.responseType="arraybuffer",n.read=()=>i.apply(n).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=et(this.item.responseType,e)),o}),n.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=et(this.item.responseType,e),r.apply(n,o)),n}}}class ka{constructor(e,s,n,i,r,o){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,this.sendMessage=i,this.isServiceUrl=r,this.tokenUrlMatcher=o}apply(e,s,n){const i=n[0],r=n[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,n);const l=new vs(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);return this.beforeFetch(l,i,r),this.setSessionTokenHeader((a,u)=>{if(!(this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(l.url))){if(n[1]===void 0&&n[0]instanceof Request)return n[0].headers.append(a,u);n[1]||(n[1]={}),n[1].headers===void 0&&(n[1]={...n[1],headers:{}}),n[1].headers instanceof Headers?n[1].headers.append(a,u):Array.isArray(n[1].headers)?n[1].headers.push([a,u]):n[1].headers[a]=u}}),e.apply(window,n).then(this.afterFetch(l)).catch(a=>{throw l.endTime=performance.now(),l.duration=l.endTime-(l.startTime||l.endTime),a})}beforeFetch(e,s,n){let i,r="GET",o={};if(typeof s=="string"?(r=(n==null?void 0:n.method)||"GET",i=Ss(s),o=(n==null?void 0:n.headers)||{}):(r=s.method||"GET",i=Ss(s.url),o=s.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}n!=null&&n.body&&(e.requestData=ys(n.body))}afterFetch(e){return s=>{e.endTime=performance.now(),e.duration=e.endTime-(e.startTime||e.endTime),e.status=s.status,e.statusText=String(s.status);let n=!1;e.header={};for(const[i,r]of s.headers)e.header[i]=r,n=r.toLowerCase().indexOf("chunked")>-1?!0:n;return n?e.readyState=3:(e.readyState=4,this.handleResponseBody(s.clone(),e).then(i=>{e.responseSize=typeof i=="string"?i.length:i.byteLength,e.responseSizeText=Nt(e.responseSize),e.response=et(e.responseType,i);const r=e.getMessage();r&&this.sendMessage(r)}).catch(i=>{if(i.name!=="AbortError")throw i})),new Proxy(s,new xa(s,e))}}handleResponseBody(e,s){const n=e.headers.get("content-type");return n&&n.includes("application/json")?(s.responseType="json",e.text()):n&&(n.includes("text/html")||n.includes("text/plain"))?(s.responseType="text",e.text()):(s.responseType="arraybuffer",e.arrayBuffer())}}class Ta{static create(e,s,n,i,r,o){return new Proxy(fetch,new ka(e,s,n,i,r,o))}}class Ea{constructor(e,s,n,i,r,o,l){this.ignoredHeaders=s,this.setSessionTokenHeader=n,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 vs(s,n,i),this.item.requestType="xhr"}get(e,s){switch(s){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 n=Reflect.get(e,s);return typeof n=="function"?n.bind(e):n}}set(e,s,n){switch(s){case"onreadystatechange":return this.setOnReadyStateChange(e,s,n);case"onabort":return this.setOnAbort(e,s,n);case"ontimeout":return this.setOnTimeout(e,s,n)}return Reflect.set(e,s,n)}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=et(this.item.responseType,this.item.response)},0),this.XMLReq.readyState===be.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 s=Reflect.get(e,"open");return(...n)=>{var o,l;const i=n[0],r=n[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=Sa(this.item.url,{}),s.apply(e,n)}}getSend(e){const s=Reflect.get(e,"send");return(...n)=>{const i=n[0];return this.item.requestData=ys(i),s.apply(e,n)}}getSetRequestHeader(e){const s=Reflect.get(e,"setRequestHeader");return(...n)=>(this.item.requestHeader||(this.item.requestHeader={}),this.item.requestHeader[n[0]]=n[1],s.apply(e,n))}setOnReadyStateChange(e,s,n){return Reflect.set(e,s,(...i)=>{this.onReadyStateChange(),n==null||n.apply(e,i)})}setOnAbort(e,s,n){return Reflect.set(e,s,(...i)=>{this.onAbort(),n.apply(e,i)})}setOnTimeout(e,s,n){return Reflect.set(e,s,(...i)=>{this.onTimeout(),n.apply(e,i)})}updateItemByReadyState(){switch(this.XMLReq.readyState){case be.UNSENT:case be.OPENED:this.item.status=be.UNSENT,this.item.statusText="Pending",this.item.startTime||(this.item.startTime=performance.now());break;case be.HEADERS_RECEIVED:this.item.status=this.XMLReq.status,this.item.statusText="Loading",this.item.header={};const e=this.XMLReq.getAllResponseHeaders()||"",s=e.split(`
646
- `);for(let n=0;n<s.length;n++){const i=s[n];if(!i)continue;const r=i.split(": "),o=r[0];this.item.header[o]=r.slice(1).join(": ")}break;case be.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 be.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 Ca{static create(e,s,n,i,r,o){return new Proxy(XMLHttpRequest,{construct(l){const a=new l;return new Proxy(a,new Ea(a,e,s,n,i,r,o))}})}}const Ia=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 _a{constructor(e,s,n,i,r){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,this.sendMessage=i,this.isServiceUrl=r}apply(e,s,n){const i=n[0],r=n[1],o=new vs(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);if(this.isServiceUrl(i))return e.apply(s,n);const l=Ss(i);if(o.method="POST",o.url=i,o.name=(l.pathname.split("/").pop()||"")+l.search,o.requestType="beacon",o.requestHeader={"Content-Type":Ia(r)},o.status=0,o.statusText="Pending",l.search&&l.searchParams){o.getData={};for(const[c,d]of l.searchParams)o.getData[c]=d}o.requestData=ys(r),o.startTime||(o.startTime=performance.now());const a=e.apply(s,n);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 u=o.getMessage();return u&&this.sendMessage(u),a}}class Ve{static hasSendBeacon(){return!!Ve.origSendBeacon}static create(e,s,n,i,r){if(Ve.hasSendBeacon())return new Proxy(Ve.origSendBeacon,new _a(e,s,n,i,r))}}Ve.origSendBeacon=(bi=window==null?void 0:window.navigator)==null?void 0:bi.sendBeacon;const gi=t=>console.warn(`Openreplay: Can't find ${t} in global context.
647
- If you're using serverside rendering in your app, make sure that tracker is loaded dynamically, otherwise ${t} won't be tracked.`);function Oa(t,e,s,n,i,r,o){var l;t.XMLHttpRequest?t.XMLHttpRequest=Ca.create(e,s,n,i,r,o):gi("XMLHttpRequest"),t.fetch?t.fetch=Ta.create(e,s,n,i,r,o):gi("fetch"),(l=t==null?void 0:t.navigator)!=null&&l.sendBeacon&&(t.navigator.sendBeacon=Ve.create(e,s,n,i,r))}function ws(t){return t.__or_req_data__||(t.__or_req_data__={body:void 0,headers:{}}),t.__or_req_data__}function mi(t){return typeof t=="string"?t.toUpperCase():"GET"}function Na(t,e={}){const s=Object.assign({failuresOnly:!1,ignoreHeaders:["cookie","set-cookie","authorization"],capturePayload:!1,sessionTokenHeader:!1,captureInIframes:!0,axiosInstances:void 0,useProxy:!0},e);s.useProxy===!1&&t.debug.warn("Network module is migrating to proxy api, to gradually migrate and test it set useProxy to true");const n=s.ignoreHeaders,i=Array.isArray(n)?c=>n.includes(c):()=>n,r=s.sessionTokenHeader===!0?"X-OpenReplay-SessionToken":s.sessionTokenHeader;function o(c){if(r){const d=t.getSessionToken();d&&t.safe(c)(r,d)}}function l(c){if(s.capturePayload||(delete c.request.body,delete c.response.body),s.sanitizer){const d=c.response.body;if(typeof d=="string")try{c.response.body=JSON.parse(d)}catch{}return s.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 u=c=>{if(s.useProxy)return Oa(c,s.ignoreHeaders,o,l,A=>t.send(A),A=>t.isServiceURL(A),s.tokenUrlMatcher);const d=c.fetch.bind(c),p=(A,k={})=>{if(!(typeof A=="string"||A instanceof URL)||t.isServiceURL(String(A)))return d(A,k);o(function(N,F){k.headers===void 0&&(k.headers={}),k.headers instanceof Headers?k.headers.append(N,F):Array.isArray(k.headers)?k.headers.push([N,F]):k.headers[N]=F});const O=performance.now();return d(A,k).then(N=>{const F=performance.now()-O;if(s.failuresOnly&&N.status<400)return N;const C=N.clone();return C.text().then(E=>{const P={},V={};if(n!==!0){const I=([M,q])=>{i(M)||(P[M]=q)};k.headers instanceof Headers?k.headers.forEach((M,q)=>I([q,M])):Array.isArray(k.headers)?k.headers.forEach(I):typeof k.headers=="object"&&Object.entries(k.headers).forEach(I),C.headers.forEach((M,q)=>{i(q)||(V[q]=M)})}const j=mi(k.method),W=l({url:String(A),method:j,status:C.status,request:{headers:P,body:k.body||null},response:{headers:V,body:E}});W&&t.send(vt("fetch",j,String(W.url),a(W.request),a(W.response),C.status,O+ze(),F,0))}).catch(E=>t.debug.error("Could not process Fetch response:",E)),N})};c.fetch=p;const y=c.XMLHttpRequest.prototype.open,w=c.XMLHttpRequest.prototype.setRequestHeader,b=c.XMLHttpRequest.prototype.send;function T(A,k){const O=this;o((F,C)=>O.setRequestHeader(F,C));let N=0;return O.addEventListener("loadstart",F=>{N=F.timeStamp}),O.addEventListener("load",t.safe(F=>{const{headers:C,body:E}=ws(O),P=N>0?F.timeStamp-N:0,j=(O.getAllResponseHeaders()||"").trim().split(/[\r\n]+/),W={};j.forEach(function(q){const G=q.split(": "),H=G.shift();i(H)||(W[H]=G.join(": "))});const I=mi(A),M=l({url:String(k),method:I,status:O.status,request:{headers:C,body:E||null},response:{headers:W,body:O.response}});M&&t.send(vt("xhr",I,String(M.url),a(M.request),a(M.response),O.status,N+ze(),P,0))})),y.apply(this,arguments)}function D(A){const k=ws(this);return k.body=A,b.apply(this,arguments)}function B(A,k){if(!i(A)){const O=ws(this);O.headers[A]=k}return w.apply(this,arguments)}s.axiosInstances||(c.XMLHttpRequest.prototype.open=T,c.XMLHttpRequest.prototype.send=D,c.XMLHttpRequest.prototype.setRequestHeader=B)};u(window),s.axiosInstances&&s.axiosInstances.forEach(c=>{va(t,c,s,l,a)}),s.captureInIframes&&t.observer.attachContextCallback(t.safe(u))}function Ra(t){t.attachEventListener(document,"selectionchange",()=>{const e=document.getSelection();if(e!==null&&!e.isCollapsed){const s=t.nodes.getID(e.anchorNode),n=t.nodes.getID(e.focusNode),i=e.toString().replace(/\s+/g," ");s&&n&&t.send(Rn(s,n,i))}else t.send(Rn(-1,-1,""))})}function Da(t){function e(){document.hidden||(t.debug.log("Openreplay: tab change to"+t.session.getTabId()),t.send(yt(t.session.getTabId())))}t.attachEventListener(window,"focus",e,!1,!1)}const Rt="/installation/javascript-sdk";function Aa(t){if(t==null)return console.error(`OpenReplay: invalid options argument type. Please, check documentation on ${mt}${Rt}`),!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 ${mt}${Rt} for more information.`),!1;t.projectKey=t.projectID.toString(),_e("`projectID` option","`projectKey` option",Rt)}else console.warn("OpenReplay: projectKey is expected to have a string type."),t.projectKey=t.projectKey.toString();return t.sessionToken!=null&&_e("`sessionToken` option","`sessionHash` start() option","/"),!0}class Fa{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,u)=>{const c=this.checkDoNotTrack(),d=new XMLHttpRequest,p=this.options.ingestPoint||Gn;d.open("POST",p+"/v1/web/not-started"),d.send(JSON.stringify({trackerVersion:"14.0.4",projectKey:this.options.projectKey,doNotTrack:c,reason:u.length?`missing api: ${u.join(",")}`:a}))},this.restartCanvasTracking=()=>{this.app!==null&&this.app.restartCanvasTracking()},this.handleError=(a,u={})=>{if(this.app!==null){if(a instanceof Error){const c=Tt(a,[],u);this.app.send(c)}else if(a instanceof ErrorEvent||"PromiseRejectionEvent"in window&&a instanceof PromiseRejectionEvent){const c=ei(a,void 0,u);c!=null&&this.app.send(c)}}},this.crossdomainMode=!!(ar()&&((l=e.crossdomain)!=null&&l.enabled)),!ve||!Aa(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 s=this.checkDoNotTrack(),n=[],i=["Map","Set","MutationObserver","performance","timing","startsWith","Blob","Worker"];if(s)n.push("doNotTrack");else for(const a of i)if(a==="timing"){if("performance"in window&&!(a in performance)){n.push(a);break}}else if(a==="startsWith"){if(!(a in String.prototype)){n.push(a);break}}else if(!(a in window)){n.push(a);break}if(n.length>0){const a=n.join(",");console.error(`OpenReplay: browser doesn't support API required for tracking or doNotTrack is set to 1. Reason: ${a}`),this.signalStartIssue("missing_api",n);return}const r=new Ro(e.projectKey,e.sessionToken,e,this.signalStartIssue,this.crossdomainMode);this.app=r,this.crossdomainMode||(ha(r),Do(r),$r(r,e),Da(r)),oa(r,e.mouse),ua(r,this.crossdomainMode),pa(r),fa(r),Lo(r,e),Uo(r,e),Wo(r),Ko(r,e),la(r,e),ga(r),ma(r),Na(r,e.network),Ra(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(),u=r.sessionStorage??window.sessionStorage;window.open=function(...c){return e.autoResetOnWindowOpen&&r.resetNextPageSession(!0),e.resetTabOnWindowOpen&&u.removeItem(e.session_tabid_key||"__openreplay_tabid"),r.resetNextPageSession(!1),u.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 s;(s=this.app)==null||s.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 s;return(s=this.app)==null?void 0:s.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 ve?!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 ${mt}${Rt}`),!1)}coldStart(e,s){if(this.browserEnvCheck()){if(this.app===null)return Promise.reject("Tracker not initialized");this.app.coldStart(e,s)}else return Promise.reject("Trying to start not in browser.")}startOfflineRecording(e,s){return this.browserEnvCheck()?this.app===null?Promise.reject("Tracker not initialized"):this.app.offlineRecording(e,s):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 _e("'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){_e("'userID' method","'setUserID' method","/"),this.setUserID(e)}setUserAnonymousID(e){typeof e=="string"&&this.app!==null&&this.app.send(_r(e))}userAnonymousID(e){_e("'userAnonymousID' method","'setUserAnonymousID' method","/"),this.setUserAnonymousID(e)}setMetadata(e,s){typeof e=="string"&&typeof s=="string"&&this.app!==null&&this.app.session.setMetadata(e,s)}metadata(e,s){_e("'metadata' method","'setMetadata' method","/"),this.setMetadata(e,s)}event(e,s=null,n=!1){if(typeof e=="string"&&this.app!==null){if(n)return this.issue(e,s);try{s=JSON.stringify(s)}catch{return}this.app.send(Cr(e,s))}}issue(e,s=null){if(typeof e=="string"&&this.app!==null){try{s=JSON.stringify(s)}catch{return}this.app.send(Fr(e,s))}}}const Ma=["climats","telckel","biobio","weinpoint","vinigrandi"],La="bMTFzLbWcXFgXK8SzyFHA6kIjelFcz5VQABVPbXdXh5XZJCDQH9BcVlrv3DF3kA";class xs{constructor(e){var s;this.baseURL="https://wineater-backend.vercel.app/",this.store=Ma.find(n=>window.location.href.includes(n)),this.token=((s=window==null?void 0:window.wineaterData)==null?void 0:s.CLIENT_TOKEN)||La}async getStoreConfig(e){console.log(e);try{const s=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(s),!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);return await s.json()}catch(s){throw console.error("Error fetching store configuration:",s),s}}async getWineRecommendations(e){console.log(window.location.href);try{const s=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})}),n=await s.json();if(!s.ok)throw new Error(`API call failed with status ${s.status}: ${n.message||"No additional error information"}`);return n}catch(s){throw console.error("Fetching wine recommendations failed:",s.message),new Error(`Error in getWineRecommendations: ${s.message}`)}}async getPossibleDishesWithMeta(e,s){try{const n=await fetch(`${this.baseURL}dish/possible_dishes`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:e,description:s})}),i=await n.json();if(console.log(i),!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("Error fetching possible dishes:",n),n}}}class Pa{constructor(){this.api=new xs,this.language="en",this.translations={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"},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"},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"},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"}}}async fetchConfig(e){console.log(e);try{const s=await this.api.getStoreConfig(e);console.log(s),this.language=s.lang}catch{this.language="en"}console.log(this.language)}translate(e){return this.translations[this.language][e]||e}}const ie=new Pa,Ba=3;let Dt=null;function ks(){const t=document.getElementById("chat-window"),e=document.getElementById("chat-icon");t.classList.contains("visible")?(Ks(),Ts(),e.style.display="flex"):(Dt&&(clearTimeout(Dt),Dt=null),Gs(),t.classList.add("visible"),e.style.display="none")}function Ts(){console.log("ghbdtn"),Ks(),document.getElementById("chat-window").classList.remove("visible");let e=parseInt(te("chatCloseCount"))||0;e+=1,e>=Ba?(console.log(e),ot("disableAutoOpen","true",1),Di("chatCloseCount")):(console.log(e),ot("chatCloseCount",e,1))}function ja(t){const e=document.getElementById("chat-window"),s=document.getElementById("message-container"),n=document.querySelector("#input-container input");s.innerHTML="",e.classList.add("visible");const i=document.createElement("div");i.className="message api",i.textContent=ie.translate("winePairingIntro"),s.appendChild(i),t.slice(0,3).forEach(o=>{const l=document.createElement("div");l.className="message dish-message",l.textContent=o,l.addEventListener("click",()=>{n.value=o}),s.appendChild(l)});const r=document.createElement("div");r.className="message api",r.textContent=ie.translate("askForDinner"),s.appendChild(r),s.scrollTop=s.scrollHeight}function vi(t=null){t?Fi(t):Gs(),document.getElementById("chat-window").classList.add("visible")}document.addEventListener("DOMContentLoaded",()=>{setupCloseButton(),setupOutsideClick()});function Ua(t){Dt=t}class Ha{constructor(){var s;this.api=new xs;const e=((s=window==null?void 0:window.wineaterData)==null?void 0:s.FIRST_MESSAGE_TEXT)||ie.translate("welcomeMessage");this.displayFirstMessage(e)}initialize(){document.getElementById("send-button").addEventListener("click",()=>this.handleUserInput()),document.getElementById("user-input").addEventListener("keypress",n=>{n.key==="Enter"&&this.handleUserInput()})}displayFirstMessage(e,s="api"){const n=document.getElementById("message-container"),i=document.createElement("div");i.className=`message ${s}`,i.textContent=e,n.appendChild(i),n.scrollTop=n.scrollHeight}async handleUserInput(){const e=document.getElementById("user-input"),s=e.value.trim();if(s){this.displayMessage(s,"user"),e.value="",this.showTypingIndicator();try{Mi(s);const n=await this.api.getWineRecommendations(s);this.hideTypingIndicator(),n&&n.length?this.displayResults(n):this.displayMessage("No results found.","api")}catch{this.hideTypingIndicator(),this.displayMessage(ie.translate("somethingWentWrong"),"api")}}}showTypingIndicator(){document.getElementById("typing-indicator").classList.add("visible")}hideTypingIndicator(){document.getElementById("typing-indicator").classList.remove("visible")}displayMessage(e,s){const n=document.getElementById("message-container"),i=document.createElement("div");i.textContent=e,i.className="message "+s,n.appendChild(i),n.scrollTop=n.scrollHeight}sendAnalytics(e){console.log(e),Pi(e)}displayResults(e){console.log(e);const s=document.getElementById("message-container");Li(e.map(n=>n.Title)),e.forEach(n=>{const i=document.createElement("div");i.className="wine-recommendation";const r=document.createElement("div");r.className="wine-item",i.appendChild(r);const o=document.createElement("img");o.src=n.Image,r.appendChild(o),console.log(r,"wine div");const l=document.createElement("div");l.innerHTML=`
654
+ `).length?this.parseOpera9(a):a.stack?this.parseOpera11(a):this.parseOpera10(a)},parseOpera9:function(a){for(var h=/Line (\d+).*script (?:in )?(\S+)/i,c=a.message.split(`
655
+ `),d=[],p=2,y=c.length;p<y;p+=2){var w=h.exec(c[p]);w&&d.push(new n({fileName:w[2],lineNumber:w[1],source:c[p]}))}return d},parseOpera10:function(a){for(var h=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,c=a.stacktrace.split(`
656
+ `),d=[],p=0,y=c.length;p<y;p+=2){var w=h.exec(c[p]);w&&d.push(new n({functionName:w[3]||void 0,fileName:w[2],lineNumber:w[1],source:c[p]}))}return d},parseOpera11:function(a){var h=a.stack.split(`
657
+ `).filter(function(c){return!!c.match(i)&&!c.match(/^Error created at/)},this);return h.map(function(c){var d=c.split("@"),p=this.extractLocation(d.pop()),y=d.shift()||"",w=y.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,b;y.match(/\(([^)]*)\)/)&&(b=y.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var T=b===void 0||b==="[arguments not available]"?void 0:b.split(",");return new n({functionName:w,args:T,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:c})},this)}}})})(Yn);var Wo=Yn.exports;const $o=Xs(Wo);function Zn(t){return[{columnNumber:t.colno,lineNumber:t.lineno,fileName:t.filename,functionName:"",source:""}]}function Tt(t,e,s={}){let n=e;try{n=$o.parse(t)}catch{}return Yt(t.name,t.message,JSON.stringify(n),JSON.stringify(s))}function ei(t,e=window,s={}){if(t instanceof ErrorEvent){if(t.error instanceof Error)return Tt(t.error,Zn(t),s);{let[n,i]=t.message.split(":");return i||(n="Error",i=t.message),Yt(n,i,JSON.stringify(Zn(t)),JSON.stringify(s))}}else if("PromiseRejectionEvent"in e&&t instanceof e.PromiseRejectionEvent){if(t.reason instanceof Error)return Tt(t.reason,[],s);{let n;try{n=JSON.stringify(t.reason)}catch{n=String(t.reason)}return Yt("Unhandled Promise Rejection",n,"[]",JSON.stringify(s))}}return null}function qo(t,e){const s=Object.assign({captureExceptions:!0},e);function n(i){function r(o){const l=ei(o,i);l!=null&&t.send(l)}t.attachEventListener(i,"unhandledrejection",r),t.attachEventListener(i,"error",r)}s.captureExceptions&&(t.observer.attachContextCallback(n),n(window))}function ti(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 Vo(t){return cr&&(t.startsWith("data:image/svg+xml")||t.match(/.svg$|/i))}const Go="https://static.openreplay.com/tracker/placeholder.jpeg";function Ko(t){function e(l,a){t.attributeSender.sendSetAttribute(l,"src",Go);const{width:h,height:c}=a.getBoundingClientRect();a.hasAttribute("width")||t.attributeSender.sendSetAttribute(l,"width",String(h)),a.hasAttribute("height")||t.attributeSender.sendSetAttribute(l,"height",String(c))}const s=function(l,a){const{srcset:h}=a;if(!h)return;const c=h.split(h.match(/,\s+/)?/,\s+/:",").map(d=>ti(d)).join(", ");t.attributeSender.sendSetAttribute(l,"srcset",c)},n=function(l,a){a.src.length>lr&&e(l,a),t.send(Kt(l,"src",a.src,t.getBaseHref()))},i=t.safe(function(l){const a=ti(l.src||"");vn(a)&&t.send(Dn(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&&!Vo(l.src)?i(l):t.sanitizer.isHidden(a)||t.sanitizer.isObscured(a)?e(a,l):(n(a,l),s(a,l)))}),o=Sn(t.safe(l=>{for(const a of l)if(a.type==="attributes"){const h=a.target,c=t.nodes.getID(h);if(c===void 0)return;a.attributeName==="src"&&n(c,h),a.attributeName==="srcset"&&s(c,h)}}));t.attachStopCallback(()=>{o.disconnect()}),t.nodes.attachNodeCallback(l=>{Y(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 Xo=["text","password","email","search","number","range","date","tel","time"];function Jo(t){return Y(t,"textarea")?!0:Y(t,"input")?Xo.includes(t.type):!1}function Yo(t){if(!Y(t,"input"))return!1;const e=t.type;return e==="checkbox"||e==="radio"}const Qo=ve&&"labels"in HTMLInputElement.prototype?t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Y(e,"label"))return e;const s=t.labels;if(s!==null&&s.length===1)return s[0]}:t=>{let e=t;for(;(e=e.parentNode)!==null;)if(Y(e,"label"))return e;const s=t.id;if(s){const n=t.ownerDocument.querySelectorAll('label[for="'+s+'"]');if(n!==null&&n.length===1)return n[0]}};function si(t){let e=Vt(t);if(e===null){const s=Qo(t);e=s&&s.innerText||t.placeholder||t.name||t.id||t.className||t.type}return mn(e).slice(0,100)}const qe={Plain:0,Obscured:1,Hidden:2};function Zo(t,e){const s=Object.assign({obscureInputNumbers:!0,obscureInputEmails:!0,defaultInputMode:qe.Obscured,obscureInputDates:!1},e);function n(c,d){let p=d.value,y=s.defaultInputMode;d.type==="password"||t.sanitizer.isHidden(c)?y=qe.Hidden:(t.sanitizer.isObscured(c)||y===qe.Plain&&(s.obscureInputNumbers&&d.type!=="date"&&/\d\d\d\d/.test(p)||s.obscureInputDates&&d.type==="date"||s.obscureInputEmails&&(d.type==="email"||~p.indexOf("@"))))&&(y=qe.Obscured);let w=0;switch(y){case qe.Hidden:w=-1,p="";break;case qe.Obscured:w=p.length,p="";break}return{value:p,mask:w}}function i(c,d){const{value:p,mask:y}=n(c,d);t.send(Er(c,p,y))}const r=new Map,o=new Map;t.attachStopCallback(()=>{r.clear(),o.clear()});function l(c,d){r.get(c)!==d.value&&(r.set(c,d.value),i(c,d))}function a(c,d){o.get(c)!==d&&(o.set(c,d),t.send(Cr(c,d)))}t.ticker.attach(()=>{r.forEach((c,d)=>{const p=t.nodes.getNode(d);if(!p)return r.delete(d);l(d,p)}),o.forEach((c,d)=>{const p=t.nodes.getNode(d);if(!p)return o.delete(d);a(d,p.checked)})},3);function h(c,d,p,y){const{value:w,mask:b}=n(c,d),T=si(d);t.send(Wr(c,w,b!==0,T,p,y))}t.nodes.attachNodeCallback(t.safe(c=>{const d=t.nodes.getID(c);if(d!==void 0){if(Y(c,"select")&&(i(d,c),t.nodes.attachNodeListener(c,"change",()=>i(d,c))),Jo(c)){l(d,c);let p=0,y=0,w=0;const b=()=>{p=pe()},T=()=>{y===0&&p!==0&&(y=pe()-p)},D=()=>{p!==0&&(w=pe()-p),h(d,c,y,w),y=0,w=0,p=0};t.nodes.attachNodeListener(c,"focus",b),t.nodes.attachNodeListener(c,"input",T),t.nodes.attachNodeListener(c,"change",D);return}if(Yo(c)){a(d,c.checked),t.nodes.attachNodeListener(c,"change",()=>a(d,c.checked));return}}}))}let le,fs,ni;function ea(t,e){if(ni=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 s={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};le={...s,...e},fs=ta(le.root,s);let n=Et(t,"all",()=>Et(t,"two",()=>Et(t,"one",()=>Et(t,"none"))));if(n){const i=li(hi(n,t));return i.length>0&&(n=i[0]),Ct(n)}else throw new Error("Selector was not found.")}function ta(t,e){return t.nodeType===Node.DOCUMENT_NODE?t:t===e.root?t.ownerDocument:t}function Et(t,e,s){let n=null,i=[],r=t,o=0;for(;r;){const l=new Date().getTime()-ni.getTime();if(le.timeoutMs!==void 0&&l>le.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${l}ms`);let a=_t(sa(r))||_t(...na(r))||_t(...ia(r))||_t(ra(r))||[ai()];const h=oa(r);if(e=="all")h&&(a=a.concat(a.filter(ps).map(c=>It(c,h))));else if(e=="two")a=a.slice(0,1),h&&(a=a.concat(a.filter(ps).map(c=>It(c,h))));else if(e=="one"){const[c]=a=a.slice(0,1);h&&ps(c)&&(a=[It(c,h)])}else e=="none"&&(a=[ai()],h&&(a=[It(a[0],h)]));for(let c of a)c.level=o;if(i.push(a),i.length>=le.seedMinLength&&(n=ii(i,s),n))break;r=r.parentElement,o++}return n||(n=ii(i,s)),!n&&s?s():n}function ii(t,e){const s=li(ci(t));if(s.length>le.threshold)return e?e():null;for(let n of s)if(oi(n))return n;return null}function Ct(t){let e=t[0],s=e.name;for(let n=1;n<t.length;n++){const i=t[n].level||0;e.level===i-1?s=`${t[n].name} > ${s}`:s=`${t[n].name} ${s}`,e=t[n]}return s}function ri(t){return t.map(e=>e.penalty).reduce((e,s)=>e+s,0)}function oi(t){const e=Ct(t);switch(fs.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 sa(t){const e=t.getAttribute("id");return e&&le.idName(e)?{name:"#"+CSS.escape(e),penalty:0}:null}function na(t){return Array.from(t.attributes).filter(s=>le.attr(s.name,s.value)).map(s=>({name:`[${CSS.escape(s.name)}="${CSS.escape(s.value)}"]`,penalty:.5}))}function ia(t){return Array.from(t.classList).filter(le.className).map(s=>({name:"."+CSS.escape(s),penalty:1}))}function ra(t){const e=t.tagName.toLowerCase();return le.tagName(e)?{name:e,penalty:2}:null}function ai(){return{name:"*",penalty:3}}function oa(t){const e=t.parentNode;if(!e)return null;let s=e.firstChild;if(!s)return null;let n=0;for(;s&&(s.nodeType===Node.ELEMENT_NODE&&n++,s!==t);)s=s.nextSibling;return n}function It(t,e){return{name:t.name+`:nth-child(${e})`,penalty:t.penalty+1}}function ps(t){return t.name!=="html"&&!t.name.startsWith("#")}function _t(...t){const e=t.filter(aa);return e.length>0?e:null}function aa(t){return t!=null}function*ci(t,e=[]){if(t.length>0)for(let s of t[0])yield*ci(t.slice(1,t.length),e.concat(s));else yield e}function li(t){return[...t].sort((e,s)=>ri(e)-ri(s))}function*hi(t,e,s={counter:0,visited:new Map}){if(t.length>2&&t.length>le.optimizedMinLength)for(let n=1;n<t.length-1;n++){if(s.counter>le.maxNumberOfTries)return;s.counter+=1;const i=[...t];i.splice(n,1);const r=Ct(i);if(s.visited.has(r))return;oi(i)&&ca(i,e)&&(yield i,s.visited.set(r,!0),yield*hi(i,e,s))}}function ca(t,e){return fs.querySelector(Ct(t))===e}function la(t,e,s){return ea(t,{root:e.body,seedMinLength:3,optimizedMinLength:(s==null?void 0:s.minSelectorDepth)||2,threshold:(s==null?void 0:s.nthThreshold)||1e3,maxNumberOfTries:(s==null?void 0:s.maxOptimiseTries)||1e4})}function gs(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 ui(t,e){return t instanceof Element?ha(t,e):null}function ha(t,e){let s=t;for(;s!==null&&s!==e.documentElement;){if(De(s,"masked"))return null;s=s.parentElement}if(ns(t)){let n=t.ownerSVGElement;for(;n!==null;)t=n,n=n.ownerSVGElement}for(s=t;s!==null&&s!==e.documentElement;){const n=s.tagName.toUpperCase();if(n==="LABEL")return null;if(n==="INPUT"||gs(s)||Vt(s)!==null)return s;s=s.parentElement}return t===e.documentElement?null:t}function ua(t,e){const{disableClickmaps:s=!1}=e||{};function n(k){const O=Vt(k);if(O!==null)return O;if(Y(k,"input"))return si(k);if(gs(k)){let N="";return k instanceof HTMLElement&&(N=t.sanitizer.getInnerTextSecure(k)),N=N||k.id||k.className,mn(N).slice(0,100)}return""}let i=-1,r=-1,o=!1,l=null,a=0,h={},c=0,d=0,p=0,y=0,w;const b=.008,T=225;function D(){const k=y/T;if(!c){c=k;return}const O=(k-c)/T;p>4&&O>b&&t.send($r(pe())),y=0,p=0,c=k}t.attachStartCallback(()=>{w=setInterval(()=>D(),T)}),t.attachStopCallback(()=>{i=-1,r=-1,o=!1,l=null,h={},w&&clearInterval(w)});const B=()=>{o&&(t.send(Ir(i,r)),o=!1)},A=(k,O=!1)=>{function N(C,E,P){return h[C]=h[C]||la(E,k,P)}const F=O?t.attachEventListener.bind(t):t.nodes.attachNodeListener.bind(t.nodes);F(k.documentElement,"mouseover",C=>{const E=ui(C.target,k);E!==l&&(l=E,a=performance.now())}),F(k,"mousemove",C=>{const[E,P]=t.observer.getDocumentOffset(k);i=C.clientX+E,r=C.clientY+P,o=!0;const V=Math.sign(C.movementX);y+=Math.abs(C.movementX)+Math.abs(C.movementY),V!==d&&(d=V,p++)},!1),F(k,"click",C=>{const E=ui(C.target,k);if(!C.clientX&&!C.clientY||E===null)return;const P=t.nodes.getID(E);if(P!==void 0){const V=C.pageX,j=C.pageY,W=k.documentElement.scrollWidth,I=k.documentElement.scrollHeight,M=di(V/W),q=di(j/I);B(),t.send(Ur(P,l===E?Math.round(performance.now()-a):0,n(E),gs(E)&&!s?N(P,E,e):"",M,q),!0)}l=null})};t.nodes.attachNodeCallback(k=>{wt(k)&&A(k)}),A(document,!0),t.ticker.attach(B,(e==null?void 0:e.trackingOffset)||7)}function di(t){return Math.round(t*1e4)}function da(t){const e=[],s=document.getElementsByTagName("*"),n=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let i=0;i<s.length;i++){const r=s[i];let o="";if(Y(r,"img")&&(o=r.currentSrc||r.src),!o){const w=getComputedStyle(r).getPropertyValue("background-image");if(w){const b=n.exec(w);b!==null&&(o=b[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(),h=Math.max(a.top,0),c=Math.max(a.left,0),d=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(d<=h||p<=c)continue;const y=(d-h)*(p-c);e.push({time:l,area:y})}return e}function fa(t,e){let s=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,n=s*t;for(let i=0;i<e.length;i++){const{time:r,area:o}=e[i];s+=o,n+=o*(r>t?r:t)}return s===0?0:n/s}function pa(t,e){const s=Object.assign({captureResourceTimings:!0,capturePageLoadTimings:!0,capturePageRenderTimings:!0,excludedResourceUrls:[]},e);if("PerformanceObserver"in window||(s.captureResourceTimings=!1),!s.captureResourceTimings)return;let n={};function i(h){var d;if(h.duration<0||!vn(h.name)||t.isServiceURL(h.name))return;n!==null&&(n[h.name]=h.startTime+h.duration);let c=!1;(d=s.excludedResourceUrls)==null||d.forEach(p=>{if(h.name.startsWith(p)){c=!0;return}}),!c&&t.send(Dn(h.startTime+ze(),h.duration,h.responseStart&&h.startTime?h.responseStart-h.startTime:0,h.transferSize>h.encodedBodySize?h.transferSize-h.encodedBodySize:0,h.encodedBodySize||0,h.decodedBodySize||0,h.name,h.initiatorType,h.transferSize,h.responseStatus&&h.responseStatus===304||h.transferSize===0))}const r=new PerformanceObserver(h=>h.getEntries().forEach(i));let o;t.attachStartCallback(function({sessionID:h}){h!==o&&(performance.getEntriesByType("resource").forEach(i),o=h),r.observe({entryTypes:["resource"]})}),t.attachStopCallback(function(){r.disconnect()});let l=0,a=0;if(s.capturePageLoadTimings){let h=!1;t.ticker.attach(()=>{if(!h&&((l===0||a===0)&&performance.getEntriesByType("paint").forEach(c=>{const{name:d,startTime:p}=c;switch(d){case"first-paint":l=p;break;case"first-contentful-paint":a=p;break}}),performance.timing.loadEventEnd||performance.now()>3e4)){h=!0;const{navigationStart:c,requestStart:d,responseStart:p,responseEnd:y,domContentLoadedEventStart:w,domContentLoadedEventEnd:b,loadEventStart:T,loadEventEnd:D}=performance.timing;t.send(Or(d-c||0,p-c||0,y-c||0,w-c||0,b-c||0,T-c||0,D-c||0,l,a))}},30)}if(s.capturePageRenderTimings){let h=0,c=0,d=0,p=null,y=!1;t.ticker.attach(()=>{if(y)return;const w=performance.now();if(n!==null&&(h=Math.max.apply(null,Object.keys(n).map(b=>n[b])),w-h>1e3&&(p=da(n),n=null)),d!==null&&(w-d>50&&(c=w),d=w-c>5e3?null:w),p!==null&&d===null||w>3e4){y=!0,n=null;const b=p===null?0:fa(a||l,p),{domContentLoadedEventEnd:T,navigationStart:D}=performance.timing,B=d===null?Math.max(c,a,T-D||0):0;t.send(Nr(b,a>h?a:h,B))}})}}function ms(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 ga(t,e){let s=!1;const n=new Map;function i(l){Wn(l)&&(ke(l)&&n.set(l,[l.scrollLeft,l.scrollTop]),wt(l)&&n.set(l,ms(l)))}const r=t.safe(()=>{e||t.send(vr(...ms(document)))}),o=t.safe((l,a)=>{const h=t.nodes.getID(a);h!==void 0&&t.send(Tr(h,l[0],l[1]))});t.attachStartCallback(r),t.attachStopCallback(()=>{s=!1,n.clear()}),t.nodes.attachNodeCallback((l,a)=>{a&&(ke(l)&&l.scrollLeft+l.scrollTop>0?n.set(l,[l.scrollLeft,l.scrollTop]):wt(l)&&n.set(l,ms(l))),xt(l)&&t.nodes.attachNodeListener(l,"scroll",h=>{i(h.target)})}),t.attachEventListener(document,"scroll",l=>{const a=l.target;if(a===document){s=!0;return}i(a)}),t.ticker.attach(()=>{s&&(r(),s=!1),n.forEach(o),n.clear()},5,!1)}function ma(t){let e,s,n,i,r=document.referrer;const o=t.safe(()=>{const{URL:h}=document;h!==e&&(e=h,t.send(Kr(e,r,i,document.title)),i=0,r=e)}),l=t.safe(()=>{const{innerWidth:h,innerHeight:c}=window;(h!==s||c!==n)&&(s=h,n=c,t.send(mr(s,n)))}),a=document.hidden===void 0?Function.prototype:t.safe(()=>t.send(Lr(document.hidden)));t.attachStartCallback(()=>{e=null,i=ze(),s=n=-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 fi(t){return xt(t)&&!!t.adoptedStyleSheets}let va=15;function pi(){return va++}const Ot=new Map;function ya(t){if(t===null||!fi(document))return;const e=new Map,s=new Map,n=o=>setTimeout(()=>{let l=t.nodes.getID(o);if(o===document&&(l=0),l===void 0)return;let a=s.get(l);a||(a=[]);const h=[],c=o.adoptedStyleSheets;if(c&&Symbol.iterator in c)for(const d of c){let p=e.get(d);const y=!p;if(p||(p=pi(),e.set(d,p)),a.includes(p)||t.send(Nn(p,l)),y){const w=d.cssRules;for(let b=0;b<w.length;b++)t.send(Jt(p,w[b].cssText,b,t.getBaseHref()))}h.push(p)}if(Symbol.iterator in a)for(const d of a)h.includes(d)||t.send(Hr(d,l));s.set(l,h)},20);function i(o){const l=Object.getOwnPropertyDescriptor(o,"adoptedStyleSheets");l&&Object.defineProperty(o,"adoptedStyleSheets",{...l,set:function(a){const h=l.set.call(this,a);return n(this),h}})}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(h){return l.call(this,h).then(c=>{const d=e.get(this);return d&&t.send(_n(d,h,t.getBaseHref())),c})},o.CSSStyleSheet.prototype.replaceSync=function(h){const c=e.get(this);return c&&t.send(_n(c,h,t.getBaseHref())),a.call(this,h)}};r(window),t.observer.attachContextCallback(t.safe(r)),t.attachStopCallback(()=>{e.clear(),s.clear()}),t.attachStartCallback(()=>{n(document)}),t.nodes.attachNodeCallback(o=>{fi(o)&&n(o)})}function ba(t){if(t===null)return;if(!window.CSSStyleSheet){t.send(Br("no_stylesheet_prototype_in_window",""));return}const e=t.safe((i,r,o)=>{const l=Ot.get(i);l&&(typeof o=="string"?t.send(Jt(l,o,r,t.getBaseHref())):t.send(On(l,r)))}),s=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=Ot.get(o);if(!l){t.debug.warn("No sheedID found for",o,Ot);return}const a=r.cssText,h=o.cssRules,c=Array.from(h).indexOf(r);c>=0?(t.send(Jt(l,a,c,t.getBaseHref())),t.send(On(l,c+1))):t.debug.warn("Rule index not found in",o,r)}),n=t.safe(i=>{const{insertRule:r,deleteRule:o}=i.CSSStyleSheet.prototype,{insertRule:l,deleteRule:a}=i.CSSGroupingRule.prototype;i.CSSStyleSheet.prototype.insertRule=function(h,c=0){return e(this,c,h),r.call(this,h,c)},i.CSSStyleSheet.prototype.deleteRule=function(h){return e(this,h),o.call(this,h)},i.CSSGroupingRule.prototype.insertRule=function(h,c=0){const d=l.call(this,h,c);return s(this),d},i.CSSGroupingRule.prototype.deleteRule=function(h=0){const c=a.call(this,h);return s(this),c}});n(window),t.observer.attachContextCallback(n),t.nodes.attachNodeCallback(i=>{if(!Y(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=pi();Ot.set(o,l),t.send(Nn(l,r));const a=o.cssRules;for(let h=0;h<a.length;h++)e(o,h,a[h].cssText)})}function Sa(t){function e(n){const i=t.nodes.getID(n);i!==void 0&&t.send(In(i))}let s=!1;t.nodes.attachNodeCallback(n=>{Y(n,"body")&&(t.nodes.attachNodeListener(n,"focus",i=>{Wn(i.target)&&(e(i.target),s=!1)}),t.nodes.attachNodeListener(n,"blur",i=>{i.relatedTarget===null&&(s=!0,setTimeout(()=>{s&&t.send(In(-1))},0))}))}),t.attachStartCallback(()=>{let n=document.activeElement;for(;n&&Y(n,"iframe")&&n.contentDocument;)n=n.contentDocument.activeElement;n&&n!==n.ownerDocument.body&&e(n)},!0)}function wa(t){if(!window.FontFace)return;const e=new Map,s=n=>{class i extends n.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],h=e.get(n.document)||[];h.push(a),e.set(n.document,h);const c=n===window?0:t.nodes.getID(n.document);if(c===void 0)return;t.active()&&t.send(Cn(c,...a))}super(...o)}}n.FontFace=i};t.observer.attachContextCallback(s),s(window),t.nodes.attachNodeCallback(t.safe(n=>{if(!wt(n))return;const i=e.get(n);if(!i)return;const r=n.defaultView===window?0:t.nodes.getID(n);r!==void 0&&i.forEach(o=>{t.send(Cn(r,...o))})}))}function xa(t,e,s,n,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:w,method:b,url:T,baseURL:D}=p.config,{data:B,headers:A,status:k,response:O}=p,{data:N,headers:F,status:C}=O||{},E=s.ignoreHeaders,P=Array.isArray(E)?H=>E.includes(H):()=>E;function V(H,v){P(v[0])||(H[v[0]]=v[1])}let j={},W={};y.toJSON?j=y.toJSON():y instanceof Headers?y.forEach((H,v)=>V(j,[v,H])):Array.isArray(y)?y.forEach(H=>V(j,H)):typeof y=="object"&&Object.entries(y).forEach(H=>V(j,H));const I=F||A;I.toJSON?W=I.toJSON():I instanceof Headers?I.forEach((H,v)=>V(W,[v,H])):Array.isArray(I)?I.forEach(H=>V(W,H)):typeof I=="object"&&Object.entries(I).forEach(([H,v])=>{P(H)||(W[H]=v)});const M=n({url:T,method:b||"",status:k||C||0,request:{headers:j,body:w},response:{headers:W,body:N||B}});if(!M){t.debug.log("Openreplay: empty request/response info, skipping");return}const q=p.config.__openreplay_timing,G=performance.now()-q;t.debug.log("Openreplay: final req object",M),t.send(vt("xhr",String(b),String(M.url),i(M.request),i(M.response),M.status,q+ze(),G,0))}function o(p){if(t.debug.log("Openreplay: capturing API request",p),p.__openreplay_timing=performance.now(),s.sessionTokenHeader){const y=typeof s.sessionTokenHeader=="string"?s.sessionTokenHeader:"X-OpenReplay-Session-Token",w=t.getSessionToken();w&&p.headers.set(y,w)}return p}function l(p){return s.failuresOnly||r(p),p}function a(p){return t.debug.log("Openreplay: capturing API request error",p),ka(p)&&p.response?r(p.response):p instanceof Error&&t.send(Tt(p,[])),Promise.reject(p)}function h(p){t.debug.log("Openreplay: failed API request, skipping",p)}const c=e.interceptors.request.use(o,h,{synchronous:!0}),d=e.interceptors.response.use(l,a,{synchronous:!0});t.attachStopCallback(()=>{var p,y,w,b;(y=(p=e.interceptors.request).eject)==null||y.call(p,c),(b=(w=e.interceptors.response).eject)==null||b.call(w,d)})}function ka(t){return Ta(t)&&t.isAxiosError===!0}function Ta(t){return t!==null&&typeof t=="object"}var be;(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"})(be||(be={}));class vs{constructor(e=[],s,n){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,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:s}=this.writeHeaders(),n={headers:e,body:this.method==="GET"?JSON.stringify(this.getData):this.requestData},i={headers:s,body:this.response},r=this.sanitize({url:this.url,method:this.method,status:this.status,request:n,response:i});if(r)return vt(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(([n,i])=>{this.isHeaderIgnored(n)||(e[n]=i)}),this.setSessionTokenHeader((n,i)=>{e[n]=i});const s={};return Object.entries(this.header).forEach(([n,i])=>{this.isHeaderIgnored(n)||(s[n]=i)}),{reqHs:e,resHs:s}}isHeaderIgnored(e){return Array.isArray(this.ignoredHeaders)?this.ignoredHeaders.map(s=>s.toLowerCase()).includes(e.toLowerCase()):this.ignoredHeaders}}const et=(t,e)=>{let s="";switch(t){case"":case"text":case"json":typeof e=="string"?s=e:bs(e)||Array.isArray(e)?s=JSON.stringify(e):typeof e<"u"&&(s=Object.prototype.toString.call(e));break;case"blob":case"document":case"arraybuffer":default:typeof e<"u"&&(s=Object.prototype.toString.call(e));break}return s},ys=t=>{if(!t)return null;let e;if(typeof t=="string"){(t[0]==="{"||t[0]==="[")&&(e=t);const s=t.split("&");s.length===1?e=t:e=s.join(",")}else if(Ca(t)){const s=[];for(const[n,i]of t)s.push(`${n}=${typeof i=="string"?i:"[object Object]"}`);e=s.join(",")}else t instanceof Blob||t instanceof ReadableStream||t instanceof ArrayBuffer?e="byte data":bs(t)?e=t:e=`can't parse body ${typeof t}`;return e},Ea=(t,e={})=>{bs(e)||(e={});let s=t?t.split("?"):[];if(s.shift(),s.length>0){s=s.join("?").split("&");for(const n of s){const i=n.split("=");try{e[i[0]]=decodeURIComponent(i[1])}catch{e[i[0]]=i[1]}}}return e};function bs(t){return t!==null&&typeof t=="object"}function Ca(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 Ss=t=>(t.startsWith("//")&&(t=`${new URL(window.location.href).protocol}${t}`),t.startsWith("http")?new URL(t):new URL(t,window.location.href));class Ia{constructor(e,s){this.resp=e,this.item=s,this.mockReader()}set(e,s,n){return Reflect.set(e,s,n)}get(e,s){const n=Reflect.get(e,s);switch(s){case"arrayBuffer":case"blob":case"formData":case"json":case"text":return()=>(this.item.responseType=s.toLowerCase(),n.apply(e).then(i=>(this.item.response=et(this.item.responseType,i),i)))}return typeof n=="function"?n.bind(e):n}mockReader(){let e;if(!this.resp.body||typeof this.resp.body.getReader!="function")return;const s=this.resp.body.getReader;this.resp.body.getReader=()=>{const n=s.apply(this.resp.body);if(this.item.readyState===be.DONE)return n;const i=n.read,r=n.cancel;return this.item.responseType="arraybuffer",n.read=()=>i.apply(n).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=et(this.item.responseType,e)),o}),n.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=et(this.item.responseType,e),r.apply(n,o)),n}}}class _a{constructor(e,s,n,i,r,o){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,this.sendMessage=i,this.isServiceUrl=r,this.tokenUrlMatcher=o}apply(e,s,n){const i=n[0],r=n[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,n);const l=new vs(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);return this.beforeFetch(l,i,r),this.setSessionTokenHeader((a,h)=>{if(!(this.tokenUrlMatcher!==void 0&&!this.tokenUrlMatcher(l.url))){if(n[1]===void 0&&n[0]instanceof Request)return n[0].headers.append(a,h);n[1]||(n[1]={}),n[1].headers===void 0&&(n[1]={...n[1],headers:{}}),n[1].headers instanceof Headers?n[1].headers.append(a,h):Array.isArray(n[1].headers)?n[1].headers.push([a,h]):n[1].headers[a]=h}}),e.apply(window,n).then(this.afterFetch(l)).catch(a=>{throw l.endTime=performance.now(),l.duration=l.endTime-(l.startTime||l.endTime),a})}beforeFetch(e,s,n){let i,r="GET",o={};if(typeof s=="string"?(r=(n==null?void 0:n.method)||"GET",i=Ss(s),o=(n==null?void 0:n.headers)||{}):(r=s.method||"GET",i=Ss(s.url),o=s.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}n!=null&&n.body&&(e.requestData=ys(n.body))}afterFetch(e){return s=>{e.endTime=performance.now(),e.duration=e.endTime-(e.startTime||e.endTime),e.status=s.status,e.statusText=String(s.status);let n=!1;e.header={};for(const[i,r]of s.headers)e.header[i]=r,n=r.toLowerCase().indexOf("chunked")>-1?!0:n;return n?e.readyState=3:(e.readyState=4,this.handleResponseBody(s.clone(),e).then(i=>{e.responseSize=typeof i=="string"?i.length:i.byteLength,e.responseSizeText=Nt(e.responseSize),e.response=et(e.responseType,i);const r=e.getMessage();r&&this.sendMessage(r)}).catch(i=>{if(i.name!=="AbortError")throw i})),new Proxy(s,new Ia(s,e))}}handleResponseBody(e,s){const n=e.headers.get("content-type");return n&&n.includes("application/json")?(s.responseType="json",e.text()):n&&(n.includes("text/html")||n.includes("text/plain"))?(s.responseType="text",e.text()):(s.responseType="arraybuffer",e.arrayBuffer())}}class Oa{static create(e,s,n,i,r,o){return new Proxy(fetch,new _a(e,s,n,i,r,o))}}class Na{constructor(e,s,n,i,r,o,l){this.ignoredHeaders=s,this.setSessionTokenHeader=n,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 vs(s,n,i),this.item.requestType="xhr"}get(e,s){switch(s){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 n=Reflect.get(e,s);return typeof n=="function"?n.bind(e):n}}set(e,s,n){switch(s){case"onreadystatechange":return this.setOnReadyStateChange(e,s,n);case"onabort":return this.setOnAbort(e,s,n);case"ontimeout":return this.setOnTimeout(e,s,n)}return Reflect.set(e,s,n)}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=et(this.item.responseType,this.item.response)},0),this.XMLReq.readyState===be.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 s=Reflect.get(e,"open");return(...n)=>{var o,l;const i=n[0],r=n[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=Ea(this.item.url,{}),s.apply(e,n)}}getSend(e){const s=Reflect.get(e,"send");return(...n)=>{const i=n[0];return this.item.requestData=ys(i),s.apply(e,n)}}getSetRequestHeader(e){const s=Reflect.get(e,"setRequestHeader");return(...n)=>(this.item.requestHeader||(this.item.requestHeader={}),this.item.requestHeader[n[0]]=n[1],s.apply(e,n))}setOnReadyStateChange(e,s,n){return Reflect.set(e,s,(...i)=>{this.onReadyStateChange(),n==null||n.apply(e,i)})}setOnAbort(e,s,n){return Reflect.set(e,s,(...i)=>{this.onAbort(),n.apply(e,i)})}setOnTimeout(e,s,n){return Reflect.set(e,s,(...i)=>{this.onTimeout(),n.apply(e,i)})}updateItemByReadyState(){switch(this.XMLReq.readyState){case be.UNSENT:case be.OPENED:this.item.status=be.UNSENT,this.item.statusText="Pending",this.item.startTime||(this.item.startTime=performance.now());break;case be.HEADERS_RECEIVED:this.item.status=this.XMLReq.status,this.item.statusText="Loading",this.item.header={};const e=this.XMLReq.getAllResponseHeaders()||"",s=e.split(`
658
+ `);for(let n=0;n<s.length;n++){const i=s[n];if(!i)continue;const r=i.split(": "),o=r[0];this.item.header[o]=r.slice(1).join(": ")}break;case be.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 be.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 Ra{static create(e,s,n,i,r,o){return new Proxy(XMLHttpRequest,{construct(l){const a=new l;return new Proxy(a,new Na(a,e,s,n,i,r,o))}})}}const Da=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 Aa{constructor(e,s,n,i,r){this.ignoredHeaders=e,this.setSessionTokenHeader=s,this.sanitize=n,this.sendMessage=i,this.isServiceUrl=r}apply(e,s,n){const i=n[0],r=n[1],o=new vs(this.ignoredHeaders,this.setSessionTokenHeader,this.sanitize);if(this.isServiceUrl(i))return e.apply(s,n);const l=Ss(i);if(o.method="POST",o.url=i,o.name=(l.pathname.split("/").pop()||"")+l.search,o.requestType="beacon",o.requestHeader={"Content-Type":Da(r)},o.status=0,o.statusText="Pending",l.search&&l.searchParams){o.getData={};for(const[c,d]of l.searchParams)o.getData[c]=d}o.requestData=ys(r),o.startTime||(o.startTime=performance.now());const a=e.apply(s,n);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 h=o.getMessage();return h&&this.sendMessage(h),a}}class Ve{static hasSendBeacon(){return!!Ve.origSendBeacon}static create(e,s,n,i,r){if(Ve.hasSendBeacon())return new Proxy(Ve.origSendBeacon,new Aa(e,s,n,i,r))}}Ve.origSendBeacon=(Ti=window==null?void 0:window.navigator)==null?void 0:Ti.sendBeacon;const gi=t=>console.warn(`Openreplay: Can't find ${t} in global context.
659
+ If you're using serverside rendering in your app, make sure that tracker is loaded dynamically, otherwise ${t} won't be tracked.`);function Fa(t,e,s,n,i,r,o){var l;t.XMLHttpRequest?t.XMLHttpRequest=Ra.create(e,s,n,i,r,o):gi("XMLHttpRequest"),t.fetch?t.fetch=Oa.create(e,s,n,i,r,o):gi("fetch"),(l=t==null?void 0:t.navigator)!=null&&l.sendBeacon&&(t.navigator.sendBeacon=Ve.create(e,s,n,i,r))}function ws(t){return t.__or_req_data__||(t.__or_req_data__={body:void 0,headers:{}}),t.__or_req_data__}function mi(t){return typeof t=="string"?t.toUpperCase():"GET"}function Ma(t,e={}){const s=Object.assign({failuresOnly:!1,ignoreHeaders:["cookie","set-cookie","authorization"],capturePayload:!1,sessionTokenHeader:!1,captureInIframes:!0,axiosInstances:void 0,useProxy:!0},e);s.useProxy===!1&&t.debug.warn("Network module is migrating to proxy api, to gradually migrate and test it set useProxy to true");const n=s.ignoreHeaders,i=Array.isArray(n)?c=>n.includes(c):()=>n,r=s.sessionTokenHeader===!0?"X-OpenReplay-SessionToken":s.sessionTokenHeader;function o(c){if(r){const d=t.getSessionToken();d&&t.safe(c)(r,d)}}function l(c){if(s.capturePayload||(delete c.request.body,delete c.response.body),s.sanitizer){const d=c.response.body;if(typeof d=="string")try{c.response.body=JSON.parse(d)}catch{}return s.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 h=c=>{if(s.useProxy)return Fa(c,s.ignoreHeaders,o,l,A=>t.send(A),A=>t.isServiceURL(A),s.tokenUrlMatcher);const d=c.fetch.bind(c),p=(A,k={})=>{if(!(typeof A=="string"||A instanceof URL)||t.isServiceURL(String(A)))return d(A,k);o(function(N,F){k.headers===void 0&&(k.headers={}),k.headers instanceof Headers?k.headers.append(N,F):Array.isArray(k.headers)?k.headers.push([N,F]):k.headers[N]=F});const O=performance.now();return d(A,k).then(N=>{const F=performance.now()-O;if(s.failuresOnly&&N.status<400)return N;const C=N.clone();return C.text().then(E=>{const P={},V={};if(n!==!0){const I=([M,q])=>{i(M)||(P[M]=q)};k.headers instanceof Headers?k.headers.forEach((M,q)=>I([q,M])):Array.isArray(k.headers)?k.headers.forEach(I):typeof k.headers=="object"&&Object.entries(k.headers).forEach(I),C.headers.forEach((M,q)=>{i(q)||(V[q]=M)})}const j=mi(k.method),W=l({url:String(A),method:j,status:C.status,request:{headers:P,body:k.body||null},response:{headers:V,body:E}});W&&t.send(vt("fetch",j,String(W.url),a(W.request),a(W.response),C.status,O+ze(),F,0))}).catch(E=>t.debug.error("Could not process Fetch response:",E)),N})};c.fetch=p;const y=c.XMLHttpRequest.prototype.open,w=c.XMLHttpRequest.prototype.setRequestHeader,b=c.XMLHttpRequest.prototype.send;function T(A,k){const O=this;o((F,C)=>O.setRequestHeader(F,C));let N=0;return O.addEventListener("loadstart",F=>{N=F.timeStamp}),O.addEventListener("load",t.safe(F=>{const{headers:C,body:E}=ws(O),P=N>0?F.timeStamp-N:0,j=(O.getAllResponseHeaders()||"").trim().split(/[\r\n]+/),W={};j.forEach(function(q){const G=q.split(": "),H=G.shift();i(H)||(W[H]=G.join(": "))});const I=mi(A),M=l({url:String(k),method:I,status:O.status,request:{headers:C,body:E||null},response:{headers:W,body:O.response}});M&&t.send(vt("xhr",I,String(M.url),a(M.request),a(M.response),O.status,N+ze(),P,0))})),y.apply(this,arguments)}function D(A){const k=ws(this);return k.body=A,b.apply(this,arguments)}function B(A,k){if(!i(A)){const O=ws(this);O.headers[A]=k}return w.apply(this,arguments)}s.axiosInstances||(c.XMLHttpRequest.prototype.open=T,c.XMLHttpRequest.prototype.send=D,c.XMLHttpRequest.prototype.setRequestHeader=B)};h(window),s.axiosInstances&&s.axiosInstances.forEach(c=>{xa(t,c,s,l,a)}),s.captureInIframes&&t.observer.attachContextCallback(t.safe(h))}function La(t){t.attachEventListener(document,"selectionchange",()=>{const e=document.getSelection();if(e!==null&&!e.isCollapsed){const s=t.nodes.getID(e.anchorNode),n=t.nodes.getID(e.focusNode),i=e.toString().replace(/\s+/g," ");s&&n&&t.send(Rn(s,n,i))}else t.send(Rn(-1,-1,""))})}function Pa(t){function e(){document.hidden||(t.debug.log("Openreplay: tab change to"+t.session.getTabId()),t.send(yt(t.session.getTabId())))}t.attachEventListener(window,"focus",e,!1,!1)}const Rt="/installation/javascript-sdk";function Ba(t){if(t==null)return console.error(`OpenReplay: invalid options argument type. Please, check documentation on ${mt}${Rt}`),!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 ${mt}${Rt} for more information.`),!1;t.projectKey=t.projectID.toString(),_e("`projectID` option","`projectKey` option",Rt)}else console.warn("OpenReplay: projectKey is expected to have a string type."),t.projectKey=t.projectKey.toString();return t.sessionToken!=null&&_e("`sessionToken` option","`sessionHash` start() option","/"),!0}class ja{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,h)=>{const c=this.checkDoNotTrack(),d=new XMLHttpRequest,p=this.options.ingestPoint||Gn;d.open("POST",p+"/v1/web/not-started"),d.send(JSON.stringify({trackerVersion:"14.0.4",projectKey:this.options.projectKey,doNotTrack:c,reason:h.length?`missing api: ${h.join(",")}`:a}))},this.restartCanvasTracking=()=>{this.app!==null&&this.app.restartCanvasTracking()},this.handleError=(a,h={})=>{if(this.app!==null){if(a instanceof Error){const c=Tt(a,[],h);this.app.send(c)}else if(a instanceof ErrorEvent||"PromiseRejectionEvent"in window&&a instanceof PromiseRejectionEvent){const c=ei(a,void 0,h);c!=null&&this.app.send(c)}}},this.crossdomainMode=!!(dr()&&((l=e.crossdomain)!=null&&l.enabled)),!ve||!Ba(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 s=this.checkDoNotTrack(),n=[],i=["Map","Set","MutationObserver","performance","timing","startsWith","Blob","Worker"];if(s)n.push("doNotTrack");else for(const a of i)if(a==="timing"){if("performance"in window&&!(a in performance)){n.push(a);break}}else if(a==="startsWith"){if(!(a in String.prototype)){n.push(a);break}}else if(!(a in window)){n.push(a);break}if(n.length>0){const a=n.join(",");console.error(`OpenReplay: browser doesn't support API required for tracking or doNotTrack is set to 1. Reason: ${a}`),this.signalStartIssue("missing_api",n);return}const r=new Lo(e.projectKey,e.sessionToken,e,this.signalStartIssue,this.crossdomainMode);this.app=r,this.crossdomainMode||(ma(r),Po(r),Xr(r,e),Pa(r)),ua(r,e.mouse),ga(r,this.crossdomainMode),ba(r),ya(r),Ho(r,e),qo(r,e),Ko(r),Zo(r,e),pa(r,e),Sa(r),wa(r),Ma(r,e.network),La(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(),h=r.sessionStorage??window.sessionStorage;window.open=function(...c){return e.autoResetOnWindowOpen&&r.resetNextPageSession(!0),e.resetTabOnWindowOpen&&h.removeItem(e.session_tabid_key||"__openreplay_tabid"),r.resetNextPageSession(!1),h.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 s;(s=this.app)==null||s.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 s;return(s=this.app)==null?void 0:s.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 ve?!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 ${mt}${Rt}`),!1)}coldStart(e,s){if(this.browserEnvCheck()){if(this.app===null)return Promise.reject("Tracker not initialized");this.app.coldStart(e,s)}else return Promise.reject("Trying to start not in browser.")}startOfflineRecording(e,s){return this.browserEnvCheck()?this.app===null?Promise.reject("Tracker not initialized"):this.app.offlineRecording(e,s):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 _e("'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){_e("'userID' method","'setUserID' method","/"),this.setUserID(e)}setUserAnonymousID(e){typeof e=="string"&&this.app!==null&&this.app.send(Ar(e))}userAnonymousID(e){_e("'userAnonymousID' method","'setUserAnonymousID' method","/"),this.setUserAnonymousID(e)}setMetadata(e,s){typeof e=="string"&&typeof s=="string"&&this.app!==null&&this.app.session.setMetadata(e,s)}metadata(e,s){_e("'metadata' method","'setMetadata' method","/"),this.setMetadata(e,s)}event(e,s=null,n=!1){if(typeof e=="string"&&this.app!==null){if(n)return this.issue(e,s);try{s=JSON.stringify(s)}catch{return}this.app.send(Rr(e,s))}}issue(e,s=null){if(typeof e=="string"&&this.app!==null){try{s=JSON.stringify(s)}catch{return}this.app.send(jr(e,s))}}}const Ua=["climats","telckel","biobio","weinpoint","vinigrandi"],Ha="bMTFzLbWcXFgXK8SzyFHA6kIjelFcz5VQABVPbXdXh5XZJCDQH9BcVlrv3DF3kA";class xs{constructor(e){var s;this.baseURL="https://wineater-backend.vercel.app/",this.store=Ua.find(n=>window.location.href.includes(n)),this.token=((s=window==null?void 0:window.wineaterData)==null?void 0:s.CLIENT_TOKEN)||Ha}async getStoreConfig(e){console.log(e);try{const s=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(s),!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);return await s.json()}catch(s){throw console.error("Error fetching store configuration:",s),s}}async getWineRecommendations(e){console.log(window.location.href);try{const s=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})}),n=await s.json();if(!s.ok)throw new Error(`API call failed with status ${s.status}: ${n.message||"No additional error information"}`);return n}catch(s){throw console.error("Fetching wine recommendations failed:",s.message),new Error(`Error in getWineRecommendations: ${s.message}`)}}async getPossibleDishesWithMeta(e,s){try{const n=await fetch(`${this.baseURL}dish/possible_dishes`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:e,description:s})}),i=await n.json();if(console.log(i),!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("Error fetching possible dishes:",n),n}}}class za{constructor(){this.api=new xs,this.language="en",this.translations={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"},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"},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"},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"}}}async fetchConfig(e){console.log(e);try{const s=await this.api.getStoreConfig(e);console.log(s),this.language=s.lang}catch{this.language="en"}console.log(this.language)}translate(e){return this.translations[this.language][e]||e}}const he=new za,Wa=3;let Dt=null;function ks(){const t=document.getElementById("chat-window"),e=document.getElementById("chat-icon");t.classList.contains("visible")?(Ks(),Ts(),e.style.display="flex"):(Dt&&(clearTimeout(Dt),Dt=null),Gs(),t.classList.add("visible"),e.style.display="none")}function Ts(){console.log("ghbdtn"),Ks(),document.getElementById("chat-window").classList.remove("visible");let e=parseInt(ee("chatCloseCount"))||0;e+=1,e>=Wa?(console.log(e),ot("disableAutoOpen","true",1),Pi("chatCloseCount")):(console.log(e),ot("chatCloseCount",e,1))}function vi(t=null){t?ji(t):Gs(),document.getElementById("chat-window").classList.add("visible")}document.addEventListener("DOMContentLoaded",()=>{setupCloseButton(),setupOutsideClick()});function $a(t){Dt=t}class yi{constructor(){var s;this.api=new xs;const e=((s=window==null?void 0:window.wineaterData)==null?void 0:s.FIRST_MESSAGE_TEXT)||he.translate("welcomeMessage");this.displayFirstMessage(e)}initialize(){document.getElementById("send-button").addEventListener("click",()=>this.handleUserInput()),document.getElementById("user-input").addEventListener("keypress",n=>{n.key==="Enter"&&this.handleUserInput()})}displayFirstMessage(e,s="api"){const n=document.getElementById("message-container"),i=document.createElement("div");i.className=`message ${s}`,i.textContent=e,n.appendChild(i),n.scrollTop=n.scrollHeight}async handleUserInput(){const e=document.getElementById("user-input"),s=e.value.trim();if(s){this.displayMessage(s,"user"),e.value="",this.showTypingIndicator();try{Ui(s);const n=await this.api.getWineRecommendations(s);this.hideTypingIndicator(),n&&n.length?this.displayResults(n):this.displayMessage("No results found.","api")}catch{this.hideTypingIndicator(),this.displayMessage(he.translate("somethingWentWrong"),"api")}}}showTypingIndicator(){document.getElementById("typing-indicator").classList.add("visible")}hideTypingIndicator(){document.getElementById("typing-indicator").classList.remove("visible")}displayMessage(e,s){const n=document.getElementById("message-container"),i=document.createElement("div");i.textContent=e,i.className="message "+s,n.appendChild(i),n.scrollTop=n.scrollHeight}sendAnalytics(e){console.log(e),zi(e)}displayResults(e){console.log(e);const s=document.getElementById("message-container");Hi(e.map(n=>n.Title)),e.forEach(n=>{const i=document.createElement("div");i.className="wine-recommendation";const r=document.createElement("div");r.className="wine-item",i.appendChild(r);const o=document.createElement("img");o.src=n.Image,r.appendChild(o),console.log(r,"wine div");const l=document.createElement("div");l.innerHTML=`
648
660
  <strong>${n.Title}</strong><br>
649
- ${ie.translate("price")}: ${n.Price}<br>
650
- ${ie.translate("region")}: ${n.Region}<br>
651
- ${ie.translate("type")}: ${n.Type}<br>
652
- <a href="${n.Url}" target="_blank">${ie.translate("moreInfo")}</a>
653
- `,l.querySelector("a").addEventListener("click",c=>{c.preventDefault(),this.sendAnalytics(n.Title),window.open(n.Url,"_blank")}),r.appendChild(l);const u=document.createElement("div");u.className="wine-description",u.innerHTML=n.Reason,i.appendChild(u),console.log(i),s.appendChild(i)}),s.scrollTop=s.scrollHeight}}const za=new xs,At={PRODUCT_PAGES:/producto\/[^\/]+\/$/},yi={FESTIVAL_PAGES:/festival/,TASTING_PAGES:/tasting/},Wa={FESTIVAL_PAGES:((Si=window.wineaterData)==null?void 0:Si.FESTIVAL_PAGES)||yi.FESTIVAL_PAGES,TASTING_PAGES:((wi=window.wineaterData)==null?void 0:wi.TASTING_PAGES)||yi.TASTING_PAGES},$a={PRODUCT_PAGES:((xi=window.wineaterData)==null?void 0:xi.PRODUCT_PAGES)||At.PRODUCT_PAGES,CART_PAGE:((ki=window.wineaterData)==null?void 0:ki.CART_PAGE)||(At==null?void 0:At.CART_PAGE)};async function qa(){var e,s;const t=window.location.href;for(const[n,i]of Object.entries(Wa))if(i.test(t))return!1;for(const[n,i]of Object.entries($a))if(i.test(t))try{const r=((e=document.querySelector('meta[name="title"]'))==null?void 0:e.getAttribute("content"))||document.title,o=((s=document.querySelector('meta[name="description"]'))==null?void 0:s.getAttribute("content"))||"",l=await za.getPossibleDishesWithMeta(r,o);console.log(l);const a=setTimeout(()=>{ja(l)},15e3);return Ua(a),!0}catch(r){return console.error("Error fetching dishes:",r),!1}return!1}const Va=new Fa({projectKey:"PA8j9fAi49i6g2QnvpNs",__DISABLE_SECURE_MODE:!0});Js.init({environmentID:"5RfiDoiqb4dHrNdQvzbkfM",cacheFlags:!0,enableAnalytics:!0});const Ga="tbMTFzLbWcXFgXK8SzyFHA6kIjelFcz5VQABVPbXdXh5XZJCDQH9BcVlrv3DF3kA";document.addEventListener("DOMContentLoaded",()=>{window.toggleChatWindow=ks,window.closeChatWindow=Ts,window.openChatWindow=vi});function Ka(){var n;Va.start();const t=Js.getValue("chat-btn-txt"),s=`
661
+ ${he.translate("price")}: ${n.Price}<br>
662
+ ${he.translate("region")}: ${n.Region}<br>
663
+ ${he.translate("type")}: ${n.Type}<br>
664
+ <a href="${n.Url}" target="_blank">${he.translate("moreInfo")}</a>
665
+ `,l.querySelector("a").addEventListener("click",c=>{c.preventDefault(),this.sendAnalytics(n.Title),window.open(n.Url,"_blank")}),r.appendChild(l);const h=document.createElement("div");h.className="wine-description",h.innerHTML=n.Reason,i.appendChild(h),console.log(i),s.appendChild(i)}),s.scrollTop=s.scrollHeight}}new xs;const At={PRODUCT_PAGES:/producto\/[^\/]+\/$/},bi={FESTIVAL_PAGES:/festival/,TASTING_PAGES:/tasting/},qa={FESTIVAL_PAGES:((Ei=window.wineaterData)==null?void 0:Ei.FESTIVAL_PAGES)||bi.FESTIVAL_PAGES,TASTING_PAGES:((Ci=window.wineaterData)==null?void 0:Ci.TASTING_PAGES)||bi.TASTING_PAGES},Va={PRODUCT_PAGES:((Ii=window.wineaterData)==null?void 0:Ii.PRODUCT_PAGES)||At.PRODUCT_PAGES,CART_PAGE:((_i=window.wineaterData)==null?void 0:_i.CART_PAGE)||(At==null?void 0:At.CART_PAGE)};async function Ga(){const t=window.location.href;for(const[e,s]of Object.entries(qa))if(s.test(t))return!1;for(const[e,s]of Object.entries(Va))if(s.test(t))try{console.log(dishes);const n=setTimeout(()=>{openChatWindow()},15e3);return $a(n),!0}catch(n){return console.error("Error fetching dishes:",n),!1}return!1}const Ka=new ja({projectKey:"PA8j9fAi49i6g2QnvpNs",__DISABLE_SECURE_MODE:!0}),Xa="tbMTFzLbWcXFgXK8SzyFHA6kIjelFcz5VQABVPbXdXh5XZJCDQH9BcVlrv3DF3kA";document.addEventListener("DOMContentLoaded",()=>{window.toggleChatWindow=ks,window.closeChatWindow=Ts,window.openChatWindow=vi});function Si(){var n;Ka.start();const t=Js.getValue("chat-btn-txt"),s=`
654
666
  <div id="chatbot-container">
655
667
  <div id="chat-icon" onclick="toggleChatWindow()">
656
668
  <img src="https://landing-static.s3.eu-central-1.amazonaws.com/images/chat-icon.svg" alt="Chat Icon"> <!-- Update the path to your logo image -->
657
- <span>${((n=window==null?void 0:window.wineaterData)==null?void 0:n.BUTTON_TEXT)||ie.translate(`chatButton${t}`)}</span>
669
+ <span>${((n=window==null?void 0:window.wineaterData)==null?void 0:n.BUTTON_TEXT)||he.translate(`chatButton${t}`)}</span>
658
670
  </div>
659
671
 
660
672
  <div id="chat-window" class="hidden">
661
673
  <div id="chat-header">
662
674
  <div id="chat-title">
663
- <h1>${ie.translate("chatTitle")}</h1>
675
+ <h1>${he.translate("chatTitle")}</h1>
664
676
  </div>
665
677
  <div id="close-btn">&times;</div>
666
678
  </div>
@@ -669,15 +681,15 @@ If you're using serverside rendering in your app, make sure that tracker is load
669
681
  <span></span><span></span><span></span>
670
682
  </div>
671
683
  <div id="input-container">
672
- <input type="text" id="user-input" placeholder="${ie.translate("inputPlaceholder")}">
673
- <button id="send-button">${ie.translate("sendButton")}</button>
684
+ <input type="text" id="user-input" placeholder="${he.translate("inputPlaceholder")}">
685
+ <button id="send-button">${he.translate("sendButton")}</button>
674
686
  </div>
675
687
  <div id="powered-by">
676
688
  <a href="https://wineater.com" target="_blank">
677
- <span>${ie.translate("poweredBy")}</span>
689
+ <span>${he.translate("poweredBy")}</span>
678
690
  <img src="https://landing-static.s3.eu-central-1.amazonaws.com/images/logo.svg" alt="Wineater Logo" id="chatbot-logo">
679
691
  </a>
680
692
  </div>
681
693
  </div>
682
694
  </div>
683
- `;document.body.insertAdjacentHTML("beforeend",s)}function Xa(){document.getElementById("close-btn").addEventListener("click",ks)}function Ja(){window.addEventListener("click",function(t){const e=document.getElementById("chat-window"),s=document.getElementById("chat-icon");!e.contains(t.target)&&!s.contains(t.target)&&(e.classList.remove("visible"),s.style.display="flex")})}function Ya(t){console.log(t);const e=document.getElementById("chat-icon"),s=document.getElementById("chat-window");e.className="",s.className="",t==="right-center"?(e.classList.add("chat-icon-right-center"),s.classList.add("right-center-aligned")):e.classList.add("chat-icon-bottom-right")}if(document.addEventListener("DOMContentLoaded",()=>{te("disableAutoOpen")||qa()}),typeof window<"u"){let t=((Ti=window==null?void 0:window.wineaterData)==null?void 0:Ti.POSITION)||"right-center";window.addEventListener("DOMContentLoaded",async()=>{var r;const s=["climats","telckel","biobio","weinpoint","vinigrandi"].find(o=>window.location.href.includes(o))||null;let n;s&&(n=s.charAt(0).toUpperCase()+s.slice(1),n==="Climats"&&(t="right-center")),await ie.fetchConfig(n||"Climats"),Ka(),Xa(),Ja(),Ya(t),ot("chatbotToken",((r=window.wineaterData)==null?void 0:r.CLIENT_TOKEN)||Ga,365),Ai(),new Ha().initialize()})}Ee.closeChatWindow=Ts,Ee.openChatWindow=vi,Ee.toggleChatWindow=ks,Object.defineProperty(Ee,Symbol.toStringTag,{value:"Module"})});
695
+ `;document.body.insertAdjacentHTML("beforeend",s)}function wi(){document.getElementById("close-btn").addEventListener("click",ks)}function xi(){window.addEventListener("click",function(t){const e=document.getElementById("chat-window"),s=document.getElementById("chat-icon");!e.contains(t.target)&&!s.contains(t.target)&&(e.classList.remove("visible"),s.style.display="flex")})}function ki(t){console.log(t);const e=document.getElementById("chat-icon"),s=document.getElementById("chat-window");e.className="",s.className="",t==="right-center"?(e.classList.add("chat-icon-right-center"),s.classList.add("right-center-aligned")):e.classList.add("chat-icon-bottom-right")}if(document.addEventListener("DOMContentLoaded",()=>{ee("disableAutoOpen")||Ga()}),typeof window<"u"){let t=((Oi=window==null?void 0:window.wineaterData)==null?void 0:Oi.POSITION)||"right-center";window.addEventListener("DOMContentLoaded",async()=>{var i;const s=["climats","telckel","biobio","weinpoint","vinigrandi"].find(r=>window.location.href.includes(r))||null;let n;s&&(n=s.charAt(0).toUpperCase()+s.slice(1),n==="Climats"&&(t="right-center")),await he.fetchConfig(n||"Climats"),ot("chatbotToken",((i=window.wineaterData)==null?void 0:i.CLIENT_TOKEN)||Xa,365),Bi(),Js.init({environmentID:"5RfiDoiqb4dHrNdQvzbkfM",cacheFlags:!1,enableAnalytics:!0,identity:ee("uniqueUserID")}).then(()=>{Si(),wi(),xi(),ki(t),new yi().initialize()}).catch(()=>{Si(),wi(),xi(),ki(t),new yi().initialize()})})}Ee.closeChatWindow=Ts,Ee.openChatWindow=vi,Ee.toggleChatWindow=ks,Object.defineProperty(Ee,Symbol.toStringTag,{value:"Module"})});