@ujet/websdk-headless 6.32.0 → 6.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.mjs +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var Nq=Object.defineProperty;var AC=r=>{throw TypeError(r)};var Lq=(r,e,t)=>e in r?Nq(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ye=(r,e,t)=>Lq(r,typeof e!="symbol"?e+"":e,t),OC=(r,e,t)=>e.has(r)||AC("Cannot "+t);var Rc=(r,e,t)=>(OC(r,e,"read from private field"),t?t.call(r):e.get(r)),yy=(r,e,t)=>e.has(r)?AC("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_y=(r,e,t,n)=>(OC(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Uq(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const s=Object.getOwnPropertyDescriptor(n,i);s&&Object.defineProperty(r,i,s.get?s:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}class Fq{constructor(){ye(this,"_hostPath","")}setPath(e){this._hostPath=e}getPath(){return this._hostPath}}const cO=new Fq;let jq=class{constructor(){ye(this,"currentAudio",null);ye(this,"cleanupCallback",null)}async playPing(){cO.getPath();const e="https://websdk.ujet.co/v3/ping.mp3";try{await this.playSound(e)}catch(t){console.warn("Chat audio play failed",{error:t})}}async playSound(e,t=1){this.cleanup();const n=new window.Audio(e);n.volume=t,this.currentAudio=n;const i=()=>{this.currentAudio===n&&(this.currentAudio=null,this.cleanupCallback=null),n.removeEventListener("ended",i),n.removeEventListener("error",i)};this.cleanupCallback=i,n.addEventListener("ended",i),n.addEventListener("error",i);try{await n.play()}catch(s){i(),console.warn("Audio play failed",{error:s})}}cleanup(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.currentTime=0),this.cleanupCallback&&this.cleanupCallback()}};var cl=(r=>(r.WAITING="waiting",r.READY="ready",r.IN_PROGRESS="in_progress",r.FINISHED="finished",r))(cl||{}),lO=(r=>(r.CONFIRMED="confirmed",r.EXITED="exited",r.PENDING="pending",r.REQUESTED="requested",r.SKIPPED="skipped",r.TIMED_OUT="timed_out",r))(lO||{}),Wu=(r=>(r.UJET="ujet_conversations",r.TWILIO="twilio_conversations",r.NEXMO="nexmo_conversations",r.MOCK="mock",r))(Wu||{}),lv=(r=>(r.INBOUND_CALL="inbound_call",r.VOICEMAIL="voicemail",r))(lv||{}),tn=(r=>(r.TEXT="text",r.NOTI="noti",r.SERVER_MESSAGE="server_message",r.TYPING="typing",r.PREVIEW="preview",r.TRANSLATION_UPDATE="translation_update",r))(tn||{}),Er=(r=>(r.MEMBER_JOINED="memberJoined",r.MEMBER_LEFT="memberLeft",r.CHAT_ENDED="chatEnded",r.CHAT_DISMISSED="chatDismissed",r.TASK_VA_STARTED="taskVaStarted",r.TASK_VA_FINISHED="taskVaFinished",r.TASK_VA_FAILED="taskVaFailed",r.ESCALATION_STARTED="escalationStarted",r.ESCALATION_ACCEPTED="escalationAccepted",r.ESCALATION_FAILED="escalationFailed",r.CHECK_IN_REQUIRED="checkInRequired",r.CHECK_IN_TIMED_OUT="checkInTimedOut",r.COBROWSE_REQUESTED_FROM_AGENT="cobrowseRequestedFromAgent",r.COBROWSE_REQUESTED_FROM_END_USER="cobrowseRequestedFromEndUser",r))(Er||{}),_i=(r=>(r.END_USER="end_user",r.USER="user",r.VIRTUAL_AGENT="virtual_agent",r.SYSTEM="system",r))(_i||{});function Vp(r,e){return`${r}-${e}`}/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */const{entries:dO,setPrototypeOf:$C,isFrozen:Bq,getPrototypeOf:qq,getOwnPropertyDescriptor:Wq}=Object;let{freeze:Si,seal:bs,create:Mb}=Object,{apply:Db,construct:Nb}=typeof Reflect<"u"&&Reflect;Si||(Si=function(e){return e});bs||(bs=function(e){return e});Db||(Db=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),s=2;s<n;s++)i[s-2]=arguments[s];return e.apply(t,i)});Nb||(Nb=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const Ph=wi(Array.prototype.forEach),Vq=wi(Array.prototype.lastIndexOf),xC=wi(Array.prototype.pop),rd=wi(Array.prototype.push),Hq=wi(Array.prototype.splice),Hp=wi(String.prototype.toLowerCase),by=wi(String.prototype.toString),Sy=wi(String.prototype.match),nd=wi(String.prototype.replace),Gq=wi(String.prototype.indexOf),zq=wi(String.prototype.trim),js=wi(Object.prototype.hasOwnProperty),pi=wi(RegExp.prototype.test),id=Kq(TypeError);function wi(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Db(r,e,n)}}function Kq(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Nb(r,t)}}function ar(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hp;$C&&$C(r,null);let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const s=t(i);s!==i&&(Bq(e)||(e[n]=s),i=s)}r[i]=!0}return r}function Jq(r){for(let e=0;e<r.length;e++)js(r,e)||(r[e]=null);return r}function ca(r){const e=Mb(null);for(const[t,n]of dO(r))js(r,t)&&(Array.isArray(n)?e[t]=Jq(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=ca(n):e[t]=n);return e}function sd(r,e){for(;r!==null;){const n=Wq(r,e);if(n){if(n.get)return wi(n.get);if(typeof n.value=="function")return wi(n.value)}r=qq(r)}function t(){return null}return t}const MC=Si(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),wy=Si(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ty=Si(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Yq=Si(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ey=Si(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Xq=Si(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),DC=Si(["#text"]),NC=Si(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Cy=Si(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),LC=Si(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ah=Si(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Qq=bs(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Zq=bs(/<%[\w\W]*|[\w\W]*%>/gm),e6=bs(/\$\{[\w\W]*/gm),t6=bs(/^data-[\-\w.\u00B7-\uFFFF]+$/),r6=bs(/^aria-[\-\w]+$/),fO=bs(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),n6=bs(/^(?:\w+script|data):/i),i6=bs(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),hO=bs(/^html$/i),s6=bs(/^[a-z][.\w]*(-[.\w]+)+$/i);var UC=Object.freeze({__proto__:null,ARIA_ATTR:r6,ATTR_WHITESPACE:i6,CUSTOM_ELEMENT:s6,DATA_ATTR:t6,DOCTYPE_NAME:hO,ERB_EXPR:Zq,IS_ALLOWED_URI:fO,IS_SCRIPT_OR_DATA:n6,MUSTACHE_EXPR:Qq,TMPLIT_EXPR:e6});const ad={element:1,text:3,progressingInstruction:7,comment:8,document:9},a6=function(){return typeof window>"u"?null:window},o6=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},FC=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function pO(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:a6();const e=vt=>pO(vt);if(e.version="3.3.1",e.removed=[],!r||!r.document||r.document.nodeType!==ad.document||!r.Element)return e.isSupported=!1,e;let{document:t}=r;const n=t,i=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:c,Element:o,NodeFilter:l,NamedNodeMap:d=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:h,DOMParser:v,trustedTypes:y}=r,w=o.prototype,k=sd(w,"cloneNode"),P=sd(w,"remove"),A=sd(w,"nextSibling"),U=sd(w,"childNodes"),L=sd(w,"parentNode");if(typeof a=="function"){const vt=t.createElement("template");vt.content&&vt.content.ownerDocument&&(t=vt.content.ownerDocument)}let x,B="";const{implementation:G,createNodeIterator:K,createDocumentFragment:D,getElementsByTagName:fe}=t,{importNode:X}=n;let pe=FC();e.isSupported=typeof dO=="function"&&typeof L=="function"&&G&&G.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Q,ERB_EXPR:Oe,TMPLIT_EXPR:Ve,DATA_ATTR:Ze,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:Re,ATTR_WHITESPACE:Je,CUSTOM_ELEMENT:Ke}=UC;let{IS_ALLOWED_URI:Y}=UC,Ee=null;const Ct=ar({},[...MC,...wy,...Ty,...Ey,...DC]);let Nt=null;const Et=ar({},[...NC,...Cy,...LC,...Ah]);let wt=Object.seal(Mb(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),te=null,ne=null;const ut=Object.seal(Mb(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let It=!0,Zt=!0,rt=!1,cn=!0,Ot=!1,$e=!0,_t=!1,zt=!1,Fe=!1,pr=!1,er=!1,Nr=!1,lr=!0,Zr=!1;const yn="user-content-";let hn=!0,Kt=!1,Vt={},kt=null;const yt=ar({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Xt=null;const rn=ar({},["audio","video","img","source","image","track"]);let Yr=null;const Mn=ar({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),kn="http://www.w3.org/1998/Math/MathML",Rn="http://www.w3.org/2000/svg",ir="http://www.w3.org/1999/xhtml";let Lr=ir,ke=!1,Pe=null;const _e=ar({},[kn,Rn,ir],by);let we=ar({},["mi","mo","mn","ms","mtext"]),le=ar({},["annotation-xml"]);const xe=ar({},["title","style","font","a","script"]);let Le=null;const he=["application/xhtml+xml","text/html"],be="text/html";let se=null,ve=null;const oe=t.createElement("form"),Qe=function(ue){return ue instanceof RegExp||ue instanceof Function},Me=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ve&&ve===ue)){if((!ue||typeof ue!="object")&&(ue={}),ue=ca(ue),Le=he.indexOf(ue.PARSER_MEDIA_TYPE)===-1?be:ue.PARSER_MEDIA_TYPE,se=Le==="application/xhtml+xml"?by:Hp,Ee=js(ue,"ALLOWED_TAGS")?ar({},ue.ALLOWED_TAGS,se):Ct,Nt=js(ue,"ALLOWED_ATTR")?ar({},ue.ALLOWED_ATTR,se):Et,Pe=js(ue,"ALLOWED_NAMESPACES")?ar({},ue.ALLOWED_NAMESPACES,by):_e,Yr=js(ue,"ADD_URI_SAFE_ATTR")?ar(ca(Mn),ue.ADD_URI_SAFE_ATTR,se):Mn,Xt=js(ue,"ADD_DATA_URI_TAGS")?ar(ca(rn),ue.ADD_DATA_URI_TAGS,se):rn,kt=js(ue,"FORBID_CONTENTS")?ar({},ue.FORBID_CONTENTS,se):yt,te=js(ue,"FORBID_TAGS")?ar({},ue.FORBID_TAGS,se):ca({}),ne=js(ue,"FORBID_ATTR")?ar({},ue.FORBID_ATTR,se):ca({}),Vt=js(ue,"USE_PROFILES")?ue.USE_PROFILES:!1,It=ue.ALLOW_ARIA_ATTR!==!1,Zt=ue.ALLOW_DATA_ATTR!==!1,rt=ue.ALLOW_UNKNOWN_PROTOCOLS||!1,cn=ue.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ot=ue.SAFE_FOR_TEMPLATES||!1,$e=ue.SAFE_FOR_XML!==!1,_t=ue.WHOLE_DOCUMENT||!1,pr=ue.RETURN_DOM||!1,er=ue.RETURN_DOM_FRAGMENT||!1,Nr=ue.RETURN_TRUSTED_TYPE||!1,Fe=ue.FORCE_BODY||!1,lr=ue.SANITIZE_DOM!==!1,Zr=ue.SANITIZE_NAMED_PROPS||!1,hn=ue.KEEP_CONTENT!==!1,Kt=ue.IN_PLACE||!1,Y=ue.ALLOWED_URI_REGEXP||fO,Lr=ue.NAMESPACE||ir,we=ue.MATHML_TEXT_INTEGRATION_POINTS||we,le=ue.HTML_INTEGRATION_POINTS||le,wt=ue.CUSTOM_ELEMENT_HANDLING||{},ue.CUSTOM_ELEMENT_HANDLING&&Qe(ue.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(wt.tagNameCheck=ue.CUSTOM_ELEMENT_HANDLING.tagNameCheck),ue.CUSTOM_ELEMENT_HANDLING&&Qe(ue.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(wt.attributeNameCheck=ue.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),ue.CUSTOM_ELEMENT_HANDLING&&typeof ue.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(wt.allowCustomizedBuiltInElements=ue.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ot&&(Zt=!1),er&&(pr=!0),Vt&&(Ee=ar({},DC),Nt=[],Vt.html===!0&&(ar(Ee,MC),ar(Nt,NC)),Vt.svg===!0&&(ar(Ee,wy),ar(Nt,Cy),ar(Nt,Ah)),Vt.svgFilters===!0&&(ar(Ee,Ty),ar(Nt,Cy),ar(Nt,Ah)),Vt.mathMl===!0&&(ar(Ee,Ey),ar(Nt,LC),ar(Nt,Ah))),ue.ADD_TAGS&&(typeof ue.ADD_TAGS=="function"?ut.tagCheck=ue.ADD_TAGS:(Ee===Ct&&(Ee=ca(Ee)),ar(Ee,ue.ADD_TAGS,se))),ue.ADD_ATTR&&(typeof ue.ADD_ATTR=="function"?ut.attributeCheck=ue.ADD_ATTR:(Nt===Et&&(Nt=ca(Nt)),ar(Nt,ue.ADD_ATTR,se))),ue.ADD_URI_SAFE_ATTR&&ar(Yr,ue.ADD_URI_SAFE_ATTR,se),ue.FORBID_CONTENTS&&(kt===yt&&(kt=ca(kt)),ar(kt,ue.FORBID_CONTENTS,se)),ue.ADD_FORBID_CONTENTS&&(kt===yt&&(kt=ca(kt)),ar(kt,ue.ADD_FORBID_CONTENTS,se)),hn&&(Ee["#text"]=!0),_t&&ar(Ee,["html","head","body"]),Ee.table&&(ar(Ee,["tbody"]),delete te.tbody),ue.TRUSTED_TYPES_POLICY){if(typeof ue.TRUSTED_TYPES_POLICY.createHTML!="function")throw id('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ue.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw id('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=ue.TRUSTED_TYPES_POLICY,B=x.createHTML("")}else x===void 0&&(x=o6(y,i)),x!==null&&typeof B=="string"&&(B=x.createHTML(""));Si&&Si(ue),ve=ue}},ot=ar({},[...wy,...Ty,...Yq]),tt=ar({},[...Ey,...Xq]),it=function(ue){let je=L(ue);(!je||!je.tagName)&&(je={namespaceURI:Lr,tagName:"template"});const st=Hp(ue.tagName),Jt=Hp(je.tagName);return Pe[ue.namespaceURI]?ue.namespaceURI===Rn?je.namespaceURI===ir?st==="svg":je.namespaceURI===kn?st==="svg"&&(Jt==="annotation-xml"||we[Jt]):!!ot[st]:ue.namespaceURI===kn?je.namespaceURI===ir?st==="math":je.namespaceURI===Rn?st==="math"&&le[Jt]:!!tt[st]:ue.namespaceURI===ir?je.namespaceURI===Rn&&!le[Jt]||je.namespaceURI===kn&&!we[Jt]?!1:!tt[st]&&(xe[st]||!ot[st]):!!(Le==="application/xhtml+xml"&&Pe[ue.namespaceURI]):!1},at=function(ue){rd(e.removed,{element:ue});try{L(ue).removeChild(ue)}catch{P(ue)}},ht=function(ue,je){try{rd(e.removed,{attribute:je.getAttributeNode(ue),from:je})}catch{rd(e.removed,{attribute:null,from:je})}if(je.removeAttribute(ue),ue==="is")if(pr||er)try{at(je)}catch{}else try{je.setAttribute(ue,"")}catch{}},jt=function(ue){let je=null,st=null;if(Fe)ue="<remove></remove>"+ue;else{const Ar=Sy(ue,/^[\r\n\t ]+/);st=Ar&&Ar[0]}Le==="application/xhtml+xml"&&Lr===ir&&(ue='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ue+"</body></html>");const Jt=x?x.createHTML(ue):ue;if(Lr===ir)try{je=new v().parseFromString(Jt,Le)}catch{}if(!je||!je.documentElement){je=G.createDocument(Lr,"template",null);try{je.documentElement.innerHTML=ke?B:Jt}catch{}}const or=je.body||je.documentElement;return ue&&st&&or.insertBefore(t.createTextNode(st),or.childNodes[0]||null),Lr===ir?fe.call(je,_t?"html":"body")[0]:_t?je.documentElement:or},pt=function(ue){return K.call(ue.ownerDocument||ue,ue,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},bt=function(ue){return ue instanceof h&&(typeof ue.nodeName!="string"||typeof ue.textContent!="string"||typeof ue.removeChild!="function"||!(ue.attributes instanceof d)||typeof ue.removeAttribute!="function"||typeof ue.setAttribute!="function"||typeof ue.namespaceURI!="string"||typeof ue.insertBefore!="function"||typeof ue.hasChildNodes!="function")},Pt=function(ue){return typeof c=="function"&&ue instanceof c};function Ur(vt,ue,je){Ph(vt,st=>{st.call(e,ue,je,ve)})}const ln=function(ue){let je=null;if(Ur(pe.beforeSanitizeElements,ue,null),bt(ue))return at(ue),!0;const st=se(ue.nodeName);if(Ur(pe.uponSanitizeElement,ue,{tagName:st,allowedTags:Ee}),$e&&ue.hasChildNodes()&&!Pt(ue.firstElementChild)&&pi(/<[/\w!]/g,ue.innerHTML)&&pi(/<[/\w!]/g,ue.textContent)||ue.nodeType===ad.progressingInstruction||$e&&ue.nodeType===ad.comment&&pi(/<[/\w]/g,ue.data))return at(ue),!0;if(!(ut.tagCheck instanceof Function&&ut.tagCheck(st))&&(!Ee[st]||te[st])){if(!te[st]&&Dn(st)&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st)))return!1;if(hn&&!kt[st]){const Jt=L(ue)||ue.parentNode,or=U(ue)||ue.childNodes;if(or&&Jt){const Ar=or.length;for(let nn=Ar-1;nn>=0;--nn){const _n=k(or[nn],!0);_n.__removalCount=(ue.__removalCount||0)+1,Jt.insertBefore(_n,A(ue))}}}return at(ue),!0}return ue instanceof o&&!it(ue)||(st==="noscript"||st==="noembed"||st==="noframes")&&pi(/<\/no(script|embed|frames)/i,ue.innerHTML)?(at(ue),!0):(Ot&&ue.nodeType===ad.text&&(je=ue.textContent,Ph([Q,Oe,Ve],Jt=>{je=nd(je,Jt," ")}),ue.textContent!==je&&(rd(e.removed,{element:ue.cloneNode()}),ue.textContent=je)),Ur(pe.afterSanitizeElements,ue,null),!1)},qt=function(ue,je,st){if(lr&&(je==="id"||je==="name")&&(st in t||st in oe))return!1;if(!(Zt&&!ne[je]&&pi(Ze,je))){if(!(It&&pi(Xe,je))){if(!(ut.attributeCheck instanceof Function&&ut.attributeCheck(je,ue))){if(!Nt[je]||ne[je]){if(!(Dn(ue)&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,ue)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(ue))&&(wt.attributeNameCheck instanceof RegExp&&pi(wt.attributeNameCheck,je)||wt.attributeNameCheck instanceof Function&&wt.attributeNameCheck(je,ue))||je==="is"&&wt.allowCustomizedBuiltInElements&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st))))return!1}else if(!Yr[je]){if(!pi(Y,nd(st,Je,""))){if(!((je==="src"||je==="xlink:href"||je==="href")&&ue!=="script"&&Gq(st,"data:")===0&&Xt[ue])){if(!(rt&&!pi(Re,nd(st,Je,"")))){if(st)return!1}}}}}}}return!0},Dn=function(ue){return ue!=="annotation-xml"&&Sy(ue,Ke)},Ri=function(ue){Ur(pe.beforeSanitizeAttributes,ue,null);const{attributes:je}=ue;if(!je||bt(ue))return;const st={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Nt,forceKeepAttr:void 0};let Jt=je.length;for(;Jt--;){const or=je[Jt],{name:Ar,namespaceURI:nn,value:_n}=or,ci=se(Ar),Ii=_n;let Hr=Ar==="value"?Ii:zq(Ii);if(st.attrName=ci,st.attrValue=Hr,st.keepAttr=!0,st.forceKeepAttr=void 0,Ur(pe.uponSanitizeAttribute,ue,st),Hr=st.attrValue,Zr&&(ci==="id"||ci==="name")&&(ht(Ar,ue),Hr=yn+Hr),$e&&pi(/((--!?|])>)|<\/(style|title|textarea)/i,Hr)){ht(Ar,ue);continue}if(ci==="attributename"&&Sy(Hr,"href")){ht(Ar,ue);continue}if(st.forceKeepAttr)continue;if(!st.keepAttr){ht(Ar,ue);continue}if(!cn&&pi(/\/>/i,Hr)){ht(Ar,ue);continue}Ot&&Ph([Q,Oe,Ve],ea=>{Hr=nd(Hr,ea," ")});const Zs=se(ue.nodeName);if(!qt(Zs,ci,Hr)){ht(Ar,ue);continue}if(x&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!nn)switch(y.getAttributeType(Zs,ci)){case"TrustedHTML":{Hr=x.createHTML(Hr);break}case"TrustedScriptURL":{Hr=x.createScriptURL(Hr);break}}if(Hr!==Ii)try{nn?ue.setAttributeNS(nn,Ar,Hr):ue.setAttribute(Ar,Hr),bt(ue)?at(ue):xC(e.removed)}catch{ht(Ar,ue)}}Ur(pe.afterSanitizeAttributes,ue,null)},Bn=function vt(ue){let je=null;const st=pt(ue);for(Ur(pe.beforeSanitizeShadowDOM,ue,null);je=st.nextNode();)Ur(pe.uponSanitizeShadowNode,je,null),ln(je),Ri(je),je.content instanceof s&&vt(je.content);Ur(pe.afterSanitizeShadowDOM,ue,null)};return e.sanitize=function(vt){let ue=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},je=null,st=null,Jt=null,or=null;if(ke=!vt,ke&&(vt="<!-->"),typeof vt!="string"&&!Pt(vt))if(typeof vt.toString=="function"){if(vt=vt.toString(),typeof vt!="string")throw id("dirty is not a string, aborting")}else throw id("toString is not a function");if(!e.isSupported)return vt;if(zt||Me(ue),e.removed=[],typeof vt=="string"&&(Kt=!1),Kt){if(vt.nodeName){const _n=se(vt.nodeName);if(!Ee[_n]||te[_n])throw id("root node is forbidden and cannot be sanitized in-place")}}else if(vt instanceof c)je=jt("<!---->"),st=je.ownerDocument.importNode(vt,!0),st.nodeType===ad.element&&st.nodeName==="BODY"||st.nodeName==="HTML"?je=st:je.appendChild(st);else{if(!pr&&!Ot&&!_t&&vt.indexOf("<")===-1)return x&&Nr?x.createHTML(vt):vt;if(je=jt(vt),!je)return pr?null:Nr?B:""}je&&Fe&&at(je.firstChild);const Ar=pt(Kt?vt:je);for(;Jt=Ar.nextNode();)ln(Jt),Ri(Jt),Jt.content instanceof s&&Bn(Jt.content);if(Kt)return vt;if(pr){if(er)for(or=D.call(je.ownerDocument);je.firstChild;)or.appendChild(je.firstChild);else or=je;return(Nt.shadowroot||Nt.shadowrootmode)&&(or=X.call(n,or,!0)),or}let nn=_t?je.outerHTML:je.innerHTML;return _t&&Ee["!doctype"]&&je.ownerDocument&&je.ownerDocument.doctype&&je.ownerDocument.doctype.name&&pi(hO,je.ownerDocument.doctype.name)&&(nn="<!DOCTYPE "+je.ownerDocument.doctype.name+`>
|
|
2
|
-
`+nn),Ot&&Ph([Q,Oe,Ve],_n=>{nn=nd(nn,_n," ")}),x&&Nr?x.createHTML(nn):nn},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ve=null,zt=!1},e.isValidAttribute=function(vt,ue,je){ve||Me({});const st=se(vt),Jt=se(ue);return qt(st,Jt,je)},e.addHook=function(vt,ue){typeof ue=="function"&&rd(pe[vt],ue)},e.removeHook=function(vt,ue){if(ue!==void 0){const je=Vq(pe[vt],ue);return je===-1?void 0:Hq(pe[vt],je,1)[0]}return xC(pe[vt])},e.removeHooks=function(vt){pe[vt]=[]},e.removeAllHooks=function(){pe=FC()},e}var u6=pO();const c6={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},l6="javascript:";var Lu;let Qc=(Lu=class extends Error{constructor(t,n,i){super(t);ye(this,"code",Lu.CODE);ye(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},ye(Lu,"CODE","UNAUTHORIZED"),Lu);function d6(r){return(r==null?void 0:r.constructor)===Object}async function jC(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Qc)throw i;n=i,console.error(i),await Xd(1e3*Math.pow(2,t))}}throw n}function Xd(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function xw(){return Math.random().toString(36).slice(2)}const f6=new TextDecoder,h6=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return f6.decode(t)},p6=r=>r.length===0,v6=(...r)=>r.every(p6),Lb=r=>{const e=u6.sanitize(r,c6);return e.includes(l6)?(console.warn("Suspicious content detected and removed."),""):e},g6=[8,4,4,4,12],m6=()=>{const r=globalThis.crypto;if(!r)return null;if(typeof r.randomUUID=="function")return r.randomUUID();if(typeof r.getRandomValues!="function")return null;const e=r.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");let n=0;return g6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},y6="prod",Mw="6.32.0",BC="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Mw};class _6{constructor(e){ye(this,"buffer");ye(this,"writeIndex",0);ye(this,"size",0);ye(this,"capacity");this.capacity=e,this.buffer=new Array(e)}push(e){this.buffer[this.writeIndex]=e,this.writeIndex++,this.writeIndex>=this.capacity&&(this.writeIndex=0),this.size<this.capacity&&this.size++}toArray(){return this.size<this.capacity?this.buffer.slice(0,this.size):[...this.buffer.slice(this.writeIndex),...this.buffer.slice(0,this.writeIndex)]}clear(){this.writeIndex=0,this.size=0,this.buffer=new Array(this.capacity)}}const Lo=class Lo{constructor(e){ye(this,"channel");this.channel=e}static addHandler(e){Lo.logHandlers.push(e)}static printLogHistoryData(e){Lo.consoleLog(e.channel,e.level,...e.args)}static consoleLog(e,t,...n){console[t](`[${t}][${e}]`,...n)}debug(...e){this.log("debug",...e)}info(...e){this.log("info",...e)}warn(...e){this.log("warn",...e)}error(...e){this.log("error",...e)}log(e,...t){const n=t.map(Dw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};ye(Lo,"logHandlers",[]),ye(Lo,"logHistory",new _6(1e3));let un=Lo;const b6=(r,e,...t)=>{let n=t.pop();return typeof n=="string"&&(t.push(n),n={}),{loglevel:e,channel:r,timestamp:new Date().toISOString(),application:zn.application,sdk_version:zn.version,device_uuid:zn.deviceId,tenant:zn.tenant,company_id:zn.companyId,tracker_id:zn.trackerId||void 0,location_url:location.href,data:w6(n),message:Dw(t.join(" "))}},qC=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],S6=[/(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}/g,/(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}/g,/[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+/g,/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g];function Dw(r){return Uc(r,new WeakSet)}function Uc(r,e){if(!r)return r;if(typeof r=="string")return S6.forEach(t=>{r=r.replace(t,"__MASKED__")}),r;if(typeof r=="object"&&e.has(r))return"[Circular]";if(typeof r=="object"&&e.add(r),Array.isArray(r))return r.map(t=>Uc(t,e));if(r instanceof Error){const t={name:r.name,message:Uc(r.message,e)};r.stack&&(t.stack=Uc(r.stack,e));for(const n of Object.getOwnPropertyNames(r))n==="name"||n==="message"||n==="stack"||(qC.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Uc(r[n],e));return t}return d6(r)&&(r={...r},Object.keys(r).forEach(t=>{qC.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Uc(r[t],e)})),r}function w6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Dw(r.data)}const T6=new un("chat-provider"),Ud="$superseded";class Yv{constructor(e,t,n,i){ye(this,"audio");ye(this,"issueChatToken");ye(this,"identity");ye(this,"channelId");ye(this,"region");ye(this,"inTask",!1);ye(this,"muted",!1);ye(this,"providerContext");ye(this,"events");this.events=e,this.region=t.region,this.audio=new jq,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){T6.warn("Chat audio play failed",{error:e})}}cleanupAudio(){this.audio&&this.audio.cleanup()}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}trackInTask(e){e.type===tn.NOTI&&e.event===Er.TASK_VA_STARTED?this.inTask=!0:e.type===tn.NOTI&&(e.event===Er.TASK_VA_FINISHED||e.event===Er.TASK_VA_FAILED)&&(this.inTask=!1)}}ye(Yv,"type","base");const vO={};function Xv(r){vO[r.type]=r}function E6(r){return vO[r]}const jv=class jv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");ye(this,"code",jv.CODE);ye(this,"status");this.name="ChatEndedError",this.status=t}};ye(jv,"CODE","CHAT_ENDED");let dv=jv;const WC=new un("MediaStore"),C6=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,k6="chat-media",VC=1,fv="file";class gO{constructor(){ye(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(HC(this.db));const n=C6.open(k6,VC);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(HC(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<VC&&(WC.info("deprecating media store"),s.deleteObjectStore(fv)),WC.info("creating media store"),s.createObjectStore(fv)}})}async save(e,t){(await this.store()).put({index:e,file:t},e)}async getAll(){const e=await this.store();return await new Promise((t,n)=>{const i=e.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const e={};return(await this.getAll()).forEach(n=>{e[n.index]=n.file}),e}async clear(){(await this.store()).clear()}}function HC(r){return r.transaction(fv,"readwrite").objectStore(fv)}const Gp={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},GC=1e4,R6=3e4,I6=9e5,mO={UPDATED:"riskFlagsUpdated"},wu=new un("Communicator");var Fo,of;class P6{constructor(e,t){ye(this,"user");ye(this,"clientEventManager");ye(this,"clientAuthenticate");ye(this,"config");ye(this,"channel");ye(this,"channelReady",!1);ye(this,"hasAuthenticated",!1);ye(this,"hasInitializedLogProxy",!1);ye(this,"queuedMessagesToBridge",[]);ye(this,"pendingBridgeRequests",{});ye(this,"bridgeIframe");ye(this,"bridgeMessageHandlers");ye(this,"tokenRefreshTimeout");ye(this,"logProxyQueue",[]);yy(this,Fo,"");yy(this,of,0);ye(this,"authRefreshInFlight",null);ye(this,"riskFlags",null);this.onReady=this.onReady.bind(this),this.onCallback=this.onCallback.bind(this),this.onRefreshToken=this.onRefreshToken.bind(this),this.onRiskFlags=this.onRiskFlags.bind(this),this.onMessageFromBridge=this.onMessageFromBridge.bind(this),this.clientAuthenticate=e.authenticate,this.clientEventManager=t,this.initConfig(e),this.channel=new MessageChannel,this.channel.port1.onmessage=this.onMessageFromBridge,this.initBridge()}get wsUrl(){return this.config.host.replace(/^http/,"ws")+"/ws"}async getAuthToken(e=!1){if(!e&&this.isAuthTokenFresh())return Rc(this,Fo);const t=await this.refreshAuthToken();if(!t)throw new Error("Auth refresh completed without a token");return t}async request(e,t){!this.hasAuthenticated&&e!=="proactive_chat_triggers"&&await this.onRefreshToken();const n={url:e,options:t};return this.postMessageWithCallbackToBridge("request",n)}leaveChatBeacon(e){var n;if(!Rc(this,Fo)||!((n=this.config)!=null&&n.host))return;const t=`${this.config.host}/api/v2/chats/${e}/leave`;fetch(t,{method:"POST",body:"{}",keepalive:!0,headers:{Authorization:`Bearer ${Rc(this,Fo)}`,"Content-Type":"application/json","UJET-SDK-Type":"Web"}}).catch(()=>{})}destroy(){delete this.channel,this.bridgeIframe&&(this.bridgeIframe.remove(),this.bridgeIframe=void 0),this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout)}getBridgeLogHistory(){return this.postMessageWithCallbackToBridge("_getLogHistory",{})}isRiskFlagEnabled(e){var t;return((t=this.riskFlags)==null?void 0:t[e])??!0}getRiskFlags(){return{...this.riskFlags??{}}}initBridge(){const e=document.createElement("iframe");e.src=this.config.bridge,e.setAttribute("style","display:none"),e.addEventListener("load",()=>{if(wu.debug("initialized iframe for origin:",this.config.bridgeOrigin),!this.channelReady){const t={type:"_init",data:this.config};wu.debug("sending message to bridge:",t),e.contentWindow.postMessage(t,this.config.bridgeOrigin,[this.channel.port2])}}),document.body.appendChild(e),this.bridgeIframe=e,this.bridgeMessageHandlers={ready:this.onReady,callback:this.onCallback,refreshToken:this.onRefreshToken,_riskFlags:this.onRiskFlags}}onReady(e){this.channelReady=!0,zn.deviceId=e.result.deviceId,zn.deviceId||wu.error("Device Id has not been provided. SDK will not work properly."),this.flushQueuedMessagesToBridge(),this.clientEventManager.triggerEvent("ready")}onCallback(e){if(!e.callbackId)return;const[t,n]=this.pendingBridgeRequests[e.callbackId];e.error?n(e.error):t(e.result),delete this.pendingBridgeRequests[e.callbackId]}async onRefreshToken(){try{await this.refreshAuthToken()}catch(e){if(!(e instanceof Qc))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Rc(this,Fo)&&Rc(this,of)-Date.now()>R6}refreshAuthToken(){return this.authRefreshInFlight??(this.authRefreshInFlight=this.performAuth().finally(()=>{this.authRefreshInFlight=null})),this.authRefreshInFlight}async performAuth(){this.hasAuthenticated=!0;let e;try{e=await this.clientAuthenticate()}catch(i){throw new Qc("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Qc("Failed to validate client authenticate response token with UJET server","server");t.auth_token&&this.setAuthToken(t.auth_token);const n=this.decodeJwt(e.token);return this.user={identifier:n.identifier,name:n.name,email:n.email},n.exp&&this.enqueueTokenRefresh(n.exp),this.initLogProxyHandler(t),wu.info("Web SDK authenticated"),this.clientEventManager.triggerEvent("authenticate"),this.clientEventManager.triggerEvent("authenticated"),t.auth_token??""}setAuthToken(e){_y(this,Fo,e),_y(this,of,this.readTokenExpiry(e))}readTokenExpiry(e){try{const{exp:t}=this.decodeJwt(e);return typeof t!="number"?0:t.toString().length===13?t:t*1e3}catch{return 0}}onRiskFlags(e){var n;const t=(n=e.result)==null?void 0:n.flags;t&&(this.riskFlags=t,this.clientEventManager.triggerEvent(mO.UPDATED,this.getRiskFlags()))}onMessageFromBridge(e){var n;wu.debug("received message from bridge:",e.data);const t=this.bridgeMessageHandlers[(n=e.data)==null?void 0:n.type];t&&t(e.data)}postMessageToBridge(e){this.channel&&this.channelReady?(wu.debug("sending message to bridge:",e),this.channel.port1.postMessage(e)):this.queuedMessagesToBridge.push(e)}flushQueuedMessagesToBridge(){for(;this.queuedMessagesToBridge.length;){const e=this.queuedMessagesToBridge.shift();this.postMessageToBridge(e)}}postMessageWithCallbackToBridge(e,t){return new Promise((n,i)=>{const s=xw()+"_"+Date.now();this.pendingBridgeRequests[s]=[n,i];const a={type:e,callbackId:s,data:t};this.postMessageToBridge(a)})}initConfig(e){var l;let t=e.host;t||(e.tenant?t=BC.replace("main.api",e.tenant):t=BC);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.32.0",c=/^https:/.test(a)?new URL(a).origin:"*",o=["twilio_chat","nexmo_chat","ujet_chat"];i&&o.push("cobrowse"),this.config={host:t,lang:n,cobrowse:i,companyId:e.companyId,location:location.href,version:e.version||"6.32.0",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,un.addHandler((t,n,...i)=>{if(n==="debug")return;const s=b6(t,n,...i);this.logProxyQueue.push(s)}),this.sendLogsToBridge())}sendLogsToBridge(){this.logProxyQueue.length&&(this.postMessageToBridge({type:"_log",data:{num_of_logs:this.logProxyQueue.length,logs:this.logProxyQueue}}),this.logProxyQueue=[]),setTimeout(()=>{this.sendLogsToBridge()},2e3)}serverAuthenticate(e){return this.postMessageWithCallbackToBridge("_auth",{modules:this.config.modules,user:{token:e,company_id:this.config.companyId}})}enqueueTokenRefresh(e){clearTimeout(this.tokenRefreshTimeout);const t=this.normalizeJwtExp(e),n=Math.max(t-Date.now()-GC,GC);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1];return JSON.parse(h6(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+I6}}Fo=new WeakMap,of=new WeakMap;const A6=new un("EventManager");class Qv{constructor(){ye(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){A6.debug(`event triggered: ${e}`);const n=this.handlers[e];n&&n.forEach(i=>{i(t)})}removeEventListener(e,t){if(this.handlers[e]){const n=this.handlers[e].indexOf(t);n!==-1&&this.handlers[e].splice(n,1)}}destroy(){this.handlers={}}}function O6(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===tn.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];yO(n,s.content)}return n})}function $6(r,e){return yO(r,e.content)}function yO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const zC={photo:2,video:2,audio:1,document:1};function x6(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(zC[t.type]||0)-(zC[e.type]||0))}function M6(r){try{const{pathname:e}=new URL(r),t=e.split("/").filter(n=>n.length>0);return t.length>0?decodeURIComponent(t[t.length-1]):"document"}catch{return"document"}}function D6(r,e){r.forEach(t=>{if(t.type==="document"&&t.media_id!=null){const n=e.find(i=>i.media_id===t.media_id);n&&n.url&&(t.document={url:n.url},t.title||(t.title=M6(n.url)))}})}const N6={confirmSessionTitle:"Screen Share Session Request",confirmSessionContent:"Do you want to share your current screen with the agent?",endSessionText:"End Screen Share Session",confirmRemoteControlTitle:"Remote Access Request",confirmRemoteControlContent:"The agent would like to have access to your currently shared screen to further assist you. Do you want to allow this?",confirmFullDeviceTitle:"Screen Share Request",confirmFullDeviceContent:"Do you want to share your full screen with the agent? The agent will not be able to control anything on the screen.",allowText:"Allow",denyText:"Deny"},L6={confirmSessionTitle:"Solicitud de sesión de conavegación",confirmSessionContent:"¿Desea compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de conavegación",confirmRemoteControlTitle:"Solicitud de acceso remoto",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actual compartida para seguir asistiéndole. ¿Desea permitirlo?",confirmFullDeviceTitle:"Solicitud de compartir pantalla",confirmFullDeviceContent:"¿Desea compartir su pantalla completa con el agente? El agente no podrá controlar nada de la pantalla.",allowText:"Permitir",denyText:"Denegar"},U6={confirmSessionTitle:"Demande de session de co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent ?",endSessionText:"Terminer la session de co-navigation",confirmRemoteControlTitle:"Demande d'accès à distance",confirmRemoteControlContent:"L'agent souhaite avoir accès à l'écran que vous partagez actuellement pour mieux vous aider. Voulez-vous l'y autoriser ?",confirmFullDeviceTitle:"Demande de partage d'écran",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent ? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran.",allowText:"Autoriser",denyText:"Refuser"},F6={confirmSessionTitle:"Screen Share-Sitzungsanfrage",confirmSessionContent:"Möchten Sie Ihren aktuellen Bildschirm für den Agenten freigeben?",endSessionText:"Screen Share-Sitzung beenden",confirmRemoteControlTitle:"Fernzugriff-Anfrage",confirmRemoteControlContent:"Der Agent möchte Zugriff auf Ihren aktuell freigegebenen Bildschirm erhalten, um Ihnen weiterhelfen zu können. Möchten Sie dies erlauben?",confirmFullDeviceTitle:"Bildschirmfreigabe",confirmFullDeviceContent:"Möchten Sie Ihren gesamten Bildschirm für den Agenten freigeben? Der Agent ist dadurch nicht in der Lage, Elemente auf Ihrem Bildschirm zu steuern.",allowText:"Erlauben",denyText:"Verweigern"},j6={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},B6={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},q6={confirmSessionTitle:"Richiesta di sessione di Screen Share",confirmSessionContent:"Vuoi condividere la tua schermata attuale con l'operatore?",endSessionText:"Termina sessione di Screen Share",confirmRemoteControlTitle:"Richiesta di accesso remoto",confirmRemoteControlContent:"L'operatore vorrebbe accedere alla tua schermata attualmente condivisa per assisterti al meglio. Acconsenti?",confirmFullDeviceTitle:"Richiesta di condivisione schermo",confirmFullDeviceContent:"Vuoi condividere il tuo intero schermo con l'operatore? L'operatore non potrà controllare nessun elemento sullo schermo.",allowText:"Consenti",denyText:"Rifiuta"},W6={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},V6={confirmSessionTitle:"Samwebbläsningssession har begärts",confirmSessionContent:"Vill du dela din aktuella skärm med vår medarbetare?",endSessionText:"Avsluta samwebbläsningssession",confirmRemoteControlTitle:"Begäran om fjärråtkomst",confirmRemoteControlContent:"Vår medarbetare skulle vilja få åtkomst till skärmen som du delar just nu för att kunna hjälpa dig vidare. Vill du tillåta detta?",confirmFullDeviceTitle:"Begäran om skärmdelning",confirmFullDeviceContent:"Vill du dela hela skärmen med medarbetaren? Medarbetaren kommer inte kunna kontrollera något på skärmen.",allowText:"Tillåt",denyText:"Neka"},H6={confirmSessionTitle:"Solicitação de Sessão de Co-navegação",confirmSessionContent:"Deseja partilhar o seu ecrã atual com o agente?",endSessionText:"Terminar Sessão de Co-navegação",confirmRemoteControlTitle:"Solicitação de Acesso Remoto",confirmRemoteControlContent:"O agente gostaria de ter acesso ao seu ecrã partilhado atualmente para ajudá-lo ainda mais. Quer permitir isto?",confirmFullDeviceTitle:"Solicitação de Partilha de Ecrã",confirmFullDeviceContent:"Deseja partilhar o seu ecrã inteiro com o agente? O agente não poderá controlar nada no ecrã.",allowText:"Permitir",denyText:"Negar"},G6={confirmSessionTitle:"Pyyntö yhteisselausistunnosta",confirmSessionContent:"Haluatko jakaa nykyisen näyttösi edustajan kanssa?",endSessionText:"Lopeta yhteisselausistunto",confirmRemoteControlTitle:"Etäkäyttöpyyntö",confirmRemoteControlContent:"Edustaja haluaisi saada käyttää tällä hetkellä jakamaasi näyttöä voidakseen auttaa sinua enemmän. Haluatko antaa siihen luvan?",confirmFullDeviceTitle:"Näytön jakamispyyntö",confirmFullDeviceContent:"Haluatko jakaa koko näyttösi edustajan kanssa? Edustaja ei pysty käyttämään mitään näytöllä olevaa.",allowText:"Salli",denyText:"Estä"},z6={confirmSessionTitle:"Samlesingsøkten er startet",confirmSessionContent:"Vil du dele skjermen din med agenten?",endSessionText:"Avslutt samlesingsøkt",confirmRemoteControlTitle:"Forespørsel om fjerntilgang",confirmRemoteControlContent:"Agenten vil ha tilgang til skjermen din for å kunne hjelpe deg videre. Vil du tillate dette?",confirmFullDeviceTitle:"Forespørsel om skjermdeling",confirmFullDeviceContent:"Vil du dele hele skjermen din med agenten? Agenten kan ikke kontrollere noe på skjermen.",allowText:"Tillat",denyText:"Avvis"},K6={confirmSessionTitle:"Forespørgsel om sambrowsingsession",confirmSessionContent:"Vil du dele din nuværende skærm med agenten",endSessionText:"Afslut sambrowsingsession",confirmRemoteControlTitle:"Anmodning om fjernadgang",confirmRemoteControlContent:"Agenten vil gerne have adgang til din nuværende delte skærm for at kunne hjælpe dig yderligere. Ønsker du at tillade dette?",confirmFullDeviceTitle:"Forespørgsel om skærmdeling",confirmFullDeviceContent:"Vil du dele din fulde skærm med agenten? Agenten vil ikke kunne styre noget på skærmen",allowText:"Tillad",denyText:"Afvis"},J6={confirmSessionTitle:"Verzoek om cobrowse-sessie",confirmSessionContent:"Wilt u uw huidige scherm delen met de agent?",endSessionText:"Cobrowse-sessie beëindigen",confirmRemoteControlTitle:"Verzoek om toegang op afstand",confirmRemoteControlContent:"De agent wil graag toegang hebben tot uw momenteel gedeelde scherm om u verder te helpen. Wilt u dit toestaan?",confirmFullDeviceTitle:"Verzoek om scherm te delen",confirmFullDeviceContent:"Wilt u uw volledige scherm delen met de agent? De agent kan niets op het scherm bedienen.",allowText:"Toestaan",denyText:"Weigeren"},Y6={confirmSessionTitle:"Oturum İsteğini Eş Zamanlı Tara",confirmSessionContent:"Mevcut ekranınızı temsilciyle paylaşmak ister misiniz?",endSessionText:"Eş zamanlı Oturum Taramayı Sonlandır",confirmRemoteControlTitle:"Uzaktan Erişim İsteği",confirmRemoteControlContent:"Temsilci şu anda paylaşılan ekranınıza size daha fazla yardımcı olabilmek için erişim sağlamak istiyor. Buna izin vermek istiyor musunuz?",confirmFullDeviceTitle:"Ekran Paylaşım İsteği",confirmFullDeviceContent:"Temsilciyle tam ekranınızı paylaşmak istiyor musunuz? Temsilci ekrandaki hiçbir şeyi kontrol edemez.",allowText:"İzin Ver",denyText:"Reddet"},X6={confirmSessionTitle:"Yêu cầu phiên cùng duyệt",confirmSessionContent:"Bạn có muốn chia sẻ màn hình hiện tại của mình với chuyên viên không?",endSessionText:"Kết thúc phiên cùng duyệt",confirmRemoteControlTitle:"Yêu cầu truy cập từ xa",confirmRemoteControlContent:"Chuyên viên muốn được cấp quyền truy cập vào màn hình bạn đang chia sẻ để hỗ trợ bạn nhiều hơn. Bạn có muốn cho phép không?",confirmFullDeviceTitle:"Yêu cầu chia sẻ màn hình",confirmFullDeviceContent:"Bạn có muốn chia sẻ toàn bộ màn hình của mình với chuyên viên không? Chuyên viên sẽ không thể điều khiển bất cứ phần nào trên màn hình.",allowText:"Cho phép",denyText:"Từ chối"},Q6={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},Z6={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},eW={confirmSessionTitle:"Žádost o relaci Screen Share",confirmSessionContent:"Chcete svou současnou obrazovku sdílet s agentem?",endSessionText:"Ukončit relaci Screen Share",confirmRemoteControlTitle:"Žádost o vzdálený přístup",confirmRemoteControlContent:"Agent by rád získal přístup k vaší stávající sdílené obrazovce, aby vám mohl dál pomoci. Chcete mu přístup povolit?",confirmFullDeviceTitle:"Žádost o sdílení obrazovky",confirmFullDeviceContent:"Chcete svou celou obrazovku sdílet s agentem? Agent nebude moci ovládat nic, co na obrazovce je.",allowText:"Povolit",denyText:"Zamítnout"},tW={confirmSessionTitle:"Prośba o sesję Screen Share",confirmSessionContent:"Czy chcesz udostępnić konsultantowi swój bieżący ekran?",endSessionText:"Zakończ sesję Screen Share",confirmRemoteControlTitle:"Prośba o zdalny dostęp",confirmRemoteControlContent:"Konsultant prosi o dostęp do Twojego aktualnie udostępnionego ekranu, aby udzielić Ci dalszej pomocy. Czy chcesz na to zezwolić?",confirmFullDeviceTitle:"Prośba o udostępnienie ekranu",confirmFullDeviceContent:"Czy chcesz udostępnić konsultantowi swój cały ekran? Konsultant nie będzie mógł kontrolować niczego na ekranie.",allowText:"Zezwól",denyText:"Odmów"},rW={confirmSessionTitle:"Screen Share munkameneti kérés",confirmSessionContent:"Megosztja az aktuális képernyőjét a képviselővel?",endSessionText:"Screen Share munkamenet befejezése",confirmRemoteControlTitle:"Távoli hozzáférési kérés",confirmRemoteControlContent:"A képviselő szeretne hozzáférni a jelenleg megosztott képernyőjéhez, hogy további segítséget nyújthasson. Engedélyezi ezt?",confirmFullDeviceTitle:"Képernyőmegosztási kérelem",confirmFullDeviceContent:"Megosztja a teljes képernyőjét az ügynökkel? Az ügynök semmit sem tud majd irányítani a képernyőn.",allowText:"Engedélyezés",denyText:"Elutasítás"},nW={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},iW={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},sW={confirmSessionTitle:"Solicitare sesiune de co-navigare",confirmSessionContent:"Doriți să partajați ecranul dumneavoastră curent cu agentul?",endSessionText:"Încheiați sesiunea de co-navigare",confirmRemoteControlTitle:"Cerere de acces la distanță",confirmRemoteControlContent:"Agentul ar dori să aibă acces la ecranul dumneavoastră partajat pentru a vă ajuta în continuare. Doriți să permiteți acest lucru?",confirmFullDeviceTitle:"Cerere de partajare a ecranului",confirmFullDeviceContent:"Doriți să partajați ecranul dumneavoastră complet cu agentul? Agentul nu va putea controla nimic de pe ecran.",allowText:"Permiteți",denyText:"Refuzați"},aW={confirmSessionTitle:"Zahtjev za sesiju zajedničkog pregledavanja",confirmSessionContent:"Želite li podijeliti svoj trenutni zaslon s agentom?",endSessionText:"Završi sesiju zajedničkog pregledavanja",confirmRemoteControlTitle:"Zahtjev za daljinski pristup",confirmRemoteControlContent:"Agent želi imati pristup vašem trenutno dijeljenom zaslonu kako bi Vam dodatno pomogao. Želite li to dopustiti?",confirmFullDeviceTitle:"Zahtjev za dijeljenje zaslona",confirmFullDeviceContent:"Želite li s agentom podijeliti svoj cijeli zaslon? Agent neće moći ništa kontrolirati na ekranu.",allowText:"Dopustiti",denyText:"Odbiti"},oW={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},uW={confirmSessionTitle:"Kahilingan sa Screen Share na Sesyon",confirmSessionContent:"Gusto mo bang ibahagi ang iyong kasalukuyang screen sa agent?",endSessionText:"Tapusin ang Screen Share na Sesyon",confirmRemoteControlTitle:"Kahilingan sa Remote Access",confirmRemoteControlContent:"Gusto ng agent na magkaroon ng access sa iyong nakabahaging screen sa kasalukuyan upang mas matulungan ka. Gusto mo bang payagan ito?",confirmFullDeviceTitle:"Kahilingan sa Pagbahagi ng Screen",confirmFullDeviceContent:"Gusto mo bang ibahagi ang buong screen sa agent? Hindi makokontrol ng agent ang kahit ano sa screen.",allowText:"Payagan",denyText:"Tanggihan"},od={en:N6,es:L6,"es-MX":{confirmSessionTitle:"Solicitud de Sesión de Co-navegación",confirmSessionContent:"¿Quiere compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de co-navegación",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actualmente compartida para poder ayudarlo. ¿Quiere permitirlo?",confirmFullDeviceTitle:"Petición de pantalla compartida",confirmFullDeviceContent:"¿Quiere compartir su pantalla completa con el agente? El agente no podrá controlar nada en la pantalla."},fr:U6,"fr-CA":{confirmSessionTitle:"Demande de session co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent?",endSessionText:"Fin de la session de co-navigation",confirmRemoteControlContent:"L'agent souhaiterait avoir accès à votre écran actuellement partagé pour mieux vous aider. Voulez-vous l'autoriser?",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran."},de:F6,ja:j6,ko:B6,it:q6,zh:W6,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:V6,pt:H6,"pt-BR":{confirmSessionContent:"Você deseja compartilhar sua tela atual com o agente?",endSessionText:"Encerrar Sessão de Co-navegação",confirmRemoteControlContent:"O agente gostaria de acessar sua tela atualmente compartilhada para melhor ajudá-lo. Você deseja permitir isso?",confirmFullDeviceTitle:"Solicitação de Compartilhamento de Tela",confirmFullDeviceContent:"Você deseja compartilhar sua tela inteira com o agente? O agente não poderá controlar nada na tela."},fi:G6,nb:z6,da:K6,nl:J6,tr:Y6,vi:X6,th:Q6,ar:Z6,cs:eW,pl:tW,hu:rW,ru:nW,hi:iW,ro:sW,hr:aW,uk:oW,tl:uW};function cW(r){const e=r.split("-")[0];return od[r]?r===e?od[r]:{...od[e],...od[r]}:od[e]}async function lW(r,e,t,n){const i=new FormData;Object.keys(t).forEach(c=>{i.append(c,t[c])}),e instanceof File?i.append("file",e,e.name):e.fileBits&&i.append("file",new File(e.fileBits,e.name,e.options),e.name);const s=await fetch(r,{method:"POST",body:i,signal:n});if(!s.ok)throw new Error(`upload failed: HTTP ${s.status}`);const a=await s.text();return dW(a)}function dW(r){var n,i;const t=(i=(n=new window.DOMParser().parseFromString(r,"text/xml").getElementsByTagName("Key")[0])==null?void 0:n.childNodes[0])==null?void 0:i.nodeValue;if(!t)throw new Error("upload response missing <Key> element");return t}const _O="chat-5565-surface-subscription-end",fW="chat-5580-nonblocking-history-hint",Oh=new un("chat-originals"),hW="web-4258-local-original-cache",pW=1e3,vW=4,KC=1e4,gW=100;function JC(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class mW{constructor(){ye(this,"byClientMessageId",new Map);ye(this,"byRedactionRef",new Map);ye(this,"inFlight",new Map);ye(this,"queue",[]);ye(this,"active",0);ye(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||ky(this.byClientMessageId,e,t)}lookup(e){if(typeof e=="string")return this.byClientMessageId.get(e)}forget(e){this.byClientMessageId.delete(e)}lookupFetched(e){return this.byRedactionRef.get(e)}fetch(e,t){const n=this.byRedactionRef.get(e);if(n!==void 0)return Promise.resolve(n);const i=this.inFlight.get(e);if(i)return i;const s=this.generation,a=this.runInSlot(s,()=>{const c=this.call(t,e);return{result:this.withTimeout(c).then(l=>this.settle(s,e,l),l=>(s===this.generation&&(l==null?void 0:l.status)===404?ky(this.byRedactionRef,e,null):Oh.info("original lookup failed",{redactionRef:e,status:l==null?void 0:l.status}),null)),transport:c}}).finally(()=>{this.inFlight.get(e)===a&&this.inFlight.delete(e)});return this.inFlight.set(e,a),a}invalidate(){this.generation+=1,this.byClientMessageId.clear(),this.byRedactionRef.clear(),this.inFlight.clear();const e=this.queue;this.queue=[],e.forEach(t=>t.cancel())}settle(e,t,n){return e!==this.generation?null:(n==null?void 0:n.redaction_ref)!==t||typeof n.content!="string"?(Oh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(ky(this.byRedactionRef,t,n.content),n.content)}call(e,t){try{return Promise.resolve(e(t))}catch(n){return Promise.reject(n)}}runInSlot(e,t){const n=()=>{if(e!==this.generation)return Promise.resolve(null);this.active+=1;const{result:i,transport:s}=t();return s.catch(()=>{}).finally(()=>this.releaseSlot()),i};return this.active<vW?n():this.queue.length>=gW?(Oh.info("original lookup queue full, skipping"),Promise.resolve(null)):new Promise(i=>{const s={start:()=>{clearTimeout(a),i(n())},cancel:()=>{clearTimeout(a),i(null)}},a=setTimeout(()=>{this.queue=this.queue.filter(c=>c!==s),Oh.info("original lookup gave up waiting for a slot"),i(null)},KC);this.queue.push(s)})}releaseSlot(){this.active-=1;const e=this.queue.shift();e&&e.start()}withTimeout(e){return new Promise((t,n)=>{const i=setTimeout(()=>{n(Object.assign(new Error("original lookup timed out"),{code:"TIMEOUT"}))},KC);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function ky(r,e,t){r.delete(e),r.set(e,t),r.size>pW&&r.delete(r.keys().next().value)}const bO=["assigned","va_assigned"],SO=["dismissed","va_dismissed"],yW=["va_assigned","va_dismissed"],_W=["queued","check_in_timeout",...bO,...SO],bW=["timeout","canceled","failed","finished"],Ds=new un("Chat"),SW=Symbol("owner-conflict"),Ry=1e3;function wW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const TW="web-4206-media-pairing-guard";class EW{constructor(e,t,n={},i){ye(this,"provider");ye(this,"store");ye(this,"globalEvents");ye(this,"state");ye(this,"connected",!1);ye(this,"allowSkipVirtualAgent",!1);ye(this,"inEscalation",!1);ye(this,"events");ye(this,"cachedFiles");ye(this,"hooks");ye(this,"originals",new mW);ye(this,"cacheOwner",null);ye(this,"restoredMessages",new Map);ye(this,"nextTrackedSweepAt",Ry);ye(this,"destroying",!1);ye(this,"leaveSent",!1);ye(this,"beaconAttempted",!1);ye(this,"connecting",!1);ye(this,"connectEnd","none");this.state=e,this.store=new gO,this.cachedFiles={},this.events=new Qv,this.hooks=n;const s=E6(this.state.provider_type);this.provider=new s(this.events,e,t,i)}_setGlobalEvents(e,t){this.globalEvents=e,this.on("message",n=>{if(this.destroying)return;n.content=Lb(n.content);const i=n[Ud]===!0;if(delete n[Ud],this.syncCacheOwner(),n.type===tn.SERVER_MESSAGE){const s=n.server_message_id??n.message_id;t(this.id,s).then(a=>{this.destroying||(n=$6(n,a),e.triggerEvent("chat.message",n))})}else if(n.type==="photo"||n.type==="video"||n.type==="document")setTimeout(()=>{if(this.destroying)return;const s=n.$index.toString();n.file=this.cachedFiles[s],e.triggerEvent("chat.message",n)},100);else{const s=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),i||this.registerMessageEvents(n),s&&this.lookupOwnOriginal(n)}}),this.on("memberJoined",n=>{e.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{e.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{e.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{e.triggerEvent("chat.typingEnded",n)}),this.on("checkInRequired",()=>{e.triggerEvent("chat.checkInRequested")}),this.on("checkInTimedOut",()=>{e.triggerEvent("chat.checkInTimedOut")}),this.on("error",n=>{Ds.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()})}handleConnectionEnded(){this.connecting&&this.connectEnd==="none"&&this.surfacesSubscriptionEnd()&&(this.connectEnd=this.connected?"done":"pending"),this.connected&&this.endConnection()}endConnection(){this.connected=!1,this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(e=>Ds.warn("provider destroy failed",{error:e}))}get id(){var e;return((e=this.state)==null?void 0:e.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var e;return((e=this.state)==null?void 0:e.provider_channel_id)||""}get lang(){var e;return((e=this.state)==null?void 0:e.lang)||""}get virtual(){return yW.indexOf(this.status)!==-1}get muted(){var e;return((e=this.provider)==null?void 0:e.muted)||!1}set muted(e){this.provider&&(this.provider.muted=e)}get agent(){return this.state?this.virtual?this.state.external_agent||this.state.virtual_agent:this.state.agent||this.state.virtual_agent:null}get allAgents(){var e,t;return{virtual:((e=this.state)==null?void 0:e.all_virtual_agents)||[],human:((t=this.state)==null?void 0:t.all_agents)||[]}}get userIdentity(){var e;return((e=this.provider)==null?void 0:e.identity)||""}get ownUserId(){return this.ownerConflict?null:this.payloadOwnerId??this.providerOwnerId}get ownerConflict(){const e=this.payloadOwnerId,t=this.providerOwnerId;return e!=null&&t!=null&&e!==t}get payloadOwnerId(){var t,n;const e=(n=(t=this.state)==null?void 0:t.end_user)==null?void 0:n.id;return typeof e=="number"&&Number.isFinite(e)?e:null}get providerOwnerId(){const[e,t]=this.userIdentity.split("-"),n=parseInt(t,10);return e===_i.END_USER&&Number.isFinite(n)?n:null}get status(){var e;return((e=this.state)==null?void 0:e.status)||""}get postSessionStatus(){var e;return((e=this.state)==null?void 0:e.post_session_transfer_status)||""}get statusText(){var e;return((e=this.state)==null?void 0:e.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return _W.indexOf(this.status)!=-1}get assigned(){return bO.indexOf(this.status)!=-1}get dismissed(){return SO.indexOf(this.status)!=-1}get ended(){return bW.indexOf(this.status)!=-1}get transcriptCount(){var e;return((e=this.state)==null?void 0:e.transcript_requested_count)||0}get createdAt(){var e;return((e=this.state)==null?void 0:e.created_at)||""}get inTask(){var e;return((e=this.provider)==null?void 0:e.inTask)||!1}get feedbackType(){var e;return this.state?this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none":"none"}get optInRequired(){var e;return((e=this.state)==null?void 0:e.post_session_opt_in_required)||!1}get postSessionRequired(){var e;return((e=this.state)==null?void 0:e.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===cl.IN_PROGRESS:!1}get checkInStatus(){var e;return((e=this.state)==null?void 0:e.check_in_status)??null}set checkInStatus(e){this.state&&(this.state.check_in_status=e)}update(e){if(!this.state||this.state.id!==e.id)return;const t=e.menus[e.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=e,this.syncCacheOwner(),t!==n&&this.triggerEvent("_menuChanged",this),e.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async connect(){if(!this.provider)return Ds.info("connecting interrupted"),!1;this.connecting=!0,this.connectEnd="none";try{if(await jC(()=>this.provider.create(),3),await jC(()=>this.connectEnd!=="none"?Promise.resolve():this.provider.join(this.state.provider_channel_id),3),this.settleEndedConnect())return Ds.info("connect abandoned: connection ended before it was announced"),!1;this.syncCacheOwner(),this.connected=!0;const e=await this.fetchMessages();if(this.destroying)return Ds.info("connect abandoned: chat destroyed while loading history"),!1;if(this.settleEndedConnect())return Ds.info("connect abandoned: connection ended while loading history"),!1;const t={chat:this,messages:e};return this.triggerEvent("connectedMessages",t),this.triggerEvent("connected",this),this.registerProviderEvents(),Ds.info("connected with provider",this.state.provider_type),!0}catch(e){return this.settleEndedConnect(),Ds.error("Failed to connect with provider",e),!1}finally{this.connecting=!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),Ds.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){Ds.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChatBeacon&&(this.beaconAttempted=!0,this.hooks.leaveChatBeacon())}resetBeaconState(){this.beaconAttempted=!1}async sendMessage(e,t){var s,a;if(this.ended)throw new dv(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,TW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){if(this.connected){const e=await this.store.getAllFiles(),t=await this.provider.fetchMessages(e);if(this.destroying||!this.state||!this.provider)return[];for(const i of t)delete i[Ud];return this.syncCacheOwner(),t.filter(i=>this.restoreOwnOriginal(i)).forEach(i=>this.lookupOwnOriginal(i)),t}else throw new Error("Please fetchMessages after chat connected.")}rememberOwnOriginal(e,t){this.destroying||!this.localOriginalCacheEnabled()||(this.syncCacheOwner(),this.originals.remember(e,t))}syncCacheOwner(){if(this.ownerConflict)return this.rebindCacheOwner(SW),null;const e=this.ownUserId;return e==null?typeof this.cacheOwner=="number"?this.cacheOwner:null:(this.rebindCacheOwner(e),e)}rebindCacheOwner(e){e!==this.cacheOwner&&(this.cacheOwner=e,this.revokeOriginals())}revokeOriginals(){this.originals.invalidate();const e=Array.from(this.restoredMessages.values());this.restoredMessages.clear(),this.nextTrackedSweepAt=Ry,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=wW(e);this.restoredMessages.set(e.$sid||t,t),this.restoredMessages.size>this.nextTrackedSweepAt&&(this.restoredMessages.forEach((n,i)=>{n.deref()===void 0&&this.restoredMessages.delete(i)}),this.nextTrackedSweepAt=Math.max(Ry,this.restoredMessages.size*2))}forgetOwnOriginal(e){this.originals.forget(e)}surfacesSubscriptionEnd(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,_O))??!0}settleEndedConnect(){return this.connectEnd==="pending"&&!this.destroying&&(this.endConnection(),this.connectEnd="done"),this.connectEnd!=="none"}localOriginalCacheEnabled(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,hW))??!0}restoreOwnOriginal(e){if(this.destroying||e.$userType!==_i.END_USER)return!1;const t=this.syncCacheOwner();if(t==null)return this.ownerConflict?(delete e.unredacted,!1):(this.applyOriginal(e,e.unredacted),!1);if(e.$userId!==t)return delete e.unredacted,!1;if(this.localOriginalCacheEnabled()&&this.applyOriginal(e,this.originals.lookup(e.client_message_id))||this.applyOriginal(e,e.unredacted))return!1;const n=e.redaction_ref;if(!JC(n)||!this.hooks.fetchMessageOriginal)return!1;const i=this.originals.lookupFetched(n);return i===null?!1:!this.applyOriginal(e,i)}applyOriginal(e,t){if(t===void 0)return!1;const n=typeof t=="string"&&t?Lb(t):"";return n?(e.unredacted=n,this.trackRestored(e),!0):(delete e.unredacted,!1)}lookupOwnOriginal(e){const t=e.redaction_ref,n=this.hooks.fetchMessageOriginal;if(this.destroying||!JC(t)||!n)return;const i=this.id,s=this.syncCacheOwner(),a=this.originals.currentGeneration;this.originals.fetch(t,n).then(c=>{if(!c||this.destroying||!this.state||this.id!==i||this.syncCacheOwner()!==s||a!==this.originals.currentGeneration)return;const o=e.unredacted;!this.applyOriginal(e,c)||e.unredacted===o||this.triggerEvent("messageUpdated",e)}).catch(c=>{Ds.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t,this.store.save(e,t)}async destroy(){this.destroying=!0,this.originals.invalidate(),this.restoredMessages.clear(),await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null,this.originals.invalidate(),this.restoredMessages.clear()}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){this.state&&(this.disconnect(),e.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(e,t){this.events.triggerEvent(e,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+e,t)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(e){switch(e.event){case Er.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case Er.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case Er.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case Er.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case Er.ESCALATION_STARTED:this.inEscalation=!0;break;case Er.ESCALATION_FAILED:case Er.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case Er.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case Er.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const CW=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),kW=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),wO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Iy=()=>kW()&&!CW();function YC(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>RW(n,`${e.comm_id}-${i}`));return e.entries=x6(t),e}),r}function RW(r,e){var t;return{$index:r.timestamp,$sid:e,$timestamp:new Date(r.timestamp),$userType:r.role,$userId:((t=r.user_data)==null?void 0:t.id)||0,user:r.user_data,type:r.type,...r.body}}const IW={en:"English (US)","en-CA":"English (Canada)","en-GB":"English (UK)",es:"Español (España)","es-MX":"Español (México)",fr:"Français (France)","fr-CA":"Français (Canada)",de:"Deutsch",ja:"日本語",ko:"한국어",it:"Italiano",zh:"中文 (简体)","zh-Hant":"中文 (繁體)",sv:"Svenska",pt:"Português (Portugal)","pt-BR":"Português (Brasil)",fi:"Suomi",nb:"Norsk",da:"Dansk",nl:"Nederlands",tr:"Türk",vi:"Tiếng Việt",th:"คนไทย",ar:"اَلْعَرَبِيَّةُ",cs:"Czech",pl:"Polish",hu:"Hungarian"};function PW(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:IW[i.lang]})),name:r.display_name,subdomain:r.subdomain,support_email:r.support_email,action_tracking:r.action_tracking_enabled,email_transcripts:r.chat_settings.email_transcripts,message_preview:r.chat_settings.message_preview,email_enhancement:r.email_enhancement_enabled,display_history:((t=r.chat_settings.display_history)==null?void 0:t.enabled)&&((n=r.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:r.use_recording,use_web:r.use_web,cobrowse_domain:r.cobrowse_domain}}function TO(r){return r.map(AW).filter(e=>e.enabled)}function AW(r){const e={id:r.id,enabled:!0,channels:[],hidden:!!r.hidden};if(!r.name||!r.name.trim())return e.enabled=!1,e;e.name=r.name.trim();const t=OW(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=TO(r.children);return e.enabled=n.length>0||t,e.children=n,e}if(!r.channels)e.enabled=t;else{const{channels:n,deflection:i}=$W(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function OW(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function $W(r){let e=null;const t=[],n=r.chat,i=s=>{!s.deflection_type&&s.deflected_reason&&(s.deflection_type=s.deflected_reason),s.deflected===void 0&&s.deflection_type&&(s.deflected=!0),t.push(s)};return n&&n.deflected&&(e={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...r.chat,type:"chat"}),r.voice_call&&r.voice_call.instant_enabled&&i({...r.voice_call,type:"instant_call"}),r.voice_call&&r.voice_call.schedule_enabled&&i({...r.voice_call,type:"scheduled_call",deflection_type:r.voice_call.schedule_deflection_type}),r.voice_call&&r.voice_call.inbound_enabled&&i({...r.voice_call,type:lv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:lv.VOICEMAIL,deflection_type:r.voice_call.deflected_reason??r.voice_call.voicemail_reason}),r.email&&r.email.enabled&&i({...r.email,type:"email"}),n&&n.deflected&&n.deflected_reason==="over_capacity"&&n.keep_waiting&&i({...n,enabled:!0,type:"keep_waiting",deflection_type:n.deflected_reason}),r.external_deflection_link&&r.external_deflection_link.enabled&&r.external_deflection_link.links.forEach(a=>{a.enabled&&i({...a,type:"external_link"})}),{channels:t,deflection:e}}const xW="ujet_voice_call",EO="twilio_voice",Kn={STATUS_CHANGED:"voice.statusChanged",RECONNECTING:"voice.reconnecting",RECONNECTED:"voice.reconnected",ERROR:"voice.error",SMART_ACTION_REQUESTED:"voice.smartActionRequested",SMART_ACTION_RESOLVED:"voice.smartActionResolved",COBROWSE_REQUESTED:"voice.cobrowseRequested",COBROWSE_RESOLVED:"voice.cobrowseResolved",RECORDING_PERMISSION_REQUIRED:"voice.recordingPermissionRequired",MIC_PERMISSION_REQUIRED:"voice.micPermissionRequired",CONNECTION_QUALITY:"voice.connectionQuality"},Nw=r=>{var e;if(r&&typeof r=="object"){const t=r;if(typeof((e=t.data)==null?void 0:e.message)=="string")return t.data.message;if(typeof t.message=="string")return t.message}return typeof r=="string"?r:String(r)},MW=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,CO=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class ws extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);ye(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Bv=class Bv extends ws{constructor(e="End user has a call in progress"){super(e,Bv.CODE),this.name="CallInProgressError"}};ye(Bv,"CODE","CALL_IN_PROGRESS");let Vu=Bv;const qv=class qv extends ws{constructor(e="Inbound voice is disabled for this menu"){super(e,qv.CODE),this.name="InboundDisabledError"}};ye(qv,"CODE","INBOUND_DISABLED");let ll=qv;const Wv=class Wv extends ws{constructor(e="Outside operation hours"){super(e,Wv.CODE),this.name="OperationHoursError"}};ye(Wv,"CODE","OPERATION_HOURS");let Hu=Wv;const Vv=class Vv extends ws{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Vv.CODE),this.name="FeatureNotEnabledError"}};ye(Vv,"CODE","FEATURE_NOT_ENABLED");let dl=Vv;const Hv=class Hv extends ws{constructor(e="Microphone permission denied",t){super(e,Hv.CODE,t),this.name="MicPermissionDeniedError"}};ye(Hv,"CODE","MIC_PERMISSION_DENIED");let fl=Hv;const Gv=class Gv extends ws{constructor(e="No active voice call"){super(e,Gv.CODE),this.name="NoActiveVoiceCallError"}};ye(Gv,"CODE","NO_ACTIVE_VOICE_CALL");let Uo=Gv;const zv=class zv extends ws{constructor(e="A voice call is active in another tab"){super(e,zv.CODE),this.name="AnotherTabVoiceCallError"}};ye(zv,"CODE","ANOTHER_TAB_VOICE_CALL");let hl=zv;const Kv=class Kv extends ws{constructor(e,t){super(e,Kv.CODE,t),this.name="ProviderError"}};ye(Kv,"CODE","PROVIDER_ERROR");let da=Kv;const Xc=class Xc extends ws{constructor(e,t){super(e,Xc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Xc.ENDED_MESSAGE}};ye(Xc,"CODE","SMART_ACTION_ERROR"),ye(Xc,"ENDED_MESSAGE","smart action is already ended");let ni=Xc;const Jv=class Jv extends ws{constructor(e,t){super(`Unrecognized voice error: ${e}`,Jv.CODE,t),this.name="UnknownVoiceError"}};ye(Jv,"CODE","UNKNOWN_VOICE_ERROR");let hv=Jv;const DW=r=>r instanceof Hu||r instanceof ll||r instanceof dl||r instanceof Vu,Ba=new un("BackgroundKeepAlive");class NW{constructor(e={}){ye(this,"active",!1);ye(this,"currentAgentName",null);ye(this,"wakeLock",null);ye(this,"audioCtx",null);ye(this,"silentSource",null);ye(this,"visibilityListener",null);ye(this,"pagehideListener",null);ye(this,"pageshowListener",null);ye(this,"resumeListener",null);ye(this,"cleanupInvoked",!1);this.deps=e}async start(e={}){this.active||(this.active=!0,this.currentAgentName=e.agentName??null,this.attachLifecycleListeners(),await this.acquireWakeLock(),this.active&&(this.applyMediaMetadata(),this.startSilentAudioLoop()))}updateAgentName(e){this.active&&this.currentAgentName!==e&&(this.currentAgentName=e,this.applyMediaMetadata())}async stop(){this.active&&(this.active=!1,this.detachLifecycleListeners(),await this.releaseWakeLock(),this.clearMediaSession(),this.stopSilentAudioLoop())}attachLifecycleListeners(){typeof document<"u"&&(this.visibilityListener=()=>{document.visibilityState==="visible"&&this.handleVisible()},document.addEventListener("visibilitychange",this.visibilityListener)),!(typeof window>"u")&&(this.pagehideListener=e=>{e!=null&&e.persisted||this.runCleanupOnce()},window.addEventListener("pagehide",this.pagehideListener),this.pageshowListener=e=>{e!=null&&e.persisted&&this.handleVisible()},window.addEventListener("pageshow",this.pageshowListener),this.resumeListener=()=>this.handleVisible(),window.addEventListener("resume",this.resumeListener))}detachLifecycleListeners(){typeof document<"u"&&this.visibilityListener&&document.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListener=null,typeof window<"u"&&(this.pagehideListener&&window.removeEventListener("pagehide",this.pagehideListener),this.pageshowListener&&window.removeEventListener("pageshow",this.pageshowListener),this.resumeListener&&window.removeEventListener("resume",this.resumeListener)),this.pagehideListener=null,this.pageshowListener=null,this.resumeListener=null}runCleanupOnce(){var e,t;if(!this.cleanupInvoked){this.cleanupInvoked=!0;try{(t=(e=this.deps).onCleanup)==null||t.call(e)}catch(n){Ba.debug("onCleanup threw during unload",n)}this.stop().catch(n=>Ba.debug("stop() during cleanup failed",n))}}handleVisible(){var e,t;(t=(e=this.audioCtx)==null?void 0:e.resume)==null||t.call(e).catch(n=>Ba.debug("audioCtx.resume failed",n)),this.acquireWakeLock(),this.applyMediaMetadata()}async acquireWakeLock(){if(typeof navigator>"u")return;const e=navigator.wakeLock;if(e!=null&&e.request&&!this.wakeLock)try{this.wakeLock=await e.request("screen")}catch(t){Ba.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){Ba.debug("wakeLock.release failed",e)}this.wakeLock=null}}applyMediaMetadata(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(!e)return;const t=globalThis.MediaMetadata;if(typeof t=="function")try{e.metadata=new t({title:this.currentAgentName?`Call with ${this.currentAgentName}`:"Voice call"})}catch(n){Ba.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){Ba.debug("mediaSession.metadata clear failed",t)}}startSilentAudioLoop(){if(typeof window>"u")return;const e=window.AudioContext||window.webkitAudioContext;if(typeof e=="function")try{this.audioCtx=new e;const t=this.audioCtx.createBuffer(1,1,22050),n=this.audioCtx.createBufferSource();n.buffer=t,n.loop=!0,n.connect(this.audioCtx.destination),n.start(),this.silentSource=n}catch(t){Ba.debug("silent audio loop start failed",t),this.audioCtx=null,this.silentSource=null}}stopSilentAudioLoop(){var e,t,n,i;try{(e=this.silentSource)==null||e.stop()}catch{}try{(t=this.silentSource)==null||t.disconnect()}catch{}this.silentSource=null,(i=(n=this.audioCtx)==null?void 0:n.close)==null||i.call(n).catch(s=>Ba.debug("audioCtx.close failed",s)),this.audioCtx=null}}const ps={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},kO="_provider.messageReceived",Oo={SMART_ACTION_REQUESTED:"smart_action_requested",SMART_ACTION_RESOLVED:"smart_action_resolved",RECORDING_PERMISSION_REQUIRED:"recording_permission_required",STATUS_CHANGED:"status_changed",SMART_ACTION_NOTIFIED:"smart_action_notified",SMART_ACTION_RESPONSE:"smart_action_response",RECORDING_PERMISSION:"recording_permission"},Wc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Py=r=>{switch(r){case"queued":case"assigned":return"queued";case"connecting":case"va_assigned":case"switching":return"connecting";case"connected":case"va_connected":return"connected";case"reconnecting":return"interrupted";case"finished":case"recovered":case"voicemail":case"canceled":case"timeout":return"ended";case"failed":return"error";case"scheduled":return"idle";default:return"error"}};class LW{constructor(e){ye(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return Wc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Ay="ujet:",br={set(r,e){try{localStorage.setItem(Ay+r,e)}catch{}},get(r){try{return localStorage.getItem(Ay+r)}catch{return null}},del(r){try{localStorage.removeItem(Ay+r)}catch{}}},pv="voice",UW=r=>{br.set(pv,String(r))},XC=()=>{const r=br.get(pv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(br.del(pv),null)},Vc=()=>{br.del(pv)},FW=new Set(["connected","va_connected"]),Oy=r=>FW.has(r),jW=new Set(["finished","canceled","expired"]),BW=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class qW{constructor(e,t,n,i,s){ye(this,"_state");ye(this,"_publicState",null);ye(this,"events");ye(this,"provider");ye(this,"methods");ye(this,"globalEvents");ye(this,"logger");ye(this,"destroyed",!1);ye(this,"isProviderConnected",!1);ye(this,"isUnloading",!1);ye(this,"startedAt",null);ye(this,"fetchEpoch",0);ye(this,"keepAlive",null);ye(this,"stateMachine");ye(this,"handledSmartActionIds",new Set);ye(this,"smartActionQueue",[]);ye(this,"currentCobrowseSmartActionId",null);ye(this,"recordingPermissionAsked",!1);ye(this,"speakerOn",!1);ye(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new Qv,this.logger=new un(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new LW(e.status),Oy(e.status)&&(this.startedAt=this.resolveStartedAtFromState()),this.registerProviderEvents()}setInternalState(e){this._state=e,this._publicState=null}get state(){if(!this._publicState){const{status:e,...t}=this._state;this._publicState=t}return this._publicState}serverStatus(){return this._state.status}get currentSmartActionId(){return this.smartActionQueue[0]??null}resolveStartedAtFromState(){const t=(this.state.participants??[]).find(n=>(n.type==="agent"||n.type==="virtual_agent")&&n.connected_at);if(t!=null&&t.connected_at){const n=new Date(t.connected_at).getTime();if(!Number.isNaN(n))return n}return Date.now()}setStatus(e,t){if(this.isUnloading)return!1;const n=this.stateMachine.transitionTo(e);if(n===null)return!1;if(this.setInternalState({...this._state,status:e}),this.stateMachine.isTerminal&&Vc(),(t==null?void 0:t.emit)!==!1){const i=(t==null?void 0:t.serverPrev)??n;this.globalEvents.triggerEvent(Kn.STATUS_CHANGED,{id:this.id,status:Py(e),prevStatus:Py(i)})}return!0}teardownActiveResources(){this.keepAlive&&(this.keepAlive.stop().catch(e=>this.logger.debug("keepAlive.stop failed",e)),this.keepAlive=null)}get id(){return this.state.id}get status(){return Py(this._state.status)}get agent(){return this.state.agent??this.state.virtual_agent??null}get duration(){return this.startedAt?Math.floor((Date.now()-this.startedAt)/1e3):0}get feedbackType(){var e;return this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none"}get recordingPermissionRequired(){return this.state.recording_option==="record_ask_user"&&this.state.recording_permission==="recording_permission_not_asked"&&!this.recordingPermissionAsked}async _connect(){var t;if(this.destroyed||this.isProviderConnected)return;if(await this.provider.create(),this.destroyed){await this.provider.destroy().catch(n=>{this.logger.debug("provider.destroy() during _connect race failed",n)});return}this.isProviderConnected=!0,this.recordingPermissionRequired&&this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});const e=(this.state.smart_actions??[]).filter(n=>!jW.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new NW({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;Oy(n)||n==="reconnecting"||Vc();try{this.provider.destroy()}catch{}}}),this.keepAlive.start({agentName:(t=this.agent)==null?void 0:t.name}).catch(n=>{this.logger.warn("background keep-alive start failed",n)})}_markUnloading(){this.isUnloading=!0}async _abandonOrFinish(){if(this.stateMachine.isTerminal)return;this.teardownActiveResources();const e=Oy(this._state.status);if(this.isProviderConnected)try{await this.provider.hangup()}catch(t){this.logger.warn("provider hangup failed",t)}try{!e&&this.methods.failCall?await this.methods.failCall(this.id,"abandoned"):this.methods.finishCall&&await this.methods.finishCall(this.id)}catch(t){this.logger.warn("server-side hangup failed",t)}this.setStatus("finished",{emit:!this.isProviderConnected})}async _destroy(){this.destroyed||(this.destroyed=!0,this.teardownActiveResources(),await this._abandonOrFinish().catch(e=>this.logger.warn("hangup during destroy failed",e)),await this.provider.destroy(),this.events.destroy())}mute(e){this.destroyed||this.isMuted()!==e&&this.provider.mute(e)}isMuted(){return this.provider.isMuted()}getRemoteAudioStream(){return this.destroyed?null:this.provider.getRemoteStream()}isSpeakerSupported(){return this.destroyed?!1:this.provider.isOutputSelectionSupported()}isSpeakerOn(){return this.speakerOn}async setSpeakerOn(e){if(!this.destroyed){if(!this.provider.isOutputSelectionSupported()){this.speakerOn=e;return}if(e){const t=this.provider.getAvailableOutputDevices().find(n=>/speaker|loud|external/i.test(n.label));if(!t)throw new da("no loudspeaker output available");await this.provider.setOutputDevice(t.deviceId)}else await this.provider.setOutputDevice("default");this.speakerOn=e}}async _escalate(){this.methods.escalateCall&&await this.methods.escalateCall(this.id)}async grantRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!0})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!0)}async denyRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!1})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!1)}async startCobrowse(e,t="end_user"){return this.cobrowseStarter(e??this.state.lang,t)}async submitTextSmartAction(e,t){await this.resolveSmartAction(e,{status:"finished",data:{text:t}})}async confirmVerificationSmartAction(e){await this.resolveSmartAction(e,{status:"finished"})}async cancelSmartAction(e){await this.resolveSmartAction(e,{status:"canceled"})}async uploadMediaForSmartAction(e,t,n){if(n==="video"){if(!this.methods.uploadVideos)throw new ni("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ni("uploadPhotos not configured");await this.methods.uploadPhotos(this.id,t,n,e)}this.markSmartActionHandled(e)}async prepareMediaUpload(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ni("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ni("uploadOnePhoto not configured");return{ref:await this.methods.uploadOnePhoto(this.id,e,n),kind:t}}async submitMediaRefsForSmartAction(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(n.length===0)throw new ni("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ni(`media ref kind '${i.kind}' does not match SmartAction type '${t}'`);const s=n.map(a=>a.ref);if(t==="video"){if(!this.methods.registerVideos)throw new ni("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ni("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(ps.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(ps.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(ps.ERROR,e=>{this.destroyed||this.stateMachine.isTerminal||(this.logger.warn("provider reported a fatal error",e),this.isProviderConnected=!1,this.teardownActiveResources(),this.globalEvents.triggerEvent(Kn.ERROR,{id:this.id,error:e==null?void 0:e.error}),this.setStatus("failed"))});for(const e of BW)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(kO,e=>{this.handleProviderMessage(e)})}async fetchAndUpdateState(){const e=++this.fetchEpoch;try{const t=await this.methods.fetchCall(this.id);if(e!==this.fetchEpoch||this.destroyed)return;this.setInternalState({...this._state,...t,status:this._state.status})}catch(t){this.logger.warn("on-demand fetchCall failed",t)}}handleProviderMessage(e){if(this.destroyed||this.isUnloading)return;const{type:t,data:n={}}=e;switch(t){case Oo.SMART_ACTION_REQUESTED:this.handleSmartActionRequested(n.smart_action);break;case Oo.SMART_ACTION_RESOLVED:this.handleSmartActionResolved(n);break;case Oo.RECORDING_PERMISSION_REQUIRED:if(this.recordingPermissionAsked)break;this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});break;case Oo.STATUS_CHANGED:this.handleStatusChanged(n);break;default:this.logger.debug("unhandled provider message type",t)}}handleSmartActionRequested(e){if(!e||this.handledSmartActionIds.has(e.id))return;if(e.type==="cobrowse"){if(this.currentCobrowseSmartActionId===e.id)return;this.currentCobrowseSmartActionId=e.id,this.globalEvents.triggerEvent(Kn.COBROWSE_REQUESTED,{smartAction:e})}else{if(this.smartActionQueue.includes(e.id))return;this.smartActionQueue.push(e.id),this.globalEvents.triggerEvent(Kn.SMART_ACTION_REQUESTED,{smartAction:e})}this.sendProviderMessage(Oo.SMART_ACTION_NOTIFIED,{smart_action_id:e.id})}handleSmartActionResolved(e){const t=e.smart_action_id;t&&(this.smartActionQueue.includes(t)&&this.globalEvents.triggerEvent(Kn.SMART_ACTION_RESOLVED,{smartActionId:t}),this.currentCobrowseSmartActionId===t&&(this.currentCobrowseSmartActionId=null,this.globalEvents.triggerEvent(Kn.COBROWSE_RESOLVED,{smartActionId:t})),this.markSmartActionHandled(t))}handleStatusChanged(e){var n,i,s;if(!e.status||this.stateMachine.isTerminal)return;if(this.fetchEpoch++,(e.agent||e.virtual_agent)&&this.setInternalState({...this._state,...e.agent&&{agent:e.agent},...e.virtual_agent&&{virtual_agent:e.virtual_agent}}),!Wc.has(e.status)){const a=((n=this._state.agent)==null?void 0:n.name)??((i=this._state.virtual_agent)==null?void 0:i.name)??null;(s=this.keepAlive)==null||s.updateAgentName(a),e.status==="connected"&&this.fetchAndUpdateState().then(()=>{this.destroyed||this._state.status!=="connected"||(this.startedAt=this.resolveStartedAtFromState())})}this.setStatus(e.status,{serverPrev:e.prev_status})}sendProviderMessage(e,t){return this.provider.sendMessage({type:e,data:t})!==null}markSmartActionHandled(e){this.handledSmartActionIds.add(e);const t=this.smartActionQueue.indexOf(e);t>=0&&this.smartActionQueue.splice(t,1)}async resolveSmartAction(e,t){if(this.sendProviderMessage(Oo.SMART_ACTION_RESPONSE,{smart_action_id:e,status:t.status,data:t.data,fail_reason:t.fail_reason})){this.markSmartActionHandled(e);return}if(!this.methods.updateSmartAction)throw new ni("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Nw(n);if(i===ni.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ni(i,n)}}}class Lw{constructor(e,t,n){ye(this,"events");ye(this,"state");ye(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}ye(Lw,"type","base");const RO={},IO=r=>{RO[r.type]=r},PO=r=>RO[r],$h=new un("methods"),QC=!0,WW="web-4191-refresh-unknown-chat-agent";class VW{constructor(e,t,n,i){ye(this,"request");ye(this,"lastDapRequestId",null);ye(this,"lastDirectAccessKeyId",null);ye(this,"dapPollGeneration",0);ye(this,"beaconLeaveChat");ye(this,"authContext");ye(this,"isRiskFlagEnabled");ye(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){$h.error(`Error fetching form data:, ${n}`)}});this.request=e,this.beaconLeaveChat=t,this.authContext=n,this.isRiskFlagEnabled=i}get(e,t){if(t){const n=[];Object.keys(t).forEach(i=>{const s=t[i];s!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}),e+="?"+n.join("&")}return this.request(e,{method:"GET"})}post(e,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(e,n)}patch(e,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(e,n)}put(e,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(e,n)}async getTriggers(e){const t={"UJET-Company-Id":e};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}submitCustomForm(e){return this.post("forms/submit",e)}async trackClientEvents(e){return await this.post("/client_events",{events:e})}async getCompany(){const e=await this.get("company");return PW(e.data)}async getFeatureFlags(){return(await this.get("feature_flags")).data}async getMenus(e,t,n){const i=this.dapPollGeneration,s={type:"web_menu",lang:e,direct_access_key:t};n!=null&&n.initialMessage&&(s.initial_message=n.initialMessage),n!=null&&n.signedCustomData&&(s.custom_data_signed=n.signedCustomData),n!=null&&n.customData&&(s.custom_data_unsigned=n.customData);let a=await this.post("menus",s);this.stashDapRequestId(a),this.isChatDapPending(a.data)&&(a=await this.pollChatDap(e,Number(a.data.max_timeout)||0,i));const c=a.headers["ujet-direct-access"],l={key:!!t,user:!!c&&c!=="false",key_id:null},d=a.headers["ujet-direct-access-key-id"];if(d){const y=Number(d);Number.isFinite(y)&&(l.key_id=y)}this.lastDirectAccessKeyId=l.key_id;let h=[];return Array.isArray(a.data)?h=a.data:$h.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:TO(h),direct:l}}stashDapRequestId(e){const t=e.headers["ujet-dap-request-id"];this.lastDapRequestId=typeof t=="string"&&t?t:null}isChatDapPending(e){return e&&!Array.isArray(e)&&e.status==="PENDING"}cancelDapPolling(){this.dapPollGeneration++}fetchRootMenus(e){return this.get("menus",{type:"web_menu",lang:e})}async pollChatDap(e,t,n){const i=this.lastDapRequestId;if(!i)return $h.warn("chat DAP pending response missing dap_request_id; falling back to root menus"),await this.fetchRootMenus(e);const s=2e3,a=Math.max(t,0)*1e3;let c=0;for(;c<a;){if(await Xd(s),c+=s,this.dapPollGeneration!==n)return{headers:{},data:[]};const o=await this.get("menus",{type:"web_menu",lang:e,dap_request_id:i});if(!this.isChatDapPending(o.data))return o}return await this.fetchRootMenus(e)}async getAfterHourMessage(e){return(await this.get(`audible_messages/${e}`)).data["after_hours.message"].text}async getTimeSlots(e,t={}){const n=t.lang||"en",i=t.rescheduleCallId;return(await this.get(`menus/${e}/time_slots`,{type:"web_menu",lang:n,reschedule_call_id:i,use_advanced_call_scheduling:QC})).data}async fetchTimeSlotAvailability(e,t="en"){return(await this.get(`menus/${e}/time_slots_available`,{type:"web_menu",lang:t})).data.slots_available}async getWaitTimes(e,t="en"){return(await this.get(`menus/${e}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(e){try{return await this.post("forms/verify",e),!0}catch{return!1}}async finishChat(e){return(await this.patch(`chats/${e}`,{status:"finished"})).data}async fetchUjetConversationMessages(e,t={}){return(await this.get(`chats/${e}/ujet_conversation/messages`,{limit:t.limit,before:t.before})).data}async leaveChat(e){await this.post(`chats/${e}/leave`,{})}leaveChatBeacon(e){var t;(t=this.beaconLeaveChat)==null||t.call(this,e)}async updatePostSession(e,t,n){const i={post_session_transfer_status:t};n!==void 0&&(i.post_session_opt_in_selection=n);try{return(await this.patch(`chats/${e}`,i)).data}catch(s){if(t===cl.IN_PROGRESS&&s.status===400)return(await this.patch(`chats/${e}`,i)).data;throw s}}async getChatDeflection(e){const{data:t}=await this.get(`chats/${e}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(e,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${e}/custom_data`,n)}async downloadChatTranscript(e){return(await this.post(`chats/${e}/generate_transcript_pdf`,{})).data}async getPdfStatus(e){return await this.get(`chat_transcript_pdfs/${e}/download_transcript`)}async sendChatTranscripts(e,t){return await this.post(`chats/${e}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(e){return(await this.get(`chats/${e}/task_va_messages`)).data}async getChatTaskMessage(e,t){return(await this.get(`chats/${e}/task_va_messages/${t}`)).data}async sendChatTaskMessage(e,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${e}/task_va_messages`,n)).data}async sendChatTextMessage(e,t,n){const i={message:{content:t,timestamp:new Date().toISOString()}};n&&(i.message.client_message_id=n),await this.post(`chats/${e}/messages`,i)}async getChatMessageOriginal(e,t){return(await this.get(`chats/${e}/messages/${t}/original`)).data}async sendPreviewMessage(e,t,n){const i={message:{content:t,timestamp:n}},{data:s}=await this.post(`chats/${e}/redact_messages`,i);return s}escalateChat(e,t){return this.post(`chats/${e}/escalations`,t)}trackEscalation(e,t,n){return this.put(`chats/${e}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(e,t){return this.post(`chats/${e}/cobrowse`,t)}requestVoiceCallCobrowse(e,t){return this.post(`calls/${e}/cobrowse`,t)}rateChat(e,t){return this.patch(`chats/${e}/rating`,t)}async getChatSurvey(e){return(await this.get(`chats/${e}/survey`)).data}sendChatSurvey(e,t){const n={chat_id:e,answers:t};return this.put(`chats/${e}/survey`,n)}trackChatEndUserEvent(e,t){return this.post(`chats/${e}/end_user_event`,t)}async createChat(e,t,n,i){const s={menu_id:e,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data};this.lastDirectAccessKeyId!==null&&(s.direct_access_key_id=this.lastDirectAccessKeyId),this.lastDapRequestId&&(s.dap_request_id=this.lastDapRequestId);const a={chat:s,cobrowsable:n.cobrowsable},c=await this.post("chats",a);this.lastDapRequestId=null;const o=c.data;return this.wrapChat(o,i)}async loadChat(e,t){const n=await this.getChat(e);return this.wrapChat(n,t)}async resumeChat(e,t){const n=await this.patch(`chats/${e}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(e=1){if(e===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return YC(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return YC(t)}}async uploadChatFile(e,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":t.type==="application/pdf"&&(n="document");const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(`chats/${e}/${n}s/upload`,{filename:i}),a={file:t,fields:s.data.fields};Iy()&&(a.file=await Ub(t));const o=(await this.request(s.data.url,a)).data.key,d=(await this.post(`chats/${e}/${n}s`,{chat_id:e,[n]:{s3_path:o,photo_type:n,filename:t.name,content_type:t.type,file_size:t.size}})).data;return d.type=n,d}buildProviderContext(e){if(this.authContext)return{getAuthToken:this.authContext.getAuthToken,wsUrl:this.authContext.wsUrl,fetchHistory:t=>this.fetchUjetConversationMessages(e,t),isRiskFlagEnabled:this.isRiskFlagEnabled}}async getChat(e){return(await this.get(`chats/${e}`)).data}async wrapChat(e,t){const n=async()=>(await this.post(`chats/${e.id}/tokens`,{provider_type:e.provider_type,device_id:t})).data,i=()=>this.leaveChat(e.id),s=()=>this.leaveChatBeacon(e.id),a=d=>this.getChatMessageOriginal(e.id,d),c=new EW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a},this.buildProviderContext(e.id)),o=async d=>{if(c.status==="va_assigned"){const h=await this.getSkipVirtualAgentSettings(c.menuId,c.lang);c.allowSkipVirtualAgent=h,c.update(d)}};c.on("initialized",async()=>{if(c.status==="queued"){const d=await this.getChat(c.id);c.update(d)}}),c.on("memberJoined",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("memberLeft",async()=>{const d=await this.getChat(c.id);c.update(d)});let l=!1;if(c.on("message",d=>{var h;!c.connected||!c.ongoing||l||d.$userType!==_i.USER||!Number.isSafeInteger(d.$userId)||d.$userId<=0||c.allAgents.human.some(v=>v.id===d.$userId)||((h=this.isRiskFlagEnabled)==null?void 0:h.call(this,WW))===!1||(l=!0,this.getChat(c.id).then(v=>{c.connected&&c.ongoing&&c.update(v)}).catch(()=>{$h.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{l=!1}))}),c.on("_chatEnded",async d=>{const h=await this.getChat(c.id);c.update(h),(!c.state||c.ended)&&c._handleChatEndedEvent(d)}),c.on("_menuChanged",async d=>{const h=await this.getChat(d.id);o(h)}),c.on("checkInRequired",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("checkInTimedOut",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.channelId)c.connect(),o(e);else{let d;for(;!d;)await this.getChat(c.id).then(h=>{h.provider_channel_id&&c.state?(d=!0,c.update(h),c.connect(),o(h)):(h.status==="canceled"||h.status==="finished")&&(d=!0)}),d||await Xd(1500)}return c}async createVoiceCall(e,t,n,i,s,a){const c={call:{type:"web_inbound_call",menu_id:e,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission,custom_data:n.custom_data,voicemail_reason:n.voicemail_reason},cobrowsable:n.cobrowsable??!1},o=await this.post("calls",c);return this.wrapVoiceCall(o.data,i,s,a)}async requestVoiceToken(e,t){return(await this.post(`calls/${e}/tokens`,{device_id:t})).data}async fetchVoiceCall(e){return(await this.get(`calls/${e}`)).data}async hangupVoiceCall(e){await this.patch(`calls/${e}`,{status:"finished"})}async failVoiceCall(e,t="abandoned",n){await this.patch(`calls/${e}`,{status:"failed",fail_reason:t,fail_details:n})}async updateVoiceCallRecordingPermission(e,t){await this.patch(`calls/${e}`,{recording_permission:t?"recording_permission_granted":"recording_permission_denied"})}async escalateVoiceCall(e){await this.post(`calls/${e}/escalate`,{})}rateVoiceCall(e,t){return this.put(`calls/${e}/rating`,t)}async getVoiceCallSurvey(e){return(await this.get(`calls/${e}/survey`)).data}submitVoiceCallSurvey(e,t){const n={call_id:e,answers:t};return this.put(`calls/${e}/survey`,n)}async updateVoiceSmartAction(e,t,n){await this.put(`calls/${e}/smart_actions/${t}`,n)}async uploadVoiceCallPhotoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/photos/upload`,t,n)}async registerVoiceCallPhotos(e,t,n,i){const s=n.map(c=>({s3_path:c,photo_type:t}));return((await this.post(`calls/${e}/photos`,{photo:s,photo_type:t,multiple:!0,smart_action_id:i})).data||[]).map(c=>c.media_id)}async uploadVoiceCallPhotos(e,t,n,i){const s=await Promise.all(t.map(a=>this.uploadVoiceCallPhotoSingle(e,a)));return await this.registerVoiceCallPhotos(e,n,s,i)}async uploadVoiceCallVideoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/videos/upload`,t,n)}async registerVoiceCallVideos(e,t,n){return await Promise.all(t.map(async i=>(await this.post(`calls/${e}/videos`,{video:{s3_path:i},smart_action_id:n})).data.media_id))}async uploadVoiceCallVideos(e,t,n){const i=await Promise.all(t.map(s=>this.uploadVoiceCallVideoSingle(e,s)));return await this.registerVoiceCallVideos(e,i,n)}async uploadFileToExternalStorage(e,t,n){const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(e,{filename:i});if(wO())return await lW(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Iy()&&(a.file=await Ub(t)),(await this.request(s.data.url,a)).data.key}async _wrapVoiceCallForRestore(e,t,n,i){return this.wrapVoiceCall(e,t,n,i)}async wrapVoiceCall(e,t,n,i){const s=async()=>await this.requestVoiceToken(e.id,t),a=async L=>await this.fetchVoiceCall(L),c=async L=>await this.hangupVoiceCall(L),o=async(L,x,B)=>await this.failVoiceCall(L,x,B),l=async L=>await this.escalateVoiceCall(L),d=async(L,x)=>await this.updateVoiceCallRecordingPermission(L,x),h=async(L,x,B)=>await this.updateVoiceSmartAction(L,x,B),v=async(L,x,B,G)=>{await this.uploadVoiceCallPhotos(L,x,B,G)},y=async(L,x,B)=>{await this.uploadVoiceCallVideos(L,x,B)},w=async(L,x,B)=>await this.uploadVoiceCallPhotoSingle(L,x,B),k=async(L,x,B)=>await this.uploadVoiceCallVideoSingle(L,x,B),P=async(L,x,B,G)=>{await this.registerVoiceCallPhotos(L,x,B,G)},A=async(L,x,B)=>{await this.registerVoiceCallVideos(L,x,B)},U=PO(this.resolveVoiceProviderType(e));if(!U)throw new da(`No voice provider registered for ${e.voip_provider}`);return new qW(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:v,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:P,registerVideos:A},U,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?EO:e.voip_provider}async createCall(e,t){const n={type:t.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:e,lang:t.lang,email:t.email,ticket_id:t.ticket_id,recording_permission:t.recording_permission||"recording_permission_not_asked",scheduled_at:t.scheduled_at,custom_data:t.custom_data,end_user:{phone_number:t.phone_number}},s=(await this.post("calls",{call:n,cobrowsable:!1,use_advanced_call_scheduling:QC,reschedule_call_id:t.reschedule_call_id})).data,{selected_menu:a,...c}=s;return{...c,menu_id:a.id}}async fetchCall(e){const n=(await this.get(`calls/${e}`)).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async cancelCall(e){const n=(await this.patch(`calls/${e}`,{status:"failed",fail_reason:"canceled"})).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(e,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:e.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&Iy()?i["email_attachments[]"]=await HW(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),(await this.request("emails",{form:i})).data}async getMedia(e,t){const n=await this.get(`media/${e}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getChatDocuments(e){const t=await this.get(`chats/${e}/documents`);return Array.isArray(t.data)?t.data:[]}async getSkipVirtualAgentSettings(e,t){return(await this.get(`menus/${e}/virtual_agent_settings`,{lang:t})).data.allow_skip_virtual_agent}async confirmCheckIn(e){return(await this.post(`chats/${e}/check_in/confirm`,null)).data}async rejoinQueue(e){return(await this.post(`chats/${e}/check_in/rejoin`,null)).data}async exitCheckIn(e){return(await this.post(`chats/${e}/check_in/exit`,null)).data}async trackCheckIn(e,t){await this.post(`chats/${e}/check_in/modal_shown`,t)}async notifyCheckInState(e,t){await this.post(`chats/${e}/check_in/end_user_status`,t)}}function HW(r){return Promise.all(r.map(Ub))}function Ub(r){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],s={type:r.type,lastModified:r.lastModified};e({name:r.name,fileBits:i,options:s})},n.onerror=t,n.readAsArrayBuffer(r)})}const AO=new un("CobrowseService");async function GW(r){return window.CobrowseIO?window.CobrowseIO:await zW(r)}async function zW(r){return new Promise(e=>{const t=document.createElement("script");t.src=r,t.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n),t.onload=function(){e(window.CobrowseIO)},t.onerror=function(){AO.error("Failed to load cobrowse script",r),e(null)}})}const ZC="https://js.cobrowse.io/CobrowseIO.js";function KW(r){return!r||r.toLowerCase()==="https://cobrowse.io"?ZC:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(AO.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),ZC)}async function JW(r,e){let t=r.instance;if(!t){const n=KW(e);t=await GW(n)}return new YW(t,r)}class YW{constructor(e,t){ye(this,"_cobrowseIO");if(this._cobrowseIO=e,!e)return;e.license=t.license;const n=t.trustedOrigins||[];n.push(location.origin),e.trustedOrigins=n,["api","capabilities","registration","messages","redactedViews","unredactedViews","confirmSession","confirmRemoteControl","confirmFullDevice","showSessionControls","hideSessionControls"].forEach(s=>{t[s]!==void 0&&(e[s]=t[s])})}get cobrowseIO(){return this._cobrowseIO}async start(){await this._cobrowseIO.client(),await this._cobrowseIO.start()}}const XW=Date.now(),OO={href:window.location.href,interval:24*60*60};function QW(r){if(!Array.isArray(r)||!r.length)return null;const e=n5(),t=e===0,n=e+1;return i5(n),r.filter(s=>{const a=e5(s,OO.href),c=t5(s.visitor_type,t),o=n>=s.page_visit_count,l=!r5(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function ZW(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-XW),0);setTimeout(()=>{e(r),br.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const e5=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(v6(t,n,i,s))return!0;if(t.length||n.length){const o=t.some(d=>d.every(h=>e.includes(h))),l=n.length>0&&n.every(d=>d.every(h=>!e.includes(h)));return o||l}const a=i.filter(o=>e.indexOf(o)!==-1).length,c=s.filter(o=>e.indexOf(o)===-1).length;return!!a||!!c};function t5(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function r5(r){try{const e=parseInt(br.get(`trigger:${r}`),10);return Date.now()/1e3-e<OO.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function n5(){try{const r=br.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function i5(r){try{br.set("visits",r.toString())}catch(e){console.error(e)}}function s5(r){return r.replace(/\/+$/,"")}const $y=new un("VoiceMultiTab"),Fb="voice:tab-lock",a5=5e3,o5=2e3,u5=250,xy=()=>{const r=br.get(Fb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},My=()=>{var i;const r=xy();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<a5)throw new hl;const e=xw(),t=()=>{br.set(Fb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=xy())==null?void 0:i.id)!==e)throw new hl;const n=setInterval(t,o5);return{release(){clearInterval(n);const s=xy();(!s||s.id===e)&&br.del(Fb)}}},ek=async()=>{if(typeof BroadcastChannel>"u")return My();let r;try{r=new BroadcastChannel(xW)}catch{return My()}const e=xw();let t=!1;r.onmessage=n=>{const i=n.data;(i.kind==="present"||i.kind==="claim")&&i.id!==e&&(t=!0)};try{r.postMessage({kind:"claim",id:e})}catch(n){$y.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return My()}if(await new Promise(n=>setTimeout(n,u5)),t)throw r.close(),new hl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){$y.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){$y.debug("BC postMessage(release) failed",n)}r.close()}}},c5=["photo","video","audio","document"],qa=new un("client");function l5(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let d5=class{constructor(e){ye(this,"VERSION",Mw);ye(this,"options");ye(this,"communicator");ye(this,"methods");ye(this,"events",new Qv);ye(this,"request");ye(this,"chat");ye(this,"_cobrowse");ye(this,"_voiceCall",null);ye(this,"_voiceTabLock",null);ye(this,"redactionSendQueue",Promise.resolve());ye(this,"fileSendQueue",Promise.resolve());ye(this,"_rehydratePromise",null);ye(this,"onPageHide");ye(this,"onPageShow");this.options=e.host?{...e,host:s5(e.host)}:e,this.communicator=new P6(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new VW(t,n,{getAuthToken:this.communicator.getAuthToken.bind(this.communicator),wsUrl:this.communicator.wsUrl},this.communicator.isRiskFlagEnabled.bind(this.communicator)),this.request=t,this.options.host&&cO.setPath(this.options.host),zn.companyId=e.companyId,e.tenant&&(zn.tenant=e.tenant),this.events.addEventListener(Kn.STATUS_CHANGED,i=>{(i==null?void 0:i.status)==="error"&&this.releaseVoiceTabLock()}),this.registerUnloadHandlers()}registerUnloadHandlers(){typeof window>"u"||(this.onPageHide=e=>{var t,n;e.persisted||((t=this.chat)==null||t.leaveBeacon(),(n=this._voiceCall)==null||n._markUnloading(),this.releaseVoiceTabLock())},this.onPageShow=e=>{var t;e.persisted&&((t=this.chat)==null||t.resetBeaconState())},window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow))}unregisterUnloadHandlers(){typeof window>"u"||(this.onPageHide&&(window.removeEventListener("pagehide",this.onPageHide),this.onPageHide=void 0),this.onPageShow&&(window.removeEventListener("pageshow",this.onPageShow),this.onPageShow=void 0))}get deviceId(){return zn.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:br.get("lang")||"en"}set lang(e){this.options.lang||br.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){this.destroyVoiceCall().catch(()=>{}),this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}destroyDuplicate(){this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}releaseVoiceTabLock(){var e;(e=this._voiceTabLock)==null||e.release(),this._voiceTabLock=null}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async checkMicPermission(){var e;if(typeof navigator>"u"||!((e=navigator.permissions)!=null&&e.query))return"unknown";try{const n=(await navigator.permissions.query({name:"microphone"})).state;return n==="granted"||n==="denied"||n==="prompt"?n:"unknown"}catch{return"unknown"}}async getCompany(){const e=await this.methods.getCompany();return zn.tenant=e.subdomain,e}async getFeatureFlags(){return await this.methods.getFeatureFlags()}isRiskFlagEnabled(e){return this.communicator.isRiskFlagEnabled(e)}getRiskFlags(){return this.communicator.getRiskFlags()}async runTrigger(e){const t=await this.methods.getTriggers(this.options.companyId),n=QW(t);n&&ZW(n,e)}async trackClientEvents(e){await this.methods.trackClientEvents(e)}async getProhibitedFileTypes(){return await this.methods.listFileTypes()}async getMenus(e,t,n){return await this.methods.getMenus(t||this.lang,e,n)}cancelMenuPolling(){this.methods.cancelDapPolling()}getCustomFormData(e){return this.methods.getCustomFormData(e)}submitCustomForm(e){return this.methods.submitCustomForm(e)}async getAfterHourMessage(e){return await this.methods.getAfterHourMessage(e||this.lang)}async getTimeSlots(e,t){return(i=>typeof i=="object"&&i!==null)(t)?await this.methods.getTimeSlots(e,{lang:t.lang||this.lang,rescheduleCallId:t.rescheduleCallId}):await this.methods.getTimeSlots(e,{lang:t||this.lang})}async fetchTimeSlotAvailability(e,t){return await this.methods.fetchTimeSlotAvailability(e,t||this.lang)}async getWaitTimes(e,t){return await this.methods.getWaitTimes(e,t||this.lang)}async verifyForm(e){return await this.methods.verifyForm(e)}async createCall(e,t){var i;!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email);const n={...t,lang:t.lang||this.lang};return await this.methods.createCall(Number(e),n)}async loadCall(e){return await this.methods.fetchCall(e)}async cancelCall(e){return await this.methods.cancelCall(e)}async createEmail(e,t){return await this.methods.createEmail(e,t.lang||this.lang,t)}async createChat(e,t={}){var i,s;if(!this.chat&&br.get("chat")&&await this.loadOngoingChat().catch(()=>null),this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=!!((s=this.options.cobrowse)!=null&&s.enabled));const n=await this.methods.createChat(Number(e),t.lang||this.lang,t,this.deviceId);return this.registerOngoingChat(n),await n.clearMediaStore(),n}async loadChat(e){try{const t=await this.methods.loadChat(e,this.deviceId);return t.ongoing?this.registerOngoingChat(t):(br.del("chat"),br.del("cobrowse")),t}catch(t){throw br.del("chat"),br.del("cobrowse"),t}}async resumeChat(e){var n;if(((n=this.chat)==null?void 0:n.id)===Number(e)){const i=await this.methods.patch(`chats/${e}`,{status:"queued"});return this.chat.update(i.data),this.chat}const t=await this.methods.resumeChat(e,this.deviceId);return this.registerOngoingChat(t),t}async loadOngoingChat(){return this._rehydratePromise?this._rehydratePromise:(this._rehydratePromise=this._doLoadOngoingChat().finally(()=>{this._rehydratePromise=null}),this._rehydratePromise)}async _doLoadOngoingChat(){const e=br.get("chat");if(!e)return br.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(br.del("chat"),null)}catch(t){throw br.del("chat"),t}}async restoreCobrowseSession(){var t;const e=br.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),qa.debug("cobrowse session restored with nonce:",e)}catch(n){qa.error("Failed to restore cobrowse session",n),br.del("cobrowse")}}async finishChat(){if(!this.chat)return;const e=await this.methods.finishChat(this.chat.id);this.chat.update(e),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()}async updatePostSession(e,t){if(!this.chat||e===cl.FINISHED||e===cl.WAITING)return;const n=await this.methods.updatePostSession(this.chat.id,e,t);this.chat.update(n)}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing)try{await this.finishChat()}catch(e){qa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return XC()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!Wc.has(this._voiceCall.serverStatus()))throw new Vu("A voice call is already active in this session");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=this.cobrowseEnabled);try{await f5()}catch(s){const a=s instanceof fl?s.cause:void 0,c=a&&typeof a=="object"&&"name"in a?a.name:void 0;if(c==="NotAllowedError"||c==="PermissionDeniedError")try{this.events.triggerEvent(Kn.MIC_PERMISSION_REQUIRED)}catch{}throw s}this.releaseVoiceTabLock(),this._voiceTabLock=await ek();let n;try{n=await this.methods.createVoiceCall(Number(e),t.lang||this.lang,t,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),tk(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return UW(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!Wc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=XC(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await ek();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(CO(s)===404)return Vc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),tk(s)}if(Wc.has(n.status))return Vc(),this.releaseVoiceTabLock(),null;let i;try{i=await this.methods._wrapVoiceCallForRestore(n,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),s}this._voiceCall=i;try{await i._connect()}catch(s){throw await i._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),Vc(),s}return this.restoreCobrowseSession().catch(s=>{qa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(Wc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Uo;await this._voiceCall._escalate()}async destroyVoiceCall(){if(!this._voiceCall){this.releaseVoiceTabLock(),Vc();return}try{await this._voiceCall._destroy()}finally{this._voiceCall=null,this.releaseVoiceTabLock()}}async getChatDeflection(){return await this.methods.getChatDeflection(this.chat.id)}async sendChatTranscripts(e){await this.methods.sendChatTranscripts(this.chat.id,e)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(e){return await this.methods.getPdfStatus(e)}async getChatSurvey(){return await this.methods.getChatSurvey(this.chat.id)}async sendChatSurvey(e){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.sendChatSurvey(this.chat.id,e)}async sendChatRate(e){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.rateChat(this.chat.id,e)}async rateVoiceCall(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="rate")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.rateVoiceCall(this._voiceCall.id,e)}async getVoiceCallSurvey(){if(!this._voiceCall)throw new Uo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="survey")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.submitVoiceCallSurvey(this._voiceCall.id,e)}async escalateChat(e){await this.methods.escalateChat(this.chat.id,e)}async trackChatEscalation(e,t){await this.methods.trackEscalation(this.chat.id,e,t)}async trackChatEndUserEvent(e){var t;!e.end_user_name&&((t=this.user)!=null&&t.name)&&(e.end_user_name=this.user.name),await this.methods.trackChatEndUserEvent(this.chat.id,e)}async getChatHistory(e=1){return await this.methods.getChatHistory(e)}async fetchMessages(){try{const e=await this.chat.fetchMessages();if(e.some(t=>t.type==="document"))try{const t=await this.methods.getChatDocuments(this.chat.id);D6(e,t)}catch(t){qa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===tn.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return O6(e,t)}return e}catch{return[]}}async sendFileMessage(e){const t=this.chat.id,n=this.fileSendQueue.then(async()=>{let i;try{i=await this.methods.uploadChatFile(t,e)}catch(s){return qa.warn("[sendFileMessage] upload failed",s),-1}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=Lb(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:tn.SERVER_MESSAGE,visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){const n=this.chat,i=n.id,s=m6();s&&n.rememberOwnOriginal(s,t);const a=this.redactionSendQueue.then(()=>this.methods.sendChatTextMessage(i,t,s??void 0));this.redactionSendQueue=a.catch(()=>{});try{await a}catch(c){throw s&&l5(c)&&n.forgetOwnOriginal(s),c}return}this.chat.sendMessage({type:tn.TEXT,content:t})}}async sendPreviewMessage(e){if(this.isRedactionAgentEnabled()){const t=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,e,t);this.chat.preview(n==null?void 0:n.content);return}this.chat.preview(e)}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(e,t){var n;try{await this.initializeCobrowse(e||this.lang);let i=br.get("cobrowse");i||(i=Date.now().toString(),br.set("cobrowse",i));const s={device_id:this.deviceId,device_name:`${zn.application} / ${zn.version}`,nonce:i,...t};return(n=this.user)!=null&&n.name&&(s.user_name=this.user.name),this.cobrowse.customData=s,await this.cobrowse.createSessionCode()}catch{return""}}async startCobrowse(e="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const t={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,t);if(!n)return;const i=br.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:e,nonce:i})}async startVoiceCobrowseInternal(e,t){if(!this.cobrowseEnabled)throw new Error("Cobrowse is not enabled.");if(!this._voiceCall)throw new Uo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=br.get("cobrowse")??"";return await this.methods.requestVoiceCallCobrowse(n,{code:s,from:t,nonce:a}),this.events.triggerEvent("cobrowse.request",{from:t}),s}async getMessageAttachment(e){if(e.$userType!==_i.END_USER&&c5.includes(e.type)){const t=await this.methods.getMedia(e.media_id,e.type);return this.chat&&this.chat.saveMedia(e.$index,t),t}return null}async checkIn(){const e=await this.methods.confirmCheckIn(this.chat.id);return this.updateCheckIn(e),e}async exitCheckIn(){const e=await this.methods.exitCheckIn(this.chat.id);return this.updateCheckIn(e),e}async notifyCheckInState(e){await this.methods.notifyCheckInState(this.chat.id,e)}async rejoinChat(){const e=await this.methods.rejoinQueue(this.chat.id);return this.updateCheckIn(e),e}async trackCheckInEvent(){const e={modal_type:"check_in"};await this.methods.trackCheckIn(this.chat.id,e)}async getLogs(){const e=await this.communicator.getBridgeLogHistory(),t=un.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{un.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{un.printLogHistoryData(t)})}updateCheckIn(e){const t={...this.chat.state};t.check_in_status=e.check_in_status,this.chat.update(t)}async initializeCobrowse(e){if(!this._cobrowse){const t=await this.getCompany(),n=this.options.cobrowse.messages||cW(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await JW(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",Gp.LOADED],["session.updated",Gp.UPDATED],["session.ended",Gp.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),qa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.events.triggerEvent("chat.ongoing",e),e._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),e.on("_requestCobrowse",t=>{t==="agent"?this.startCobrowse(t):this.initializeCobrowse(e.lang).catch(n=>{qa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{br.del("chat"),br.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,br.set("chat",e.id.toString()),e.cobrowsable&&br.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{qa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const f5=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new fl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new fl(Nw(e),e)}},h5=new Map([["call_in_progress",Vu],["inbound_disabled",ll],["outside_operation_hours",Hu],["operation_hours",Hu],["feature_not_enabled",dl],["invalid_call_type",dl]]),p5=new Map([[409,Hu],[403,ll],[400,Vu]]),tk=r=>{var a,c;if(r instanceof ws)return r;const e=r&&typeof r=="object"?r:{},t=(a=e.data)==null?void 0:a.error_code,n=((c=e.data)==null?void 0:c.message)??e.message??"",i=t?h5.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?p5.get(e.status):void 0;return s?new s(n):new hv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Zv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function $O(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var jb={exports:{}},Zo=vv;function vv(){}vv.mixin=function(r){var e=r.prototype||r;e.isWildEmitter=!0,e.on=function(t,n,i){this.callbacks=this.callbacks||{};var s=arguments.length===3,a=s?arguments[1]:void 0,c=s?arguments[2]:arguments[1];return c._groupName=a,(this.callbacks[t]=this.callbacks[t]||[]).push(c),this},e.once=function(t,n,i){var s=this,a=arguments.length===3,c=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];function l(){s.off(t,l),o.apply(this,arguments)}return this.on(t,c,l),this},e.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,s,a;for(n in this.callbacks)for(a=this.callbacks[n],i=0,s=a.length;i<s;i++)a[i]._groupName===t&&(a.splice(i,1),i--,s--);return this},e.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],s;return i?arguments.length===1?(delete this.callbacks[t],this):(s=i.indexOf(n),s!==-1&&(i.splice(s,1),i.length===0&&delete this.callbacks[t]),this):this},e.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],s=this.getWildcardCallbacks(t),a,c,o;if(i)for(o=i.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,n);if(s)for(c=s.length,o=s.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,[t].concat(n));return this},e.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,s=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(s=s.concat(this.callbacks[n]));return s}};vv.mixin(vv);var xO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.prefix=t(e)})(Ye,function(e){var t=function(d){for(var h=1,v=arguments.length,y;h<v;h++)for(y in arguments[h])Object.prototype.hasOwnProperty.call(arguments[h],y)&&(d[y]=arguments[h][y]);return d},n={template:"[%t] %l:",levelFormatter:function(d){return d.toUpperCase()},nameFormatter:function(d){return d||"root"},timestampFormatter:function(d){return d.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,s={},a=function(d){if(!d||!d.getLogger)throw new TypeError("Argument is not a root logger");i=d},c=function(d,h){if(!d||!d.setLevel)throw new TypeError("Argument is not a logger");var v=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(P,A,U){var L=v(P,A,U),x=s[U]||s[""],B=x.template.indexOf("%t")!==-1,G=x.template.indexOf("%l")!==-1,K=x.template.indexOf("%n")!==-1;return function(){for(var D="",fe=arguments.length,X=Array(fe),pe=0;pe<fe;pe++)X[pe]=arguments[pe];if(y||!s[U]){var Q=x.timestampFormatter(new Date),Oe=x.levelFormatter(P),Ve=x.nameFormatter(U);x.format?D+=x.format(Oe,Ve,Q):(D+=x.template,B&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,Ve))),X.length&&typeof X[0]=="string"?X[0]=D+" "+X[0]:X.unshift(D)}L.apply(void 0,X)}}return s[y]||(d.methodFactory=k),h=h||{},h.template&&(h.format=void 0),s[y]=t({},w,h),d.setLevel(d.getLevel()),i||d.warn("It is necessary to call the function reg() of loglevel-plugin-prefix before calling apply. From the next release, it will throw an error. See more: https://github.com/kutuluk/loglevel-plugin-prefix/blob/master/README.md"),d},o={reg:a,apply:c},l;return e&&(l=e.prefix,o.noConflict=function(){return e.prefix===o&&(e.prefix=l),o}),o})})(xO);var v5=xO.exports,MO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Ye,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},a=null;function c(k,P){var A=k[P];if(typeof A.bind=="function")return A.bind(k);try{return Function.prototype.bind.call(A,k)}catch{return function(){return Function.prototype.apply.apply(A,[k,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(k){return k==="debug"&&(k="log"),typeof console===t?!1:k==="trace"&&n?o:console[k]!==void 0?c(console,k):console.log!==void 0?c(console,"log"):e}function d(){for(var k=this.getLevel(),P=0;P<i.length;P++){var A=i[P];this[A]=P<k?e:this.methodFactory(A,k,this.name)}if(this.log=this.debug,typeof console===t&&k<this.levels.SILENT)return"No console available for logging"}function h(k){return function(){typeof console!==t&&(d.call(this),this[k].apply(this,arguments))}}function v(k,P,A){return l(k)||h.apply(this,arguments)}function y(k,P){var A=this,U,L,x,B="loglevel";typeof k=="string"?B+=":"+k:typeof k=="symbol"&&(B=void 0);function G(pe){var Q=(i[pe]||"silent").toUpperCase();if(!(typeof window===t||!B)){try{window.localStorage[B]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(B)+"="+Q+";"}catch{}}}function K(){var pe;if(!(typeof window===t||!B)){try{pe=window.localStorage[B]}catch{}if(typeof pe===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(B),Ve=Q.indexOf(Oe+"=");Ve!==-1&&(pe=/^([^;]+)/.exec(Q.slice(Ve+Oe.length+1))[1])}catch{}return A.levels[pe]===void 0&&(pe=void 0),pe}}function D(){if(!(typeof window===t||!B)){try{window.localStorage.removeItem(B)}catch{}try{window.document.cookie=encodeURIComponent(B)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function fe(pe){var Q=pe;if(typeof Q=="string"&&A.levels[Q.toUpperCase()]!==void 0&&(Q=A.levels[Q.toUpperCase()]),typeof Q=="number"&&Q>=0&&Q<=A.levels.SILENT)return Q;throw new TypeError("log.setLevel() called with invalid level: "+pe)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=P||v,A.getLevel=function(){return x??L??U},A.setLevel=function(pe,Q){return x=fe(pe),Q!==!1&&G(x),d.call(A)},A.setDefaultLevel=function(pe){L=fe(pe),K()||A.setLevel(pe,!1)},A.resetLevel=function(){x=null,D(),d.call(A)},A.enableAll=function(pe){A.setLevel(A.levels.TRACE,pe)},A.disableAll=function(pe){A.setLevel(A.levels.SILENT,pe)},A.rebuild=function(){if(a!==A&&(U=fe(a.getLevel())),d.call(A),a===A)for(var pe in s)s[pe].rebuild()},U=fe(a?a.getLevel():"WARN");var X=K();X!=null&&(x=fe(X)),d.call(A)}a=new y,a.getLogger=function(P){if(typeof P!="symbol"&&typeof P!="string"||P==="")throw new TypeError("You must supply a name when creating a logger.");var A=s[P];return A||(A=s[P]=new y(P,a.methodFactory)),A};var w=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=w),a},a.getLoggers=function(){return s},a.default=a,a})})(MO);var Kr=MO.exports;const g5=Zv(Kr),m5=Uq({__proto__:null,default:g5},[Kr]);var Bb={exports:{}},y5={"error:application:call:params":{type:"error:application:call:params",description:"not a valid String[] of usernames param"},"error:application:callServer:params":{type:"error:application:call:params",description:"not a valid String of phone number"},"error:call:reject":{type:"error:call:reject",description:"failed to reject the call"},"error:getUserMedia:permissions":{type:"error:getUserMedia:permissions",description:"missing getUserMedia permissions"},"error:media:params":{type:"error:media:params",description:"currently supported params media type= {audio:{muted:false, earmuffed:false}}"},"error:media:reenable":{type:"error:media:reenable",description:"missing reconnectRtcId required to reenable media"},"error:self":{type:"error:self",description:"Conversation Object is missing self (me)"},"error:user:relogin":{type:"error:user:relogin",description:"please relogin"},"error:seen:own-message":{type:"error:seen:own-message",description:"attempt to send seen for own message"},"error:already-seen":{type:"error:already-seen",description:"already marked as seen"},"error:delivered:own-message":{type:"error:delivered:own-message",description:"attempt to send delivered for own message"},"error:already-delivered":{type:"error:already-delivered",description:"already marked as delivered"},"error:fetch-image":{type:"error:fetch-image",description:"xhr.status received other than 200"},"error:delete-image":{type:"error:delete-image",description:"xhr.status received other than 204"},"error:missing:params":{type:"error:missing:params",description:"missing parameters"},"error:invite:missing:params":{type:"error:missing:params",description:"This invite cannot be sent to empty username and user_id"},"error:invalid:param:type":{type:"error:invalid:param:type",description:"Invalid Object type, passed in the parameters"},"error:audio:already-connecting":{type:"error:audio:already-connecting",description:"Audio call already in progress"},"error:audio:not-enabled":{type:"error:audio:not-enabled",description:"Audio is not enabled"},"error:media:already-connecting":{type:"error:media:already-connecting",description:"Media is already in progress"},"error:media:unsupported-browser":{type:"error:media:unsupported-browser",description:"This action is not supported on this browser"},"error:media:extension":{type:"error:media:extension",description:"Chrome extension has thrown an error"},"error:media:extension-not-installed":{type:"error:media:extension-not-installed",description:"Chrome extension should be installed"},"error:media:update:streams":{type:"error:media:update:streams",description:"cant update more than one stream"},"error:media:update:invalid":{type:"error:media:update:invalid",description:"state of media is not supported for this update"},"error:media:stream:not-found":{type:"error:media:stream:not-found",description:"A stream with the given index was not found"},"error:audio:dtmf:invalid-digit":{type:"error:audio:dtmf:invalid-digit",description:"not a valid string of dtmf digits (0-9,a-d,A-D,p,P,*,#)"},"error:audio:dtmf:audio-disabled":{type:"error:audio:dtmf:audio-disabled",description:"Audio must be enabled to send DTMF"},"error:invalid-order":{type:"error:invalid-order",description:"params not valid. Order must be asc or desc"},"error:custom-event:invalid":{type:"error:custom-event:invalid",description:"Custom event type not valid"},"error:message-event:invalid":{type:"error:message-event:invalid",description:"message_type is missing or is invalid"},"error:invalid-cursor":{type:"error:invalid-cursor",description:"page does not exist"},"error:client:reconnection_failed":{type:"error:client:reconnection_failed",description:"websocket failed to reconnect"},"error:conversation-service:version":{type:"error:conversation:version",description:'Wrong version of Conversation Service API. It should be one of "v1" or "v3"'},"error:no-media-offer":{type:"error:no-media-offer",description:"Media preload attempt without having an offer available"}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0}),e.NexmoApiError=e.NexmoClientError=void 0;const t=y5,n=Kr;function i(c,o){o&&o.code&&(o.type=o.code,delete o.code),Object.assign(c,o),c.message="type: "+c.type+", description: "+(c.description?c.description:"")}class s{constructor(o){const l=t[o];l?i(this,l):(this.message=o&&o.message?o.message:o,this.stack=o.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoClientError=s;class a{constructor(o){this.log=n.getLogger(this.constructor.name),o?i(this,o):(this.message=o&&o.message?o.message:o,this.stack=o&&o.stack?o.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoApiError=a,r.exports={NexmoClientError:s,NexmoApiError:a}})(Bb,Bb.exports);var Ts=Bb.exports,qb={exports:{}},Uw={},eg={},eo={},uf={},pa={},cf={},ro={},El={},lf={},va={};Object.defineProperty(va,"__esModule",{value:!0});va.ERROR_PACKET=va.PACKET_TYPES_REVERSE=va.PACKET_TYPES=void 0;const ya=Object.create(null);va.PACKET_TYPES=ya;ya.open="0";ya.close="1";ya.ping="2";ya.pong="3";ya.message="4";ya.upgrade="5";ya.noop="6";const DO=Object.create(null);va.PACKET_TYPES_REVERSE=DO;Object.keys(ya).forEach(r=>{DO[ya[r]]=r});const _5={type:"error",data:"parser error"};va.ERROR_PACKET=_5;Object.defineProperty(lf,"__esModule",{value:!0});lf.encodePacket=void 0;lf.encodePacketToBinary=S5;const b5=va,NO=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",LO=typeof ArrayBuffer=="function",UO=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,FO=({type:r,data:e},t,n)=>NO&&e instanceof Blob?t?n(e):rk(e,n):LO&&(e instanceof ArrayBuffer||UO(e))?t?n(e):rk(new Blob([e]),n):n(b5.PACKET_TYPES[r]+(e||""));lf.encodePacket=FO;const rk=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function nk(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Dy;function S5(r,e){if(NO&&r.data instanceof Blob)return r.data.arrayBuffer().then(nk).then(e);if(LO&&(r.data instanceof ArrayBuffer||UO(r.data)))return e(nk(r.data));FO(r,!1,t=>{Dy||(Dy=new TextEncoder),e(Dy.encode(t))})}var tg={},pl={};Object.defineProperty(pl,"__esModule",{value:!0});pl.decode=pl.encode=void 0;const Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Id=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Hc.length;r++)Id[Hc.charCodeAt(r)]=r;const w5=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Hc[e[t]>>2],i+=Hc[(e[t]&3)<<4|e[t+1]>>4],i+=Hc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Hc[e[t+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};pl.encode=w5;const T5=r=>{let e=r.length*.75,t=r.length,n,i=0,s,a,c,o;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const l=new ArrayBuffer(e),d=new Uint8Array(l);for(n=0;n<t;n+=4)s=Id[r.charCodeAt(n)],a=Id[r.charCodeAt(n+1)],c=Id[r.charCodeAt(n+2)],o=Id[r.charCodeAt(n+3)],d[i++]=s<<2|a>>4,d[i++]=(a&15)<<4|c>>2,d[i++]=(c&3)<<6|o&63;return l};pl.decode=T5;Object.defineProperty(tg,"__esModule",{value:!0});tg.decodePacket=void 0;const xh=va,E5=pl,C5=typeof ArrayBuffer=="function",k5=(r,e)=>{if(typeof r!="string")return{type:"message",data:jO(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:R5(r.substring(1),e)}:xh.PACKET_TYPES_REVERSE[t]?r.length>1?{type:xh.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:xh.PACKET_TYPES_REVERSE[t]}:xh.ERROR_PACKET};tg.decodePacket=k5;const R5=(r,e)=>{if(C5){const t=(0,E5.decode)(r);return jO(t,e)}else return{base64:!0,data:r}},jO=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.decodePayload=r.decodePacket=r.encodePayload=r.encodePacket=r.protocol=void 0,r.createPacketEncoderStream=c,r.createPacketDecoderStream=h;const e=lf;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=tg;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=va,i="",s=(v,y)=>{const w=v.length,k=new Array(w);let P=0;v.forEach((A,U)=>{(0,e.encodePacket)(A,!1,L=>{k[U]=L,++P===w&&y(k.join(i))})})};r.encodePayload=s;const a=(v,y)=>{const w=v.split(i),k=[];for(let P=0;P<w.length;P++){const A=(0,t.decodePacket)(w[P],y);if(k.push(A),A.type==="error")break}return k};r.decodePayload=a;function c(){return new TransformStream({transform(v,y){(0,e.encodePacketToBinary)(v,w=>{const k=w.length;let P;if(k<126)P=new Uint8Array(1),new DataView(P.buffer).setUint8(0,k);else if(k<65536){P=new Uint8Array(3);const A=new DataView(P.buffer);A.setUint8(0,126),A.setUint16(1,k)}else{P=new Uint8Array(9);const A=new DataView(P.buffer);A.setUint8(0,127),A.setBigUint64(1,BigInt(k))}v.data&&typeof v.data!="string"&&(P[0]|=128),y.enqueue(P),y.enqueue(w)})}})}let o;function l(v){return v.reduce((y,w)=>y+w.length,0)}function d(v,y){if(v[0].length===y)return v.shift();const w=new Uint8Array(y);let k=0;for(let P=0;P<y;P++)w[P]=v[0][k++],k===v[0].length&&(v.shift(),k=0);return v.length&&k<v[0].length&&(v[0]=v[0].slice(k)),w}function h(v,y){o||(o=new TextDecoder);const w=[];let k=0,P=-1,A=!1;return new TransformStream({transform(U,L){for(w.push(U);;){if(k===0){if(l(w)<1)break;const x=d(w,1);A=(x[0]&128)===128,P=x[0]&127,P<126?k=3:P===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const x=d(w,2);P=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const x=d(w,8),B=new DataView(x.buffer,x.byteOffset,x.length),G=B.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}P=G*Math.pow(2,32)+B.getUint32(4),k=3}else{if(l(w)<P)break;const x=d(w,P);L.enqueue((0,t.decodePacket)(A?x:o.decode(x),y)),k=0}if(P===0||P>v){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(El);function bi(r){if(r)return I5(r)}function I5(r){for(var e in bi.prototype)r[e]=bi.prototype[e];return r}bi.prototype.on=bi.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};bi.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};bi.prototype.off=bi.prototype.removeListener=bi.prototype.removeAllListeners=bi.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};bi.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};bi.prototype.emitReserved=bi.prototype.emit;bi.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};bi.prototype.hasListeners=function(r){return!!this.listeners(r).length};const P5=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Cl=$O(P5);var Ys={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=A5;Li.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0);Li.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();Li.defaultBinaryType="arraybuffer";function A5(){}Object.defineProperty(Ys,"__esModule",{value:!0});Ys.pick=O5;Ys.installTimerFunctions=M5;Ys.byteLength=N5;Ys.randomString=U5;const No=Li;function O5(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const $5=No.globalThisShim.setTimeout,x5=No.globalThisShim.clearTimeout;function M5(r,e){e.useNativeTimers?(r.setTimeoutFn=$5.bind(No.globalThisShim),r.clearTimeoutFn=x5.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const D5=1.33;function N5(r){return typeof r=="string"?L5(r):Math.ceil((r.byteLength||r.size)*D5)}function L5(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function U5(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var df={};Object.defineProperty(df,"__esModule",{value:!0});df.encode=F5;df.decode=j5;function F5(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function j5(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var Wb={exports:{}},Ny,ik;function B5(){if(ik)return Ny;ik=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Ny=function(d,h){h=h||{};var v=typeof d;if(v==="string"&&d.length>0)return a(d);if(v==="number"&&isFinite(d))return h.long?o(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function a(d){if(d=String(d),!(d.length>100)){var h=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(h){var v=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function c(d){var h=Math.abs(d);return h>=n?Math.round(d/n)+"d":h>=t?Math.round(d/t)+"h":h>=e?Math.round(d/e)+"m":h>=r?Math.round(d/r)+"s":d+"ms"}function o(d){var h=Math.abs(d);return h>=n?l(d,h,n,"day"):h>=t?l(d,h,t,"hour"):h>=e?l(d,h,e,"minute"):h>=r?l(d,h,r,"second"):d+" ms"}function l(d,h,v,y){var w=h>=v*1.5;return Math.round(d/v)+" "+y+(w?"s":"")}return Ny}function q5(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=B5(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let h=0;for(let v=0;v<d.length;v++)h=(h<<5)-h+d.charCodeAt(v),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,v=null,y,w;function k(...P){if(!k.enabled)return;const A=k,U=Number(new Date),L=U-(h||U);A.diff=L,A.prev=h,A.curr=U,h=U,P[0]=t.coerce(P[0]),typeof P[0]!="string"&&P.unshift("%O");let x=0;P[0]=P[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";x++;const D=t.formatters[K];if(typeof D=="function"){const fe=P[x];G=D.call(A,fe),P.splice(x,1),x--}return G}),t.formatArgs.call(A,P),(A.log||t.log).apply(A,P)}return k.namespace=d,k.useColors=t.useColors(),k.color=t.selectColor(d),k.extend=n,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:P=>{v=P}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const v=t(this.namespace+(typeof h>"u"?":":h)+d);return v.log=this.log,v}function i(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];const h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const v of h)v[0]==="-"?t.skips.push(v.slice(1)):t.names.push(v)}function s(d,h){let v=0,y=0,w=-1,k=0;for(;v<d.length;)if(y<h.length&&(h[y]===d[v]||h[y]==="*"))h[y]==="*"?(w=y,k=v,y++):(v++,y++);else if(w!==-1)y=w+1,k++,v=k;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function a(){const d=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),d}function c(d){for(const h of t.skips)if(s(d,h))return!1;for(const h of t.names)if(s(d,h))return!0;return!1}function o(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var W5=q5;(function(r,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=t,e.storage=a(),e.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;o.splice(1,0,l,"color: inherit");let d=0,h=0;o[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(d++,v==="%c"&&(h=d))}),o.splice(h,0,l)}e.log=console.debug||console.log||(()=>{});function i(o){try{o?e.storage.setItem("debug",o):e.storage.removeItem("debug")}catch{}}function s(){let o;try{o=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!o&&typeof process<"u"&&"env"in process&&(o=process.env.DEBUG),o}function a(){try{return localStorage}catch{}}r.exports=W5(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(Wb,Wb.exports);var Xs=Wb.exports,V5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ro,"__esModule",{value:!0});ro.Transport=ro.TransportError=void 0;const H5=El,G5=Cl,z5=Ys,K5=df,J5=V5(Xs),Y5=(0,J5.default)("engine.io-client:transport");class BO extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=BO;class X5 extends G5.Emitter{constructor(e){super(),this.writable=!1,(0,z5.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new BO(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Y5("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,H5.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=(0,K5.encode)(e);return t.length?"?"+t:""}}ro.Transport=X5;var Q5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cf,"__esModule",{value:!0});cf.Polling=void 0;const Z5=ro,eV=Ys,sk=El,tV=Q5(Xs),Ns=(0,tV.default)("engine.io-client:polling");class rV extends Z5.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{Ns("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Ns("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Ns("pre-pause polling complete"),--n||t()})),this.writable||(Ns("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Ns("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Ns("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ns("polling got data %s",e);const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,sk.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ns('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{Ns("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ns("transport open - closing"),e()):(Ns("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,sk.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,eV.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}cf.Polling=rV;var rg={};Object.defineProperty(rg,"__esModule",{value:!0});rg.hasCORS=void 0;let qO=!1;try{qO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}rg.hasCORS=qO;var nV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pa,"__esModule",{value:!0});pa.XHR=pa.Request=pa.BaseXHR=void 0;const iV=cf,sV=Cl,ak=Ys,WO=Li,aV=rg,oV=nV(Xs),Vb=(0,oV.default)("engine.io-client:polling");function uV(){}class VO extends iV.Polling{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){Vb("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}pa.BaseXHR=VO;let Uu=class zp extends sV.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,ak.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=(0,ak.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{Vb("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Vb("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=zp.requestsCount++,zp.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=uV,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete zp.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};pa.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ok);else if(typeof addEventListener=="function"){const r="onpagehide"in WO.globalThisShim?"pagehide":"unload";addEventListener(r,ok,!1)}}function ok(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const cV=function(){const r=HO({xdomain:!1});return r&&r.responseType!==null}();class lV extends VO{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=cV&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(HO,this.uri(),e)}}pa.XHR=lV;function HO(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||aV.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new WO.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},dV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jo,"__esModule",{value:!0});Jo.WS=Jo.BaseWS=void 0;const fV=ro,uk=Ys,hV=El,Hb=Li,pV=dV(Xs),vV=(0,pV.default)("engine.io-client:websocket"),GO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class zO extends fV.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=GO?{}:(0,uk.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;(0,hV.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{vV("websocket closed before onclose event")}i&&(0,Hb.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,uk.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=zO;const Ly=Hb.globalThisShim.WebSocket||Hb.globalThisShim.MozWebSocket;class gV extends zO{createSocket(e,t,n){return GO?new Ly(e,t,n):t?new Ly(e,t):new Ly(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=gV;var ff={},mV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ff,"__esModule",{value:!0});ff.WT=void 0;const yV=ro,_V=Li,ck=El,bV=mV(Xs),ud=(0,bV.default)("engine.io-client:webtransport");class SV extends yV.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{ud("transport closed gracefully"),this.onClose()}).catch(e=>{ud("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=(0,ck.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,ck.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:c,value:o})=>{if(c){ud("session is closed");return}ud("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{ud("an error occurred while reading: %s",c)})};s();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,_V.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}ff.WT=SV;Object.defineProperty(uf,"__esModule",{value:!0});uf.transports=void 0;const wV=pa,TV=Jo,EV=ff;uf.transports={websocket:TV.WS,webtransport:EV.WT,polling:wV.XHR};var ng={};Object.defineProperty(ng,"__esModule",{value:!0});ng.parse=RV;const CV=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kV=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function RV(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=CV.exec(r||""),s={},a=14;for(;a--;)s[kV[a]]=i[a]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=IV(s,s.path),s.queryKey=PV(s,s.query),s}function IV(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function PV(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var AV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eo,"__esModule",{value:!0});eo.Socket=eo.SocketWithUpgrade=eo.SocketWithoutUpgrade=void 0;const OV=uf,lk=Ys,$V=df,dk=ng,xV=Cl,KO=El,Uy=Li,MV=AV(Xs),zr=(0,MV.default)("engine.io-client:socket"),Gb=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fd=[];Gb&&addEventListener("offline",()=>{zr("closing %d connection(s) because the network was lost",Fd.length),Fd.forEach(r=>r())},!1);class to extends xV.Emitter{constructor(e,t){if(super(),this.binaryType=Uy.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=(0,dk.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,dk.parse)(t.host).host);(0,lk.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,$V.decode)(this.opts.query)),Gb&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(zr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Fd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Uy.createCookieJar)()),this._open()}createTransport(e){zr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=KO.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return zr("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&to.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){zr("setting transport %s",e.name),this.transport&&(zr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){zr("socket open"),this.readyState="open",to.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(zr('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else zr('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();zr("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=(0,lk.byteLength)(i)),n>0&&t>this._maxPayload)return zr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return zr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(zr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Uy.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),zr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(zr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return zr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(zr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Gb&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Fd.indexOf(this._offlineEventListener);n!==-1&&(zr("removing listener for the 'offline' event"),Fd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=KO.protocol;class JO extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){zr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){zr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(zr('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",h=>{if(!n)if(h.type==="pong"&&h.data==="probe"){if(zr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",zr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(zr("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{zr('probe transport "%s" failed',e);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const v=new Error("probe error: "+h);v.transport=t.name,s(),zr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",v)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(zr('"%s" works - aborting "%s"',h.name,t.name),s())}const d=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",c),this.off("close",o),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",c),this.once("close",o),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}eo.SocketWithUpgrade=JO;let DV=class extends JO{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>OV.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=DV;var ig={};Object.defineProperty(ig,"__esModule",{value:!0});ig.Fetch=void 0;const NV=cf;class LV extends NV.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;const n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}}ig.Fetch=LV;(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.nextTick=r.parse=r.installTimerFunctions=r.transports=r.TransportError=r.Transport=r.protocol=r.SocketWithUpgrade=r.SocketWithoutUpgrade=r.Socket=void 0;const e=eo;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return e.Socket}});var t=eo;Object.defineProperty(r,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(r,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),r.protocol=e.Socket.protocol;var n=ro;Object.defineProperty(r,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(r,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=uf;Object.defineProperty(r,"transports",{enumerable:!0,get:function(){return i.transports}});var s=Ys;Object.defineProperty(r,"installTimerFunctions",{enumerable:!0,get:function(){return s.installTimerFunctions}});var a=ng;Object.defineProperty(r,"parse",{enumerable:!0,get:function(){return a.parse}});var c=Li;Object.defineProperty(r,"nextTick",{enumerable:!0,get:function(){return c.nextTick}});var o=ig;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=pa;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=pa;Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return d.XHR}});var h=Jo;Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return h.WS}});var v=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var y=ff;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(eg);var UV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Uw,"__esModule",{value:!0});Uw.url=BV;const FV=eg,jV=UV(Xs),fk=(0,jV.default)("socket.io-client:url");function BV(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(fk("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),fk("parse %s",r),n=(0,FV.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}var sg={},hf={},Qi={},ag={},pf={};Object.defineProperty(pf,"__esModule",{value:!0});pf.isBinary=XO;pf.hasBinary=Kp;const qV=typeof ArrayBuffer=="function",WV=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,YO=Object.prototype.toString,VV=typeof Blob=="function"||typeof Blob<"u"&&YO.call(Blob)==="[object BlobConstructor]",HV=typeof File=="function"||typeof File<"u"&&YO.call(File)==="[object FileConstructor]";function XO(r){return qV&&(r instanceof ArrayBuffer||WV(r))||VV&&r instanceof Blob||HV&&r instanceof File}function Kp(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Kp(r[t]))return!0;return!1}if(XO(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Kp(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Kp(r[t]))return!0;return!1}Object.defineProperty(ag,"__esModule",{value:!0});ag.deconstructPacket=zV;ag.reconstructPacket=KV;const GV=pf;function zV(r){const e=[],t=r.data,n=r;return n.data=zb(t,e),n.attachments=e.length,{packet:n,buffers:e}}function zb(r,e){if(!r)return r;if((0,GV.isBinary)(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=zb(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=zb(r[n],e));return t}return r}function KV(r,e){return r.data=Kb(r.data,e),delete r.attachments,r}function Kb(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Kb(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Kb(r[t],e));return r}Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Decoder=Qi.Encoder=Qi.PacketType=Qi.protocol=void 0;Qi.isPacketValid=nH;const JV=Cl,QO=ag,ZO=pf,YV=Xs,Jb=(0,YV.default)("socket.io-parser"),e$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Qi.protocol=5;var Fr;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Fr||(Qi.PacketType=Fr={}));class XV{constructor(e){this.replacer=e}encode(e){return Jb("encoding packet %j",e),(e.type===Fr.EVENT||e.type===Fr.ACK)&&(0,ZO.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fr.EVENT?Fr.BINARY_EVENT:Fr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fr.BINARY_EVENT||e.type===Fr.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Jb("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,QO.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Qi.Encoder=XV;class Fw extends JV.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Fr.BINARY_EVENT;n||t.type===Fr.BINARY_ACK?(t.type=n?Fr.EVENT:Fr.ACK,this.reconstructor=new QV(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,ZO.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Fr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Fr.BINARY_EVENT||n.type===Fr.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(Fw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return Jb("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Fr.CONNECT:return gv(t);case Fr.DISCONNECT:return t===void 0;case Fr.CONNECT_ERROR:return typeof t=="string"||gv(t);case Fr.EVENT:case Fr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&e$.indexOf(t[0])===-1);case Fr.ACK:case Fr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Qi.Decoder=Fw;class QV{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=(0,QO.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function ZV(r){return typeof r=="string"}const eH=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function tH(r){return r===void 0||eH(r)}function gv(r){return Object.prototype.toString.call(r)==="[object Object]"}function rH(r,e){switch(r){case Fr.CONNECT:return e===void 0||gv(e);case Fr.DISCONNECT:return e===void 0;case Fr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&e$.indexOf(e[0])===-1);case Fr.ACK:return Array.isArray(e);case Fr.CONNECT_ERROR:return typeof e=="string"||gv(e);default:return!1}}function nH(r){return ZV(r.nsp)&&tH(r.id)&&rH(r.type,r.data)}var og={};Object.defineProperty(og,"__esModule",{value:!0});og.on=iH;function iH(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var sH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(hf,"__esModule",{value:!0});hf.Socket=void 0;const Ls=Qi,Mh=og,aH=Cl,oH=sH(Xs),bn=(0,oH.default)("socket.io-client:socket"),uH=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class cH extends aH.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[(0,Mh.on)(e,"open",this.onopen.bind(this)),(0,Mh.on)(e,"packet",this.onpacket.bind(this)),(0,Mh.on)(e,"error",this.onerror.bind(this)),(0,Mh.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(uH.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const a={type:Ls.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++;bn("emitting packet with ack id %d",d);const h=t.pop();this._registerAckCallback(d,h),a.id=d}const c=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,o=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?bn("discard packet as the transport is not currently writable"):o?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(bn("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));bn("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(a,c)=>a?i(a):n(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?bn("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(bn("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(bn("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(bn("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!e){bn("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,bn("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){bn("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ls.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){bn("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ls.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ls.PacketType.EVENT:case Ls.PacketType.BINARY_EVENT:this.onevent(e);break;case Ls.PacketType.ACK:case Ls.PacketType.BINARY_ACK:this.onack(e);break;case Ls.PacketType.DISCONNECT:this.ondisconnect();break;case Ls.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];bn("emitting event %j",t),e.id!=null&&(bn("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,bn("sending ack %j",i),t.packet({type:Ls.PacketType.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];if(typeof t!="function"){bn("bad ack %s",e.id);return}delete this.acks[e.id],bn("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){bn("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){bn("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(bn("performing disconnect (%s)",this.nsp),this.packet({type:Ls.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}hf.Socket=cH;var jw={};Object.defineProperty(jw,"__esModule",{value:!0});jw.Backoff=kl;function kl(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}kl.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};kl.prototype.reset=function(){this.attempts=0};kl.prototype.setMin=function(r){this.ms=r};kl.prototype.setMax=function(r){this.max=r};kl.prototype.setJitter=function(r){this.jitter=r};var lH=Ye&&Ye.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),dH=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),fH=Ye&&Ye.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&lH(e,r,t);return dH(e,r),e},hH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(sg,"__esModule",{value:!0});sg.Manager=void 0;const Fy=eg,pH=hf,vH=fH(Qi),Tu=og,gH=jw,mH=Cl,yH=hH(Xs),Hn=(0,yH.default)("socket.io-client:manager");class _H extends mH.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Fy.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new gH.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||vH;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(Hn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Hn("opening %s",this.uri),this.engine=new Fy.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Tu.on)(t,"open",function(){n.onopen(),e&&e()}),s=c=>{Hn("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Tu.on)(t,"error",s);if(this._timeout!==!1){const c=this._timeout;Hn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Hn("connect attempt timed out after %d",c),i(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&o.unref(),this.subs.push(()=>{this.clearTimeoutFn(o)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){Hn("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push((0,Tu.on)(e,"ping",this.onping.bind(this)),(0,Tu.on)(e,"data",this.ondata.bind(this)),(0,Tu.on)(e,"error",this.onerror.bind(this)),(0,Tu.on)(e,"close",this.onclose.bind(this)),(0,Tu.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Fy.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Hn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new pH.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Hn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Hn("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){Hn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Hn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Hn("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Hn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Hn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Hn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Hn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Hn("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}sg.Manager=_H;(function(r,e){var t=Ye&&Ye.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.Socket=e.Manager=e.protocol=void 0,e.io=l,e.connect=l,e.default=l;const n=Uw,i=sg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=hf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Xs).default)("socket.io-client"),o={};function l(v,y){typeof v=="object"&&(y=v,v=void 0),y=y||{};const w=(0,n.url)(v,y.path||"/socket.io"),k=w.source,P=w.id,A=w.path,U=o[P]&&A in o[P].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||U;let x;return L?(c("ignoring socket cache for %s",k),x=new i.Manager(k,y)):(o[P]||(c("new io instance for %s",k),o[P]=new i.Manager(k,y)),x=o[P]),w.query&&!y.query&&(y.query=w.queryKey),x.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Qi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=eg;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return h.Fetch}}),Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return h.NodeXHR}}),Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return h.XHR}}),Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return h.NodeWebSocket}}),Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return h.WebSocket}}),Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return h.WebTransport}}),r.exports=l})(qb,qb.exports);var t$=qb.exports,r$={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(p,g,b){for(var _=b,S=0,T=p.length;S<T;S++)_=g(_,p[S],S,p);return _},n=function(p,g){return t(p,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(p,g){return t(p,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(p,g){return t(p,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(p){var g=[],b;for(b in p)Object.prototype.hasOwnProperty.call(p,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(p,c[_])&&g.push(c[_]);return g},l=function(p){return Object.prototype.toString.call(p)==="[object Array]"},d=function(p){return p<10?"0"+p:p},h=function(){var p=new Date;return p.getUTCFullYear()+"-"+d(p.getUTCMonth()+1)+"-"+d(p.getUTCDate())+"T"+d(p.getUTCHours())+":"+d(p.getUTCMinutes())+":"+d(p.getUTCSeconds())+"."+(p.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(p,g){return p===void 0&&(p=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=p&&b<=g}},y.stringWithLength=function(p){return typeof p=="string"&&!!p.length};var w={},k=v.filter,P=v.reduce,A=v.keys,U=v.isArray,L=v.includes,x=y.intRange,B=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:B},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return p===!0||p===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(p){return typeof p=="function"||U(p)&&k(p,function(g){return typeof g=="function"}).length===p.length}},endpoints:{defaultValue:function(){return{notify:"https://notify.bugsnag.com",sessions:"https://sessions.bugsnag.com"}},message:"should be an object containing endpoint URLs { notify, sessions }. sessions is optional if autoCaptureSessions=false",validate:function(p,g){return p&&typeof p=="object"&&B(p.notify)&&(g.autoCaptureSessions===!1||B(p.sessions))&&k(A(p),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(p,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(p){return p===!0||p===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(p){return p===null||U(p)&&k(p,function(g){return typeof g=="string"}).length===p.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(p){return typeof p=="string"&&p.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(p){return x(0,40)(p)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return typeof p=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(p){return typeof p=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(p){return typeof p=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(p){return!p||p&&P(["debug","info","warn","error"],function(g,b){return g&&typeof p[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(p){return U(p)&&p.length===k(p,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");return P(A(g),function(b,_){return b[_]=p[_]!==void 0?p[_]:g[_].defaultValue(p[_],p),b},{})},w.validate=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");var b=P(A(g),function(_,S){return g[S].validate(p[S],p)?_:_.concat({key:S,message:g[S].message,value:p[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(p){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(p[_]=b[_])}return p},G.apply(this,arguments)}var K=w.schema,D=v.map,fe=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:fe},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?pe():void 0}})},pe=function(){var p={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];p[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),p},Q=v.isoDate,Oe=function(){function p(b,_,S,T){b===void 0&&(b="[anonymous]"),_===void 0&&(_={}),S===void 0&&(S="manual"),T===void 0&&(T=Q()),this.type=S,this.name=b,this.metaData=_,this.timestamp=T}var g=p.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},p}(),Ve=Oe,Ze=function(p,g,b){var _=p.length,S=0,T=function(){if(S>=_)return b(null,!1);g(p[S],function(E,I){if(E)return b(E,!1);if(I===!0)return b(null,!0);S++,T()})};T()},Xe=function(p){return p.app&&typeof p.app.releaseStage=="string"?p.app.releaseStage:p.config.releaseStage},Re=Je;function Je(p){switch(Object.prototype.toString.call(p)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return p instanceof Error}}var Ke=Re,Y=function(p,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(p);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ee(p,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ee(p,S))}b(p,function(T,E){if(T)return g(T),_(null,!1);_(null,Ee(p,E))})}catch(T){g(T),_(null,!1)}}},Ee=function(p,g){return p.isIgnored()||g===!1},Ct={};(function(p,g){typeof Ct=="object"?Ct=g():p.StackFrame=g()})(this,function(){function p(Se){return!isNaN(parseFloat(Se))&&isFinite(Se)}function g(Se){return Se.charAt(0).toUpperCase()+Se.substring(1)}function b(Se){return function(){return this[Se]}}var _=["isConstructor","isEval","isNative","isToplevel"],S=["columnNumber","lineNumber"],T=["fileName","functionName","source"],E=["args"],I=_.concat(S,T,E);function q(Se){if(Se instanceof Object)for(var Ge=0;Ge<I.length;Ge++)Se.hasOwnProperty(I[Ge])&&Se[I[Ge]]!==void 0&&this["set"+g(I[Ge])](Se[I[Ge]])}q.prototype={getArgs:function(){return this.args},setArgs:function(Se){if(Object.prototype.toString.call(Se)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=Se},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(Se){if(Se instanceof q)this.evalOrigin=Se;else if(Se instanceof Object)this.evalOrigin=new q(Se);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var Se=this.getFunctionName()||"{anonymous}",Ge="("+(this.getArgs()||[]).join(",")+")",gt=this.getFileName()?"@"+this.getFileName():"",et=p(this.getLineNumber())?":"+this.getLineNumber():"",ct=p(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var H=0;H<_.length;H++)q.prototype["get"+g(_[H])]=b(_[H]),q.prototype["set"+g(_[H])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[H]);for(var J=0;J<S.length;J++)q.prototype["get"+g(S[J])]=b(S[J]),q.prototype["set"+g(S[J])]=function(Se){return function(Ge){if(!p(Ge))throw new TypeError(Se+" must be a Number");this[Se]=Number(Ge)}}(S[J]);for(var ae=0;ae<T.length;ae++)q.prototype["get"+g(T[ae])]=b(T[ae]),q.prototype["set"+g(T[ae])]=function(Se){return function(Ge){this[Se]=String(Ge)}}(T[ae]);return q});var Nt={};(function(p,g){typeof Nt=="object"?Nt=g(Ct):p.ErrorStackParser=g(p.StackFrame)})(this,function(g){var b=/(^|@)\S+\:\d+/,_=/^\s*at .*(\S+\:\d+|\(native\))/m,S=/^(eval@)?(\[native code\])?$/;return{parse:function(E){if(typeof E.stacktrace<"u"||typeof E["opera#sourceloc"]<"u")return this.parseOpera(E);if(E.stack&&E.stack.match(_))return this.parseV8OrIE(E);if(E.stack)return this.parseFFOrSafari(E);throw new Error("Cannot parse given Error object")},extractLocation:function(E){if(E.indexOf(":")===-1)return[E];var I=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,q=I.exec(E.replace(/[\(\)]/g,""));return[q[1],q[2]||void 0,q[3]||void 0]},parseV8OrIE:function(E){var I=E.stack.split(`
|
|
2
|
+
`+nn),Ot&&Ph([Q,Oe,Ve],_n=>{nn=nd(nn,_n," ")}),x&&Nr?x.createHTML(nn):nn},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ve=null,zt=!1},e.isValidAttribute=function(vt,ue,je){ve||Me({});const st=se(vt),Jt=se(ue);return qt(st,Jt,je)},e.addHook=function(vt,ue){typeof ue=="function"&&rd(pe[vt],ue)},e.removeHook=function(vt,ue){if(ue!==void 0){const je=Vq(pe[vt],ue);return je===-1?void 0:Hq(pe[vt],je,1)[0]}return xC(pe[vt])},e.removeHooks=function(vt){pe[vt]=[]},e.removeAllHooks=function(){pe=FC()},e}var u6=pO();const c6={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},l6="javascript:";var Lu;let Qc=(Lu=class extends Error{constructor(t,n,i){super(t);ye(this,"code",Lu.CODE);ye(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},ye(Lu,"CODE","UNAUTHORIZED"),Lu);function d6(r){return(r==null?void 0:r.constructor)===Object}async function jC(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Qc)throw i;n=i,console.error(i),await Xd(1e3*Math.pow(2,t))}}throw n}function Xd(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function xw(){return Math.random().toString(36).slice(2)}const f6=new TextDecoder,h6=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return f6.decode(t)},p6=r=>r.length===0,v6=(...r)=>r.every(p6),Lb=r=>{const e=u6.sanitize(r,c6);return e.includes(l6)?(console.warn("Suspicious content detected and removed."),""):e},g6=[8,4,4,4,12],m6=()=>{const r=globalThis.crypto;if(!r)return null;if(typeof r.randomUUID=="function")return r.randomUUID();if(typeof r.getRandomValues!="function")return null;const e=r.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");let n=0;return g6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},y6="prod",Mw="6.33.0",BC="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Mw};class _6{constructor(e){ye(this,"buffer");ye(this,"writeIndex",0);ye(this,"size",0);ye(this,"capacity");this.capacity=e,this.buffer=new Array(e)}push(e){this.buffer[this.writeIndex]=e,this.writeIndex++,this.writeIndex>=this.capacity&&(this.writeIndex=0),this.size<this.capacity&&this.size++}toArray(){return this.size<this.capacity?this.buffer.slice(0,this.size):[...this.buffer.slice(this.writeIndex),...this.buffer.slice(0,this.writeIndex)]}clear(){this.writeIndex=0,this.size=0,this.buffer=new Array(this.capacity)}}const Lo=class Lo{constructor(e){ye(this,"channel");this.channel=e}static addHandler(e){Lo.logHandlers.push(e)}static printLogHistoryData(e){Lo.consoleLog(e.channel,e.level,...e.args)}static consoleLog(e,t,...n){console[t](`[${t}][${e}]`,...n)}debug(...e){this.log("debug",...e)}info(...e){this.log("info",...e)}warn(...e){this.log("warn",...e)}error(...e){this.log("error",...e)}log(e,...t){const n=t.map(Dw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};ye(Lo,"logHandlers",[]),ye(Lo,"logHistory",new _6(1e3));let un=Lo;const b6=(r,e,...t)=>{let n=t.pop();return typeof n=="string"&&(t.push(n),n={}),{loglevel:e,channel:r,timestamp:new Date().toISOString(),application:zn.application,sdk_version:zn.version,device_uuid:zn.deviceId,tenant:zn.tenant,company_id:zn.companyId,tracker_id:zn.trackerId||void 0,location_url:location.href,data:w6(n),message:Dw(t.join(" "))}},qC=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],S6=[/(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}/g,/(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}/g,/[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+/g,/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g];function Dw(r){return Uc(r,new WeakSet)}function Uc(r,e){if(!r)return r;if(typeof r=="string")return S6.forEach(t=>{r=r.replace(t,"__MASKED__")}),r;if(typeof r=="object"&&e.has(r))return"[Circular]";if(typeof r=="object"&&e.add(r),Array.isArray(r))return r.map(t=>Uc(t,e));if(r instanceof Error){const t={name:r.name,message:Uc(r.message,e)};r.stack&&(t.stack=Uc(r.stack,e));for(const n of Object.getOwnPropertyNames(r))n==="name"||n==="message"||n==="stack"||(qC.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Uc(r[n],e));return t}return d6(r)&&(r={...r},Object.keys(r).forEach(t=>{qC.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Uc(r[t],e)})),r}function w6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Dw(r.data)}const T6=new un("chat-provider"),Ud="$superseded";class Yv{constructor(e,t,n,i){ye(this,"audio");ye(this,"issueChatToken");ye(this,"identity");ye(this,"channelId");ye(this,"region");ye(this,"inTask",!1);ye(this,"muted",!1);ye(this,"providerContext");ye(this,"events");this.events=e,this.region=t.region,this.audio=new jq,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){T6.warn("Chat audio play failed",{error:e})}}cleanupAudio(){this.audio&&this.audio.cleanup()}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}trackInTask(e){e.type===tn.NOTI&&e.event===Er.TASK_VA_STARTED?this.inTask=!0:e.type===tn.NOTI&&(e.event===Er.TASK_VA_FINISHED||e.event===Er.TASK_VA_FAILED)&&(this.inTask=!1)}}ye(Yv,"type","base");const vO={};function Xv(r){vO[r.type]=r}function E6(r){return vO[r]}const jv=class jv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");ye(this,"code",jv.CODE);ye(this,"status");this.name="ChatEndedError",this.status=t}};ye(jv,"CODE","CHAT_ENDED");let dv=jv;const WC=new un("MediaStore"),C6=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,k6="chat-media",VC=1,fv="file";class gO{constructor(){ye(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(HC(this.db));const n=C6.open(k6,VC);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(HC(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<VC&&(WC.info("deprecating media store"),s.deleteObjectStore(fv)),WC.info("creating media store"),s.createObjectStore(fv)}})}async save(e,t){(await this.store()).put({index:e,file:t},e)}async getAll(){const e=await this.store();return await new Promise((t,n)=>{const i=e.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const e={};return(await this.getAll()).forEach(n=>{e[n.index]=n.file}),e}async clear(){(await this.store()).clear()}}function HC(r){return r.transaction(fv,"readwrite").objectStore(fv)}const Gp={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},GC=1e4,R6=3e4,I6=9e5,mO={UPDATED:"riskFlagsUpdated"},wu=new un("Communicator");var Fo,of;class P6{constructor(e,t){ye(this,"user");ye(this,"clientEventManager");ye(this,"clientAuthenticate");ye(this,"config");ye(this,"channel");ye(this,"channelReady",!1);ye(this,"hasAuthenticated",!1);ye(this,"hasInitializedLogProxy",!1);ye(this,"queuedMessagesToBridge",[]);ye(this,"pendingBridgeRequests",{});ye(this,"bridgeIframe");ye(this,"bridgeMessageHandlers");ye(this,"tokenRefreshTimeout");ye(this,"logProxyQueue",[]);yy(this,Fo,"");yy(this,of,0);ye(this,"authRefreshInFlight",null);ye(this,"riskFlags",null);this.onReady=this.onReady.bind(this),this.onCallback=this.onCallback.bind(this),this.onRefreshToken=this.onRefreshToken.bind(this),this.onRiskFlags=this.onRiskFlags.bind(this),this.onMessageFromBridge=this.onMessageFromBridge.bind(this),this.clientAuthenticate=e.authenticate,this.clientEventManager=t,this.initConfig(e),this.channel=new MessageChannel,this.channel.port1.onmessage=this.onMessageFromBridge,this.initBridge()}get wsUrl(){return this.config.host.replace(/^http/,"ws")+"/ws"}async getAuthToken(e=!1){if(!e&&this.isAuthTokenFresh())return Rc(this,Fo);const t=await this.refreshAuthToken();if(!t)throw new Error("Auth refresh completed without a token");return t}async request(e,t){!this.hasAuthenticated&&e!=="proactive_chat_triggers"&&await this.onRefreshToken();const n={url:e,options:t};return this.postMessageWithCallbackToBridge("request",n)}leaveChatBeacon(e){var n;if(!Rc(this,Fo)||!((n=this.config)!=null&&n.host))return;const t=`${this.config.host}/api/v2/chats/${e}/leave`;fetch(t,{method:"POST",body:"{}",keepalive:!0,headers:{Authorization:`Bearer ${Rc(this,Fo)}`,"Content-Type":"application/json","UJET-SDK-Type":"Web"}}).catch(()=>{})}destroy(){delete this.channel,this.bridgeIframe&&(this.bridgeIframe.remove(),this.bridgeIframe=void 0),this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout)}getBridgeLogHistory(){return this.postMessageWithCallbackToBridge("_getLogHistory",{})}isRiskFlagEnabled(e){var t;return((t=this.riskFlags)==null?void 0:t[e])??!0}getRiskFlags(){return{...this.riskFlags??{}}}initBridge(){const e=document.createElement("iframe");e.src=this.config.bridge,e.setAttribute("style","display:none"),e.addEventListener("load",()=>{if(wu.debug("initialized iframe for origin:",this.config.bridgeOrigin),!this.channelReady){const t={type:"_init",data:this.config};wu.debug("sending message to bridge:",t),e.contentWindow.postMessage(t,this.config.bridgeOrigin,[this.channel.port2])}}),document.body.appendChild(e),this.bridgeIframe=e,this.bridgeMessageHandlers={ready:this.onReady,callback:this.onCallback,refreshToken:this.onRefreshToken,_riskFlags:this.onRiskFlags}}onReady(e){this.channelReady=!0,zn.deviceId=e.result.deviceId,zn.deviceId||wu.error("Device Id has not been provided. SDK will not work properly."),this.flushQueuedMessagesToBridge(),this.clientEventManager.triggerEvent("ready")}onCallback(e){if(!e.callbackId)return;const[t,n]=this.pendingBridgeRequests[e.callbackId];e.error?n(e.error):t(e.result),delete this.pendingBridgeRequests[e.callbackId]}async onRefreshToken(){try{await this.refreshAuthToken()}catch(e){if(!(e instanceof Qc))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Rc(this,Fo)&&Rc(this,of)-Date.now()>R6}refreshAuthToken(){return this.authRefreshInFlight??(this.authRefreshInFlight=this.performAuth().finally(()=>{this.authRefreshInFlight=null})),this.authRefreshInFlight}async performAuth(){this.hasAuthenticated=!0;let e;try{e=await this.clientAuthenticate()}catch(i){throw new Qc("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Qc("Failed to validate client authenticate response token with UJET server","server");t.auth_token&&this.setAuthToken(t.auth_token);const n=this.decodeJwt(e.token);return this.user={identifier:n.identifier,name:n.name,email:n.email},n.exp&&this.enqueueTokenRefresh(n.exp),this.initLogProxyHandler(t),wu.info("Web SDK authenticated"),this.clientEventManager.triggerEvent("authenticate"),this.clientEventManager.triggerEvent("authenticated"),t.auth_token??""}setAuthToken(e){_y(this,Fo,e),_y(this,of,this.readTokenExpiry(e))}readTokenExpiry(e){try{const{exp:t}=this.decodeJwt(e);return typeof t!="number"?0:t.toString().length===13?t:t*1e3}catch{return 0}}onRiskFlags(e){var n;const t=(n=e.result)==null?void 0:n.flags;t&&(this.riskFlags=t,this.clientEventManager.triggerEvent(mO.UPDATED,this.getRiskFlags()))}onMessageFromBridge(e){var n;wu.debug("received message from bridge:",e.data);const t=this.bridgeMessageHandlers[(n=e.data)==null?void 0:n.type];t&&t(e.data)}postMessageToBridge(e){this.channel&&this.channelReady?(wu.debug("sending message to bridge:",e),this.channel.port1.postMessage(e)):this.queuedMessagesToBridge.push(e)}flushQueuedMessagesToBridge(){for(;this.queuedMessagesToBridge.length;){const e=this.queuedMessagesToBridge.shift();this.postMessageToBridge(e)}}postMessageWithCallbackToBridge(e,t){return new Promise((n,i)=>{const s=xw()+"_"+Date.now();this.pendingBridgeRequests[s]=[n,i];const a={type:e,callbackId:s,data:t};this.postMessageToBridge(a)})}initConfig(e){var l;let t=e.host;t||(e.tenant?t=BC.replace("main.api",e.tenant):t=BC);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.33.0",c=/^https:/.test(a)?new URL(a).origin:"*",o=["twilio_chat","nexmo_chat","ujet_chat"];i&&o.push("cobrowse"),this.config={host:t,lang:n,cobrowse:i,companyId:e.companyId,location:location.href,version:e.version||"6.33.0",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,un.addHandler((t,n,...i)=>{if(n==="debug")return;const s=b6(t,n,...i);this.logProxyQueue.push(s)}),this.sendLogsToBridge())}sendLogsToBridge(){this.logProxyQueue.length&&(this.postMessageToBridge({type:"_log",data:{num_of_logs:this.logProxyQueue.length,logs:this.logProxyQueue}}),this.logProxyQueue=[]),setTimeout(()=>{this.sendLogsToBridge()},2e3)}serverAuthenticate(e){return this.postMessageWithCallbackToBridge("_auth",{modules:this.config.modules,user:{token:e,company_id:this.config.companyId}})}enqueueTokenRefresh(e){clearTimeout(this.tokenRefreshTimeout);const t=this.normalizeJwtExp(e),n=Math.max(t-Date.now()-GC,GC);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1];return JSON.parse(h6(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+I6}}Fo=new WeakMap,of=new WeakMap;const A6=new un("EventManager");class Qv{constructor(){ye(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){A6.debug(`event triggered: ${e}`);const n=this.handlers[e];n&&n.forEach(i=>{i(t)})}removeEventListener(e,t){if(this.handlers[e]){const n=this.handlers[e].indexOf(t);n!==-1&&this.handlers[e].splice(n,1)}}destroy(){this.handlers={}}}function O6(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===tn.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];yO(n,s.content)}return n})}function $6(r,e){return yO(r,e.content)}function yO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const zC={photo:2,video:2,audio:1,document:1};function x6(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(zC[t.type]||0)-(zC[e.type]||0))}function M6(r){try{const{pathname:e}=new URL(r),t=e.split("/").filter(n=>n.length>0);return t.length>0?decodeURIComponent(t[t.length-1]):"document"}catch{return"document"}}function D6(r,e){r.forEach(t=>{if(t.type==="document"&&t.media_id!=null){const n=e.find(i=>i.media_id===t.media_id);n&&n.url&&(t.document={url:n.url},t.title||(t.title=M6(n.url)))}})}const N6={confirmSessionTitle:"Screen Share Session Request",confirmSessionContent:"Do you want to share your current screen with the agent?",endSessionText:"End Screen Share Session",confirmRemoteControlTitle:"Remote Access Request",confirmRemoteControlContent:"The agent would like to have access to your currently shared screen to further assist you. Do you want to allow this?",confirmFullDeviceTitle:"Screen Share Request",confirmFullDeviceContent:"Do you want to share your full screen with the agent? The agent will not be able to control anything on the screen.",allowText:"Allow",denyText:"Deny"},L6={confirmSessionTitle:"Solicitud de sesión de conavegación",confirmSessionContent:"¿Desea compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de conavegación",confirmRemoteControlTitle:"Solicitud de acceso remoto",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actual compartida para seguir asistiéndole. ¿Desea permitirlo?",confirmFullDeviceTitle:"Solicitud de compartir pantalla",confirmFullDeviceContent:"¿Desea compartir su pantalla completa con el agente? El agente no podrá controlar nada de la pantalla.",allowText:"Permitir",denyText:"Denegar"},U6={confirmSessionTitle:"Demande de session de co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent ?",endSessionText:"Terminer la session de co-navigation",confirmRemoteControlTitle:"Demande d'accès à distance",confirmRemoteControlContent:"L'agent souhaite avoir accès à l'écran que vous partagez actuellement pour mieux vous aider. Voulez-vous l'y autoriser ?",confirmFullDeviceTitle:"Demande de partage d'écran",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent ? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran.",allowText:"Autoriser",denyText:"Refuser"},F6={confirmSessionTitle:"Screen Share-Sitzungsanfrage",confirmSessionContent:"Möchten Sie Ihren aktuellen Bildschirm für den Agenten freigeben?",endSessionText:"Screen Share-Sitzung beenden",confirmRemoteControlTitle:"Fernzugriff-Anfrage",confirmRemoteControlContent:"Der Agent möchte Zugriff auf Ihren aktuell freigegebenen Bildschirm erhalten, um Ihnen weiterhelfen zu können. Möchten Sie dies erlauben?",confirmFullDeviceTitle:"Bildschirmfreigabe",confirmFullDeviceContent:"Möchten Sie Ihren gesamten Bildschirm für den Agenten freigeben? Der Agent ist dadurch nicht in der Lage, Elemente auf Ihrem Bildschirm zu steuern.",allowText:"Erlauben",denyText:"Verweigern"},j6={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},B6={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},q6={confirmSessionTitle:"Richiesta di sessione di Screen Share",confirmSessionContent:"Vuoi condividere la tua schermata attuale con l'operatore?",endSessionText:"Termina sessione di Screen Share",confirmRemoteControlTitle:"Richiesta di accesso remoto",confirmRemoteControlContent:"L'operatore vorrebbe accedere alla tua schermata attualmente condivisa per assisterti al meglio. Acconsenti?",confirmFullDeviceTitle:"Richiesta di condivisione schermo",confirmFullDeviceContent:"Vuoi condividere il tuo intero schermo con l'operatore? L'operatore non potrà controllare nessun elemento sullo schermo.",allowText:"Consenti",denyText:"Rifiuta"},W6={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},V6={confirmSessionTitle:"Samwebbläsningssession har begärts",confirmSessionContent:"Vill du dela din aktuella skärm med vår medarbetare?",endSessionText:"Avsluta samwebbläsningssession",confirmRemoteControlTitle:"Begäran om fjärråtkomst",confirmRemoteControlContent:"Vår medarbetare skulle vilja få åtkomst till skärmen som du delar just nu för att kunna hjälpa dig vidare. Vill du tillåta detta?",confirmFullDeviceTitle:"Begäran om skärmdelning",confirmFullDeviceContent:"Vill du dela hela skärmen med medarbetaren? Medarbetaren kommer inte kunna kontrollera något på skärmen.",allowText:"Tillåt",denyText:"Neka"},H6={confirmSessionTitle:"Solicitação de Sessão de Co-navegação",confirmSessionContent:"Deseja partilhar o seu ecrã atual com o agente?",endSessionText:"Terminar Sessão de Co-navegação",confirmRemoteControlTitle:"Solicitação de Acesso Remoto",confirmRemoteControlContent:"O agente gostaria de ter acesso ao seu ecrã partilhado atualmente para ajudá-lo ainda mais. Quer permitir isto?",confirmFullDeviceTitle:"Solicitação de Partilha de Ecrã",confirmFullDeviceContent:"Deseja partilhar o seu ecrã inteiro com o agente? O agente não poderá controlar nada no ecrã.",allowText:"Permitir",denyText:"Negar"},G6={confirmSessionTitle:"Pyyntö yhteisselausistunnosta",confirmSessionContent:"Haluatko jakaa nykyisen näyttösi edustajan kanssa?",endSessionText:"Lopeta yhteisselausistunto",confirmRemoteControlTitle:"Etäkäyttöpyyntö",confirmRemoteControlContent:"Edustaja haluaisi saada käyttää tällä hetkellä jakamaasi näyttöä voidakseen auttaa sinua enemmän. Haluatko antaa siihen luvan?",confirmFullDeviceTitle:"Näytön jakamispyyntö",confirmFullDeviceContent:"Haluatko jakaa koko näyttösi edustajan kanssa? Edustaja ei pysty käyttämään mitään näytöllä olevaa.",allowText:"Salli",denyText:"Estä"},z6={confirmSessionTitle:"Samlesingsøkten er startet",confirmSessionContent:"Vil du dele skjermen din med agenten?",endSessionText:"Avslutt samlesingsøkt",confirmRemoteControlTitle:"Forespørsel om fjerntilgang",confirmRemoteControlContent:"Agenten vil ha tilgang til skjermen din for å kunne hjelpe deg videre. Vil du tillate dette?",confirmFullDeviceTitle:"Forespørsel om skjermdeling",confirmFullDeviceContent:"Vil du dele hele skjermen din med agenten? Agenten kan ikke kontrollere noe på skjermen.",allowText:"Tillat",denyText:"Avvis"},K6={confirmSessionTitle:"Forespørgsel om sambrowsingsession",confirmSessionContent:"Vil du dele din nuværende skærm med agenten",endSessionText:"Afslut sambrowsingsession",confirmRemoteControlTitle:"Anmodning om fjernadgang",confirmRemoteControlContent:"Agenten vil gerne have adgang til din nuværende delte skærm for at kunne hjælpe dig yderligere. Ønsker du at tillade dette?",confirmFullDeviceTitle:"Forespørgsel om skærmdeling",confirmFullDeviceContent:"Vil du dele din fulde skærm med agenten? Agenten vil ikke kunne styre noget på skærmen",allowText:"Tillad",denyText:"Afvis"},J6={confirmSessionTitle:"Verzoek om cobrowse-sessie",confirmSessionContent:"Wilt u uw huidige scherm delen met de agent?",endSessionText:"Cobrowse-sessie beëindigen",confirmRemoteControlTitle:"Verzoek om toegang op afstand",confirmRemoteControlContent:"De agent wil graag toegang hebben tot uw momenteel gedeelde scherm om u verder te helpen. Wilt u dit toestaan?",confirmFullDeviceTitle:"Verzoek om scherm te delen",confirmFullDeviceContent:"Wilt u uw volledige scherm delen met de agent? De agent kan niets op het scherm bedienen.",allowText:"Toestaan",denyText:"Weigeren"},Y6={confirmSessionTitle:"Oturum İsteğini Eş Zamanlı Tara",confirmSessionContent:"Mevcut ekranınızı temsilciyle paylaşmak ister misiniz?",endSessionText:"Eş zamanlı Oturum Taramayı Sonlandır",confirmRemoteControlTitle:"Uzaktan Erişim İsteği",confirmRemoteControlContent:"Temsilci şu anda paylaşılan ekranınıza size daha fazla yardımcı olabilmek için erişim sağlamak istiyor. Buna izin vermek istiyor musunuz?",confirmFullDeviceTitle:"Ekran Paylaşım İsteği",confirmFullDeviceContent:"Temsilciyle tam ekranınızı paylaşmak istiyor musunuz? Temsilci ekrandaki hiçbir şeyi kontrol edemez.",allowText:"İzin Ver",denyText:"Reddet"},X6={confirmSessionTitle:"Yêu cầu phiên cùng duyệt",confirmSessionContent:"Bạn có muốn chia sẻ màn hình hiện tại của mình với chuyên viên không?",endSessionText:"Kết thúc phiên cùng duyệt",confirmRemoteControlTitle:"Yêu cầu truy cập từ xa",confirmRemoteControlContent:"Chuyên viên muốn được cấp quyền truy cập vào màn hình bạn đang chia sẻ để hỗ trợ bạn nhiều hơn. Bạn có muốn cho phép không?",confirmFullDeviceTitle:"Yêu cầu chia sẻ màn hình",confirmFullDeviceContent:"Bạn có muốn chia sẻ toàn bộ màn hình của mình với chuyên viên không? Chuyên viên sẽ không thể điều khiển bất cứ phần nào trên màn hình.",allowText:"Cho phép",denyText:"Từ chối"},Q6={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},Z6={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},eW={confirmSessionTitle:"Žádost o relaci Screen Share",confirmSessionContent:"Chcete svou současnou obrazovku sdílet s agentem?",endSessionText:"Ukončit relaci Screen Share",confirmRemoteControlTitle:"Žádost o vzdálený přístup",confirmRemoteControlContent:"Agent by rád získal přístup k vaší stávající sdílené obrazovce, aby vám mohl dál pomoci. Chcete mu přístup povolit?",confirmFullDeviceTitle:"Žádost o sdílení obrazovky",confirmFullDeviceContent:"Chcete svou celou obrazovku sdílet s agentem? Agent nebude moci ovládat nic, co na obrazovce je.",allowText:"Povolit",denyText:"Zamítnout"},tW={confirmSessionTitle:"Prośba o sesję Screen Share",confirmSessionContent:"Czy chcesz udostępnić konsultantowi swój bieżący ekran?",endSessionText:"Zakończ sesję Screen Share",confirmRemoteControlTitle:"Prośba o zdalny dostęp",confirmRemoteControlContent:"Konsultant prosi o dostęp do Twojego aktualnie udostępnionego ekranu, aby udzielić Ci dalszej pomocy. Czy chcesz na to zezwolić?",confirmFullDeviceTitle:"Prośba o udostępnienie ekranu",confirmFullDeviceContent:"Czy chcesz udostępnić konsultantowi swój cały ekran? Konsultant nie będzie mógł kontrolować niczego na ekranie.",allowText:"Zezwól",denyText:"Odmów"},rW={confirmSessionTitle:"Screen Share munkameneti kérés",confirmSessionContent:"Megosztja az aktuális képernyőjét a képviselővel?",endSessionText:"Screen Share munkamenet befejezése",confirmRemoteControlTitle:"Távoli hozzáférési kérés",confirmRemoteControlContent:"A képviselő szeretne hozzáférni a jelenleg megosztott képernyőjéhez, hogy további segítséget nyújthasson. Engedélyezi ezt?",confirmFullDeviceTitle:"Képernyőmegosztási kérelem",confirmFullDeviceContent:"Megosztja a teljes képernyőjét az ügynökkel? Az ügynök semmit sem tud majd irányítani a képernyőn.",allowText:"Engedélyezés",denyText:"Elutasítás"},nW={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},iW={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},sW={confirmSessionTitle:"Solicitare sesiune de co-navigare",confirmSessionContent:"Doriți să partajați ecranul dumneavoastră curent cu agentul?",endSessionText:"Încheiați sesiunea de co-navigare",confirmRemoteControlTitle:"Cerere de acces la distanță",confirmRemoteControlContent:"Agentul ar dori să aibă acces la ecranul dumneavoastră partajat pentru a vă ajuta în continuare. Doriți să permiteți acest lucru?",confirmFullDeviceTitle:"Cerere de partajare a ecranului",confirmFullDeviceContent:"Doriți să partajați ecranul dumneavoastră complet cu agentul? Agentul nu va putea controla nimic de pe ecran.",allowText:"Permiteți",denyText:"Refuzați"},aW={confirmSessionTitle:"Zahtjev za sesiju zajedničkog pregledavanja",confirmSessionContent:"Želite li podijeliti svoj trenutni zaslon s agentom?",endSessionText:"Završi sesiju zajedničkog pregledavanja",confirmRemoteControlTitle:"Zahtjev za daljinski pristup",confirmRemoteControlContent:"Agent želi imati pristup vašem trenutno dijeljenom zaslonu kako bi Vam dodatno pomogao. Želite li to dopustiti?",confirmFullDeviceTitle:"Zahtjev za dijeljenje zaslona",confirmFullDeviceContent:"Želite li s agentom podijeliti svoj cijeli zaslon? Agent neće moći ništa kontrolirati na ekranu.",allowText:"Dopustiti",denyText:"Odbiti"},oW={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},uW={confirmSessionTitle:"Kahilingan sa Screen Share na Sesyon",confirmSessionContent:"Gusto mo bang ibahagi ang iyong kasalukuyang screen sa agent?",endSessionText:"Tapusin ang Screen Share na Sesyon",confirmRemoteControlTitle:"Kahilingan sa Remote Access",confirmRemoteControlContent:"Gusto ng agent na magkaroon ng access sa iyong nakabahaging screen sa kasalukuyan upang mas matulungan ka. Gusto mo bang payagan ito?",confirmFullDeviceTitle:"Kahilingan sa Pagbahagi ng Screen",confirmFullDeviceContent:"Gusto mo bang ibahagi ang buong screen sa agent? Hindi makokontrol ng agent ang kahit ano sa screen.",allowText:"Payagan",denyText:"Tanggihan"},od={en:N6,es:L6,"es-MX":{confirmSessionTitle:"Solicitud de Sesión de Co-navegación",confirmSessionContent:"¿Quiere compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de co-navegación",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actualmente compartida para poder ayudarlo. ¿Quiere permitirlo?",confirmFullDeviceTitle:"Petición de pantalla compartida",confirmFullDeviceContent:"¿Quiere compartir su pantalla completa con el agente? El agente no podrá controlar nada en la pantalla."},fr:U6,"fr-CA":{confirmSessionTitle:"Demande de session co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent?",endSessionText:"Fin de la session de co-navigation",confirmRemoteControlContent:"L'agent souhaiterait avoir accès à votre écran actuellement partagé pour mieux vous aider. Voulez-vous l'autoriser?",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran."},de:F6,ja:j6,ko:B6,it:q6,zh:W6,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:V6,pt:H6,"pt-BR":{confirmSessionContent:"Você deseja compartilhar sua tela atual com o agente?",endSessionText:"Encerrar Sessão de Co-navegação",confirmRemoteControlContent:"O agente gostaria de acessar sua tela atualmente compartilhada para melhor ajudá-lo. Você deseja permitir isso?",confirmFullDeviceTitle:"Solicitação de Compartilhamento de Tela",confirmFullDeviceContent:"Você deseja compartilhar sua tela inteira com o agente? O agente não poderá controlar nada na tela."},fi:G6,nb:z6,da:K6,nl:J6,tr:Y6,vi:X6,th:Q6,ar:Z6,cs:eW,pl:tW,hu:rW,ru:nW,hi:iW,ro:sW,hr:aW,uk:oW,tl:uW};function cW(r){const e=r.split("-")[0];return od[r]?r===e?od[r]:{...od[e],...od[r]}:od[e]}async function lW(r,e,t,n){const i=new FormData;Object.keys(t).forEach(c=>{i.append(c,t[c])}),e instanceof File?i.append("file",e,e.name):e.fileBits&&i.append("file",new File(e.fileBits,e.name,e.options),e.name);const s=await fetch(r,{method:"POST",body:i,signal:n});if(!s.ok)throw new Error(`upload failed: HTTP ${s.status}`);const a=await s.text();return dW(a)}function dW(r){var n,i;const t=(i=(n=new window.DOMParser().parseFromString(r,"text/xml").getElementsByTagName("Key")[0])==null?void 0:n.childNodes[0])==null?void 0:i.nodeValue;if(!t)throw new Error("upload response missing <Key> element");return t}const _O="chat-5565-surface-subscription-end",fW="chat-5580-nonblocking-history-hint",Oh=new un("chat-originals"),hW="web-4258-local-original-cache",pW=1e3,vW=4,KC=1e4,gW=100;function JC(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class mW{constructor(){ye(this,"byClientMessageId",new Map);ye(this,"byRedactionRef",new Map);ye(this,"inFlight",new Map);ye(this,"queue",[]);ye(this,"active",0);ye(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||ky(this.byClientMessageId,e,t)}lookup(e){if(typeof e=="string")return this.byClientMessageId.get(e)}forget(e){this.byClientMessageId.delete(e)}lookupFetched(e){return this.byRedactionRef.get(e)}fetch(e,t){const n=this.byRedactionRef.get(e);if(n!==void 0)return Promise.resolve(n);const i=this.inFlight.get(e);if(i)return i;const s=this.generation,a=this.runInSlot(s,()=>{const c=this.call(t,e);return{result:this.withTimeout(c).then(l=>this.settle(s,e,l),l=>(s===this.generation&&(l==null?void 0:l.status)===404?ky(this.byRedactionRef,e,null):Oh.info("original lookup failed",{redactionRef:e,status:l==null?void 0:l.status}),null)),transport:c}}).finally(()=>{this.inFlight.get(e)===a&&this.inFlight.delete(e)});return this.inFlight.set(e,a),a}invalidate(){this.generation+=1,this.byClientMessageId.clear(),this.byRedactionRef.clear(),this.inFlight.clear();const e=this.queue;this.queue=[],e.forEach(t=>t.cancel())}settle(e,t,n){return e!==this.generation?null:(n==null?void 0:n.redaction_ref)!==t||typeof n.content!="string"?(Oh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(ky(this.byRedactionRef,t,n.content),n.content)}call(e,t){try{return Promise.resolve(e(t))}catch(n){return Promise.reject(n)}}runInSlot(e,t){const n=()=>{if(e!==this.generation)return Promise.resolve(null);this.active+=1;const{result:i,transport:s}=t();return s.catch(()=>{}).finally(()=>this.releaseSlot()),i};return this.active<vW?n():this.queue.length>=gW?(Oh.info("original lookup queue full, skipping"),Promise.resolve(null)):new Promise(i=>{const s={start:()=>{clearTimeout(a),i(n())},cancel:()=>{clearTimeout(a),i(null)}},a=setTimeout(()=>{this.queue=this.queue.filter(c=>c!==s),Oh.info("original lookup gave up waiting for a slot"),i(null)},KC);this.queue.push(s)})}releaseSlot(){this.active-=1;const e=this.queue.shift();e&&e.start()}withTimeout(e){return new Promise((t,n)=>{const i=setTimeout(()=>{n(Object.assign(new Error("original lookup timed out"),{code:"TIMEOUT"}))},KC);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function ky(r,e,t){r.delete(e),r.set(e,t),r.size>pW&&r.delete(r.keys().next().value)}const bO=["assigned","va_assigned"],SO=["dismissed","va_dismissed"],yW=["va_assigned","va_dismissed"],_W=["queued","check_in_timeout",...bO,...SO],bW=["timeout","canceled","failed","finished"],Ds=new un("Chat"),SW=Symbol("owner-conflict"),Ry=1e3;function wW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const TW="web-4206-media-pairing-guard";class EW{constructor(e,t,n={},i){ye(this,"provider");ye(this,"store");ye(this,"globalEvents");ye(this,"state");ye(this,"connected",!1);ye(this,"allowSkipVirtualAgent",!1);ye(this,"inEscalation",!1);ye(this,"events");ye(this,"cachedFiles");ye(this,"hooks");ye(this,"originals",new mW);ye(this,"cacheOwner",null);ye(this,"restoredMessages",new Map);ye(this,"nextTrackedSweepAt",Ry);ye(this,"destroying",!1);ye(this,"leaveSent",!1);ye(this,"beaconAttempted",!1);ye(this,"connecting",!1);ye(this,"connectEnd","none");this.state=e,this.store=new gO,this.cachedFiles={},this.events=new Qv,this.hooks=n;const s=E6(this.state.provider_type);this.provider=new s(this.events,e,t,i)}_setGlobalEvents(e,t){this.globalEvents=e,this.on("message",n=>{if(this.destroying)return;n.content=Lb(n.content);const i=n[Ud]===!0;if(delete n[Ud],this.syncCacheOwner(),n.type===tn.SERVER_MESSAGE){const s=n.server_message_id??n.message_id;t(this.id,s).then(a=>{this.destroying||(n=$6(n,a),e.triggerEvent("chat.message",n))})}else if(n.type==="photo"||n.type==="video"||n.type==="document")setTimeout(()=>{if(this.destroying)return;const s=n.$index.toString();n.file=this.cachedFiles[s],e.triggerEvent("chat.message",n)},100);else{const s=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),i||this.registerMessageEvents(n),s&&this.lookupOwnOriginal(n)}}),this.on("memberJoined",n=>{e.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{e.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{e.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{e.triggerEvent("chat.typingEnded",n)}),this.on("checkInRequired",()=>{e.triggerEvent("chat.checkInRequested")}),this.on("checkInTimedOut",()=>{e.triggerEvent("chat.checkInTimedOut")}),this.on("error",n=>{Ds.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()})}handleConnectionEnded(){this.connecting&&this.connectEnd==="none"&&this.surfacesSubscriptionEnd()&&(this.connectEnd=this.connected?"done":"pending"),this.connected&&this.endConnection()}endConnection(){this.connected=!1,this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(e=>Ds.warn("provider destroy failed",{error:e}))}get id(){var e;return((e=this.state)==null?void 0:e.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var e;return((e=this.state)==null?void 0:e.provider_channel_id)||""}get lang(){var e;return((e=this.state)==null?void 0:e.lang)||""}get virtual(){return yW.indexOf(this.status)!==-1}get muted(){var e;return((e=this.provider)==null?void 0:e.muted)||!1}set muted(e){this.provider&&(this.provider.muted=e)}get agent(){return this.state?this.virtual?this.state.external_agent||this.state.virtual_agent:this.state.agent||this.state.virtual_agent:null}get allAgents(){var e,t;return{virtual:((e=this.state)==null?void 0:e.all_virtual_agents)||[],human:((t=this.state)==null?void 0:t.all_agents)||[]}}get userIdentity(){var e;return((e=this.provider)==null?void 0:e.identity)||""}get ownUserId(){return this.ownerConflict?null:this.payloadOwnerId??this.providerOwnerId}get ownerConflict(){const e=this.payloadOwnerId,t=this.providerOwnerId;return e!=null&&t!=null&&e!==t}get payloadOwnerId(){var t,n;const e=(n=(t=this.state)==null?void 0:t.end_user)==null?void 0:n.id;return typeof e=="number"&&Number.isFinite(e)?e:null}get providerOwnerId(){const[e,t]=this.userIdentity.split("-"),n=parseInt(t,10);return e===_i.END_USER&&Number.isFinite(n)?n:null}get status(){var e;return((e=this.state)==null?void 0:e.status)||""}get postSessionStatus(){var e;return((e=this.state)==null?void 0:e.post_session_transfer_status)||""}get statusText(){var e;return((e=this.state)==null?void 0:e.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return _W.indexOf(this.status)!=-1}get assigned(){return bO.indexOf(this.status)!=-1}get dismissed(){return SO.indexOf(this.status)!=-1}get ended(){return bW.indexOf(this.status)!=-1}get transcriptCount(){var e;return((e=this.state)==null?void 0:e.transcript_requested_count)||0}get createdAt(){var e;return((e=this.state)==null?void 0:e.created_at)||""}get inTask(){var e;return((e=this.provider)==null?void 0:e.inTask)||!1}get feedbackType(){var e;return this.state?this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none":"none"}get optInRequired(){var e;return((e=this.state)==null?void 0:e.post_session_opt_in_required)||!1}get postSessionRequired(){var e;return((e=this.state)==null?void 0:e.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===cl.IN_PROGRESS:!1}get checkInStatus(){var e;return((e=this.state)==null?void 0:e.check_in_status)??null}set checkInStatus(e){this.state&&(this.state.check_in_status=e)}update(e){if(!this.state||this.state.id!==e.id)return;const t=e.menus[e.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=e,this.syncCacheOwner(),t!==n&&this.triggerEvent("_menuChanged",this),e.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async connect(){if(!this.provider)return Ds.info("connecting interrupted"),!1;this.connecting=!0,this.connectEnd="none";try{if(await jC(()=>this.provider.create(),3),await jC(()=>this.connectEnd!=="none"?Promise.resolve():this.provider.join(this.state.provider_channel_id),3),this.settleEndedConnect())return Ds.info("connect abandoned: connection ended before it was announced"),!1;this.syncCacheOwner(),this.connected=!0;const e=await this.fetchMessages();if(this.destroying)return Ds.info("connect abandoned: chat destroyed while loading history"),!1;if(this.settleEndedConnect())return Ds.info("connect abandoned: connection ended while loading history"),!1;const t={chat:this,messages:e};return this.triggerEvent("connectedMessages",t),this.triggerEvent("connected",this),this.registerProviderEvents(),Ds.info("connected with provider",this.state.provider_type),!0}catch(e){return this.settleEndedConnect(),Ds.error("Failed to connect with provider",e),!1}finally{this.connecting=!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),Ds.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){Ds.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChatBeacon&&(this.beaconAttempted=!0,this.hooks.leaveChatBeacon())}resetBeaconState(){this.beaconAttempted=!1}async sendMessage(e,t){var s,a;if(this.ended)throw new dv(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,TW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){if(this.connected){const e=await this.store.getAllFiles(),t=await this.provider.fetchMessages(e);if(this.destroying||!this.state||!this.provider)return[];for(const i of t)delete i[Ud];return this.syncCacheOwner(),t.filter(i=>this.restoreOwnOriginal(i)).forEach(i=>this.lookupOwnOriginal(i)),t}else throw new Error("Please fetchMessages after chat connected.")}rememberOwnOriginal(e,t){this.destroying||!this.localOriginalCacheEnabled()||(this.syncCacheOwner(),this.originals.remember(e,t))}syncCacheOwner(){if(this.ownerConflict)return this.rebindCacheOwner(SW),null;const e=this.ownUserId;return e==null?typeof this.cacheOwner=="number"?this.cacheOwner:null:(this.rebindCacheOwner(e),e)}rebindCacheOwner(e){e!==this.cacheOwner&&(this.cacheOwner=e,this.revokeOriginals())}revokeOriginals(){this.originals.invalidate();const e=Array.from(this.restoredMessages.values());this.restoredMessages.clear(),this.nextTrackedSweepAt=Ry,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=wW(e);this.restoredMessages.set(e.$sid||t,t),this.restoredMessages.size>this.nextTrackedSweepAt&&(this.restoredMessages.forEach((n,i)=>{n.deref()===void 0&&this.restoredMessages.delete(i)}),this.nextTrackedSweepAt=Math.max(Ry,this.restoredMessages.size*2))}forgetOwnOriginal(e){this.originals.forget(e)}surfacesSubscriptionEnd(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,_O))??!0}settleEndedConnect(){return this.connectEnd==="pending"&&!this.destroying&&(this.endConnection(),this.connectEnd="done"),this.connectEnd!=="none"}localOriginalCacheEnabled(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,hW))??!0}restoreOwnOriginal(e){if(this.destroying||e.$userType!==_i.END_USER)return!1;const t=this.syncCacheOwner();if(t==null)return this.ownerConflict?(delete e.unredacted,!1):(this.applyOriginal(e,e.unredacted),!1);if(e.$userId!==t)return delete e.unredacted,!1;if(this.localOriginalCacheEnabled()&&this.applyOriginal(e,this.originals.lookup(e.client_message_id))||this.applyOriginal(e,e.unredacted))return!1;const n=e.redaction_ref;if(!JC(n)||!this.hooks.fetchMessageOriginal)return!1;const i=this.originals.lookupFetched(n);return i===null?!1:!this.applyOriginal(e,i)}applyOriginal(e,t){if(t===void 0)return!1;const n=typeof t=="string"&&t?Lb(t):"";return n?(e.unredacted=n,this.trackRestored(e),!0):(delete e.unredacted,!1)}lookupOwnOriginal(e){const t=e.redaction_ref,n=this.hooks.fetchMessageOriginal;if(this.destroying||!JC(t)||!n)return;const i=this.id,s=this.syncCacheOwner(),a=this.originals.currentGeneration;this.originals.fetch(t,n).then(c=>{if(!c||this.destroying||!this.state||this.id!==i||this.syncCacheOwner()!==s||a!==this.originals.currentGeneration)return;const o=e.unredacted;!this.applyOriginal(e,c)||e.unredacted===o||this.triggerEvent("messageUpdated",e)}).catch(c=>{Ds.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t,this.store.save(e,t)}async destroy(){this.destroying=!0,this.originals.invalidate(),this.restoredMessages.clear(),await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null,this.originals.invalidate(),this.restoredMessages.clear()}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){this.state&&(this.disconnect(),e.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(e,t){this.events.triggerEvent(e,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+e,t)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(e){switch(e.event){case Er.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case Er.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case Er.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case Er.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case Er.ESCALATION_STARTED:this.inEscalation=!0;break;case Er.ESCALATION_FAILED:case Er.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case Er.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case Er.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const CW=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),kW=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),wO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Iy=()=>kW()&&!CW();function YC(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>RW(n,`${e.comm_id}-${i}`));return e.entries=x6(t),e}),r}function RW(r,e){var t;return{$index:r.timestamp,$sid:e,$timestamp:new Date(r.timestamp),$userType:r.role,$userId:((t=r.user_data)==null?void 0:t.id)||0,user:r.user_data,type:r.type,...r.body}}const IW={en:"English (US)","en-CA":"English (Canada)","en-GB":"English (UK)",es:"Español (España)","es-MX":"Español (México)",fr:"Français (France)","fr-CA":"Français (Canada)",de:"Deutsch",ja:"日本語",ko:"한국어",it:"Italiano",zh:"中文 (简体)","zh-Hant":"中文 (繁體)",sv:"Svenska",pt:"Português (Portugal)","pt-BR":"Português (Brasil)",fi:"Suomi",nb:"Norsk",da:"Dansk",nl:"Nederlands",tr:"Türk",vi:"Tiếng Việt",th:"คนไทย",ar:"اَلْعَرَبِيَّةُ",cs:"Czech",pl:"Polish",hu:"Hungarian"};function PW(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:IW[i.lang]})),name:r.display_name,subdomain:r.subdomain,support_email:r.support_email,action_tracking:r.action_tracking_enabled,email_transcripts:r.chat_settings.email_transcripts,message_preview:r.chat_settings.message_preview,email_enhancement:r.email_enhancement_enabled,display_history:((t=r.chat_settings.display_history)==null?void 0:t.enabled)&&((n=r.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:r.use_recording,use_web:r.use_web,cobrowse_domain:r.cobrowse_domain}}function TO(r){return r.map(AW).filter(e=>e.enabled)}function AW(r){const e={id:r.id,enabled:!0,channels:[],hidden:!!r.hidden};if(!r.name||!r.name.trim())return e.enabled=!1,e;e.name=r.name.trim();const t=OW(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=TO(r.children);return e.enabled=n.length>0||t,e.children=n,e}if(!r.channels)e.enabled=t;else{const{channels:n,deflection:i}=$W(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function OW(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function $W(r){let e=null;const t=[],n=r.chat,i=s=>{!s.deflection_type&&s.deflected_reason&&(s.deflection_type=s.deflected_reason),s.deflected===void 0&&s.deflection_type&&(s.deflected=!0),t.push(s)};return n&&n.deflected&&(e={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...r.chat,type:"chat"}),r.voice_call&&r.voice_call.instant_enabled&&i({...r.voice_call,type:"instant_call"}),r.voice_call&&r.voice_call.schedule_enabled&&i({...r.voice_call,type:"scheduled_call",deflection_type:r.voice_call.schedule_deflection_type}),r.voice_call&&r.voice_call.inbound_enabled&&i({...r.voice_call,type:lv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:lv.VOICEMAIL,deflection_type:r.voice_call.deflected_reason??r.voice_call.voicemail_reason}),r.email&&r.email.enabled&&i({...r.email,type:"email"}),n&&n.deflected&&n.deflected_reason==="over_capacity"&&n.keep_waiting&&i({...n,enabled:!0,type:"keep_waiting",deflection_type:n.deflected_reason}),r.external_deflection_link&&r.external_deflection_link.enabled&&r.external_deflection_link.links.forEach(a=>{a.enabled&&i({...a,type:"external_link"})}),{channels:t,deflection:e}}const xW="ujet_voice_call",EO="twilio_voice",Kn={STATUS_CHANGED:"voice.statusChanged",RECONNECTING:"voice.reconnecting",RECONNECTED:"voice.reconnected",ERROR:"voice.error",SMART_ACTION_REQUESTED:"voice.smartActionRequested",SMART_ACTION_RESOLVED:"voice.smartActionResolved",COBROWSE_REQUESTED:"voice.cobrowseRequested",COBROWSE_RESOLVED:"voice.cobrowseResolved",RECORDING_PERMISSION_REQUIRED:"voice.recordingPermissionRequired",MIC_PERMISSION_REQUIRED:"voice.micPermissionRequired",CONNECTION_QUALITY:"voice.connectionQuality"},Nw=r=>{var e;if(r&&typeof r=="object"){const t=r;if(typeof((e=t.data)==null?void 0:e.message)=="string")return t.data.message;if(typeof t.message=="string")return t.message}return typeof r=="string"?r:String(r)},MW=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,CO=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class ws extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);ye(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Bv=class Bv extends ws{constructor(e="End user has a call in progress"){super(e,Bv.CODE),this.name="CallInProgressError"}};ye(Bv,"CODE","CALL_IN_PROGRESS");let Vu=Bv;const qv=class qv extends ws{constructor(e="Inbound voice is disabled for this menu"){super(e,qv.CODE),this.name="InboundDisabledError"}};ye(qv,"CODE","INBOUND_DISABLED");let ll=qv;const Wv=class Wv extends ws{constructor(e="Outside operation hours"){super(e,Wv.CODE),this.name="OperationHoursError"}};ye(Wv,"CODE","OPERATION_HOURS");let Hu=Wv;const Vv=class Vv extends ws{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Vv.CODE),this.name="FeatureNotEnabledError"}};ye(Vv,"CODE","FEATURE_NOT_ENABLED");let dl=Vv;const Hv=class Hv extends ws{constructor(e="Microphone permission denied",t){super(e,Hv.CODE,t),this.name="MicPermissionDeniedError"}};ye(Hv,"CODE","MIC_PERMISSION_DENIED");let fl=Hv;const Gv=class Gv extends ws{constructor(e="No active voice call"){super(e,Gv.CODE),this.name="NoActiveVoiceCallError"}};ye(Gv,"CODE","NO_ACTIVE_VOICE_CALL");let Uo=Gv;const zv=class zv extends ws{constructor(e="A voice call is active in another tab"){super(e,zv.CODE),this.name="AnotherTabVoiceCallError"}};ye(zv,"CODE","ANOTHER_TAB_VOICE_CALL");let hl=zv;const Kv=class Kv extends ws{constructor(e,t){super(e,Kv.CODE,t),this.name="ProviderError"}};ye(Kv,"CODE","PROVIDER_ERROR");let da=Kv;const Xc=class Xc extends ws{constructor(e,t){super(e,Xc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Xc.ENDED_MESSAGE}};ye(Xc,"CODE","SMART_ACTION_ERROR"),ye(Xc,"ENDED_MESSAGE","smart action is already ended");let ni=Xc;const Jv=class Jv extends ws{constructor(e,t){super(`Unrecognized voice error: ${e}`,Jv.CODE,t),this.name="UnknownVoiceError"}};ye(Jv,"CODE","UNKNOWN_VOICE_ERROR");let hv=Jv;const DW=r=>r instanceof Hu||r instanceof ll||r instanceof dl||r instanceof Vu,Ba=new un("BackgroundKeepAlive");class NW{constructor(e={}){ye(this,"active",!1);ye(this,"currentAgentName",null);ye(this,"wakeLock",null);ye(this,"audioCtx",null);ye(this,"silentSource",null);ye(this,"visibilityListener",null);ye(this,"pagehideListener",null);ye(this,"pageshowListener",null);ye(this,"resumeListener",null);ye(this,"cleanupInvoked",!1);this.deps=e}async start(e={}){this.active||(this.active=!0,this.currentAgentName=e.agentName??null,this.attachLifecycleListeners(),await this.acquireWakeLock(),this.active&&(this.applyMediaMetadata(),this.startSilentAudioLoop()))}updateAgentName(e){this.active&&this.currentAgentName!==e&&(this.currentAgentName=e,this.applyMediaMetadata())}async stop(){this.active&&(this.active=!1,this.detachLifecycleListeners(),await this.releaseWakeLock(),this.clearMediaSession(),this.stopSilentAudioLoop())}attachLifecycleListeners(){typeof document<"u"&&(this.visibilityListener=()=>{document.visibilityState==="visible"&&this.handleVisible()},document.addEventListener("visibilitychange",this.visibilityListener)),!(typeof window>"u")&&(this.pagehideListener=e=>{e!=null&&e.persisted||this.runCleanupOnce()},window.addEventListener("pagehide",this.pagehideListener),this.pageshowListener=e=>{e!=null&&e.persisted&&this.handleVisible()},window.addEventListener("pageshow",this.pageshowListener),this.resumeListener=()=>this.handleVisible(),window.addEventListener("resume",this.resumeListener))}detachLifecycleListeners(){typeof document<"u"&&this.visibilityListener&&document.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListener=null,typeof window<"u"&&(this.pagehideListener&&window.removeEventListener("pagehide",this.pagehideListener),this.pageshowListener&&window.removeEventListener("pageshow",this.pageshowListener),this.resumeListener&&window.removeEventListener("resume",this.resumeListener)),this.pagehideListener=null,this.pageshowListener=null,this.resumeListener=null}runCleanupOnce(){var e,t;if(!this.cleanupInvoked){this.cleanupInvoked=!0;try{(t=(e=this.deps).onCleanup)==null||t.call(e)}catch(n){Ba.debug("onCleanup threw during unload",n)}this.stop().catch(n=>Ba.debug("stop() during cleanup failed",n))}}handleVisible(){var e,t;(t=(e=this.audioCtx)==null?void 0:e.resume)==null||t.call(e).catch(n=>Ba.debug("audioCtx.resume failed",n)),this.acquireWakeLock(),this.applyMediaMetadata()}async acquireWakeLock(){if(typeof navigator>"u")return;const e=navigator.wakeLock;if(e!=null&&e.request&&!this.wakeLock)try{this.wakeLock=await e.request("screen")}catch(t){Ba.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){Ba.debug("wakeLock.release failed",e)}this.wakeLock=null}}applyMediaMetadata(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(!e)return;const t=globalThis.MediaMetadata;if(typeof t=="function")try{e.metadata=new t({title:this.currentAgentName?`Call with ${this.currentAgentName}`:"Voice call"})}catch(n){Ba.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){Ba.debug("mediaSession.metadata clear failed",t)}}startSilentAudioLoop(){if(typeof window>"u")return;const e=window.AudioContext||window.webkitAudioContext;if(typeof e=="function")try{this.audioCtx=new e;const t=this.audioCtx.createBuffer(1,1,22050),n=this.audioCtx.createBufferSource();n.buffer=t,n.loop=!0,n.connect(this.audioCtx.destination),n.start(),this.silentSource=n}catch(t){Ba.debug("silent audio loop start failed",t),this.audioCtx=null,this.silentSource=null}}stopSilentAudioLoop(){var e,t,n,i;try{(e=this.silentSource)==null||e.stop()}catch{}try{(t=this.silentSource)==null||t.disconnect()}catch{}this.silentSource=null,(i=(n=this.audioCtx)==null?void 0:n.close)==null||i.call(n).catch(s=>Ba.debug("audioCtx.close failed",s)),this.audioCtx=null}}const ps={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},kO="_provider.messageReceived",Oo={SMART_ACTION_REQUESTED:"smart_action_requested",SMART_ACTION_RESOLVED:"smart_action_resolved",RECORDING_PERMISSION_REQUIRED:"recording_permission_required",STATUS_CHANGED:"status_changed",SMART_ACTION_NOTIFIED:"smart_action_notified",SMART_ACTION_RESPONSE:"smart_action_response",RECORDING_PERMISSION:"recording_permission"},Wc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Py=r=>{switch(r){case"queued":case"assigned":return"queued";case"connecting":case"va_assigned":case"switching":return"connecting";case"connected":case"va_connected":return"connected";case"reconnecting":return"interrupted";case"finished":case"recovered":case"voicemail":case"canceled":case"timeout":return"ended";case"failed":return"error";case"scheduled":return"idle";default:return"error"}};class LW{constructor(e){ye(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return Wc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Ay="ujet:",br={set(r,e){try{localStorage.setItem(Ay+r,e)}catch{}},get(r){try{return localStorage.getItem(Ay+r)}catch{return null}},del(r){try{localStorage.removeItem(Ay+r)}catch{}}},pv="voice",UW=r=>{br.set(pv,String(r))},XC=()=>{const r=br.get(pv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(br.del(pv),null)},Vc=()=>{br.del(pv)},FW=new Set(["connected","va_connected"]),Oy=r=>FW.has(r),jW=new Set(["finished","canceled","expired"]),BW=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class qW{constructor(e,t,n,i,s){ye(this,"_state");ye(this,"_publicState",null);ye(this,"events");ye(this,"provider");ye(this,"methods");ye(this,"globalEvents");ye(this,"logger");ye(this,"destroyed",!1);ye(this,"isProviderConnected",!1);ye(this,"isUnloading",!1);ye(this,"startedAt",null);ye(this,"fetchEpoch",0);ye(this,"keepAlive",null);ye(this,"stateMachine");ye(this,"handledSmartActionIds",new Set);ye(this,"smartActionQueue",[]);ye(this,"currentCobrowseSmartActionId",null);ye(this,"recordingPermissionAsked",!1);ye(this,"speakerOn",!1);ye(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new Qv,this.logger=new un(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new LW(e.status),Oy(e.status)&&(this.startedAt=this.resolveStartedAtFromState()),this.registerProviderEvents()}setInternalState(e){this._state=e,this._publicState=null}get state(){if(!this._publicState){const{status:e,...t}=this._state;this._publicState=t}return this._publicState}serverStatus(){return this._state.status}get currentSmartActionId(){return this.smartActionQueue[0]??null}resolveStartedAtFromState(){const t=(this.state.participants??[]).find(n=>(n.type==="agent"||n.type==="virtual_agent")&&n.connected_at);if(t!=null&&t.connected_at){const n=new Date(t.connected_at).getTime();if(!Number.isNaN(n))return n}return Date.now()}setStatus(e,t){if(this.isUnloading)return!1;const n=this.stateMachine.transitionTo(e);if(n===null)return!1;if(this.setInternalState({...this._state,status:e}),this.stateMachine.isTerminal&&Vc(),(t==null?void 0:t.emit)!==!1){const i=(t==null?void 0:t.serverPrev)??n;this.globalEvents.triggerEvent(Kn.STATUS_CHANGED,{id:this.id,status:Py(e),prevStatus:Py(i)})}return!0}teardownActiveResources(){this.keepAlive&&(this.keepAlive.stop().catch(e=>this.logger.debug("keepAlive.stop failed",e)),this.keepAlive=null)}get id(){return this.state.id}get status(){return Py(this._state.status)}get agent(){return this.state.agent??this.state.virtual_agent??null}get duration(){return this.startedAt?Math.floor((Date.now()-this.startedAt)/1e3):0}get feedbackType(){var e;return this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none"}get recordingPermissionRequired(){return this.state.recording_option==="record_ask_user"&&this.state.recording_permission==="recording_permission_not_asked"&&!this.recordingPermissionAsked}async _connect(){var t;if(this.destroyed||this.isProviderConnected)return;if(await this.provider.create(),this.destroyed){await this.provider.destroy().catch(n=>{this.logger.debug("provider.destroy() during _connect race failed",n)});return}this.isProviderConnected=!0,this.recordingPermissionRequired&&this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});const e=(this.state.smart_actions??[]).filter(n=>!jW.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new NW({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;Oy(n)||n==="reconnecting"||Vc();try{this.provider.destroy()}catch{}}}),this.keepAlive.start({agentName:(t=this.agent)==null?void 0:t.name}).catch(n=>{this.logger.warn("background keep-alive start failed",n)})}_markUnloading(){this.isUnloading=!0}async _abandonOrFinish(){if(this.stateMachine.isTerminal)return;this.teardownActiveResources();const e=Oy(this._state.status);if(this.isProviderConnected)try{await this.provider.hangup()}catch(t){this.logger.warn("provider hangup failed",t)}try{!e&&this.methods.failCall?await this.methods.failCall(this.id,"abandoned"):this.methods.finishCall&&await this.methods.finishCall(this.id)}catch(t){this.logger.warn("server-side hangup failed",t)}this.setStatus("finished",{emit:!this.isProviderConnected})}async _destroy(){this.destroyed||(this.destroyed=!0,this.teardownActiveResources(),await this._abandonOrFinish().catch(e=>this.logger.warn("hangup during destroy failed",e)),await this.provider.destroy(),this.events.destroy())}mute(e){this.destroyed||this.isMuted()!==e&&this.provider.mute(e)}isMuted(){return this.provider.isMuted()}getRemoteAudioStream(){return this.destroyed?null:this.provider.getRemoteStream()}isSpeakerSupported(){return this.destroyed?!1:this.provider.isOutputSelectionSupported()}isSpeakerOn(){return this.speakerOn}async setSpeakerOn(e){if(!this.destroyed){if(!this.provider.isOutputSelectionSupported()){this.speakerOn=e;return}if(e){const t=this.provider.getAvailableOutputDevices().find(n=>/speaker|loud|external/i.test(n.label));if(!t)throw new da("no loudspeaker output available");await this.provider.setOutputDevice(t.deviceId)}else await this.provider.setOutputDevice("default");this.speakerOn=e}}async _escalate(){this.methods.escalateCall&&await this.methods.escalateCall(this.id)}async grantRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!0})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!0)}async denyRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!1})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!1)}async startCobrowse(e,t="end_user"){return this.cobrowseStarter(e??this.state.lang,t)}async submitTextSmartAction(e,t){await this.resolveSmartAction(e,{status:"finished",data:{text:t}})}async confirmVerificationSmartAction(e){await this.resolveSmartAction(e,{status:"finished"})}async cancelSmartAction(e){await this.resolveSmartAction(e,{status:"canceled"})}async uploadMediaForSmartAction(e,t,n){if(n==="video"){if(!this.methods.uploadVideos)throw new ni("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ni("uploadPhotos not configured");await this.methods.uploadPhotos(this.id,t,n,e)}this.markSmartActionHandled(e)}async prepareMediaUpload(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ni("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ni("uploadOnePhoto not configured");return{ref:await this.methods.uploadOnePhoto(this.id,e,n),kind:t}}async submitMediaRefsForSmartAction(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(n.length===0)throw new ni("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ni(`media ref kind '${i.kind}' does not match SmartAction type '${t}'`);const s=n.map(a=>a.ref);if(t==="video"){if(!this.methods.registerVideos)throw new ni("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ni("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(ps.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(ps.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(ps.ERROR,e=>{this.destroyed||this.stateMachine.isTerminal||(this.logger.warn("provider reported a fatal error",e),this.isProviderConnected=!1,this.teardownActiveResources(),this.globalEvents.triggerEvent(Kn.ERROR,{id:this.id,error:e==null?void 0:e.error}),this.setStatus("failed"))});for(const e of BW)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(kO,e=>{this.handleProviderMessage(e)})}async fetchAndUpdateState(){const e=++this.fetchEpoch;try{const t=await this.methods.fetchCall(this.id);if(e!==this.fetchEpoch||this.destroyed)return;this.setInternalState({...this._state,...t,status:this._state.status})}catch(t){this.logger.warn("on-demand fetchCall failed",t)}}handleProviderMessage(e){if(this.destroyed||this.isUnloading)return;const{type:t,data:n={}}=e;switch(t){case Oo.SMART_ACTION_REQUESTED:this.handleSmartActionRequested(n.smart_action);break;case Oo.SMART_ACTION_RESOLVED:this.handleSmartActionResolved(n);break;case Oo.RECORDING_PERMISSION_REQUIRED:if(this.recordingPermissionAsked)break;this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});break;case Oo.STATUS_CHANGED:this.handleStatusChanged(n);break;default:this.logger.debug("unhandled provider message type",t)}}handleSmartActionRequested(e){if(!e||this.handledSmartActionIds.has(e.id))return;if(e.type==="cobrowse"){if(this.currentCobrowseSmartActionId===e.id)return;this.currentCobrowseSmartActionId=e.id,this.globalEvents.triggerEvent(Kn.COBROWSE_REQUESTED,{smartAction:e})}else{if(this.smartActionQueue.includes(e.id))return;this.smartActionQueue.push(e.id),this.globalEvents.triggerEvent(Kn.SMART_ACTION_REQUESTED,{smartAction:e})}this.sendProviderMessage(Oo.SMART_ACTION_NOTIFIED,{smart_action_id:e.id})}handleSmartActionResolved(e){const t=e.smart_action_id;t&&(this.smartActionQueue.includes(t)&&this.globalEvents.triggerEvent(Kn.SMART_ACTION_RESOLVED,{smartActionId:t}),this.currentCobrowseSmartActionId===t&&(this.currentCobrowseSmartActionId=null,this.globalEvents.triggerEvent(Kn.COBROWSE_RESOLVED,{smartActionId:t})),this.markSmartActionHandled(t))}handleStatusChanged(e){var n,i,s;if(!e.status||this.stateMachine.isTerminal)return;if(this.fetchEpoch++,(e.agent||e.virtual_agent)&&this.setInternalState({...this._state,...e.agent&&{agent:e.agent},...e.virtual_agent&&{virtual_agent:e.virtual_agent}}),!Wc.has(e.status)){const a=((n=this._state.agent)==null?void 0:n.name)??((i=this._state.virtual_agent)==null?void 0:i.name)??null;(s=this.keepAlive)==null||s.updateAgentName(a),e.status==="connected"&&this.fetchAndUpdateState().then(()=>{this.destroyed||this._state.status!=="connected"||(this.startedAt=this.resolveStartedAtFromState())})}this.setStatus(e.status,{serverPrev:e.prev_status})}sendProviderMessage(e,t){return this.provider.sendMessage({type:e,data:t})!==null}markSmartActionHandled(e){this.handledSmartActionIds.add(e);const t=this.smartActionQueue.indexOf(e);t>=0&&this.smartActionQueue.splice(t,1)}async resolveSmartAction(e,t){if(this.sendProviderMessage(Oo.SMART_ACTION_RESPONSE,{smart_action_id:e,status:t.status,data:t.data,fail_reason:t.fail_reason})){this.markSmartActionHandled(e);return}if(!this.methods.updateSmartAction)throw new ni("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Nw(n);if(i===ni.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ni(i,n)}}}class Lw{constructor(e,t,n){ye(this,"events");ye(this,"state");ye(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}ye(Lw,"type","base");const RO={},IO=r=>{RO[r.type]=r},PO=r=>RO[r],$h=new un("methods"),QC=!0,WW="web-4191-refresh-unknown-chat-agent";class VW{constructor(e,t,n,i){ye(this,"request");ye(this,"lastDapRequestId",null);ye(this,"lastDirectAccessKeyId",null);ye(this,"dapPollGeneration",0);ye(this,"beaconLeaveChat");ye(this,"authContext");ye(this,"isRiskFlagEnabled");ye(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){$h.error(`Error fetching form data:, ${n}`)}});this.request=e,this.beaconLeaveChat=t,this.authContext=n,this.isRiskFlagEnabled=i}get(e,t){if(t){const n=[];Object.keys(t).forEach(i=>{const s=t[i];s!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}),e+="?"+n.join("&")}return this.request(e,{method:"GET"})}post(e,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(e,n)}patch(e,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(e,n)}put(e,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(e,n)}async getTriggers(e){const t={"UJET-Company-Id":e};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}submitCustomForm(e){return this.post("forms/submit",e)}async trackClientEvents(e){return await this.post("/client_events",{events:e})}async getCompany(){const e=await this.get("company");return PW(e.data)}async getFeatureFlags(){return(await this.get("feature_flags")).data}async getMenus(e,t,n){const i=this.dapPollGeneration,s={type:"web_menu",lang:e,direct_access_key:t};n!=null&&n.initialMessage&&(s.initial_message=n.initialMessage),n!=null&&n.signedCustomData&&(s.custom_data_signed=n.signedCustomData),n!=null&&n.customData&&(s.custom_data_unsigned=n.customData);let a=await this.post("menus",s);this.stashDapRequestId(a),this.isChatDapPending(a.data)&&(a=await this.pollChatDap(e,Number(a.data.max_timeout)||0,i));const c=a.headers["ujet-direct-access"],l={key:!!t,user:!!c&&c!=="false",key_id:null},d=a.headers["ujet-direct-access-key-id"];if(d){const y=Number(d);Number.isFinite(y)&&(l.key_id=y)}this.lastDirectAccessKeyId=l.key_id;let h=[];return Array.isArray(a.data)?h=a.data:$h.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:TO(h),direct:l}}stashDapRequestId(e){const t=e.headers["ujet-dap-request-id"];this.lastDapRequestId=typeof t=="string"&&t?t:null}isChatDapPending(e){return e&&!Array.isArray(e)&&e.status==="PENDING"}cancelDapPolling(){this.dapPollGeneration++}fetchRootMenus(e){return this.get("menus",{type:"web_menu",lang:e})}async pollChatDap(e,t,n){const i=this.lastDapRequestId;if(!i)return $h.warn("chat DAP pending response missing dap_request_id; falling back to root menus"),await this.fetchRootMenus(e);const s=2e3,a=Math.max(t,0)*1e3;let c=0;for(;c<a;){if(await Xd(s),c+=s,this.dapPollGeneration!==n)return{headers:{},data:[]};const o=await this.get("menus",{type:"web_menu",lang:e,dap_request_id:i});if(!this.isChatDapPending(o.data))return o}return await this.fetchRootMenus(e)}async getAfterHourMessage(e){return(await this.get(`audible_messages/${e}`)).data["after_hours.message"].text}async getTimeSlots(e,t={}){const n=t.lang||"en",i=t.rescheduleCallId;return(await this.get(`menus/${e}/time_slots`,{type:"web_menu",lang:n,reschedule_call_id:i,use_advanced_call_scheduling:QC})).data}async fetchTimeSlotAvailability(e,t="en"){return(await this.get(`menus/${e}/time_slots_available`,{type:"web_menu",lang:t})).data.slots_available}async getWaitTimes(e,t="en"){return(await this.get(`menus/${e}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(e){try{return await this.post("forms/verify",e),!0}catch{return!1}}async finishChat(e){return(await this.patch(`chats/${e}`,{status:"finished"})).data}async fetchUjetConversationMessages(e,t={}){return(await this.get(`chats/${e}/ujet_conversation/messages`,{limit:t.limit,before:t.before})).data}async leaveChat(e){await this.post(`chats/${e}/leave`,{})}leaveChatBeacon(e){var t;(t=this.beaconLeaveChat)==null||t.call(this,e)}async updatePostSession(e,t,n){const i={post_session_transfer_status:t};n!==void 0&&(i.post_session_opt_in_selection=n);try{return(await this.patch(`chats/${e}`,i)).data}catch(s){if(t===cl.IN_PROGRESS&&s.status===400)return(await this.patch(`chats/${e}`,i)).data;throw s}}async getChatDeflection(e){const{data:t}=await this.get(`chats/${e}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(e,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${e}/custom_data`,n)}async downloadChatTranscript(e){return(await this.post(`chats/${e}/generate_transcript_pdf`,{})).data}async getPdfStatus(e){return await this.get(`chat_transcript_pdfs/${e}/download_transcript`)}async sendChatTranscripts(e,t){return await this.post(`chats/${e}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(e){return(await this.get(`chats/${e}/task_va_messages`)).data}async getChatTaskMessage(e,t){return(await this.get(`chats/${e}/task_va_messages/${t}`)).data}async sendChatTaskMessage(e,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${e}/task_va_messages`,n)).data}async sendChatTextMessage(e,t,n){const i={message:{content:t,timestamp:new Date().toISOString()}};n&&(i.message.client_message_id=n),await this.post(`chats/${e}/messages`,i)}async getChatMessageOriginal(e,t){return(await this.get(`chats/${e}/messages/${t}/original`)).data}async sendPreviewMessage(e,t,n){const i={message:{content:t,timestamp:n}},{data:s}=await this.post(`chats/${e}/redact_messages`,i);return s}escalateChat(e,t){return this.post(`chats/${e}/escalations`,t)}trackEscalation(e,t,n){return this.put(`chats/${e}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(e,t){return this.post(`chats/${e}/cobrowse`,t)}requestVoiceCallCobrowse(e,t){return this.post(`calls/${e}/cobrowse`,t)}rateChat(e,t){return this.patch(`chats/${e}/rating`,t)}async getChatSurvey(e){return(await this.get(`chats/${e}/survey`)).data}sendChatSurvey(e,t){const n={chat_id:e,answers:t};return this.put(`chats/${e}/survey`,n)}trackChatEndUserEvent(e,t){return this.post(`chats/${e}/end_user_event`,t)}async createChat(e,t,n,i){const s={menu_id:e,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data};this.lastDirectAccessKeyId!==null&&(s.direct_access_key_id=this.lastDirectAccessKeyId),this.lastDapRequestId&&(s.dap_request_id=this.lastDapRequestId);const a={chat:s,cobrowsable:n.cobrowsable},c=await this.post("chats",a);this.lastDapRequestId=null;const o=c.data;return this.wrapChat(o,i)}async loadChat(e,t){const n=await this.getChat(e);return this.wrapChat(n,t)}async resumeChat(e,t){const n=await this.patch(`chats/${e}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(e=1){if(e===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return YC(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return YC(t)}}async uploadChatFile(e,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":t.type==="application/pdf"&&(n="document");const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(`chats/${e}/${n}s/upload`,{filename:i}),a={file:t,fields:s.data.fields};Iy()&&(a.file=await Ub(t));const o=(await this.request(s.data.url,a)).data.key,d=(await this.post(`chats/${e}/${n}s`,{chat_id:e,[n]:{s3_path:o,photo_type:n,filename:t.name,content_type:t.type,file_size:t.size}})).data;return d.type=n,d}buildProviderContext(e){if(this.authContext)return{getAuthToken:this.authContext.getAuthToken,wsUrl:this.authContext.wsUrl,fetchHistory:t=>this.fetchUjetConversationMessages(e,t),isRiskFlagEnabled:this.isRiskFlagEnabled}}async getChat(e){return(await this.get(`chats/${e}`)).data}async wrapChat(e,t){const n=async()=>(await this.post(`chats/${e.id}/tokens`,{provider_type:e.provider_type,device_id:t})).data,i=()=>this.leaveChat(e.id),s=()=>this.leaveChatBeacon(e.id),a=d=>this.getChatMessageOriginal(e.id,d),c=new EW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a},this.buildProviderContext(e.id)),o=async d=>{if(c.status==="va_assigned"){const h=await this.getSkipVirtualAgentSettings(c.menuId,c.lang);c.allowSkipVirtualAgent=h,c.update(d)}};c.on("initialized",async()=>{if(c.status==="queued"){const d=await this.getChat(c.id);c.update(d)}}),c.on("memberJoined",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("memberLeft",async()=>{const d=await this.getChat(c.id);c.update(d)});let l=!1;if(c.on("message",d=>{var h;!c.connected||!c.ongoing||l||d.$userType!==_i.USER||!Number.isSafeInteger(d.$userId)||d.$userId<=0||c.allAgents.human.some(v=>v.id===d.$userId)||((h=this.isRiskFlagEnabled)==null?void 0:h.call(this,WW))===!1||(l=!0,this.getChat(c.id).then(v=>{c.connected&&c.ongoing&&c.update(v)}).catch(()=>{$h.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{l=!1}))}),c.on("_chatEnded",async d=>{const h=await this.getChat(c.id);c.update(h),(!c.state||c.ended)&&c._handleChatEndedEvent(d)}),c.on("_menuChanged",async d=>{const h=await this.getChat(d.id);o(h)}),c.on("checkInRequired",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("checkInTimedOut",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.channelId)c.connect(),o(e);else{let d;for(;!d;)await this.getChat(c.id).then(h=>{h.provider_channel_id&&c.state?(d=!0,c.update(h),c.connect(),o(h)):(h.status==="canceled"||h.status==="finished")&&(d=!0)}),d||await Xd(1500)}return c}async createVoiceCall(e,t,n,i,s,a){const c={call:{type:"web_inbound_call",menu_id:e,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission,custom_data:n.custom_data,voicemail_reason:n.voicemail_reason},cobrowsable:n.cobrowsable??!1},o=await this.post("calls",c);return this.wrapVoiceCall(o.data,i,s,a)}async requestVoiceToken(e,t){return(await this.post(`calls/${e}/tokens`,{device_id:t})).data}async fetchVoiceCall(e){return(await this.get(`calls/${e}`)).data}async hangupVoiceCall(e){await this.patch(`calls/${e}`,{status:"finished"})}async failVoiceCall(e,t="abandoned",n){await this.patch(`calls/${e}`,{status:"failed",fail_reason:t,fail_details:n})}async updateVoiceCallRecordingPermission(e,t){await this.patch(`calls/${e}`,{recording_permission:t?"recording_permission_granted":"recording_permission_denied"})}async escalateVoiceCall(e){await this.post(`calls/${e}/escalate`,{})}rateVoiceCall(e,t){return this.put(`calls/${e}/rating`,t)}async getVoiceCallSurvey(e){return(await this.get(`calls/${e}/survey`)).data}submitVoiceCallSurvey(e,t){const n={call_id:e,answers:t};return this.put(`calls/${e}/survey`,n)}async updateVoiceSmartAction(e,t,n){await this.put(`calls/${e}/smart_actions/${t}`,n)}async uploadVoiceCallPhotoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/photos/upload`,t,n)}async registerVoiceCallPhotos(e,t,n,i){const s=n.map(c=>({s3_path:c,photo_type:t}));return((await this.post(`calls/${e}/photos`,{photo:s,photo_type:t,multiple:!0,smart_action_id:i})).data||[]).map(c=>c.media_id)}async uploadVoiceCallPhotos(e,t,n,i){const s=await Promise.all(t.map(a=>this.uploadVoiceCallPhotoSingle(e,a)));return await this.registerVoiceCallPhotos(e,n,s,i)}async uploadVoiceCallVideoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/videos/upload`,t,n)}async registerVoiceCallVideos(e,t,n){return await Promise.all(t.map(async i=>(await this.post(`calls/${e}/videos`,{video:{s3_path:i},smart_action_id:n})).data.media_id))}async uploadVoiceCallVideos(e,t,n){const i=await Promise.all(t.map(s=>this.uploadVoiceCallVideoSingle(e,s)));return await this.registerVoiceCallVideos(e,i,n)}async uploadFileToExternalStorage(e,t,n){const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(e,{filename:i});if(wO())return await lW(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Iy()&&(a.file=await Ub(t)),(await this.request(s.data.url,a)).data.key}async _wrapVoiceCallForRestore(e,t,n,i){return this.wrapVoiceCall(e,t,n,i)}async wrapVoiceCall(e,t,n,i){const s=async()=>await this.requestVoiceToken(e.id,t),a=async L=>await this.fetchVoiceCall(L),c=async L=>await this.hangupVoiceCall(L),o=async(L,x,B)=>await this.failVoiceCall(L,x,B),l=async L=>await this.escalateVoiceCall(L),d=async(L,x)=>await this.updateVoiceCallRecordingPermission(L,x),h=async(L,x,B)=>await this.updateVoiceSmartAction(L,x,B),v=async(L,x,B,G)=>{await this.uploadVoiceCallPhotos(L,x,B,G)},y=async(L,x,B)=>{await this.uploadVoiceCallVideos(L,x,B)},w=async(L,x,B)=>await this.uploadVoiceCallPhotoSingle(L,x,B),k=async(L,x,B)=>await this.uploadVoiceCallVideoSingle(L,x,B),P=async(L,x,B,G)=>{await this.registerVoiceCallPhotos(L,x,B,G)},A=async(L,x,B)=>{await this.registerVoiceCallVideos(L,x,B)},U=PO(this.resolveVoiceProviderType(e));if(!U)throw new da(`No voice provider registered for ${e.voip_provider}`);return new qW(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:v,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:P,registerVideos:A},U,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?EO:e.voip_provider}async createCall(e,t){const n={type:t.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:e,lang:t.lang,email:t.email,ticket_id:t.ticket_id,recording_permission:t.recording_permission||"recording_permission_not_asked",scheduled_at:t.scheduled_at,custom_data:t.custom_data,end_user:{phone_number:t.phone_number}},s=(await this.post("calls",{call:n,cobrowsable:!1,use_advanced_call_scheduling:QC,reschedule_call_id:t.reschedule_call_id})).data,{selected_menu:a,...c}=s;return{...c,menu_id:a.id}}async fetchCall(e){const n=(await this.get(`calls/${e}`)).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async cancelCall(e){const n=(await this.patch(`calls/${e}`,{status:"failed",fail_reason:"canceled"})).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(e,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:e.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&Iy()?i["email_attachments[]"]=await HW(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),(await this.request("emails",{form:i})).data}async getMedia(e,t){const n=await this.get(`media/${e}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getChatDocuments(e){const t=await this.get(`chats/${e}/documents`);return Array.isArray(t.data)?t.data:[]}async getSkipVirtualAgentSettings(e,t){return(await this.get(`menus/${e}/virtual_agent_settings`,{lang:t})).data.allow_skip_virtual_agent}async confirmCheckIn(e){return(await this.post(`chats/${e}/check_in/confirm`,null)).data}async rejoinQueue(e){return(await this.post(`chats/${e}/check_in/rejoin`,null)).data}async exitCheckIn(e){return(await this.post(`chats/${e}/check_in/exit`,null)).data}async trackCheckIn(e,t){await this.post(`chats/${e}/check_in/modal_shown`,t)}async notifyCheckInState(e,t){await this.post(`chats/${e}/check_in/end_user_status`,t)}}function HW(r){return Promise.all(r.map(Ub))}function Ub(r){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],s={type:r.type,lastModified:r.lastModified};e({name:r.name,fileBits:i,options:s})},n.onerror=t,n.readAsArrayBuffer(r)})}const AO=new un("CobrowseService");async function GW(r){return window.CobrowseIO?window.CobrowseIO:await zW(r)}async function zW(r){return new Promise(e=>{const t=document.createElement("script");t.src=r,t.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n),t.onload=function(){e(window.CobrowseIO)},t.onerror=function(){AO.error("Failed to load cobrowse script",r),e(null)}})}const ZC="https://js.cobrowse.io/CobrowseIO.js";function KW(r){return!r||r.toLowerCase()==="https://cobrowse.io"?ZC:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(AO.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),ZC)}async function JW(r,e){let t=r.instance;if(!t){const n=KW(e);t=await GW(n)}return new YW(t,r)}class YW{constructor(e,t){ye(this,"_cobrowseIO");if(this._cobrowseIO=e,!e)return;e.license=t.license;const n=t.trustedOrigins||[];n.push(location.origin),e.trustedOrigins=n,["api","capabilities","registration","messages","redactedViews","unredactedViews","confirmSession","confirmRemoteControl","confirmFullDevice","showSessionControls","hideSessionControls"].forEach(s=>{t[s]!==void 0&&(e[s]=t[s])})}get cobrowseIO(){return this._cobrowseIO}async start(){await this._cobrowseIO.client(),await this._cobrowseIO.start()}}const XW=Date.now(),OO={href:window.location.href,interval:24*60*60};function QW(r){if(!Array.isArray(r)||!r.length)return null;const e=n5(),t=e===0,n=e+1;return i5(n),r.filter(s=>{const a=e5(s,OO.href),c=t5(s.visitor_type,t),o=n>=s.page_visit_count,l=!r5(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function ZW(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-XW),0);setTimeout(()=>{e(r),br.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const e5=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(v6(t,n,i,s))return!0;if(t.length||n.length){const o=t.some(d=>d.every(h=>e.includes(h))),l=n.length>0&&n.every(d=>d.every(h=>!e.includes(h)));return o||l}const a=i.filter(o=>e.indexOf(o)!==-1).length,c=s.filter(o=>e.indexOf(o)===-1).length;return!!a||!!c};function t5(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function r5(r){try{const e=parseInt(br.get(`trigger:${r}`),10);return Date.now()/1e3-e<OO.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function n5(){try{const r=br.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function i5(r){try{br.set("visits",r.toString())}catch(e){console.error(e)}}function s5(r){return r.replace(/\/+$/,"")}const $y=new un("VoiceMultiTab"),Fb="voice:tab-lock",a5=5e3,o5=2e3,u5=250,xy=()=>{const r=br.get(Fb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},My=()=>{var i;const r=xy();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<a5)throw new hl;const e=xw(),t=()=>{br.set(Fb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=xy())==null?void 0:i.id)!==e)throw new hl;const n=setInterval(t,o5);return{release(){clearInterval(n);const s=xy();(!s||s.id===e)&&br.del(Fb)}}},ek=async()=>{if(typeof BroadcastChannel>"u")return My();let r;try{r=new BroadcastChannel(xW)}catch{return My()}const e=xw();let t=!1;r.onmessage=n=>{const i=n.data;(i.kind==="present"||i.kind==="claim")&&i.id!==e&&(t=!0)};try{r.postMessage({kind:"claim",id:e})}catch(n){$y.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return My()}if(await new Promise(n=>setTimeout(n,u5)),t)throw r.close(),new hl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){$y.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){$y.debug("BC postMessage(release) failed",n)}r.close()}}},c5=["photo","video","audio","document"],qa=new un("client");function l5(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let d5=class{constructor(e){ye(this,"VERSION",Mw);ye(this,"options");ye(this,"communicator");ye(this,"methods");ye(this,"events",new Qv);ye(this,"request");ye(this,"chat");ye(this,"_cobrowse");ye(this,"_voiceCall",null);ye(this,"_voiceTabLock",null);ye(this,"redactionSendQueue",Promise.resolve());ye(this,"fileSendQueue",Promise.resolve());ye(this,"_rehydratePromise",null);ye(this,"onPageHide");ye(this,"onPageShow");this.options=e.host?{...e,host:s5(e.host)}:e,this.communicator=new P6(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new VW(t,n,{getAuthToken:this.communicator.getAuthToken.bind(this.communicator),wsUrl:this.communicator.wsUrl},this.communicator.isRiskFlagEnabled.bind(this.communicator)),this.request=t,this.options.host&&cO.setPath(this.options.host),zn.companyId=e.companyId,e.tenant&&(zn.tenant=e.tenant),this.events.addEventListener(Kn.STATUS_CHANGED,i=>{(i==null?void 0:i.status)==="error"&&this.releaseVoiceTabLock()}),this.registerUnloadHandlers()}registerUnloadHandlers(){typeof window>"u"||(this.onPageHide=e=>{var t,n;e.persisted||((t=this.chat)==null||t.leaveBeacon(),(n=this._voiceCall)==null||n._markUnloading(),this.releaseVoiceTabLock())},this.onPageShow=e=>{var t;e.persisted&&((t=this.chat)==null||t.resetBeaconState())},window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow))}unregisterUnloadHandlers(){typeof window>"u"||(this.onPageHide&&(window.removeEventListener("pagehide",this.onPageHide),this.onPageHide=void 0),this.onPageShow&&(window.removeEventListener("pageshow",this.onPageShow),this.onPageShow=void 0))}get deviceId(){return zn.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:br.get("lang")||"en"}set lang(e){this.options.lang||br.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){this.destroyVoiceCall().catch(()=>{}),this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}destroyDuplicate(){this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}releaseVoiceTabLock(){var e;(e=this._voiceTabLock)==null||e.release(),this._voiceTabLock=null}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async checkMicPermission(){var e;if(typeof navigator>"u"||!((e=navigator.permissions)!=null&&e.query))return"unknown";try{const n=(await navigator.permissions.query({name:"microphone"})).state;return n==="granted"||n==="denied"||n==="prompt"?n:"unknown"}catch{return"unknown"}}async getCompany(){const e=await this.methods.getCompany();return zn.tenant=e.subdomain,e}async getFeatureFlags(){return await this.methods.getFeatureFlags()}isRiskFlagEnabled(e){return this.communicator.isRiskFlagEnabled(e)}getRiskFlags(){return this.communicator.getRiskFlags()}async runTrigger(e){const t=await this.methods.getTriggers(this.options.companyId),n=QW(t);n&&ZW(n,e)}async trackClientEvents(e){await this.methods.trackClientEvents(e)}async getProhibitedFileTypes(){return await this.methods.listFileTypes()}async getMenus(e,t,n){return await this.methods.getMenus(t||this.lang,e,n)}cancelMenuPolling(){this.methods.cancelDapPolling()}getCustomFormData(e){return this.methods.getCustomFormData(e)}submitCustomForm(e){return this.methods.submitCustomForm(e)}async getAfterHourMessage(e){return await this.methods.getAfterHourMessage(e||this.lang)}async getTimeSlots(e,t){return(i=>typeof i=="object"&&i!==null)(t)?await this.methods.getTimeSlots(e,{lang:t.lang||this.lang,rescheduleCallId:t.rescheduleCallId}):await this.methods.getTimeSlots(e,{lang:t||this.lang})}async fetchTimeSlotAvailability(e,t){return await this.methods.fetchTimeSlotAvailability(e,t||this.lang)}async getWaitTimes(e,t){return await this.methods.getWaitTimes(e,t||this.lang)}async verifyForm(e){return await this.methods.verifyForm(e)}async createCall(e,t){var i;!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email);const n={...t,lang:t.lang||this.lang};return await this.methods.createCall(Number(e),n)}async loadCall(e){return await this.methods.fetchCall(e)}async cancelCall(e){return await this.methods.cancelCall(e)}async createEmail(e,t){return await this.methods.createEmail(e,t.lang||this.lang,t)}async createChat(e,t={}){var i,s;if(!this.chat&&br.get("chat")&&await this.loadOngoingChat().catch(()=>null),this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=!!((s=this.options.cobrowse)!=null&&s.enabled));const n=await this.methods.createChat(Number(e),t.lang||this.lang,t,this.deviceId);return this.registerOngoingChat(n),await n.clearMediaStore(),n}async loadChat(e){try{const t=await this.methods.loadChat(e,this.deviceId);return t.ongoing?this.registerOngoingChat(t):(br.del("chat"),br.del("cobrowse")),t}catch(t){throw br.del("chat"),br.del("cobrowse"),t}}async resumeChat(e){var n;if(((n=this.chat)==null?void 0:n.id)===Number(e)){const i=await this.methods.patch(`chats/${e}`,{status:"queued"});return this.chat.update(i.data),this.chat}const t=await this.methods.resumeChat(e,this.deviceId);return this.registerOngoingChat(t),t}async loadOngoingChat(){return this._rehydratePromise?this._rehydratePromise:(this._rehydratePromise=this._doLoadOngoingChat().finally(()=>{this._rehydratePromise=null}),this._rehydratePromise)}async _doLoadOngoingChat(){const e=br.get("chat");if(!e)return br.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(br.del("chat"),null)}catch(t){throw br.del("chat"),t}}async restoreCobrowseSession(){var t;const e=br.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),qa.debug("cobrowse session restored with nonce:",e)}catch(n){qa.error("Failed to restore cobrowse session",n),br.del("cobrowse")}}async finishChat(){if(!this.chat)return;const e=await this.methods.finishChat(this.chat.id);this.chat.update(e),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()}async updatePostSession(e,t){if(!this.chat||e===cl.FINISHED||e===cl.WAITING)return;const n=await this.methods.updatePostSession(this.chat.id,e,t);this.chat.update(n)}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing)try{await this.finishChat()}catch(e){qa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return XC()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!Wc.has(this._voiceCall.serverStatus()))throw new Vu("A voice call is already active in this session");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=this.cobrowseEnabled);try{await f5()}catch(s){const a=s instanceof fl?s.cause:void 0,c=a&&typeof a=="object"&&"name"in a?a.name:void 0;if(c==="NotAllowedError"||c==="PermissionDeniedError")try{this.events.triggerEvent(Kn.MIC_PERMISSION_REQUIRED)}catch{}throw s}this.releaseVoiceTabLock(),this._voiceTabLock=await ek();let n;try{n=await this.methods.createVoiceCall(Number(e),t.lang||this.lang,t,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),tk(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return UW(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!Wc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=XC(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await ek();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(CO(s)===404)return Vc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),tk(s)}if(Wc.has(n.status))return Vc(),this.releaseVoiceTabLock(),null;let i;try{i=await this.methods._wrapVoiceCallForRestore(n,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),s}this._voiceCall=i;try{await i._connect()}catch(s){throw await i._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),Vc(),s}return this.restoreCobrowseSession().catch(s=>{qa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(Wc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Uo;await this._voiceCall._escalate()}async destroyVoiceCall(){if(!this._voiceCall){this.releaseVoiceTabLock(),Vc();return}try{await this._voiceCall._destroy()}finally{this._voiceCall=null,this.releaseVoiceTabLock()}}async getChatDeflection(){return await this.methods.getChatDeflection(this.chat.id)}async sendChatTranscripts(e){await this.methods.sendChatTranscripts(this.chat.id,e)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(e){return await this.methods.getPdfStatus(e)}async getChatSurvey(){return await this.methods.getChatSurvey(this.chat.id)}async sendChatSurvey(e){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.sendChatSurvey(this.chat.id,e)}async sendChatRate(e){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.rateChat(this.chat.id,e)}async rateVoiceCall(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="rate")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.rateVoiceCall(this._voiceCall.id,e)}async getVoiceCallSurvey(){if(!this._voiceCall)throw new Uo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="survey")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.submitVoiceCallSurvey(this._voiceCall.id,e)}async escalateChat(e){await this.methods.escalateChat(this.chat.id,e)}async trackChatEscalation(e,t){await this.methods.trackEscalation(this.chat.id,e,t)}async trackChatEndUserEvent(e){var t;!e.end_user_name&&((t=this.user)!=null&&t.name)&&(e.end_user_name=this.user.name),await this.methods.trackChatEndUserEvent(this.chat.id,e)}async getChatHistory(e=1){return await this.methods.getChatHistory(e)}async fetchMessages(){try{const e=await this.chat.fetchMessages();if(e.some(t=>t.type==="document"))try{const t=await this.methods.getChatDocuments(this.chat.id);D6(e,t)}catch(t){qa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===tn.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return O6(e,t)}return e}catch{return[]}}async sendFileMessage(e){const t=this.chat.id,n=this.fileSendQueue.then(async()=>{let i;try{i=await this.methods.uploadChatFile(t,e)}catch(s){return qa.warn("[sendFileMessage] upload failed",s),-1}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=Lb(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:tn.SERVER_MESSAGE,visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){const n=this.chat,i=n.id,s=m6();s&&n.rememberOwnOriginal(s,t);const a=this.redactionSendQueue.then(()=>this.methods.sendChatTextMessage(i,t,s??void 0));this.redactionSendQueue=a.catch(()=>{});try{await a}catch(c){throw s&&l5(c)&&n.forgetOwnOriginal(s),c}return}this.chat.sendMessage({type:tn.TEXT,content:t})}}async sendPreviewMessage(e){if(this.isRedactionAgentEnabled()){const t=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,e,t);this.chat.preview(n==null?void 0:n.content);return}this.chat.preview(e)}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(e,t){var n;try{await this.initializeCobrowse(e||this.lang);let i=br.get("cobrowse");i||(i=Date.now().toString(),br.set("cobrowse",i));const s={device_id:this.deviceId,device_name:`${zn.application} / ${zn.version}`,nonce:i,...t};return(n=this.user)!=null&&n.name&&(s.user_name=this.user.name),this.cobrowse.customData=s,await this.cobrowse.createSessionCode()}catch{return""}}async startCobrowse(e="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const t={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,t);if(!n)return;const i=br.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:e,nonce:i})}async startVoiceCobrowseInternal(e,t){if(!this.cobrowseEnabled)throw new Error("Cobrowse is not enabled.");if(!this._voiceCall)throw new Uo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=br.get("cobrowse")??"";return await this.methods.requestVoiceCallCobrowse(n,{code:s,from:t,nonce:a}),this.events.triggerEvent("cobrowse.request",{from:t}),s}async getMessageAttachment(e){if(e.$userType!==_i.END_USER&&c5.includes(e.type)){const t=await this.methods.getMedia(e.media_id,e.type);return this.chat&&this.chat.saveMedia(e.$index,t),t}return null}async checkIn(){const e=await this.methods.confirmCheckIn(this.chat.id);return this.updateCheckIn(e),e}async exitCheckIn(){const e=await this.methods.exitCheckIn(this.chat.id);return this.updateCheckIn(e),e}async notifyCheckInState(e){await this.methods.notifyCheckInState(this.chat.id,e)}async rejoinChat(){const e=await this.methods.rejoinQueue(this.chat.id);return this.updateCheckIn(e),e}async trackCheckInEvent(){const e={modal_type:"check_in"};await this.methods.trackCheckIn(this.chat.id,e)}async getLogs(){const e=await this.communicator.getBridgeLogHistory(),t=un.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{un.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{un.printLogHistoryData(t)})}updateCheckIn(e){const t={...this.chat.state};t.check_in_status=e.check_in_status,this.chat.update(t)}async initializeCobrowse(e){if(!this._cobrowse){const t=await this.getCompany(),n=this.options.cobrowse.messages||cW(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await JW(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",Gp.LOADED],["session.updated",Gp.UPDATED],["session.ended",Gp.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),qa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.events.triggerEvent("chat.ongoing",e),e._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),e.on("_requestCobrowse",t=>{t==="agent"?this.startCobrowse(t):this.initializeCobrowse(e.lang).catch(n=>{qa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{br.del("chat"),br.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,br.set("chat",e.id.toString()),e.cobrowsable&&br.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{qa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const f5=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new fl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new fl(Nw(e),e)}},h5=new Map([["call_in_progress",Vu],["inbound_disabled",ll],["outside_operation_hours",Hu],["operation_hours",Hu],["feature_not_enabled",dl],["invalid_call_type",dl]]),p5=new Map([[409,Hu],[403,ll],[400,Vu]]),tk=r=>{var a,c;if(r instanceof ws)return r;const e=r&&typeof r=="object"?r:{},t=(a=e.data)==null?void 0:a.error_code,n=((c=e.data)==null?void 0:c.message)??e.message??"",i=t?h5.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?p5.get(e.status):void 0;return s?new s(n):new hv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Zv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function $O(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var jb={exports:{}},Zo=vv;function vv(){}vv.mixin=function(r){var e=r.prototype||r;e.isWildEmitter=!0,e.on=function(t,n,i){this.callbacks=this.callbacks||{};var s=arguments.length===3,a=s?arguments[1]:void 0,c=s?arguments[2]:arguments[1];return c._groupName=a,(this.callbacks[t]=this.callbacks[t]||[]).push(c),this},e.once=function(t,n,i){var s=this,a=arguments.length===3,c=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];function l(){s.off(t,l),o.apply(this,arguments)}return this.on(t,c,l),this},e.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,s,a;for(n in this.callbacks)for(a=this.callbacks[n],i=0,s=a.length;i<s;i++)a[i]._groupName===t&&(a.splice(i,1),i--,s--);return this},e.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],s;return i?arguments.length===1?(delete this.callbacks[t],this):(s=i.indexOf(n),s!==-1&&(i.splice(s,1),i.length===0&&delete this.callbacks[t]),this):this},e.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],s=this.getWildcardCallbacks(t),a,c,o;if(i)for(o=i.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,n);if(s)for(c=s.length,o=s.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,[t].concat(n));return this},e.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,s=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(s=s.concat(this.callbacks[n]));return s}};vv.mixin(vv);var xO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.prefix=t(e)})(Ye,function(e){var t=function(d){for(var h=1,v=arguments.length,y;h<v;h++)for(y in arguments[h])Object.prototype.hasOwnProperty.call(arguments[h],y)&&(d[y]=arguments[h][y]);return d},n={template:"[%t] %l:",levelFormatter:function(d){return d.toUpperCase()},nameFormatter:function(d){return d||"root"},timestampFormatter:function(d){return d.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,s={},a=function(d){if(!d||!d.getLogger)throw new TypeError("Argument is not a root logger");i=d},c=function(d,h){if(!d||!d.setLevel)throw new TypeError("Argument is not a logger");var v=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(P,A,U){var L=v(P,A,U),x=s[U]||s[""],B=x.template.indexOf("%t")!==-1,G=x.template.indexOf("%l")!==-1,K=x.template.indexOf("%n")!==-1;return function(){for(var D="",fe=arguments.length,X=Array(fe),pe=0;pe<fe;pe++)X[pe]=arguments[pe];if(y||!s[U]){var Q=x.timestampFormatter(new Date),Oe=x.levelFormatter(P),Ve=x.nameFormatter(U);x.format?D+=x.format(Oe,Ve,Q):(D+=x.template,B&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,Ve))),X.length&&typeof X[0]=="string"?X[0]=D+" "+X[0]:X.unshift(D)}L.apply(void 0,X)}}return s[y]||(d.methodFactory=k),h=h||{},h.template&&(h.format=void 0),s[y]=t({},w,h),d.setLevel(d.getLevel()),i||d.warn("It is necessary to call the function reg() of loglevel-plugin-prefix before calling apply. From the next release, it will throw an error. See more: https://github.com/kutuluk/loglevel-plugin-prefix/blob/master/README.md"),d},o={reg:a,apply:c},l;return e&&(l=e.prefix,o.noConflict=function(){return e.prefix===o&&(e.prefix=l),o}),o})})(xO);var v5=xO.exports,MO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Ye,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},a=null;function c(k,P){var A=k[P];if(typeof A.bind=="function")return A.bind(k);try{return Function.prototype.bind.call(A,k)}catch{return function(){return Function.prototype.apply.apply(A,[k,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(k){return k==="debug"&&(k="log"),typeof console===t?!1:k==="trace"&&n?o:console[k]!==void 0?c(console,k):console.log!==void 0?c(console,"log"):e}function d(){for(var k=this.getLevel(),P=0;P<i.length;P++){var A=i[P];this[A]=P<k?e:this.methodFactory(A,k,this.name)}if(this.log=this.debug,typeof console===t&&k<this.levels.SILENT)return"No console available for logging"}function h(k){return function(){typeof console!==t&&(d.call(this),this[k].apply(this,arguments))}}function v(k,P,A){return l(k)||h.apply(this,arguments)}function y(k,P){var A=this,U,L,x,B="loglevel";typeof k=="string"?B+=":"+k:typeof k=="symbol"&&(B=void 0);function G(pe){var Q=(i[pe]||"silent").toUpperCase();if(!(typeof window===t||!B)){try{window.localStorage[B]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(B)+"="+Q+";"}catch{}}}function K(){var pe;if(!(typeof window===t||!B)){try{pe=window.localStorage[B]}catch{}if(typeof pe===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(B),Ve=Q.indexOf(Oe+"=");Ve!==-1&&(pe=/^([^;]+)/.exec(Q.slice(Ve+Oe.length+1))[1])}catch{}return A.levels[pe]===void 0&&(pe=void 0),pe}}function D(){if(!(typeof window===t||!B)){try{window.localStorage.removeItem(B)}catch{}try{window.document.cookie=encodeURIComponent(B)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function fe(pe){var Q=pe;if(typeof Q=="string"&&A.levels[Q.toUpperCase()]!==void 0&&(Q=A.levels[Q.toUpperCase()]),typeof Q=="number"&&Q>=0&&Q<=A.levels.SILENT)return Q;throw new TypeError("log.setLevel() called with invalid level: "+pe)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=P||v,A.getLevel=function(){return x??L??U},A.setLevel=function(pe,Q){return x=fe(pe),Q!==!1&&G(x),d.call(A)},A.setDefaultLevel=function(pe){L=fe(pe),K()||A.setLevel(pe,!1)},A.resetLevel=function(){x=null,D(),d.call(A)},A.enableAll=function(pe){A.setLevel(A.levels.TRACE,pe)},A.disableAll=function(pe){A.setLevel(A.levels.SILENT,pe)},A.rebuild=function(){if(a!==A&&(U=fe(a.getLevel())),d.call(A),a===A)for(var pe in s)s[pe].rebuild()},U=fe(a?a.getLevel():"WARN");var X=K();X!=null&&(x=fe(X)),d.call(A)}a=new y,a.getLogger=function(P){if(typeof P!="symbol"&&typeof P!="string"||P==="")throw new TypeError("You must supply a name when creating a logger.");var A=s[P];return A||(A=s[P]=new y(P,a.methodFactory)),A};var w=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=w),a},a.getLoggers=function(){return s},a.default=a,a})})(MO);var Kr=MO.exports;const g5=Zv(Kr),m5=Uq({__proto__:null,default:g5},[Kr]);var Bb={exports:{}},y5={"error:application:call:params":{type:"error:application:call:params",description:"not a valid String[] of usernames param"},"error:application:callServer:params":{type:"error:application:call:params",description:"not a valid String of phone number"},"error:call:reject":{type:"error:call:reject",description:"failed to reject the call"},"error:getUserMedia:permissions":{type:"error:getUserMedia:permissions",description:"missing getUserMedia permissions"},"error:media:params":{type:"error:media:params",description:"currently supported params media type= {audio:{muted:false, earmuffed:false}}"},"error:media:reenable":{type:"error:media:reenable",description:"missing reconnectRtcId required to reenable media"},"error:self":{type:"error:self",description:"Conversation Object is missing self (me)"},"error:user:relogin":{type:"error:user:relogin",description:"please relogin"},"error:seen:own-message":{type:"error:seen:own-message",description:"attempt to send seen for own message"},"error:already-seen":{type:"error:already-seen",description:"already marked as seen"},"error:delivered:own-message":{type:"error:delivered:own-message",description:"attempt to send delivered for own message"},"error:already-delivered":{type:"error:already-delivered",description:"already marked as delivered"},"error:fetch-image":{type:"error:fetch-image",description:"xhr.status received other than 200"},"error:delete-image":{type:"error:delete-image",description:"xhr.status received other than 204"},"error:missing:params":{type:"error:missing:params",description:"missing parameters"},"error:invite:missing:params":{type:"error:missing:params",description:"This invite cannot be sent to empty username and user_id"},"error:invalid:param:type":{type:"error:invalid:param:type",description:"Invalid Object type, passed in the parameters"},"error:audio:already-connecting":{type:"error:audio:already-connecting",description:"Audio call already in progress"},"error:audio:not-enabled":{type:"error:audio:not-enabled",description:"Audio is not enabled"},"error:media:already-connecting":{type:"error:media:already-connecting",description:"Media is already in progress"},"error:media:unsupported-browser":{type:"error:media:unsupported-browser",description:"This action is not supported on this browser"},"error:media:extension":{type:"error:media:extension",description:"Chrome extension has thrown an error"},"error:media:extension-not-installed":{type:"error:media:extension-not-installed",description:"Chrome extension should be installed"},"error:media:update:streams":{type:"error:media:update:streams",description:"cant update more than one stream"},"error:media:update:invalid":{type:"error:media:update:invalid",description:"state of media is not supported for this update"},"error:media:stream:not-found":{type:"error:media:stream:not-found",description:"A stream with the given index was not found"},"error:audio:dtmf:invalid-digit":{type:"error:audio:dtmf:invalid-digit",description:"not a valid string of dtmf digits (0-9,a-d,A-D,p,P,*,#)"},"error:audio:dtmf:audio-disabled":{type:"error:audio:dtmf:audio-disabled",description:"Audio must be enabled to send DTMF"},"error:invalid-order":{type:"error:invalid-order",description:"params not valid. Order must be asc or desc"},"error:custom-event:invalid":{type:"error:custom-event:invalid",description:"Custom event type not valid"},"error:message-event:invalid":{type:"error:message-event:invalid",description:"message_type is missing or is invalid"},"error:invalid-cursor":{type:"error:invalid-cursor",description:"page does not exist"},"error:client:reconnection_failed":{type:"error:client:reconnection_failed",description:"websocket failed to reconnect"},"error:conversation-service:version":{type:"error:conversation:version",description:'Wrong version of Conversation Service API. It should be one of "v1" or "v3"'},"error:no-media-offer":{type:"error:no-media-offer",description:"Media preload attempt without having an offer available"}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0}),e.NexmoApiError=e.NexmoClientError=void 0;const t=y5,n=Kr;function i(c,o){o&&o.code&&(o.type=o.code,delete o.code),Object.assign(c,o),c.message="type: "+c.type+", description: "+(c.description?c.description:"")}class s{constructor(o){const l=t[o];l?i(this,l):(this.message=o&&o.message?o.message:o,this.stack=o.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoClientError=s;class a{constructor(o){this.log=n.getLogger(this.constructor.name),o?i(this,o):(this.message=o&&o.message?o.message:o,this.stack=o&&o.stack?o.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoApiError=a,r.exports={NexmoClientError:s,NexmoApiError:a}})(Bb,Bb.exports);var Ts=Bb.exports,qb={exports:{}},Uw={},eg={},eo={},uf={},pa={},cf={},ro={},El={},lf={},va={};Object.defineProperty(va,"__esModule",{value:!0});va.ERROR_PACKET=va.PACKET_TYPES_REVERSE=va.PACKET_TYPES=void 0;const ya=Object.create(null);va.PACKET_TYPES=ya;ya.open="0";ya.close="1";ya.ping="2";ya.pong="3";ya.message="4";ya.upgrade="5";ya.noop="6";const DO=Object.create(null);va.PACKET_TYPES_REVERSE=DO;Object.keys(ya).forEach(r=>{DO[ya[r]]=r});const _5={type:"error",data:"parser error"};va.ERROR_PACKET=_5;Object.defineProperty(lf,"__esModule",{value:!0});lf.encodePacket=void 0;lf.encodePacketToBinary=S5;const b5=va,NO=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",LO=typeof ArrayBuffer=="function",UO=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,FO=({type:r,data:e},t,n)=>NO&&e instanceof Blob?t?n(e):rk(e,n):LO&&(e instanceof ArrayBuffer||UO(e))?t?n(e):rk(new Blob([e]),n):n(b5.PACKET_TYPES[r]+(e||""));lf.encodePacket=FO;const rk=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function nk(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Dy;function S5(r,e){if(NO&&r.data instanceof Blob)return r.data.arrayBuffer().then(nk).then(e);if(LO&&(r.data instanceof ArrayBuffer||UO(r.data)))return e(nk(r.data));FO(r,!1,t=>{Dy||(Dy=new TextEncoder),e(Dy.encode(t))})}var tg={},pl={};Object.defineProperty(pl,"__esModule",{value:!0});pl.decode=pl.encode=void 0;const Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Id=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Hc.length;r++)Id[Hc.charCodeAt(r)]=r;const w5=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Hc[e[t]>>2],i+=Hc[(e[t]&3)<<4|e[t+1]>>4],i+=Hc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Hc[e[t+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};pl.encode=w5;const T5=r=>{let e=r.length*.75,t=r.length,n,i=0,s,a,c,o;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const l=new ArrayBuffer(e),d=new Uint8Array(l);for(n=0;n<t;n+=4)s=Id[r.charCodeAt(n)],a=Id[r.charCodeAt(n+1)],c=Id[r.charCodeAt(n+2)],o=Id[r.charCodeAt(n+3)],d[i++]=s<<2|a>>4,d[i++]=(a&15)<<4|c>>2,d[i++]=(c&3)<<6|o&63;return l};pl.decode=T5;Object.defineProperty(tg,"__esModule",{value:!0});tg.decodePacket=void 0;const xh=va,E5=pl,C5=typeof ArrayBuffer=="function",k5=(r,e)=>{if(typeof r!="string")return{type:"message",data:jO(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:R5(r.substring(1),e)}:xh.PACKET_TYPES_REVERSE[t]?r.length>1?{type:xh.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:xh.PACKET_TYPES_REVERSE[t]}:xh.ERROR_PACKET};tg.decodePacket=k5;const R5=(r,e)=>{if(C5){const t=(0,E5.decode)(r);return jO(t,e)}else return{base64:!0,data:r}},jO=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.decodePayload=r.decodePacket=r.encodePayload=r.encodePacket=r.protocol=void 0,r.createPacketEncoderStream=c,r.createPacketDecoderStream=h;const e=lf;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=tg;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=va,i="",s=(v,y)=>{const w=v.length,k=new Array(w);let P=0;v.forEach((A,U)=>{(0,e.encodePacket)(A,!1,L=>{k[U]=L,++P===w&&y(k.join(i))})})};r.encodePayload=s;const a=(v,y)=>{const w=v.split(i),k=[];for(let P=0;P<w.length;P++){const A=(0,t.decodePacket)(w[P],y);if(k.push(A),A.type==="error")break}return k};r.decodePayload=a;function c(){return new TransformStream({transform(v,y){(0,e.encodePacketToBinary)(v,w=>{const k=w.length;let P;if(k<126)P=new Uint8Array(1),new DataView(P.buffer).setUint8(0,k);else if(k<65536){P=new Uint8Array(3);const A=new DataView(P.buffer);A.setUint8(0,126),A.setUint16(1,k)}else{P=new Uint8Array(9);const A=new DataView(P.buffer);A.setUint8(0,127),A.setBigUint64(1,BigInt(k))}v.data&&typeof v.data!="string"&&(P[0]|=128),y.enqueue(P),y.enqueue(w)})}})}let o;function l(v){return v.reduce((y,w)=>y+w.length,0)}function d(v,y){if(v[0].length===y)return v.shift();const w=new Uint8Array(y);let k=0;for(let P=0;P<y;P++)w[P]=v[0][k++],k===v[0].length&&(v.shift(),k=0);return v.length&&k<v[0].length&&(v[0]=v[0].slice(k)),w}function h(v,y){o||(o=new TextDecoder);const w=[];let k=0,P=-1,A=!1;return new TransformStream({transform(U,L){for(w.push(U);;){if(k===0){if(l(w)<1)break;const x=d(w,1);A=(x[0]&128)===128,P=x[0]&127,P<126?k=3:P===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const x=d(w,2);P=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const x=d(w,8),B=new DataView(x.buffer,x.byteOffset,x.length),G=B.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}P=G*Math.pow(2,32)+B.getUint32(4),k=3}else{if(l(w)<P)break;const x=d(w,P);L.enqueue((0,t.decodePacket)(A?x:o.decode(x),y)),k=0}if(P===0||P>v){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(El);function bi(r){if(r)return I5(r)}function I5(r){for(var e in bi.prototype)r[e]=bi.prototype[e];return r}bi.prototype.on=bi.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};bi.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};bi.prototype.off=bi.prototype.removeListener=bi.prototype.removeAllListeners=bi.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};bi.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};bi.prototype.emitReserved=bi.prototype.emit;bi.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};bi.prototype.hasListeners=function(r){return!!this.listeners(r).length};const P5=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Cl=$O(P5);var Ys={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=A5;Li.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0);Li.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();Li.defaultBinaryType="arraybuffer";function A5(){}Object.defineProperty(Ys,"__esModule",{value:!0});Ys.pick=O5;Ys.installTimerFunctions=M5;Ys.byteLength=N5;Ys.randomString=U5;const No=Li;function O5(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const $5=No.globalThisShim.setTimeout,x5=No.globalThisShim.clearTimeout;function M5(r,e){e.useNativeTimers?(r.setTimeoutFn=$5.bind(No.globalThisShim),r.clearTimeoutFn=x5.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const D5=1.33;function N5(r){return typeof r=="string"?L5(r):Math.ceil((r.byteLength||r.size)*D5)}function L5(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function U5(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var df={};Object.defineProperty(df,"__esModule",{value:!0});df.encode=F5;df.decode=j5;function F5(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function j5(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var Wb={exports:{}},Ny,ik;function B5(){if(ik)return Ny;ik=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Ny=function(d,h){h=h||{};var v=typeof d;if(v==="string"&&d.length>0)return a(d);if(v==="number"&&isFinite(d))return h.long?o(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function a(d){if(d=String(d),!(d.length>100)){var h=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(h){var v=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function c(d){var h=Math.abs(d);return h>=n?Math.round(d/n)+"d":h>=t?Math.round(d/t)+"h":h>=e?Math.round(d/e)+"m":h>=r?Math.round(d/r)+"s":d+"ms"}function o(d){var h=Math.abs(d);return h>=n?l(d,h,n,"day"):h>=t?l(d,h,t,"hour"):h>=e?l(d,h,e,"minute"):h>=r?l(d,h,r,"second"):d+" ms"}function l(d,h,v,y){var w=h>=v*1.5;return Math.round(d/v)+" "+y+(w?"s":"")}return Ny}function q5(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=B5(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let h=0;for(let v=0;v<d.length;v++)h=(h<<5)-h+d.charCodeAt(v),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,v=null,y,w;function k(...P){if(!k.enabled)return;const A=k,U=Number(new Date),L=U-(h||U);A.diff=L,A.prev=h,A.curr=U,h=U,P[0]=t.coerce(P[0]),typeof P[0]!="string"&&P.unshift("%O");let x=0;P[0]=P[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";x++;const D=t.formatters[K];if(typeof D=="function"){const fe=P[x];G=D.call(A,fe),P.splice(x,1),x--}return G}),t.formatArgs.call(A,P),(A.log||t.log).apply(A,P)}return k.namespace=d,k.useColors=t.useColors(),k.color=t.selectColor(d),k.extend=n,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:P=>{v=P}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const v=t(this.namespace+(typeof h>"u"?":":h)+d);return v.log=this.log,v}function i(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];const h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const v of h)v[0]==="-"?t.skips.push(v.slice(1)):t.names.push(v)}function s(d,h){let v=0,y=0,w=-1,k=0;for(;v<d.length;)if(y<h.length&&(h[y]===d[v]||h[y]==="*"))h[y]==="*"?(w=y,k=v,y++):(v++,y++);else if(w!==-1)y=w+1,k++,v=k;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function a(){const d=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),d}function c(d){for(const h of t.skips)if(s(d,h))return!1;for(const h of t.names)if(s(d,h))return!0;return!1}function o(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var W5=q5;(function(r,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=t,e.storage=a(),e.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;o.splice(1,0,l,"color: inherit");let d=0,h=0;o[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(d++,v==="%c"&&(h=d))}),o.splice(h,0,l)}e.log=console.debug||console.log||(()=>{});function i(o){try{o?e.storage.setItem("debug",o):e.storage.removeItem("debug")}catch{}}function s(){let o;try{o=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!o&&typeof process<"u"&&"env"in process&&(o=process.env.DEBUG),o}function a(){try{return localStorage}catch{}}r.exports=W5(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(Wb,Wb.exports);var Xs=Wb.exports,V5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ro,"__esModule",{value:!0});ro.Transport=ro.TransportError=void 0;const H5=El,G5=Cl,z5=Ys,K5=df,J5=V5(Xs),Y5=(0,J5.default)("engine.io-client:transport");class BO extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=BO;class X5 extends G5.Emitter{constructor(e){super(),this.writable=!1,(0,z5.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new BO(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Y5("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,H5.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=(0,K5.encode)(e);return t.length?"?"+t:""}}ro.Transport=X5;var Q5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cf,"__esModule",{value:!0});cf.Polling=void 0;const Z5=ro,eV=Ys,sk=El,tV=Q5(Xs),Ns=(0,tV.default)("engine.io-client:polling");class rV extends Z5.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{Ns("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Ns("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Ns("pre-pause polling complete"),--n||t()})),this.writable||(Ns("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Ns("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Ns("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ns("polling got data %s",e);const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,sk.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ns('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{Ns("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ns("transport open - closing"),e()):(Ns("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,sk.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,eV.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}cf.Polling=rV;var rg={};Object.defineProperty(rg,"__esModule",{value:!0});rg.hasCORS=void 0;let qO=!1;try{qO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}rg.hasCORS=qO;var nV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pa,"__esModule",{value:!0});pa.XHR=pa.Request=pa.BaseXHR=void 0;const iV=cf,sV=Cl,ak=Ys,WO=Li,aV=rg,oV=nV(Xs),Vb=(0,oV.default)("engine.io-client:polling");function uV(){}class VO extends iV.Polling{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){Vb("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}pa.BaseXHR=VO;let Uu=class zp extends sV.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,ak.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=(0,ak.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{Vb("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Vb("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=zp.requestsCount++,zp.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=uV,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete zp.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};pa.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ok);else if(typeof addEventListener=="function"){const r="onpagehide"in WO.globalThisShim?"pagehide":"unload";addEventListener(r,ok,!1)}}function ok(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const cV=function(){const r=HO({xdomain:!1});return r&&r.responseType!==null}();class lV extends VO{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=cV&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(HO,this.uri(),e)}}pa.XHR=lV;function HO(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||aV.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new WO.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},dV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jo,"__esModule",{value:!0});Jo.WS=Jo.BaseWS=void 0;const fV=ro,uk=Ys,hV=El,Hb=Li,pV=dV(Xs),vV=(0,pV.default)("engine.io-client:websocket"),GO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class zO extends fV.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=GO?{}:(0,uk.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;(0,hV.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{vV("websocket closed before onclose event")}i&&(0,Hb.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,uk.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=zO;const Ly=Hb.globalThisShim.WebSocket||Hb.globalThisShim.MozWebSocket;class gV extends zO{createSocket(e,t,n){return GO?new Ly(e,t,n):t?new Ly(e,t):new Ly(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=gV;var ff={},mV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ff,"__esModule",{value:!0});ff.WT=void 0;const yV=ro,_V=Li,ck=El,bV=mV(Xs),ud=(0,bV.default)("engine.io-client:webtransport");class SV extends yV.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{ud("transport closed gracefully"),this.onClose()}).catch(e=>{ud("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=(0,ck.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,ck.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:c,value:o})=>{if(c){ud("session is closed");return}ud("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{ud("an error occurred while reading: %s",c)})};s();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,_V.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}ff.WT=SV;Object.defineProperty(uf,"__esModule",{value:!0});uf.transports=void 0;const wV=pa,TV=Jo,EV=ff;uf.transports={websocket:TV.WS,webtransport:EV.WT,polling:wV.XHR};var ng={};Object.defineProperty(ng,"__esModule",{value:!0});ng.parse=RV;const CV=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kV=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function RV(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=CV.exec(r||""),s={},a=14;for(;a--;)s[kV[a]]=i[a]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=IV(s,s.path),s.queryKey=PV(s,s.query),s}function IV(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function PV(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var AV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eo,"__esModule",{value:!0});eo.Socket=eo.SocketWithUpgrade=eo.SocketWithoutUpgrade=void 0;const OV=uf,lk=Ys,$V=df,dk=ng,xV=Cl,KO=El,Uy=Li,MV=AV(Xs),zr=(0,MV.default)("engine.io-client:socket"),Gb=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fd=[];Gb&&addEventListener("offline",()=>{zr("closing %d connection(s) because the network was lost",Fd.length),Fd.forEach(r=>r())},!1);class to extends xV.Emitter{constructor(e,t){if(super(),this.binaryType=Uy.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=(0,dk.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,dk.parse)(t.host).host);(0,lk.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,$V.decode)(this.opts.query)),Gb&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(zr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Fd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Uy.createCookieJar)()),this._open()}createTransport(e){zr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=KO.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return zr("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&to.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){zr("setting transport %s",e.name),this.transport&&(zr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){zr("socket open"),this.readyState="open",to.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(zr('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else zr('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();zr("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=(0,lk.byteLength)(i)),n>0&&t>this._maxPayload)return zr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return zr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(zr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Uy.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),zr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(zr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return zr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(zr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Gb&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Fd.indexOf(this._offlineEventListener);n!==-1&&(zr("removing listener for the 'offline' event"),Fd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=KO.protocol;class JO extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){zr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){zr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(zr('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",h=>{if(!n)if(h.type==="pong"&&h.data==="probe"){if(zr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",zr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(zr("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{zr('probe transport "%s" failed',e);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const v=new Error("probe error: "+h);v.transport=t.name,s(),zr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",v)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(zr('"%s" works - aborting "%s"',h.name,t.name),s())}const d=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",c),this.off("close",o),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",c),this.once("close",o),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}eo.SocketWithUpgrade=JO;let DV=class extends JO{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>OV.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=DV;var ig={};Object.defineProperty(ig,"__esModule",{value:!0});ig.Fetch=void 0;const NV=cf;class LV extends NV.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;const n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}}ig.Fetch=LV;(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.nextTick=r.parse=r.installTimerFunctions=r.transports=r.TransportError=r.Transport=r.protocol=r.SocketWithUpgrade=r.SocketWithoutUpgrade=r.Socket=void 0;const e=eo;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return e.Socket}});var t=eo;Object.defineProperty(r,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(r,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),r.protocol=e.Socket.protocol;var n=ro;Object.defineProperty(r,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(r,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=uf;Object.defineProperty(r,"transports",{enumerable:!0,get:function(){return i.transports}});var s=Ys;Object.defineProperty(r,"installTimerFunctions",{enumerable:!0,get:function(){return s.installTimerFunctions}});var a=ng;Object.defineProperty(r,"parse",{enumerable:!0,get:function(){return a.parse}});var c=Li;Object.defineProperty(r,"nextTick",{enumerable:!0,get:function(){return c.nextTick}});var o=ig;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=pa;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=pa;Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return d.XHR}});var h=Jo;Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return h.WS}});var v=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var y=ff;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(eg);var UV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Uw,"__esModule",{value:!0});Uw.url=BV;const FV=eg,jV=UV(Xs),fk=(0,jV.default)("socket.io-client:url");function BV(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(fk("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),fk("parse %s",r),n=(0,FV.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}var sg={},hf={},Qi={},ag={},pf={};Object.defineProperty(pf,"__esModule",{value:!0});pf.isBinary=XO;pf.hasBinary=Kp;const qV=typeof ArrayBuffer=="function",WV=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,YO=Object.prototype.toString,VV=typeof Blob=="function"||typeof Blob<"u"&&YO.call(Blob)==="[object BlobConstructor]",HV=typeof File=="function"||typeof File<"u"&&YO.call(File)==="[object FileConstructor]";function XO(r){return qV&&(r instanceof ArrayBuffer||WV(r))||VV&&r instanceof Blob||HV&&r instanceof File}function Kp(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Kp(r[t]))return!0;return!1}if(XO(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Kp(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Kp(r[t]))return!0;return!1}Object.defineProperty(ag,"__esModule",{value:!0});ag.deconstructPacket=zV;ag.reconstructPacket=KV;const GV=pf;function zV(r){const e=[],t=r.data,n=r;return n.data=zb(t,e),n.attachments=e.length,{packet:n,buffers:e}}function zb(r,e){if(!r)return r;if((0,GV.isBinary)(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=zb(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=zb(r[n],e));return t}return r}function KV(r,e){return r.data=Kb(r.data,e),delete r.attachments,r}function Kb(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Kb(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Kb(r[t],e));return r}Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Decoder=Qi.Encoder=Qi.PacketType=Qi.protocol=void 0;Qi.isPacketValid=nH;const JV=Cl,QO=ag,ZO=pf,YV=Xs,Jb=(0,YV.default)("socket.io-parser"),e$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Qi.protocol=5;var Fr;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Fr||(Qi.PacketType=Fr={}));class XV{constructor(e){this.replacer=e}encode(e){return Jb("encoding packet %j",e),(e.type===Fr.EVENT||e.type===Fr.ACK)&&(0,ZO.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fr.EVENT?Fr.BINARY_EVENT:Fr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fr.BINARY_EVENT||e.type===Fr.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Jb("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,QO.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Qi.Encoder=XV;class Fw extends JV.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Fr.BINARY_EVENT;n||t.type===Fr.BINARY_ACK?(t.type=n?Fr.EVENT:Fr.ACK,this.reconstructor=new QV(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,ZO.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Fr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Fr.BINARY_EVENT||n.type===Fr.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(Fw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return Jb("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Fr.CONNECT:return gv(t);case Fr.DISCONNECT:return t===void 0;case Fr.CONNECT_ERROR:return typeof t=="string"||gv(t);case Fr.EVENT:case Fr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&e$.indexOf(t[0])===-1);case Fr.ACK:case Fr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Qi.Decoder=Fw;class QV{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=(0,QO.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function ZV(r){return typeof r=="string"}const eH=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function tH(r){return r===void 0||eH(r)}function gv(r){return Object.prototype.toString.call(r)==="[object Object]"}function rH(r,e){switch(r){case Fr.CONNECT:return e===void 0||gv(e);case Fr.DISCONNECT:return e===void 0;case Fr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&e$.indexOf(e[0])===-1);case Fr.ACK:return Array.isArray(e);case Fr.CONNECT_ERROR:return typeof e=="string"||gv(e);default:return!1}}function nH(r){return ZV(r.nsp)&&tH(r.id)&&rH(r.type,r.data)}var og={};Object.defineProperty(og,"__esModule",{value:!0});og.on=iH;function iH(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var sH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(hf,"__esModule",{value:!0});hf.Socket=void 0;const Ls=Qi,Mh=og,aH=Cl,oH=sH(Xs),bn=(0,oH.default)("socket.io-client:socket"),uH=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class cH extends aH.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[(0,Mh.on)(e,"open",this.onopen.bind(this)),(0,Mh.on)(e,"packet",this.onpacket.bind(this)),(0,Mh.on)(e,"error",this.onerror.bind(this)),(0,Mh.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(uH.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const a={type:Ls.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++;bn("emitting packet with ack id %d",d);const h=t.pop();this._registerAckCallback(d,h),a.id=d}const c=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,o=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?bn("discard packet as the transport is not currently writable"):o?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(bn("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));bn("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(a,c)=>a?i(a):n(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?bn("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(bn("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(bn("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(bn("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!e){bn("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,bn("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){bn("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ls.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){bn("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ls.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ls.PacketType.EVENT:case Ls.PacketType.BINARY_EVENT:this.onevent(e);break;case Ls.PacketType.ACK:case Ls.PacketType.BINARY_ACK:this.onack(e);break;case Ls.PacketType.DISCONNECT:this.ondisconnect();break;case Ls.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];bn("emitting event %j",t),e.id!=null&&(bn("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,bn("sending ack %j",i),t.packet({type:Ls.PacketType.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];if(typeof t!="function"){bn("bad ack %s",e.id);return}delete this.acks[e.id],bn("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){bn("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){bn("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(bn("performing disconnect (%s)",this.nsp),this.packet({type:Ls.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}hf.Socket=cH;var jw={};Object.defineProperty(jw,"__esModule",{value:!0});jw.Backoff=kl;function kl(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}kl.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};kl.prototype.reset=function(){this.attempts=0};kl.prototype.setMin=function(r){this.ms=r};kl.prototype.setMax=function(r){this.max=r};kl.prototype.setJitter=function(r){this.jitter=r};var lH=Ye&&Ye.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),dH=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),fH=Ye&&Ye.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&lH(e,r,t);return dH(e,r),e},hH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(sg,"__esModule",{value:!0});sg.Manager=void 0;const Fy=eg,pH=hf,vH=fH(Qi),Tu=og,gH=jw,mH=Cl,yH=hH(Xs),Hn=(0,yH.default)("socket.io-client:manager");class _H extends mH.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Fy.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new gH.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||vH;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(Hn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Hn("opening %s",this.uri),this.engine=new Fy.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Tu.on)(t,"open",function(){n.onopen(),e&&e()}),s=c=>{Hn("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Tu.on)(t,"error",s);if(this._timeout!==!1){const c=this._timeout;Hn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Hn("connect attempt timed out after %d",c),i(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&o.unref(),this.subs.push(()=>{this.clearTimeoutFn(o)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){Hn("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push((0,Tu.on)(e,"ping",this.onping.bind(this)),(0,Tu.on)(e,"data",this.ondata.bind(this)),(0,Tu.on)(e,"error",this.onerror.bind(this)),(0,Tu.on)(e,"close",this.onclose.bind(this)),(0,Tu.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Fy.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Hn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new pH.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Hn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Hn("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){Hn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Hn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Hn("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Hn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Hn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Hn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Hn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Hn("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}sg.Manager=_H;(function(r,e){var t=Ye&&Ye.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.Socket=e.Manager=e.protocol=void 0,e.io=l,e.connect=l,e.default=l;const n=Uw,i=sg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=hf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Xs).default)("socket.io-client"),o={};function l(v,y){typeof v=="object"&&(y=v,v=void 0),y=y||{};const w=(0,n.url)(v,y.path||"/socket.io"),k=w.source,P=w.id,A=w.path,U=o[P]&&A in o[P].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||U;let x;return L?(c("ignoring socket cache for %s",k),x=new i.Manager(k,y)):(o[P]||(c("new io instance for %s",k),o[P]=new i.Manager(k,y)),x=o[P]),w.query&&!y.query&&(y.query=w.queryKey),x.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Qi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=eg;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return h.Fetch}}),Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return h.NodeXHR}}),Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return h.XHR}}),Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return h.NodeWebSocket}}),Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return h.WebSocket}}),Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return h.WebTransport}}),r.exports=l})(qb,qb.exports);var t$=qb.exports,r$={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(p,g,b){for(var _=b,S=0,T=p.length;S<T;S++)_=g(_,p[S],S,p);return _},n=function(p,g){return t(p,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(p,g){return t(p,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(p,g){return t(p,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(p){var g=[],b;for(b in p)Object.prototype.hasOwnProperty.call(p,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(p,c[_])&&g.push(c[_]);return g},l=function(p){return Object.prototype.toString.call(p)==="[object Array]"},d=function(p){return p<10?"0"+p:p},h=function(){var p=new Date;return p.getUTCFullYear()+"-"+d(p.getUTCMonth()+1)+"-"+d(p.getUTCDate())+"T"+d(p.getUTCHours())+":"+d(p.getUTCMinutes())+":"+d(p.getUTCSeconds())+"."+(p.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(p,g){return p===void 0&&(p=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=p&&b<=g}},y.stringWithLength=function(p){return typeof p=="string"&&!!p.length};var w={},k=v.filter,P=v.reduce,A=v.keys,U=v.isArray,L=v.includes,x=y.intRange,B=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:B},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return p===!0||p===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(p){return typeof p=="function"||U(p)&&k(p,function(g){return typeof g=="function"}).length===p.length}},endpoints:{defaultValue:function(){return{notify:"https://notify.bugsnag.com",sessions:"https://sessions.bugsnag.com"}},message:"should be an object containing endpoint URLs { notify, sessions }. sessions is optional if autoCaptureSessions=false",validate:function(p,g){return p&&typeof p=="object"&&B(p.notify)&&(g.autoCaptureSessions===!1||B(p.sessions))&&k(A(p),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(p,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(p){return p===!0||p===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(p){return p===null||U(p)&&k(p,function(g){return typeof g=="string"}).length===p.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(p){return typeof p=="string"&&p.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(p){return x(0,40)(p)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return typeof p=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(p){return typeof p=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(p){return typeof p=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(p){return!p||p&&P(["debug","info","warn","error"],function(g,b){return g&&typeof p[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(p){return U(p)&&p.length===k(p,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");return P(A(g),function(b,_){return b[_]=p[_]!==void 0?p[_]:g[_].defaultValue(p[_],p),b},{})},w.validate=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");var b=P(A(g),function(_,S){return g[S].validate(p[S],p)?_:_.concat({key:S,message:g[S].message,value:p[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(p){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(p[_]=b[_])}return p},G.apply(this,arguments)}var K=w.schema,D=v.map,fe=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:fe},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?pe():void 0}})},pe=function(){var p={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];p[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),p},Q=v.isoDate,Oe=function(){function p(b,_,S,T){b===void 0&&(b="[anonymous]"),_===void 0&&(_={}),S===void 0&&(S="manual"),T===void 0&&(T=Q()),this.type=S,this.name=b,this.metaData=_,this.timestamp=T}var g=p.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},p}(),Ve=Oe,Ze=function(p,g,b){var _=p.length,S=0,T=function(){if(S>=_)return b(null,!1);g(p[S],function(E,I){if(E)return b(E,!1);if(I===!0)return b(null,!0);S++,T()})};T()},Xe=function(p){return p.app&&typeof p.app.releaseStage=="string"?p.app.releaseStage:p.config.releaseStage},Re=Je;function Je(p){switch(Object.prototype.toString.call(p)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return p instanceof Error}}var Ke=Re,Y=function(p,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(p);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ee(p,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ee(p,S))}b(p,function(T,E){if(T)return g(T),_(null,!1);_(null,Ee(p,E))})}catch(T){g(T),_(null,!1)}}},Ee=function(p,g){return p.isIgnored()||g===!1},Ct={};(function(p,g){typeof Ct=="object"?Ct=g():p.StackFrame=g()})(this,function(){function p(Se){return!isNaN(parseFloat(Se))&&isFinite(Se)}function g(Se){return Se.charAt(0).toUpperCase()+Se.substring(1)}function b(Se){return function(){return this[Se]}}var _=["isConstructor","isEval","isNative","isToplevel"],S=["columnNumber","lineNumber"],T=["fileName","functionName","source"],E=["args"],I=_.concat(S,T,E);function q(Se){if(Se instanceof Object)for(var Ge=0;Ge<I.length;Ge++)Se.hasOwnProperty(I[Ge])&&Se[I[Ge]]!==void 0&&this["set"+g(I[Ge])](Se[I[Ge]])}q.prototype={getArgs:function(){return this.args},setArgs:function(Se){if(Object.prototype.toString.call(Se)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=Se},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(Se){if(Se instanceof q)this.evalOrigin=Se;else if(Se instanceof Object)this.evalOrigin=new q(Se);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var Se=this.getFunctionName()||"{anonymous}",Ge="("+(this.getArgs()||[]).join(",")+")",gt=this.getFileName()?"@"+this.getFileName():"",et=p(this.getLineNumber())?":"+this.getLineNumber():"",ct=p(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var H=0;H<_.length;H++)q.prototype["get"+g(_[H])]=b(_[H]),q.prototype["set"+g(_[H])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[H]);for(var J=0;J<S.length;J++)q.prototype["get"+g(S[J])]=b(S[J]),q.prototype["set"+g(S[J])]=function(Se){return function(Ge){if(!p(Ge))throw new TypeError(Se+" must be a Number");this[Se]=Number(Ge)}}(S[J]);for(var ae=0;ae<T.length;ae++)q.prototype["get"+g(T[ae])]=b(T[ae]),q.prototype["set"+g(T[ae])]=function(Se){return function(Ge){this[Se]=String(Ge)}}(T[ae]);return q});var Nt={};(function(p,g){typeof Nt=="object"?Nt=g(Ct):p.ErrorStackParser=g(p.StackFrame)})(this,function(g){var b=/(^|@)\S+\:\d+/,_=/^\s*at .*(\S+\:\d+|\(native\))/m,S=/^(eval@)?(\[native code\])?$/;return{parse:function(E){if(typeof E.stacktrace<"u"||typeof E["opera#sourceloc"]<"u")return this.parseOpera(E);if(E.stack&&E.stack.match(_))return this.parseV8OrIE(E);if(E.stack)return this.parseFFOrSafari(E);throw new Error("Cannot parse given Error object")},extractLocation:function(E){if(E.indexOf(":")===-1)return[E];var I=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,q=I.exec(E.replace(/[\(\)]/g,""));return[q[1],q[2]||void 0,q[3]||void 0]},parseV8OrIE:function(E){var I=E.stack.split(`
|
|
3
3
|
`).filter(function(q){return!!q.match(_)},this);return I.map(function(q){q.indexOf("(eval ")>-1&&(q=q.replace(/eval code/g,"eval").replace(/(\(eval at [^\()]*)|(\)\,.*$)/g,""));var H=q.replace(/^\s+/,"").replace(/\(eval code/g,"("),J=H.match(/ (\((.+):(\d+):(\d+)\)$)/);H=J?H.replace(J[0],""):H;var ae=H.split(/\s+/).slice(1),Se=this.extractLocation(J?J[1]:ae.pop()),Ge=ae.join(" ")||void 0,gt=["eval","<anonymous>"].indexOf(Se[0])>-1?void 0:Se[0];return new g({functionName:Ge,fileName:gt,lineNumber:Se[1],columnNumber:Se[2],source:q})},this)},parseFFOrSafari:function(E){var I=E.stack.split(`
|
|
4
4
|
`).filter(function(q){return!q.match(S)},this);return I.map(function(q){if(q.indexOf(" > eval")>-1&&(q=q.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g,":$1")),q.indexOf("@")===-1&&q.indexOf(":")===-1)return new g({functionName:q});var H=/((.*".+"[^@]*)?[^@]*)(?:@)/,J=q.match(H),ae=J&&J[1]?J[1]:void 0,Se=this.extractLocation(q.replace(H,""));return new g({functionName:ae,fileName:Se[0],lineNumber:Se[1],columnNumber:Se[2],source:q})},this)},parseOpera:function(E){return!E.stacktrace||E.message.indexOf(`
|
|
5
5
|
`)>-1&&E.message.split(`
|
package/dist/index.mjs
CHANGED
|
@@ -762,7 +762,7 @@ const a6 = new TextDecoder(), o6 = (r) => {
|
|
|
762
762
|
const s = t.slice(n, n + i);
|
|
763
763
|
return n += i, s;
|
|
764
764
|
}).join("-");
|
|
765
|
-
}, N_e = "prod", dO = "6.
|
|
765
|
+
}, N_e = "prod", dO = "6.33.0", UC = "https://main.api.ujet.co", ri = {
|
|
766
766
|
companyId: "",
|
|
767
767
|
tenant: "",
|
|
768
768
|
trackerId: "",
|
|
@@ -1240,14 +1240,14 @@ class E6 {
|
|
|
1240
1240
|
var l;
|
|
1241
1241
|
let t = e.host;
|
|
1242
1242
|
t || (e.tenant ? t = UC.replace("main.api", e.tenant) : t = UC);
|
|
1243
|
-
const n = e.lang || "en", i = !!((l = e.cobrowse) != null && l.enabled), a = (e.bridge || "https://websdk.ujet.co/v3/bridge.html") + "?6.
|
|
1243
|
+
const n = e.lang || "en", i = !!((l = e.cobrowse) != null && l.enabled), a = (e.bridge || "https://websdk.ujet.co/v3/bridge.html") + "?6.33.0", c = /^https:/.test(a) ? new URL(a).origin : "*", o = ["twilio_chat", "nexmo_chat", "ujet_chat"];
|
|
1244
1244
|
i && o.push("cobrowse"), this.config = {
|
|
1245
1245
|
host: t,
|
|
1246
1246
|
lang: n,
|
|
1247
1247
|
cobrowse: i,
|
|
1248
1248
|
companyId: e.companyId,
|
|
1249
1249
|
location: location.href,
|
|
1250
|
-
version: e.version || "6.
|
|
1250
|
+
version: e.version || "6.33.0",
|
|
1251
1251
|
bridge: a,
|
|
1252
1252
|
bridgeOrigin: c,
|
|
1253
1253
|
modules: o
|